using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.IO.Compression; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Reflection.Emit; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security.Cryptography; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using BepInEx; using BepInEx.Configuration; using BepInEx.Logging; using HarmonyLib; using HeimKit.Configuration; using HeimKit.Core.Diagnostics; using HeimKit.Core.Lifecycle; using HeimKit.Core.Native; using HeimKit.Core.Ownership; using HeimKit.Core.Players; using HeimKit.Core.Players.Models; using HeimKit.Core.Prefabs; using HeimKit.Core.Scheduling; using HeimKit.Core.World; using HeimKit.Features.AFKNightWatch; using HeimKit.Features.AFKNightWatch.Models; using HeimKit.Features.AFKRaidWatch; using HeimKit.Features.AFKRaidWatch.Models; using HeimKit.Features.DoorKeeper; using HeimKit.Features.ForestRenewal; using HeimKit.Features.ForestRenewal.Models; using HeimKit.Features.HeimMender; using HeimKit.Features.HeimMender.Models; using HeimKit.Features.InfiniteTorches; using HeimKit.Features.InfiniteTorches.Models; using HeimKit.Features.SeaSalvage; using HeimKit.Features.SeaSalvage.Models; using HeimKit.Features.SharedMap; using HeimKit.Features.SharedMap.Models; using HeimKit.Features.TameTravel; using HeimKit.Features.TameTravel.Models; using HeimKit.Features.WeatherGuard; using HeimKit.Features.WeatherGuard.Models; using Microsoft.CodeAnalysis; using SoftReferenceableAssets; using UnityEngine; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: AssemblyCompany("HeimKit")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("0.2.0.0")] [assembly: AssemblyInformationalVersion("0.2.0")] [assembly: AssemblyProduct("HeimKit")] [assembly: AssemblyTitle("HeimKit")] [assembly: InternalsVisibleTo("HeimKit.Tests")] [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.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class NullableAttribute : Attribute { public readonly byte[] NullableFlags; public NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class NullableContextAttribute : Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace HeimKit { [BepInPlugin("heimkit", "HeimKit", "0.2.0")] [BepInProcess("valheim_server.exe")] public sealed class Plugin : BaseUnityPlugin { private ModuleHost? _host; private PlayerServices? _players; private WorldObjectProvider? _world; private void Awake() { //IL_00de: 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) _host = new ModuleHost(((BaseUnityPlugin)this).Logger); DiagnosticLog.StartSession(); DiagnosticLog.Write(((BaseUnityPlugin)this).Logger, "HeimKit", "Starting version 0.2.0 at " + DiagnosticLog.WallClock().ToString("yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture) + ". Build configuration: Release.", (LogLevel)16); try { ConfigurationLoader.Load(Paths.ConfigPath, ((BaseUnityPlugin)this).Logger, delegate(ConfigFile val) { _players = new PlayerServices(val, ((BaseUnityPlugin)this).Logger); _world = new WorldObjectProvider(_players.Presence); _host.Register(() => new InfiniteTorches(val, ((BaseUnityPlugin)this).Logger, _players), "InfiniteTorches"); _host.Register(() => new WeatherGuard(val, ((BaseUnityPlugin)this).Logger, _players), "WeatherGuard"); _host.Register(() => new AFKNightWatch(val, ((BaseUnityPlugin)this).Logger, _players), "AFKNightWatch"); _host.Register(() => new AFKRaidWatch(val, ((BaseUnityPlugin)this).Logger, _players), "AFKRaidWatch"); _host.Register(() => new SharedMap(val, ((BaseUnityPlugin)this).Logger, _players), "SharedMap"); _host.Register(() => new DoorKeeper(val, ((BaseUnityPlugin)this).Logger, _players), "DoorKeeper"); _host.Register(() => new ForestRenewal(val, ((BaseUnityPlugin)this).Logger, _players), "ForestRenewal"); _host.Register(() => new SeaSalvage(val, ((BaseUnityPlugin)this).Logger, _players), "SeaSalvage"); _host.Register(() => new TameTravel(val, ((BaseUnityPlugin)this).Logger, _players), "TameTravel"); _host.Register(() => new HeimMender(val, ((BaseUnityPlugin)this).Logger, _players), "HeimMender"); return val; }); } catch (Exception ex) { _players?.Dispose(); _players = null; _host.Dispose(); _world?.Dispose(); _world = null; ManualLogSource logger = ((BaseUnityPlugin)this).Logger; LogTopic config = CoreLogTopics.Config; Exception error = ex; DiagnosticLog.Write(logger, "HeimKit", config, "Modules disabled because configuration setup failed.", default(LogFields), (LogLevel)2, verbose: false, error); return; } _host.Initialize(((object)Version.CurrentVersion/*cast due to .constrained prefix*/).ToString()); } private void Update() { float unscaledTime = Time.unscaledTime; WorldServices.Refresh(); _players?.Tick(unscaledTime); _world?.Tick(unscaledTime); _host?.Tick(unscaledTime); _players?.Events.ReportProcessing(); } private void OnDestroy() { _host?.Dispose(); _host = null; _world?.Dispose(); _world = null; _players?.Dispose(); _players = null; PrefabRegistry.Current.Clear(); } } } namespace HeimKit.Features.WeatherGuard { public sealed class WeatherGuard : IServerModule { private readonly WeatherGuardSettings _settings; private readonly ManualLogSource _logger; private readonly GameVersionCompatibility _compatibility; private readonly string _configPath; private readonly WeatherGuardCoverageRequests _coverageRequests; private readonly WeatherGuardDiagnostics _adminDiagnostics; private WeatherGuardController? _controller; private ZDOMan? _world; private readonly PlayerServices _players; private IDisposable? _presenceRegistration; private bool? _occupied; private readonly PlayerProcessingNotices _processing; private float _coverageNow; private readonly Action _coverageReport; public string Name => "WeatherGuard"; public bool IsActive { get; private set; } private static bool ServerReady => WorldServices.Terrain; public WeatherGuard(ConfigFile config, ManualLogSource logger, PlayerServices players) { _coverageReport = ReportCoverage; _logger = logger; _compatibility = GameVersionCompatibility.Resolve(config, logger); _players = players; _settings = new WeatherGuardSettings(config, logger); _processing = new PlayerProcessingNotices(logger, Name, () => _settings.DebugLogging.Enabled); _configPath = config.ConfigFilePath; _coverageRequests = new WeatherGuardCoverageRequests(Path.GetDirectoryName(_configPath), logger); _adminDiagnostics = new WeatherGuardDiagnostics(logger, debug: false); } public void Initialize(string gameVersion) { Shutdown(); DiagnosticLog.Write(_logger, Name, _settings.Enabled.Value ? "Enabled." : "Disabled.", (LogLevel)16); _settings.DebugLogging.ReportStartup(_logger, Name, _settings.Enabled.Value); WeatherGuardDiagnostics.StartupSettings(_logger, _settings); if (!_settings.Enabled.Value) { return; } if (!_compatibility.Supports(gameVersion)) { DiagnosticLog.Write(_logger, "WeatherGuard", "DISABLED (unsupported Valheim version " + gameVersion + "; required version " + _compatibility.RequiredVersion + "; built-in audited version 1.0.20).", (LogLevel)4); return; } IsActive = true; if (_settings.DebugLogging.Enabled) { DiagnosticLog.Write(_logger, Name, "Waiting for joined players and dedicated-server world", (LogLevel)32); } _presenceRegistration = _players.Events.Subscribe(PresenceChanged, Fail, () => _processing.IsEmptyPaused, () => _processing.IsRunning, () => _processing.IsServerReady); } public void Tick(float now) { if (IsActive && !_settings.Enabled.Value) { Shutdown(); } if (IsActive) { if (ServerReady) { _processing.ServerReady(); } if (_occupied != true) { StopController(); } else { StartController(); _controller?.Tick(now); } } PollCoverage(now); } private void PresenceChanged(bool? occupied) { _occupied = occupied; if (IsActive && occupied != true) { StopController(); if (occupied.HasValue) { _processing.EmptyPaused(); } else { _processing.Unavailable("player presence unavailable"); } } } private void StartController() { _ = ZNet.instance; ZDOMan instance = ZDOMan.instance; if (!WorldServices.Terrain) { StopController(); _processing.Paused("world services unavailable"); return; } if (_world != instance && _controller != null) { StopController(); _processing.Paused("world changed"); } if (_controller == null) { _world = instance; _controller = new WeatherGuardController(this, _logger, _settings.DebugLogging, _settings.DebugLogLevel.Value, _settings.LogWorldCreatedItems.Value, _settings.ProtectRain.Value, _settings.ProtectUnderwater.Value, _settings.ExcludedPrefabs.Value, _players.Presence); _controller.Install(); _processing.Ready(); } } private void StopController() { WeatherGuardController controller = _controller; _controller = null; if (controller != null) { ModuleScheduler.Current.Forget(controller); } _world = null; try { controller?.Dispose(); } finally { WorldObjectProvider.Current?.ReleaseOwner(Name); } } private void PollCoverage(float now) { _coverageNow = now; _coverageRequests.Poll(now, _coverageReport); } private void ReportCoverage() { _adminDiagnostics.Coverage(((_controller != null && _world == ZDOMan.instance && WorldServices.Terrain) ? _controller.Coverage(_coverageNow) : null) ?? new CoverageSnapshot { State = ((!IsActive) ? "module_inactive" : ((_occupied == false) ? "server_empty" : ((!_occupied.HasValue) ? "player_presence_unavailable" : "waiting_for_world"))), RainEnabled = _settings.ProtectRain.Value, UnderwaterEnabled = _settings.ProtectUnderwater.Value }); } internal void Fail(Exception error) { DiagnosticLog.Write(_logger, "WeatherGuard", CoreLogTopics.Lifecycle, "Disabled after controller error; returning pieces to vanilla ownership.", default(LogFields), (LogLevel)2, verbose: false, error); Shutdown(); } public void Shutdown() { IsActive = false; _occupied = null; _processing.Reset(); IDisposable registration = _presenceRegistration; _presenceRegistration = null; ModuleCleanup.Run(_logger, Name, delegate { registration?.Dispose(); }, StopController); } } internal sealed class WeatherGuardController : IDisposable { private readonly WeatherGuard _module; private readonly IPlayerPresence _presence; private readonly ManualLogSource _log; private readonly WeatherGuardDiagnostics _diagnostics; private readonly Action _confirmedPiece; private readonly bool _protectRain; private readonly bool _protectUnderwater; private readonly HashSet _excludedPrefabs; private float _lastScopeScan = -1f; private bool _scopeLimited; private readonly FieldRef _rainWet = NativeAccess.Field("m_rainWet"); private readonly ZDOMan _manager; private readonly WeatherGuardPatches _patches; private readonly List _near = new List(); private readonly List _distant = new List(); private readonly List _scratch = new List(); private readonly List _farScratch = new List(); private readonly HashSet _nearIds = new HashSet(); private readonly HashSet _distantIds = new HashSet(); private readonly HashSet _instanceSeen = new HashSet(); private readonly HashSet _regions = new HashSet(); private readonly List _positions = new List(); private readonly Dictionary _protected = new Dictionary(); private readonly Dictionary _readyContexts = new Dictionary(); private readonly PrefabCatalog _contextPrefabs = PrefabRegistry.Current.Catalog("WeatherGuardController._contextPrefabs"); private readonly List _contextObjects = new List(); private readonly List _release = new List(); private readonly Dictionary _exclusions = new Dictionary(); private readonly Dictionary _releaseReasons = new Dictionary(); private readonly Dictionary _releaseTotals = new Dictionary(); private readonly Dictionary _rainEvidence = new Dictionary(); private readonly HashSet _managedExposure = new HashSet(); private readonly HashSet _eligibleExposure = new HashSet(); private readonly List _staleDebug = new List(); private readonly HashSet _observedCandidates = new HashSet(); private readonly Dictionary _candidateReasons = new Dictionary(); private int _rainProbeCursor; private int _exposureProbeCursor; private readonly WeatherGuardExposureTracking _exposure = new WeatherGuardExposureTracking(); private readonly List _eligiblePieces = new List(); private readonly Dictionary _playerBiomes = new Dictionary(); private bool _candidateScanStarted; private ZDOID _recentPlayerCandidate; private readonly FieldRef _roof = NativeAccess.Field("m_haveRoof"); private readonly FieldRef _shield = NativeAccess.Field("m_shieldChangeID"); private readonly FieldRef _rainTimer = NativeAccess.Field("m_rainTimer"); private readonly FieldRef _creationTime = NativeAccess.Field("m_createTime"); private readonly FieldRef _coverTimer = NativeAccess.Field("m_updateCoverTimer"); private readonly Func _shouldUpdate = NativeAccess.Method>(typeof(WearNTear), "ShouldUpdate", new Type[1] { typeof(float) }); private readonly Func _underWater = NativeAccess.Method>(typeof(WearNTear), "IsUnderWater", Array.Empty()); private readonly Func _canBeRemoved = NativeAccess.Method>(typeof(WearNTear), "CanBeRemoved", Array.Empty()); private readonly Func _createZones = NativeAccess.Method>(typeof(ZoneSystem), "CreateLocalZones", new Type[1] { typeof(Vector3) }); private readonly FieldRef _creator = NativeAccess.Field("m_creator"); private readonly FieldRef _creatorIndex = NativeAccess.Field("m_creatorPlatformUserIDIndex"); private readonly PrefabCatalog<(string Name, bool Wear, bool Static, bool NoRoofWear, float Health, bool Building, bool Container)> _eligibility = PrefabRegistry.Current.Catalog<(string, bool, bool, bool, float, bool, bool)>("WeatherGuardController._eligibility"); private bool _announced; private int _eligible; private int _waiting; private int _waitingTerrain; private int _waitingObjects; private int _waitingInstance; private long _acquired; private long _released; private long _blockedData; private long _blockedOwner; private long _blockedBroadcast; private long _commands; private long _wearPasses; private long _ownerLosses; private long _weatherGates; private long _wetOpportunities; private long _weatherSuppressedTotal; private long _confirmedPreventions; private readonly Dictionary _decisions = new Dictionary(); private long _nativeCommands; private long _supportPasses; private int _peers; private int _readyPeers; private int _characterWaits; internal Action ConfirmedPiece => _confirmedPiece; internal static WeatherGuardController? Active { get; private set; } internal long ServerId => ZDOMan.GetSessionID(); internal bool Running { get { if (Active == this && _module.IsActive && _manager == ZDOMan.instance && (_protectRain || _protectUnderwater)) { return WorldServices.Terrain; } return false; } } public WeatherGuardController(WeatherGuard module, ManualLogSource log, DebugLoggingPolicy debug, DebugLogLevel level, bool logWorldCreated, bool protectRain, bool protectUnderwater, string excludedPrefabs, IPlayerPresence presence) { _confirmedPiece = WeatherDamageSuppressed; _presence = presence; _protectRain = protectRain; _protectUnderwater = protectUnderwater; _excludedPrefabs = WeatherGuardRules.ParseExcludedPrefabs(excludedPrefabs, out var rejected); if (rejected > 0) { DiagnosticLog.Write(log, "WeatherGuard", $"Ignored {rejected} invalid or over-limit prefab exclusions. Review WeatherGuard.ExcludedPrefabs.", (LogLevel)4); } _module = module; _log = log; _diagnostics = new WeatherGuardDiagnostics(log, debug, level, logWorldCreated); _manager = ZDOMan.instance; _patches = new WeatherGuardPatches(); } public void Install() { WorldObjectProvider.CheckLiveInstanceCompatibility(); if (_creator == null || _creatorIndex == null || _rainWet == null || _createZones == null || _roof == null || _shield == null || _rainTimer == null || _coverTimer == null || _creationTime == null || _shouldUpdate == null || _underWater == null || _canBeRemoved == null) { throw new MissingMemberException("WeatherGuard terrain/instance/wear evidence APIs unavailable."); } List list = new List(); foreach (string excludedPrefab in _excludedPrefabs) { if ((Object)(object)PrefabRegistry.Current.Prefab(excludedPrefab) == (Object)null) { list.Add(excludedPrefab); } } if (list.Count > 0) { DiagnosticLog.Write(_log, "WeatherGuard", $"{list.Count} excluded prefab identifiers were not found. Review WeatherGuard.ExcludedPrefabs; matching remains exact.", (LogLevel)4); } Active = this; try { _patches.Install(); } catch { Dispose(); throw; } } internal bool Protects(ZDOID id) { //IL_000e: Unknown result type (might be due to invalid IL or missing references) if (Running) { return _protected.ContainsKey(id); } return false; } internal void Fail(Exception error) { _module.Fail(error); } internal void OwnerBlocked(ZDO zdo, long requested) { _blockedOwner++; } internal void DataBlocked(int count) { _blockedData += count; } internal void Reassert(ZDOID id, uint revision, ushort ownerRevision) { //IL_0006: 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) if (_protected.TryGetValue(id, out ZDO value) && value.IsValid()) { (uint, ushort) tuple = WeatherGuardRules.ReassertRevisions(value.DataRevision, value.OwnerRevision, revision, ownerRevision); value.DataRevision = tuple.Item1; value.OwnerRevision = tuple.Item2; ZDOMan.instance.ForceSendZDO(id); } } internal void BroadcastBlocked(int count = 1) { _blockedBroadcast += count; } internal void Resend(ZDOID id) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Unknown result type (might be due to invalid IL or missing references) if (_protected.TryGetValue(id, out ZDO value) && value.IsValid()) { ZDOMan.instance.ForceSendZDO(id); } } internal void CommandRouted() { _commands++; } internal void WearPass() { _wearPasses++; } internal bool SuppressWeather(WearNTear wear, bool native) { if (_protectRain && _protectUnderwater) { return native; } return WeatherGuardRules.SuppressWeatherDamage(native, _protectRain, _protectUnderwater, _rainWet.Invoke(wear), _underWater(wear)); } internal bool WeatherDamageMayApply(WearNTear wear) { int num; if (_canBeRemoved(wear)) { num = ((!ZoneSystem.instance.GetGlobalKey((GlobalKeys)37)) ? 1 : 0); if (num != 0) { goto IL_0057; } } else { num = 0; } if (_diagnostics.StepsEnabled) { _decisions.TryGetValue("native_final_damage_disabled", out var value); _decisions["native_final_damage_disabled"] = value + 1; } goto IL_0057; IL_0057: return (byte)num != 0; } internal string? PiecePrefab(ZDO zdo) { GameObject? obj = PrefabRegistry.Current.Prefab(zdo.GetPrefab()); if (obj == null) { return null; } return ((Object)obj).name; } internal void WeatherDamageSuppressed(ZDOID id, string? prefab = null) { //IL_0015: Unknown result type (might be due to invalid IL or missing references) _confirmedPreventions++; _diagnostics.WeatherDamageSuppressed(id, prefab); } internal void WearConditions(WearNTear wear, float time) { //IL_0041: Unknown result type (might be due to invalid IL or missing references) if (_diagnostics.StepsEnabled) { int num = _shield.Invoke(wear); bool flag = _underWater(wear); string key = ((!_shouldUpdate(wear, time)) ? "waiting_warmup" : (ShieldGenerator.IsInsideShieldCached(((Component)wear).transform.position, ref num) ? "shielded" : ((wear.GetHealthPercentage() <= 0.5f) ? "health_at_or_below_half" : ((!flag && _roof.Invoke(wear)) ? "native_cached_roof_covered" : ((!flag && !EnvMan.IsWet()) ? "native_environment_dry" : ((_rainTimer.Invoke(wear) == 0f) ? "starting_wet_timer" : ((time - _rainTimer.Invoke(wear) <= 60f) ? "waiting_wet_timer" : "native_conditions_met"))))))); _decisions.TryGetValue(key, out var value); _decisions[key] = value + 1; } } internal void WeatherGate(WearNTear wear, bool branchBypassed) { //IL_0058: Unknown result type (might be due to invalid IL or missing references) //IL_00a5: Unknown result type (might be due to invalid IL or missing references) _weatherGates++; if (branchBypassed) { _weatherSuppressedTotal++; } if (_diagnostics.DebugEnabled) { int num = _shield.Invoke(wear); bool flag = wear.m_noRoofWear && wear.GetHealthPercentage() > 0.5f && !ShieldGenerator.IsInsideShieldCached(((Component)wear).transform.position, ref num) && wear.IsWet(); if (flag) { _wetOpportunities++; } ZDO zDO = ((Component)wear).GetComponent().GetZDO(); if (flag) { TrackRain(zDO, wear, "eligible"); } if (_rainEvidence.TryGetValue(zDO.m_uid, out RainEvidence value)) { value.ObserveGate(Time.time, flag, branchBypassed); } } } internal WearObservation? BeginWear(WearNTear wear, ZNetView view, bool protectedPiece, float time) { //IL_00c4: Unknown result type (might be due to invalid IL or missing references) //IL_0288: Unknown result type (might be due to invalid IL or missing references) if (!_diagnostics.DebugEnabled) { return null; } ZDO zDO = view.GetZDO(); string text = Eligibility(zDO, ZNetScene.instance); if (!protectedPiece && text != "world-created" && text != "eligible") { return null; } if (text == "world-created" && !_diagnostics.LogWorldCreatedItems) { return null; } bool flag = !_roof.Invoke(wear) || _underWater(wear); if (flag) { TrackRain(zDO, wear, text); } if (!_diagnostics.TryWearSample(Time.unscaledTime, ((object)Unsafe.As(ref zDO.m_uid)/*cast due to .constrained prefix*/).ToString(), protectedPiece, flag)) { return null; } int num = _shield.Invoke(wear); bool flag2 = ShieldGenerator.IsInsideShieldCached(((Component)wear).transform.position, ref num); WearObservation wearObservation = new WearObservation { Identity = Identity(zDO), Protected = protectedPiece, Owner = view.IsOwner(), Warmup = !_shouldUpdate(wear, time), Before = zDO.GetFloat(ZDOVars.s_health, wear.m_health), Fields = new Dictionary { ["eligibility"] = text, ["environment_wet"] = EnvMan.IsWet(), ["cached_roof"] = _roof.Invoke(wear), ["shielded"] = flag2, ["underwater"] = _underWater(wear), ["native_health_fraction"] = wear.GetHealthPercentage(), ["removable"] = _canBeRemoved(wear), ["no_building_fall"] = ZoneSystem.instance.GetGlobalKey((GlobalKeys)37) } }; if (_diagnostics.VerboseAfterNormalEnabled) { Dictionary fields = wearObservation.Fields; fields["native_rain_wet"] = _rainWet.Invoke(wear); fields["processor"] = (view.IsOwner() ? "server" : ((zDO.GetOwner() == 0L) ? "none" : "client")); EnvMan instance = EnvMan.instance; fields["server_environment"] = ((instance == null) ? null : instance.GetCurrentEnvironment()?.m_name); GameObject val = default(GameObject); fields["fresh_roof"] = WearNTear.RoofCheck(((Component)wear).transform, ((Component)wear).transform.position, ref val, wear.m_roofCheckOffset); fields["cover_timer_s"] = _coverTimer.Invoke(wear); fields["warmup_remaining_s"] = Math.Max(0f, 30f - (time - _creationTime.Invoke(wear))); fields["maximum_health"] = wear.m_health; fields["native_rain_timer_start_game_s"] = _rainTimer.Invoke(wear); fields["game_time_s"] = time; } return wearObservation; } internal void EndWear(WearNTear wear, WearObservation? observation, Exception? error) { //IL_003f: Unknown result type (might be due to invalid IL or missing references) if (_diagnostics.DebugEnabled) { ZNetView component = ((Component)wear).GetComponent(); if (_diagnostics.DebugEnabled && (Object)(object)component != (Object)null && component.IsValid() && _rainEvidence.TryGetValue(component.GetZDO().m_uid, out RainEvidence value)) { UpdateRain(component.GetZDO(), wear, value); } if (observation != null) { ZNetView component2 = ((Component)wear).GetComponent(); float? after = (((Object)(object)component2 != (Object)null && component2.IsValid()) ? new float?(component2.GetZDO().GetFloat(ZDOVars.s_health, wear.m_health)) : ((float?)null)); _diagnostics.Wear(observation, after, error != null, error); } } } internal WearObservation? BeginCommand(WearNTear wear, string method) { //IL_001f: Unknown result type (might be due to invalid IL or missing references) ZNetView component = ((Component)wear).GetComponent(); if ((Object)(object)component == (Object)null || !component.IsValid() || !Protects(component.GetZDO().m_uid)) { return null; } _nativeCommands++; if (!_diagnostics.ReserveCommand(Time.unscaledTime)) { return null; } ZDO zDO = component.GetZDO(); return new WearObservation { Protected = true, Owner = component.IsOwner(), Identity = Identity(zDO), Fields = new Dictionary { ["command"] = method, ["processor"] = (component.IsOwner() ? "server" : "client") }, Before = zDO.GetFloat(ZDOVars.s_health, wear.m_health) }; } internal void EndCommand(WearNTear wear, WearObservation? observation, Exception? error) { //IL_003f: Unknown result type (might be due to invalid IL or missing references) if (_diagnostics.DebugEnabled) { ZNetView component = ((Component)wear).GetComponent(); if (_diagnostics.DebugEnabled && (Object)(object)component != (Object)null && component.IsValid() && _rainEvidence.TryGetValue(component.GetZDO().m_uid, out RainEvidence value)) { UpdateRain(component.GetZDO(), wear, value); } if (observation != null) { ZNetView component2 = ((Component)wear).GetComponent(); float? after = (((Object)(object)component2 != (Object)null && component2.IsValid()) ? new float?(component2.GetZDO().GetFloat(ZDOVars.s_health, wear.m_health)) : ((float?)null)); _diagnostics.Command(observation, after, error != null, error); } } } internal void SupportPass(WearNTear wear) { //IL_0027: Unknown result type (might be due to invalid IL or missing references) ZNetView component = ((Component)wear).GetComponent(); if ((Object)(object)component != (Object)null && component.IsValid() && component.IsOwner() && Protects(component.GetZDO().m_uid)) { _supportPasses++; } } private Dictionary Identity(ZDO zdo) { //IL_004f: Unknown result type (might be due to invalid IL or missing references) Dictionary obj = new Dictionary { ["object"] = ((object)Unsafe.As(ref zdo.m_uid)/*cast due to .constrained prefix*/).ToString() }; GameObject? obj2 = PrefabRegistry.Current.Prefab(zdo.GetPrefab()); obj["prefab"] = ((obj2 != null) ? ((Object)obj2).name : null); obj["pos"] = zdo.GetPosition(); return obj; } private Dictionary Fields(ZDO zdo, params (string Key, object? Value)[] values) { Dictionary dictionary = Identity(zdo); for (int i = 0; i < values.Length; i++) { (string, object) tuple = values[i]; dictionary[tuple.Item1] = tuple.Item2; } return dictionary; } private static string ObservedHealth(ZDO zdo) { float f = zdo.GetFloat(ZDOVars.s_health, float.NaN); if (!float.IsNaN(f)) { return f.ToString(CultureInfo.InvariantCulture); } return "unknown_or_nan"; } private static void Count(Dictionary counts, string reason) { counts.TryGetValue(reason, out var value); counts[reason] = value + 1; } private void TrackRain(ZDO zdo, WearNTear wear, string reason) { //IL_0022: 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_0050: 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_013a: Unknown result type (might be due to invalid IL or missing references) //IL_0164: Unknown result type (might be due to invalid IL or missing references) //IL_00b4: Unknown result type (might be due to invalid IL or missing references) //IL_00ba: Unknown result type (might be due to invalid IL or missing references) //IL_00cd: Unknown result type (might be due to invalid IL or missing references) if ((reason == "world-created" && !_diagnostics.LogWorldCreatedItems) || _rainEvidence.ContainsKey(zdo.m_uid) || (reason != "eligible" && reason != "world-created")) { return; } int num = 0; ZDOID key = ZDOID.None; foreach (KeyValuePair item in _rainEvidence) { if (item.Value.Eligibility == reason) { num++; key = item.Key; } } if (num >= 3) { if (reason != "eligible" || zdo.m_uid != _recentPlayerCandidate) { return; } _rainEvidence.Remove(key); } float num2 = zdo.GetFloat(ZDOVars.s_health, wear.m_health); RainEvidence rainEvidence = new RainEvidence { Identity = Identity(zdo), Eligibility = reason, Started = Time.unscaledTime, FirstHealth = num2, MaximumHealth = wear.m_health, Health = num2, MinimumHealth = num2, Owner = zdo.GetOwner(), Protected = Protects(zdo.m_uid), Creator = zdo.GetLong(ZDOVars.s_creator, 0L) }; _rainEvidence.Add(zdo.m_uid, rainEvidence); UpdateRain(zdo, wear, rainEvidence); } private void UpdateRain(ZDO zdo, WearNTear wear, RainEvidence history) { //IL_001a: Unknown result type (might be due to invalid IL or missing references) //IL_0157: Unknown result type (might be due to invalid IL or missing references) //IL_01cb: Unknown result type (might be due to invalid IL or missing references) history.ObserveState(zdo.GetFloat(ZDOVars.s_health, wear.m_health), zdo.GetOwner(), Protects(zdo.m_uid), zdo.GetLong(ZDOVars.s_creator, 0L)); history.ProtectionReason = (history.Protected ? "eligible" : ((history.Eligibility != "eligible") ? history.Eligibility : ((!TerrainReady(zdo, ZoneSystem.instance)) ? "waiting_terrain" : ((!ContextReady(zdo, ZNetScene.instance, ZoneSystem.instance)) ? "waiting_objects" : ((_protected.Count >= 8192) ? "capacity_limit" : "awaiting_acquisition"))))); int num = _shield.Invoke(wear); Dictionary obj = new Dictionary { ["native_rain_wet"] = _rainWet.Invoke(wear), ["processor"] = ((zdo.GetOwner() == ServerId) ? "server" : ((zdo.GetOwner() == 0L) ? "none" : "client")), ["cached_roof"] = _roof.Invoke(wear), ["cover_timer"] = _coverTimer.Invoke(wear), ["piece_biome"] = Biome(zdo.GetPosition()), ["environment_wet"] = EnvMan.IsWet() }; EnvMan instance = EnvMan.instance; obj["server_environment"] = ((instance == null) ? null : instance.GetCurrentEnvironment()?.m_name); obj["underwater"] = _underWater(wear); obj["shielded"] = ShieldGenerator.IsInsideShieldCached(((Component)wear).transform.position, ref num); obj["health_above_half"] = wear.GetHealthPercentage() > 0.5f; obj["removable"] = _canBeRemoved(wear); obj["no_building_fall"] = ZoneSystem.instance.GetGlobalKey((GlobalKeys)37); obj["warmup"] = !_shouldUpdate(wear, Time.time); obj["warmup_remaining_s"] = Math.Max(0f, 30f - (Time.time - _creationTime.Invoke(wear))); history.Fields = obj; if (history.LastGateTime >= 0f && Time.time - history.LastGateTime > 10f) { history.WetSeconds = 0f; history.LastGateTime = -1f; } } private void RefreshRainEvidence(ZNetScene scene) { //IL_004c: Unknown result type (might be due to invalid IL or missing references) //IL_00b0: Unknown result type (might be due to invalid IL or missing references) //IL_007c: 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_028c: Unknown result type (might be due to invalid IL or missing references) //IL_0291: Unknown result type (might be due to invalid IL or missing references) //IL_0299: Unknown result type (might be due to invalid IL or missing references) //IL_01a4: Unknown result type (might be due to invalid IL or missing references) //IL_035a: Unknown result type (might be due to invalid IL or missing references) //IL_0387: Unknown result type (might be due to invalid IL or missing references) if (!_diagnostics.DebugEnabled) { return; } List staleDebug = _staleDebug; staleDebug.Clear(); WearNTear wear = default(WearNTear); foreach (KeyValuePair pair in _rainEvidence) { ZDO zdo = _manager.GetZDO(pair.Key); if (zdo == null || !zdo.IsValid() || !_nearIds.Contains(pair.Key)) { _diagnostics.Record(Time.unscaledTime, "rain ended", () => (Message: "Rain tracking ended", Fields: new Dictionary { ["object"] = ((object)pair.Key/*cast due to .constrained prefix*/).ToString(), ["reason"] = ((zdo == null) ? "missing_world_record" : ((!zdo.IsValid()) ? "invalid_world_record" : "outside_retained_region")), ["last_health"] = pair.Value.Health, ["minimum_health"] = pair.Value.MinimumHealth })); staleDebug.Add(pair.Key); continue; } string currentEligibility = Eligibility(zdo, scene); if (currentEligibility != pair.Value.Eligibility) { _diagnostics.Record(Time.unscaledTime, "rain ended", () => (Message: "Rain tracking role changed", Fields: new Dictionary { ["object"] = ((object)pair.Key/*cast due to .constrained prefix*/).ToString(), ["previous_eligibility"] = pair.Value.Eligibility, ["eligibility"] = currentEligibility, ["last_health"] = pair.Value.Health, ["minimum_health"] = pair.Value.MinimumHealth })); staleDebug.Add(pair.Key); continue; } ZNetView val = scene.FindInstance(zdo); if ((Object)(object)val != (Object)null && ((Component)val).TryGetComponent(ref wear)) { UpdateRain(zdo, wear, pair.Value); continue; } pair.Value.ObserveState(zdo.GetFloat(ZDOVars.s_health, pair.Value.MaximumHealth), zdo.GetOwner(), Protects(zdo.m_uid), zdo.GetLong(ZDOVars.s_creator, 0L)); pair.Value.WetSeconds = 0f; pair.Value.LastGateTime = -1f; pair.Value.ProtectionReason = ((pair.Value.Eligibility == "eligible") ? "waiting_instance" : pair.Value.Eligibility); pair.Value.Fields = new Dictionary { ["server_instance"] = false, ["native_conditions"] = null }; } foreach (ZDOID item in staleDebug) { _rainEvidence.Remove(item); } int num = 0; WearNTear val4 = default(WearNTear); GameObject val5 = default(GameObject); for (int num2 = 0; num2 < _near.Count; num2++) { if (num >= 12) { break; } _rainProbeCursor %= _near.Count; ZDO val2 = _near[_rainProbeCursor++]; string text = Eligibility(val2, scene); if (text != "world-created" || !_diagnostics.LogWorldCreatedItems) { continue; } ZNetView val3 = scene.FindInstance(val2); if (!((Object)(object)val3 == (Object)null) && ((Component)val3).TryGetComponent(ref val4)) { num++; bool flag = WearNTear.RoofCheck(((Component)val4).transform, ((Component)val4).transform.position, ref val5, val4.m_roofCheckOffset); if (!flag) { TrackRain(val2, val4, text); } if (_rainEvidence.TryGetValue(val2.m_uid, out RainEvidence value)) { value.FreshRoof = flag; value.FreshRoofAt = Time.unscaledTime; } } } } private static string Biome(Vector3 position) { //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Unknown result type (might be due to invalid IL or missing references) if (WorldGenerator.instance != null) { return ((object)WorldGenerator.instance.GetBiome(position)/*cast due to .constrained prefix*/).ToString(); } return "unknown"; } private void RefreshExposure(ZNetScene scene, float now) { //IL_0039: Unknown result type (might be due to invalid IL or missing references) //IL_0063: Unknown result type (might be due to invalid IL or missing references) //IL_00a6: Unknown result type (might be due to invalid IL or missing references) //IL_0175: 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_01ad: 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_01ff: Unknown result type (might be due to invalid IL or missing references) HashSet managedExposure = _managedExposure; managedExposure.Clear(); _eligibleExposure.Clear(); foreach (ZDO eligiblePiece in _eligiblePieces) { ZNetView val = scene.FindInstance(eligiblePiece); if (Protects(eligiblePiece.m_uid) && (Object)(object)val != (Object)null && val.IsValid() && val.IsOwner()) { managedExposure.Add(eligiblePiece.m_uid); } } foreach (ZDO eligiblePiece2 in _eligiblePieces) { _eligibleExposure.Add(eligiblePiece2.m_uid); } _exposure.Retain(_eligibleExposure, managedExposure); int num = 0; WearNTear val4 = default(WearNTear); GameObject val5 = default(GameObject); for (int i = 0; i < _eligiblePieces.Count; i++) { if (num >= 12) { break; } _exposureProbeCursor %= _eligiblePieces.Count; ZDO val2 = _eligiblePieces[_exposureProbeCursor++]; ZNetView val3 = scene.FindInstance(val2); if (!((Object)(object)val3 == (Object)null) && val3.IsValid() && ContextReady(val2, scene, ZoneSystem.instance) && ((Component)val3).TryGetComponent(ref val4)) { num++; bool flag = WearNTear.RoofCheck(((Component)val4).transform, ((Component)val4).transform.position, ref val5, val4.m_roofCheckOffset); bool underwater = _underWater(val4); _exposure.Observe(val2.m_uid, flag, underwater, managedExposure.Contains(val2.m_uid), _roof.Invoke(val4), Biome(val2.GetPosition()), now); if (!flag && _diagnostics.DebugEnabled) { TrackRain(val2, val4, "eligible"); } if (_rainEvidence.TryGetValue(val2.m_uid, out RainEvidence value)) { value.FreshRoof = flag; value.FreshRoofAt = now; } } } } public void Tick(float now) { //IL_0351: Unknown result type (might be due to invalid IL or missing references) //IL_0150: Unknown result type (might be due to invalid IL or missing references) //IL_039e: Unknown result type (might be due to invalid IL or missing references) //IL_018e: Unknown result type (might be due to invalid IL or missing references) //IL_0193: Unknown result type (might be due to invalid IL or missing references) //IL_01b4: Unknown result type (might be due to invalid IL or missing references) //IL_01b6: Unknown result type (might be due to invalid IL or missing references) //IL_01bb: Unknown result type (might be due to invalid IL or missing references) //IL_01c3: Unknown result type (might be due to invalid IL or missing references) //IL_01a8: Unknown result type (might be due to invalid IL or missing references) //IL_03bf: Unknown result type (might be due to invalid IL or missing references) //IL_0429: Unknown result type (might be due to invalid IL or missing references) //IL_0209: Unknown result type (might be due to invalid IL or missing references) //IL_0210: Unknown result type (might be due to invalid IL or missing references) //IL_04ca: Unknown result type (might be due to invalid IL or missing references) //IL_04cf: Unknown result type (might be due to invalid IL or missing references) //IL_04d2: 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_0277: Unknown result type (might be due to invalid IL or missing references) //IL_0493: 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_056b: Unknown result type (might be due to invalid IL or missing references) //IL_0570: Unknown result type (might be due to invalid IL or missing references) //IL_0578: Unknown result type (might be due to invalid IL or missing references) //IL_061c: Unknown result type (might be due to invalid IL or missing references) //IL_0583: Unknown result type (might be due to invalid IL or missing references) //IL_02f0: Unknown result type (might be due to invalid IL or missing references) //IL_05b0: Unknown result type (might be due to invalid IL or missing references) //IL_05b5: Unknown result type (might be due to invalid IL or missing references) //IL_05bd: Unknown result type (might be due to invalid IL or missing references) //IL_06af: Unknown result type (might be due to invalid IL or missing references) //IL_069b: Unknown result type (might be due to invalid IL or missing references) //IL_0654: Unknown result type (might be due to invalid IL or missing references) //IL_0659: Unknown result type (might be due to invalid IL or missing references) //IL_07a2: Unknown result type (might be due to invalid IL or missing references) //IL_06ef: Unknown result type (might be due to invalid IL or missing references) //IL_0717: Unknown result type (might be due to invalid IL or missing references) //IL_071c: Unknown result type (might be due to invalid IL or missing references) //IL_087b: Unknown result type (might be due to invalid IL or missing references) //IL_08dd: Unknown result type (might be due to invalid IL or missing references) _diagnostics.PollPreventionRollup(); if (!ModuleScheduler.Current.Due(this, "processing", now, 1f)) { return; } _eligiblePieces.Clear(); _playerBiomes.Clear(); ZDOMan instance = ZDOMan.instance; ZNetScene instance2 = ZNetScene.instance; ZoneSystem instance3 = ZoneSystem.instance; if (!WorldServices.Terrain) { return; } _near.Clear(); _distant.Clear(); _nearIds.Clear(); _distantIds.Clear(); _regions.Clear(); _positions.Clear(); _readyContexts.Clear(); bool flag = false; _peers = (_readyPeers = (_characterWaits = 0)); _exclusions.Clear(); _releaseReasons.Clear(); for (int i = 0; i < _presence.Peers.Count; i++) { ZNetPeer val = _presence.Peers[i]; _peers++; if (!val.IsReady()) { continue; } _readyPeers++; if (((ZDOID)(ref val.m_characterID)).IsNone()) { _characterWaits++; continue; } ZDO zDO = instance.GetZDO(val.m_characterID); if (zDO == null || !zDO.IsValid() || zDO.GetOwner() != val.m_uid) { _characterWaits++; continue; } Vector3 position = zDO.GetPosition(); if (_diagnostics.StepsEnabled) { Count(_playerBiomes, Biome(position)); } Vector2s zone = ZoneSystem.GetZone(position); if (_regions.Contains(zone)) { continue; } if (_regions.Count >= 8) { flag = true; continue; } _scratch.Clear(); _farScratch.Clear(); WorldObjectProvider.Current.For("WeatherGuard").Query(zone, ZNet.instance.GetSyncedSimulationDistance(), _scratch, _farScratch); if (_near.Count + _distant.Count + _scratch.Count + _farScratch.Count > 32768) { flag = true; continue; } _regions.Add(zone); _positions.Add(position); foreach (ZDO item in _scratch) { if (_nearIds.Add(item.m_uid)) { _near.Add(item); } } foreach (ZDO item2 in _farScratch) { if (_distantIds.Add(item2.m_uid)) { _distant.Add(item2); } } } for (int num = _distant.Count - 1; num >= 0; num--) { if (_nearIds.Contains(_distant[num].m_uid)) { _distant.RemoveAt(num); } } _release.Clear(); foreach (KeyValuePair item3 in _protected) { ZDO zDO2 = instance.GetZDO(item3.Key); string text = ((zDO2 == null || !zDO2.IsValid()) ? "destroyed/invalid" : ((!_nearIds.Contains(item3.Key)) ? "outside retained region" : ((Eligibility(zDO2, instance2) != "eligible") ? Eligibility(zDO2, instance2) : ((!Ready(zDO2, instance2, instance3)) ? "context lost" : "")))); if (text != "") { _release.Add(item3.Key); Count(_releaseReasons, text); Count(_releaseTotals, text); } else if (zDO2.GetOwner() != ServerId) { _ownerLosses++; if (_diagnostics.OptionalEnabled) { RecordOwner(now, zDO2); } ObjectAuthority.Assign(zDO2, ServerId); instance.ForceSendZDO(zDO2.m_uid); } } foreach (ZDOID item4 in _release) { Release(item4); } _eligible = (_waiting = (_waitingTerrain = (_waitingObjects = (_waitingInstance = 0)))); if (_diagnostics.DebugEnabled) { _observedCandidates.IntersectWith(_nearIds); List staleDebug = _staleDebug; staleDebug.Clear(); foreach (ZDOID key in _candidateReasons.Keys) { if (!_nearIds.Contains(key)) { staleDebug.Add(key); } } foreach (ZDOID item5 in staleDebug) { _candidateReasons.Remove(item5); } } foreach (ZDO item6 in _near) { string text2 = Eligibility(item6, instance2); string value = null; bool flag2 = _diagnostics.DebugEnabled && (!_candidateReasons.TryGetValue(item6.m_uid, out value) || value != text2); if (flag2 && value != null) { if (text2 == "eligible") { _recentPlayerCandidate = item6.m_uid; } if (_diagnostics.OptionalEnabled) { RecordEligibility(now, item6, value, text2); } } if (_diagnostics.DebugEnabled && (text2 != "not a wear piece" || _candidateReasons.ContainsKey(item6.m_uid))) { _candidateReasons[item6.m_uid] = text2; } bool flag3 = false; if (_diagnostics.DebugEnabled && (text2 == "eligible" || text2 == "world-created") && _observedCandidates.Add(item6.m_uid)) { flag3 = true; if (_candidateScanStarted && text2 == "eligible") { _recentPlayerCandidate = item6.m_uid; } if (_diagnostics.OptionalEnabled) { RecordDiscovery(now, item6, text2); } } if (text2 != "eligible") { Count(_exclusions, text2); if (text2 != "not a wear piece" && flag2 && !flag3) { RecordExclusion(now, item6, text2); } continue; } _eligible++; _eligiblePieces.Add(item6); if (_protected.ContainsKey(item6.m_uid)) { continue; } if (_protected.Count >= 8192) { flag = true; continue; } bool flag4 = (Object)(object)instance2.FindInstance(item6) != (Object)null; bool flag5 = TerrainReady(item6, instance3); bool flag6 = flag5 && ContextReady(item6, instance2, instance3); if (!WeatherGuardRules.MayAcquire(flag4, flag5, flag6, withinCapacity: true)) { _waiting++; if (!flag5) { _waitingTerrain++; } if (!flag4) { _waitingInstance++; } if (flag5 && !flag6) { _waitingObjects++; } if (_diagnostics.OptionalEnabled) { RecordContext(now, item6, flag4, flag5, flag6, instance3, instance2); } } else { _protected.Add(item6.m_uid, item6); Piece component = ((Component)instance2.FindInstance(item6)).GetComponent(); _creator.Invoke(component) = item6.GetLong(ZDOVars.s_creator, 0L); _creatorIndex.Invoke(component) = item6.GetInt(ZDOVars.s_creatorIndex, -1); ObjectAuthority.Assign(item6, ServerId); instance.ForceSendZDO(item6.m_uid); _acquired++; } } if (_protected.Count > 0 && !_announced) { _announced = true; _diagnostics.InitialAcquisition(_protected.Count); } _diagnostics.CapacityState(flag); _candidateScanStarted |= _near.Count > 0; _lastScopeScan = now; _scopeLimited = flag; if (_diagnostics.StepsEnabled) { RefreshExposure(instance2, now); } RefreshRainEvidence(instance2); if (_diagnostics.SummaryReady(now)) { ReportStatus(now, flag); } } private void RecordOwner(float now, ZDO zdo) { _diagnostics.Record(now, "ownership", () => (Message: "Owner change observed; server ownership reasserted; cause unknown", Fields: Fields(zdo, ("observed_owner", zdo.GetOwner()), ("server_owner", ServerId)))); } private void RecordEligibility(float now, ZDO zdo, string previous, string reason) { _diagnostics.Record(now, "discovery", () => (Message: "Eligibility changed", Fields: Fields(zdo, ("previous_eligibility", previous), ("eligibility", reason)))); } private void RecordDiscovery(float now, ZDO zdo, string reason) { _diagnostics.Record(now, _candidateScanStarted ? "discovery" : "initial discovery", () => (Message: "Structural candidate first observed; creation time unknown", Fields: Fields(zdo, ("eligibility", reason), ("discovery", _candidateScanStarted ? "later_scan" : "initial_scan")))); } private void RecordExclusion(float now, ZDO zdo, string reason) { _diagnostics.Record(now, "eligibility", () => (Message: "Excluded from protection", Fields: Fields(zdo, ("reason", reason), ("stored_health", ObservedHealth(zdo))))); } private void RecordContext(float now, ZDO zdo, bool instanceReady, bool terrainReady, bool objectsReady, ZoneSystem zones, ZNetScene scene) { _diagnostics.Record(now, "context", delegate { Dictionary dictionary = Fields(zdo, ("instance_loaded", instanceReady), ("terrain_loaded", terrainReady), ("surrounding_objects_loaded", objectsReady), ("locations_generated", zones.LocationsGenerated)); if (_diagnostics.VerboseAfterNormalEnabled) { foreach (KeyValuePair item in ContextBlocker(zdo, scene, zones)) { dictionary[item.Key] = item.Value; } } return (Message: "Waiting for server context", Fields: dictionary); }); } private void ReportStatus(float now, bool limited) { if (!_diagnostics.SummaryReady(now)) { return; } _diagnostics.Report(now, () => new WeatherGuardStatus { RainProtection = _protectRain, UnderwaterProtection = _protectUnderwater, Protected = _protected.Count, Eligible = _eligible, Waiting = _waiting, WaitingTerrain = _waitingTerrain, WaitingInstance = _waitingInstance, WaitingObjects = _waitingObjects, Regions = _regions.Count, Nearby = _near.Count, Distant = _distant.Count, Acquired = _acquired, Released = _released, BlockedData = _blockedData, BlockedOwner = _blockedOwner, BlockedBroadcast = _blockedBroadcast, Commands = _commands, WearPasses = _wearPasses, Limited = limited, Peers = _peers, ReadyPeers = _readyPeers, CharacterWaits = _characterWaits, Exclusions = new Dictionary(_exclusions), ReleaseReasons = new Dictionary(_releaseReasons), ReleaseTotals = new Dictionary(_releaseTotals), OwnerLosses = _ownerLosses, WeatherGates = _weatherGates, WetOpportunities = _wetOpportunities, Decisions = new Dictionary(_decisions), WeatherSuppressed = _weatherSuppressedTotal, ConfirmedPreventions = _confirmedPreventions, NativeCommands = _nativeCommands, SupportPasses = _supportPasses }, () => _rainEvidence.Values, ProtectionStatus, delegate { Dictionary dictionary = _exposure.Counts(_eligible, now); dictionary["player_biomes"] = string.Join(",", _playerBiomes.Select, string>((KeyValuePair pair) => pair.Key + ":" + pair.Value)); EnvMan instance = EnvMan.instance; dictionary["server_environment"] = ((instance == null) ? null : instance.GetCurrentEnvironment()?.m_name); dictionary["server_environment_wet"] = EnvMan.IsWet(); dictionary["weather_immune_skipped"] = (_exclusions.TryGetValue("weather immune", out var value) ? value : 0); return dictionary; }); } internal CoverageSnapshot Coverage(float now) { //IL_0167: Unknown result type (might be due to invalid IL or missing references) CoverageSnapshot coverageSnapshot = new CoverageSnapshot { State = ((_regions.Count == 0) ? "no_ready_player_regions" : "ready"), Observed = (_lastScopeScan >= 0f && _regions.Count > 0), ScanAge = ((_lastScopeScan < 0f) ? ((float?)null) : new float?(Math.Max(0f, now - _lastScopeScan))), Regions = _regions.Count, NearbyRecords = _near.Count, DistantRecords = _distant.Count, Limited = _scopeLimited, RainEnabled = _protectRain, UnderwaterEnabled = _protectUnderwater }; if (!coverageSnapshot.Observed) { return coverageSnapshot; } using List.Enumerator enumerator = _near.GetEnumerator(); ZDO current; string text; ZNetView val; bool flag; int num; int num2; bool flag2; bool managed; string waitReason; for (; enumerator.MoveNext(); flag2 = (byte)num2 != 0, managed = flag && flag2 && Protects(current.m_uid) && val.IsOwner(), waitReason = ((num == 0) ? "waiting_terrain" : ((!flag2) ? "waiting_objects" : ((_protected.Count >= 8192) ? "capacity_limit" : "waiting_server_ownership"))), coverageSnapshot.Add(text, managed, flag, waitReason)) { current = enumerator.Current; text = Eligibility(current, ZNetScene.instance); val = ZNetScene.instance.FindInstance(current); flag = (Object)(object)val != (Object)null && val.IsValid(); if (text == "eligible") { num = (TerrainReady(current, ZoneSystem.instance) ? 1 : 0); if (num != 0) { num2 = (ContextReady(current, ZNetScene.instance, ZoneSystem.instance) ? 1 : 0); continue; } } else { num = 0; } num2 = 0; } return coverageSnapshot; } private IEnumerable ProtectionStatus() { foreach (ZDO item in _near) { string text = Eligibility(item, ZNetScene.instance); if (!(text != "eligible") || !(text != "world-created") || !(text != "excluded_prefab") || !(text != "weather_protection_disabled")) { bool flag = item.GetLong(ZDOVars.s_creator, 0L) == 0; if (!flag || _diagnostics.LogWorldCreatedItems) { bool flag2 = Protects(item.m_uid); string reason = ((text != "eligible") ? text : (flag2 ? "eligible" : (((Object)(object)ZNetScene.instance.FindInstance(item) == (Object)null) ? "waiting_instance" : ((!TerrainReady(item, ZoneSystem.instance)) ? "waiting_terrain" : ((!ContextReady(item, ZNetScene.instance, ZoneSystem.instance)) ? "waiting_objects" : ((_protected.Count >= 8192) ? "capacity_limit" : "awaiting_acquisition")))))); yield return new ProtectionObservation { Identity = Identity(item), Protected = flag2, RainProtection = _protectRain, UnderwaterProtection = _protectUnderwater, Reason = reason, Origin = (flag ? "world_created" : "player_built") }; } } } } private string Eligibility(ZDO zdo, ZNetScene scene) { //IL_00b6: Unknown result type (might be due to invalid IL or missing references) //IL_00bc: Invalid comparison between Unknown and I4 //IL_00bf: Unknown result type (might be due to invalid IL or missing references) //IL_00c5: Invalid comparison between Unknown and I4 //IL_00c8: Unknown result type (might be due to invalid IL or missing references) //IL_00ce: Invalid comparison between Unknown and I4 if (!zdo.IsValid()) { return "invalid world data"; } int prefab = zdo.GetPrefab(); if (!_eligibility.TryGetValue(prefab, out (string, bool, bool, bool, float, bool, bool) value)) { GameObject val = PrefabRegistry.Current.Prefab(prefab); if ((Object)(object)val == (Object)null) { return "missing prefab"; } Piece val2 = PrefabRegistry.Component(val); WearNTear val3 = PrefabRegistry.Component(val); value = (((Object)val).name, (Object)(object)val2 != (Object)null && (Object)(object)val3 != (Object)null, (Object)(object)val3 != (Object)null && val3.m_staticPosition, (Object)(object)val3 != (Object)null && val3.m_noRoofWear, ((Object)(object)val3 != (Object)null) ? val3.m_health : 0f, (Object)(object)val2 != (Object)null && ((int)val2.m_category == 2 || (int)val2.m_category == 3 || (int)val2.m_category == 5), (Object)(object)PrefabRegistry.Component(val) != (Object)null); if (_eligibility.Count < 4096) { _eligibility[prefab] = value; } } if (!value.Item2) { return "not a wear piece"; } return WeatherGuardRules.SelectionReason(WeatherGuardRules.Exclusion(zdo.GetLong(ZDOVars.s_creator, 0L), zdo.Persistent, value.Item3, value.Item4, zdo.GetFloat(ZDOVars.s_health, value.Item5), value.Item6, value.Item7), value.Item1, _excludedPrefabs, _protectRain, _protectUnderwater); } private Dictionary ContextBlocker(ZDO zdo, ZNetScene scene, ZoneSystem zones) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0067: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0086: Unknown result type (might be due to invalid IL or missing references) //IL_008a: Unknown result type (might be due to invalid IL or missing references) //IL_0058: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_0123: Unknown result type (might be due to invalid IL or missing references) //IL_01a8: 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) Vector2s sector = zdo.GetSector(); for (int i = sector.x - 1; i <= sector.x + 1; i++) { for (int j = sector.y - 1; j <= sector.y + 1; j++) { if (!zones.IsZoneLoaded(new Vector2s(i, j))) { return new Dictionary { ["missing_terrain_sector"] = $"{i},{j}" }; } } } List list = new List(); WorldObjectProvider.Current.For("WeatherGuard").Query(sector, new SimulationDistance(1, 0, false), list); foreach (ZDO item in list) { GameObject val = PrefabRegistry.Current.Prefab(item.GetPrefab()); if (val != null && RequiresContext(item, scene) && (Object)(object)scene.FindInstance(item) == (Object)null) { return new Dictionary { ["missing_object"] = ((object)Unsafe.As(ref item.m_uid)/*cast due to .constrained prefix*/).ToString(), ["missing_prefab"] = ((Object)val).name, ["missing_pos"] = item.GetPosition(), ["missing_persistent"] = item.Persistent, ["prefab_colliders"] = PrefabRegistry.Children(val, inactive: true).Length, ["prefab_rigidbodies"] = PrefabRegistry.Children(val, inactive: true).Length, ["prefab_wear_piece"] = (Object)(object)PrefabRegistry.Component(val) != (Object)null, ["retained_near"] = _nearIds.Contains(item.m_uid), ["retained_distant"] = _distantIds.Contains(item.m_uid) }; } } return new Dictionary { ["missing_dependency"] = "not_found_in_sample" }; } private static bool TerrainReady(ZDO zdo, ZoneSystem zones) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0007: 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_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Unknown result type (might be due to invalid IL or missing references) Vector2s sector = zdo.GetSector(); for (int i = sector.x - 1; i <= sector.x + 1; i++) { for (int j = sector.y - 1; j <= sector.y + 1; j++) { if (!zones.IsZoneLoaded(new Vector2s(i, j))) { return false; } } } return true; } private bool ContextReady(ZDO zdo, ZNetScene scene, ZoneSystem zones) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_00a5: 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_0042: Unknown result type (might be due to invalid IL or missing references) Vector2s sector = zdo.GetSector(); if (_readyContexts.TryGetValue(sector, out var value)) { return value; } value = TerrainReady(zdo, zones); if (value) { _contextObjects.Clear(); WorldObjectProvider.Current.For("WeatherGuard").Query(sector, new SimulationDistance(1, 0, false), _contextObjects); foreach (ZDO contextObject in _contextObjects) { if (RequiresContext(contextObject, scene) && (Object)(object)scene.FindInstance(contextObject) == (Object)null) { value = false; break; } } } _readyContexts.Add(sector, value); return value; } private bool RequiresContext(ZDO zdo, ZNetScene scene) { int prefab = zdo.GetPrefab(); if (_contextPrefabs.TryGetValue(prefab, out var value)) { return value; } GameObject val = PrefabRegistry.Current.Prefab(prefab); if ((Object)(object)val == (Object)null) { return false; } value = WeatherGuardRules.RequiresContext(PrefabRegistry.Children(val, inactive: true).Length, (Object)(object)PrefabRegistry.Component(val) != (Object)null, (Object)(object)PrefabRegistry.Component(val) != (Object)null); _contextPrefabs.Add(prefab, value); return value; } private bool Ready(ZDO zdo, ZNetScene scene, ZoneSystem zones) { if ((Object)(object)scene.FindInstance(zdo) != (Object)null) { return ContextReady(zdo, scene, zones); } return false; } internal void LoadTerrain() { //IL_0051: 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_0062: Unknown result type (might be due to invalid IL or missing references) if (!Running || (Object)(object)ZoneSystem.instance == (Object)null || !ZoneSystem.instance.LocationsGenerated) { return; } float unscaledTime = Time.unscaledTime; if (!ModuleScheduler.Current.Due(this, "terrain", unscaledTime, 0.1f)) { return; } foreach (Vector3 position in _positions) { _createZones(ZoneSystem.instance, position); } } internal void AddInstances(List near, List distant) { //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_0060: Unknown result type (might be due to invalid IL or missing references) //IL_00a7: Unknown result type (might be due to invalid IL or missing references) //IL_00f7: Unknown result type (might be due to invalid IL or missing references) if (!Running) { return; } HashSet instanceSeen = _instanceSeen; instanceSeen.Clear(); foreach (ZDO item in near) { instanceSeen.Add(item.m_uid); } foreach (ZDO item2 in distant) { instanceSeen.Add(item2.m_uid); } foreach (ZDO item3 in _near) { if (item3.IsValid() && instanceSeen.Add(item3.m_uid)) { near.Add(item3); } } foreach (ZDO item4 in _distant) { if (item4.IsValid() && instanceSeen.Add(item4.m_uid)) { distant.Add(item4); } } WorldObjectProvider.Current.IncludeLiveInstances(near, distant, _positions); } private void Release(ZDOID id) { //IL_0006: 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_004a: Unknown result type (might be due to invalid IL or missing references) if (_protected.TryGetValue(id, out ZDO value)) { _protected.Remove(id); if (value.IsValid() && value.GetOwner() == ServerId) { ObjectAuthority.Assign(value, 0L); } if (value.IsValid()) { _manager.ForceSendZDO(id); } _released++; } } public void Dispose() { //IL_00ab: Unknown result type (might be due to invalid IL or missing references) _diagnostics.Dispose(); if (Active == this) { Active = null; } bool flag = true; try { flag = ModuleCleanup.Run(_log, _module.Name, _patches.Dispose); } finally { try { Exception ex = null; int num = 0; foreach (ZDO value in _protected.Values) { try { if (value.IsValid() && _manager == ZDOMan.instance && value.GetOwner() == ServerId) { ObjectAuthority.Assign(value, 0L); _manager.ForceSendZDO(value.m_uid); } } catch (Exception ex2) { flag = false; if (ex == null) { ex = ex2; } num++; } } if (ex != null) { DiagnosticLog.Write(_log, _module.Name, CoreLogTopics.Lifecycle, "Ownership release failed for some pieces; remaining releases attempted.", new(string, object)[1] { ("release_failures", num) }, (LogLevel)2, verbose: false, ex); } } finally { _protected.Clear(); _positions.Clear(); _near.Clear(); _distant.Clear(); _rainEvidence.Clear(); _observedCandidates.Clear(); _contextPrefabs.Clear(); _candidateReasons.Clear(); } } if (!flag) { throw new InvalidOperationException("Controller cleanup did not complete; paused state cannot be confirmed."); } } } public sealed class WeatherGuardCoverageRequests { public const string FileName = "heimkit-weatherguard-coverage.request"; private readonly string _path; private readonly ManualLogSource _logger; private readonly ScheduleToken _nextPoll = new ScheduleToken(); private bool _warned; public WeatherGuardCoverageRequests(string configDirectory, ManualLogSource logger) { _path = Path.Combine(configDirectory, "heimkit-weatherguard-coverage.request"); _logger = logger; } public void Poll(float now, Action report) { if (!_nextPoll.Ready(now)) { return; } _nextPoll.Postpone(now, 1f); try { if (!File.Exists(_path)) { return; } File.Delete(_path); _warned = false; } catch (Exception ex) when (ex is IOException || ex is UnauthorizedAccessException) { if (!_warned) { _warned = true; DiagnosticLog.Write(_logger, "WeatherGuard", "Could not consume coverage request; correct file access to retry", (LogLevel)4); } return; } try { report(); } catch (Exception error) { DiagnosticLog.Write(_logger, "WeatherGuard", CoreLogTopics.Lifecycle, "Coverage request consumed but report failed; processing state unchanged", default(LogFields), (LogLevel)2, verbose: false, error); } } } internal sealed class WeatherGuardDebugLogLevelValues : AcceptableValueBase { public WeatherGuardDebugLogLevelValues() : base(typeof(DebugLogLevel)) { } public override bool IsValid(object value) { if (value is DebugLogLevel debugLogLevel) { if (debugLogLevel != DebugLogLevel.Medium) { return debugLogLevel == DebugLogLevel.Detailed; } return true; } return false; } public override object Clamp(object value) { if (!((AcceptableValueBase)this).IsValid(value)) { return DebugLogLevel.Detailed; } return value; } public override string ToDescriptionString() { return "# Acceptable values: Medium, Detailed"; } } public sealed class WeatherGuardDiagnostics : FeatureDiagnostics, IDisposable { private readonly ManualLogSource _logger; private readonly HashSet _prevented = new HashSet(); private DateTime _windowStart = DiagnosticLog.WallClock(); private long _preventionCount; private ZDOID _singlePiece; private string? _singlePrefab; private readonly Func _debugEnabled; private readonly DebugLogLevel _level; private readonly HashSet _wearPhases = new HashSet(); public const int MediumSampleLimit = 12; private readonly Dictionary Ids)> _wearStreams = new Dictionary)>(); private WeatherGuardStatus? _previous; private readonly Dictionary _reported = new Dictionary(); private float _lastSummary; private bool _capacityLimited; public const int SampleLimit = 6; public const int WearSampleLimit = 3; internal bool LogWorldCreatedItems { get; } private bool Enabled => base.DiagnosticsEnabled; internal bool StepsEnabled => Enabled; internal bool DebugEnabled { get { if (Enabled) { return _level == DebugLogLevel.Detailed; } return false; } } private (float Health, float Lost, long Bypasses, long Gates) Previous(RainEvidence watch) { if (!_reported.TryGetValue(watch, out (float, float, long, long) value)) { return (Health: watch.FirstHealth, Lost: 0f, Bypasses: 0L, Gates: 0L); } return value; } public WeatherGuardDiagnostics(ManualLogSource logger, bool debug, DebugLogLevel level = DebugLogLevel.Detailed, bool logWorldCreated = true) : this(logger, () => debug, level, logWorldCreated) { } public WeatherGuardDiagnostics(ManualLogSource logger, DebugLoggingPolicy policy, DebugLogLevel level, bool logWorldCreated) : this(logger, () => policy.Enabled, level, logWorldCreated) { } private WeatherGuardDiagnostics(ManualLogSource logger, Func debugEnabled, DebugLogLevel level, bool logWorldCreated) { _logger = logger; _debugEnabled = debugEnabled; ConfigureDiagnostics(debugEnabled, logger, "WeatherGuard"); _level = level; LogWorldCreatedItems = logWorldCreated; } private void Write(LogTopic topic, string result, Dictionary fields, LogLevel level = (LogLevel)32, Exception? error = null) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0004: Invalid comparison between Unknown and I4 //IL_0034: Unknown result type (might be due to invalid IL or missing references) if ((int)level != 32 || base.DiagnosticsEnabled) { LogFields logFields = fields; int num = ((error == null) ? 8 : 5); DiagnosticLog.Write(_logger, "WeatherGuard", topic, result, logFields.Take(num), level, verbose: false, error); if (base.VerboseEnabled && fields.Count > num) { DiagnosticLog.Write(_logger, "WeatherGuard", topic, Subject(fields, "Additional evidence"), logFields.Skip(num), (LogLevel)32, verbose: true); } } } private static string Subject(Dictionary fields, string evidence) { object value; object obj = (fields.TryGetValue("object", out value) ? value : null); object obj2 = (fields.TryGetValue("prefab", out value) ? value : null); if (obj != null) { if (obj2 != null) { return $"{evidence} for {obj2} (piece {obj})."; } return $"{evidence} for piece {obj}."; } return evidence + " for the preceding record."; } public static void StartupSettings(ManualLogSource logger, WeatherGuardSettings settings) { if (settings.DebugLogging.Enabled && settings.DebugLogLevel.Value == DebugLogLevel.Detailed) { if (DiagnosticLog.DebugAvailable(logger, "WeatherGuard")) { DiagnosticLog.Write(logger, "WeatherGuard", CoreLogTopics.Config, "Loaded settings and processing limits.", new LogField[8] { DiagnosticLog.FieldAlways("rain_protection_enabled", settings.ProtectRain.Value), DiagnosticLog.FieldAlways("underwater_protection_enabled", settings.ProtectUnderwater.Value), (Key: "excluded_prefabs", Value: settings.ExcludedPrefabs.Value), (Key: "debug_log_level", Value: settings.DebugLogLevel.Value), DiagnosticLog.FieldAlways("log_world_created_items", settings.LogWorldCreatedItems.Value), (Key: "maximum_regions", Value: 8), (Key: "maximum_objects", Value: 32768), (Key: "maximum_protected", Value: 8192) }, (LogLevel)32); } if (DiagnosticLog.VerboseConfigured && DiagnosticLog.DebugAvailable(logger, "WeatherGuard", verbose: true)) { DiagnosticLog.Write(logger, "WeatherGuard", CoreLogTopics.Config, "Additional evidence for the loaded settings and processing limits.", new(string, object)[6] { ("roof_check_max_age_s", 30), ("roof_probe_limit_per_scan", 12), ("native_wet_timer_threshold_game_s", 60), ("native_weather_damage_percent", 5), ("scope", "eligible_player_built_pieces_in_retained_regions"), ("wetness_source", "server_environment_not_player_local_weather") }, (LogLevel)32, verbose: true); } } } public void CapacityState(bool limited) { if (limited != _capacityLimited) { _capacityLimited = limited; DiagnosticLog.Write(_logger, "WeatherGuard", limited ? "Processing capacity reached. Unmanaged pieces retain vanilla processing; see debug status." : "Processing capacity limit cleared.", (LogLevel)(limited ? 4 : 16)); } } public void WeatherDamageSuppressed(ZDOID id, string? prefab = null) { //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_0049: Unknown result type (might be due to invalid IL or missing references) //IL_004a: Unknown result type (might be due to invalid IL or missing references) PollPreventionRollup(); if (!_prevented.Contains(id)) { if (_prevented.Count < 8192) { _prevented.Add(id); } if (_preventionCount++ == 0L) { _singlePiece = id; _singlePrefab = prefab; } } } public void PollPreventionRollup() { DateTime dateTime = DiagnosticLog.WallClock(); if (dateTime < _windowStart) { FlushPreventions(); _windowStart = dateTime; } else if (!(dateTime - _windowStart < TimeSpan.FromMinutes(10.0))) { FlushPreventions(partial: false); long num = (dateTime - _windowStart).Ticks / TimeSpan.FromMinutes(10.0).Ticks; _windowStart = _windowStart.AddTicks(num * TimeSpan.FromMinutes(10.0).Ticks); } } public unsafe void FlushPreventions(bool partial = true) { //IL_00e6: Unknown result type (might be due to invalid IL or missing references) //IL_00eb: Unknown result type (might be due to invalid IL or missing references) //IL_0050: Unknown result type (might be due to invalid IL or missing references) //IL_0055: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Unknown result type (might be due to invalid IL or missing references) if (_preventionCount > 0) { string text; if (_preventionCount == 1) { if (string.IsNullOrEmpty(_singlePrefab)) { ZDOID singlePiece = _singlePiece; text = "piece " + ((object)(*(ZDOID*)(&singlePiece))/*cast due to .constrained prefix*/).ToString(); } else { string? singlePrefab = _singlePrefab; ZDOID singlePiece = _singlePiece; text = singlePrefab + " (piece " + ((object)(*(ZDOID*)(&singlePiece))/*cast due to .constrained prefix*/).ToString() + ")"; } } else { text = _preventionCount + " pieces"; } string text2 = text; string text3 = (partial ? (" since " + _windowStart.ToString("HH:mm", CultureInfo.InvariantCulture)) : " in the last 10 minutes"); DiagnosticLog.Write(_logger, "WeatherGuard", "Prevented weather damage to " + text2 + text3 + ".", (LogLevel)16); } _preventionCount = 0L; _prevented.Clear(); _singlePiece = ZDOID.None; _singlePrefab = null; } public void InitialAcquisition(int protectedCount) { if (Enabled) { Write(WeatherGuardLogTopics.Protection, "Acquired initial protection for eligible pieces.", new Dictionary { ["protected"] = protectedCount }, (LogLevel)32); } } private static string Counts(Dictionary counts) { return string.Join(",", from p in counts orderby p.Key select $"{p.Key}:{p.Value}"); } private static string ReleaseChanges(Dictionary current, Dictionary previous) { Dictionary dictionary = new Dictionary(); foreach (KeyValuePair item in current) { previous.TryGetValue(item.Key, out var value); int num = Math.Max(0, item.Value - value); if (num > 0) { dictionary[item.Key] = num; } } return Counts(dictionary); } private static long Delta(long current, long previous) { return Math.Max(0L, current - previous); } public void Report(float now, Func snapshot, Func>? rain = null, Func>? protection = null, Func>? exposure = null) { if (!Enabled || !_budget.Reserve(now, "summary", 1, countOmitted: false)) { return; } WeatherGuardStatus weatherGuardStatus = snapshot(); WeatherGuardStatus weatherGuardStatus2 = _previous ?? new WeatherGuardStatus(); Dictionary fields = new Dictionary { ["eligible"] = weatherGuardStatus.Eligible, ["managed"] = weatherGuardStatus.Protected, ["waiting"] = weatherGuardStatus.Waiting, ["wear_calls"] = Delta(weatherGuardStatus.WearPasses, weatherGuardStatus2.WearPasses), ["native_weather_due"] = Delta(weatherGuardStatus.WeatherGates, weatherGuardStatus2.WeatherGates), ["weather_contributions_removed"] = Delta(weatherGuardStatus.WeatherSuppressed, weatherGuardStatus2.WeatherSuppressed), ["confirmed_preventions"] = Delta(weatherGuardStatus.ConfirmedPreventions, weatherGuardStatus2.ConfirmedPreventions) }; Write(CoreLogTopics.Scope, "Observed the protection path in the last minute.", fields, (LogLevel)32); if (base.VerboseEnabled) { Dictionary dictionary = new Dictionary(); foreach (KeyValuePair decision in weatherGuardStatus.Decisions) { weatherGuardStatus2.Decisions.TryGetValue(decision.Key, out var value); dictionary[decision.Key] = Delta(decision.Value, value); } if (exposure != null) { foreach (KeyValuePair item in exposure()) { dictionary[item.Key] = item.Value; } } if (_level == DebugLogLevel.Detailed) { dictionary["waiting_terrain"] = weatherGuardStatus.WaitingTerrain; dictionary["waiting_instance"] = weatherGuardStatus.WaitingInstance; dictionary["waiting_objects"] = weatherGuardStatus.WaitingObjects; dictionary["ready_players"] = weatherGuardStatus.ReadyPeers; dictionary["waiting_character"] = weatherGuardStatus.CharacterWaits; dictionary["exclusions"] = Counts(weatherGuardStatus.Exclusions); dictionary["capacity_limited"] = weatherGuardStatus.Limited; dictionary["omitted_messages"] = _budget.TakeOmitted(); } DiagnosticLog.Write(_logger, "WeatherGuard", CoreLogTopics.Scope, "Observed supporting protection evidence in the last minute.", dictionary, (LogLevel)32, verbose: true); } if (_level == DebugLogLevel.Medium) { _previous = weatherGuardStatus; _lastSummary = now; return; } RainEvidence[] array = rain?.Invoke().Take(6).ToArray() ?? Array.Empty(); if (Enabled) { Write(WeatherGuardLogTopics.Protection, "Observed protection and network activity in the last minute.", new Dictionary { ["acquired"] = Delta(weatherGuardStatus.Acquired, weatherGuardStatus2.Acquired), ["released"] = Delta(weatherGuardStatus.Released, weatherGuardStatus2.Released), ["release_reasons"] = ReleaseChanges(weatherGuardStatus.ReleaseTotals, weatherGuardStatus2.ReleaseTotals), ["support_passes"] = Delta(weatherGuardStatus.SupportPasses, weatherGuardStatus2.SupportPasses), ["native_commands"] = Delta(weatherGuardStatus.NativeCommands, weatherGuardStatus2.NativeCommands), ["blocked_client_records"] = Delta(weatherGuardStatus.BlockedData, weatherGuardStatus2.BlockedData), ["prevented_transfers"] = Delta(weatherGuardStatus.BlockedOwner, weatherGuardStatus2.BlockedOwner), ["owner_losses"] = Delta(weatherGuardStatus.OwnerLosses, weatherGuardStatus2.OwnerLosses) }, (LogLevel)32); } if (base.VerboseEnabled) { DiagnosticLog.Write(_logger, "WeatherGuard", WeatherGuardLogTopics.Ownership, "Observed supporting ownership and network evidence in the last minute.", new(string, object)[10] { ("interval_s", (_previous == null) ? 0f : Math.Max(0f, now - _lastSummary)), ("blocked_broadcasts", Delta(weatherGuardStatus.BlockedBroadcast, weatherGuardStatus2.BlockedBroadcast)), ("routed_commands", Delta(weatherGuardStatus.Commands, weatherGuardStatus2.Commands)), ("lifetime_release_reasons", Counts(weatherGuardStatus.ReleaseTotals)), ("lifetime_acquired", weatherGuardStatus.Acquired), ("lifetime_released", weatherGuardStatus.Released), ("lifetime_native_weather_due", weatherGuardStatus.WeatherGates), ("regions", weatherGuardStatus.Regions), ("nearby_records", weatherGuardStatus.Nearby), ("distant_records", weatherGuardStatus.Distant) }, (LogLevel)32, verbose: true); } RainEvidence[] array2 = array; foreach (RainEvidence watch in array2) { Rain(now, watch); } _reported.Clear(); array2 = array; foreach (RainEvidence rainEvidence in array2) { _reported[rainEvidence] = (rainEvidence.Health, rainEvidence.HealthLost, rainEvidence.WeatherBypasses, rainEvidence.Gates); } _previous = weatherGuardStatus; _lastSummary = now; } private static bool Flag(Dictionary fields, string key) { bool flag = default(bool); int num; if (fields.TryGetValue(key, out object value)) { if (value is bool) { flag = (bool)value; num = 1; } else { num = 0; } } else { num = 0; } return (byte)((uint)num & (flag ? 1u : 0u)) != 0; } private static string Blockers(Dictionary fields, bool owner, bool warmup) { List list = new List(); if (!owner) { list.Add("not_server_processed"); } if (warmup) { list.Add("warmup"); } if (!fields.ContainsKey("environment_wet")) { list.Add("conditions_unknown"); } else if (!Flag(fields, "environment_wet") && !Flag(fields, "underwater")) { list.Add("server_environment_dry"); } if (Flag(fields, "cached_roof") && !Flag(fields, "underwater")) { list.Add((Flag(fields, "roof_cache_disagrees") || (fields.TryGetValue("fresh_roof", out object value) && value is bool && !(bool)value)) ? "native_roof_cache_disagrees_with_geometry" : "covered"); } if (Flag(fields, "shielded")) { list.Add("shielded"); } if (fields.ContainsKey("health_above_half") && !Flag(fields, "health_above_half")) { list.Add("health_at_or_below_half"); } if (fields.TryGetValue("native_health_fraction", out object value2) && value2 is float num && num <= 0.5f) { list.Add("health_at_or_below_half"); } if (fields.ContainsKey("removable") && !Flag(fields, "removable")) { list.Add("not_removable"); } if (Flag(fields, "no_building_fall")) { list.Add("no_building_fall"); } if (list.Count != 0) { return string.Join(",", list); } return "none"; } private void Rain(float now, RainEvidence watch) { (float, float, long, long) tuple = Previous(watch); if (!(watch.HealthLost <= tuple.Item2) && Enabled) { Dictionary fields = new Dictionary(watch.Identity) { ["managed"] = watch.Protected, ["health_before"] = tuple.Item1, ["health_after"] = DiagnosticLog.Kept(watch.Health), ["health_lost"] = watch.HealthLost - tuple.Item2, ["weather_cause"] = "unconfirmed" }; Write(WeatherGuardLogTopics.Rain, "Observed health loss since the previous sample; weather cause is unconfirmed.", fields, (LogLevel)32); if (base.VerboseEnabled) { DiagnosticLog.Write(_logger, "WeatherGuard", WeatherGuardLogTopics.Rain, Subject(watch.Identity, "Rain and health evidence since the previous sample"), new(string, object)[6] { ("eligibility", watch.Eligibility), ("health_minimum", watch.MinimumHealth), ("weather_contributions_due", Delta(watch.Gates, tuple.Item4)), ("weather_contributions_removed", Delta(watch.WeatherBypasses, tuple.Item3)), ("lifetime_owner_changes_observed", watch.OwnerChanges), ("lifetime_management_changes_observed", watch.ProtectionChanges) }, (LogLevel)32, verbose: true); } } } public void Sample(float now, Func describe) { Sample(now, "acquisition", describe); } public void Sample(float now, string stream, Func describe) { if (DebugEnabled) { SampleEnabled(now, stream, describe); } } private void SampleEnabled(float now, string stream, Func describe) { Record(now, stream, () => (Message: describe(), Fields: new Dictionary())); } public void Record(float now, string stream, Func<(string Message, Dictionary Fields)> describe) { if (!DebugEnabled) { return; } string stream2 = ((stream == "acquisition" || stream == "ownership") ? "protection_samples" : ((stream.Contains("discovery") || stream == "eligibility" || stream == "rain ended") ? "discovery_samples" : "evidence_samples")); LogTopic topic = ((stream == "ownership") ? WeatherGuardLogTopics.Ownership : (stream.StartsWith("rain", StringComparison.Ordinal) ? WeatherGuardLogTopics.Rain : WeatherGuardLogTopics.Protection)); if (_budget.Reserve(now, stream2, 6)) { (string, Dictionary) tuple = describe(); Dictionary item = tuple.Item2; object value; object value2; object obj = (item.TryGetValue("eligibility", out value) ? value : (item.TryGetValue("reason", out value2) ? value2 : null)); if ((!stream.Contains("discovery") && !(stream == "eligibility")) || obj == null || object.Equals(obj, "eligible") || (LogWorldCreatedItems && object.Equals(obj, "world-created"))) { Write(topic, tuple.Item1, item, (LogLevel)32); } } } public bool ReserveCommand(float now) { if (DebugEnabled) { return _budget.Reserve(now, "native_commands", 6); } return false; } public void Command(WearObservation observation, float? after, bool failed, Exception? error = null) { if (DebugEnabled || failed) { object value; string text = (observation.Fields.TryGetValue("command", out value) ? ((value as string) ?? "") : ""); string text2 = text switch { "RPC_Remove" => "removal handler", "RPC_Repair" => "repair handler", "RPC_Damage" => "damage handler", _ => "receiver", }; Dictionary fields = new Dictionary(observation.Identity) { ["command"] = text, ["health_before"] = DiagnosticLog.Kept(observation.Before), ["health_after"] = (after.HasValue ? DiagnosticLog.Kept(after.Value) : "unavailable"), ["protection"] = (observation.Protected ? "active" : "unknown"), ["weather_damage"] = "unconfirmed", ["object_available_after"] = after.HasValue }; Write(WeatherGuardLogTopics.Wear, failed ? ("Native " + text2 + " raised an exception.") : ("Native " + text2 + " ran on a protected piece; its health outcome was observed."), fields, (LogLevel)(failed ? 2 : 32), error); if (base.VerboseEnabled) { Dictionary dictionary = new Dictionary(observation.Fields) { ["action"] = (failed ? "native_command_failed" : "native_command_executed"), ["health_change"] = ((!after.HasValue) ? "unavailable" : ((after.Value < observation.Before) ? "loss_observed" : ((after.Value > observation.Before) ? "increase_observed" : "unchanged"))), ["damage_context"] = "native_command" }; dictionary.Remove("command"); DiagnosticLog.Write(_logger, "WeatherGuard", WeatherGuardLogTopics.Wear, Subject(observation.Identity, "Native command evidence"), dictionary, (LogLevel)32, verbose: true); } } } public bool TryWearSample(float now, string id, bool protectedPiece, bool exposed = false) { if (!DebugEnabled) { return false; } string key = $"{protectedPiece}:{exposed}"; if (!_wearStreams.TryGetValue(key, out (float, HashSet) value) || now < value.Item1 || now - value.Item1 >= 60f) { value = (now, new HashSet()); } if (value.Item2.Count >= 3 || !value.Item2.Add(id)) { return false; } _wearStreams[key] = value; return _budget.Reserve(now, "evidence_samples", 6); } public void Wear(WearObservation observation, float? after, bool failed, Exception? error = null) { if (!DebugEnabled && !failed) { return; } string text = Blockers(observation.Fields, observation.Owner, observation.Warmup); string item = text + ":" + observation.GateReached + ":" + observation.Suppressed; bool flag = after.HasValue && after.Value < observation.Before; if (failed || flag || _wearPhases.Add(item)) { observation.Fields.TryGetValue("eligibility", out object value); Dictionary fields = new Dictionary(observation.Identity) { ["blockers"] = text, ["protection"] = (observation.Protected ? "active" : (object.Equals(value, "eligible") ? "waiting" : "excluded")), ["health_before"] = DiagnosticLog.Kept(observation.Before), ["health_after"] = (after.HasValue ? DiagnosticLog.Kept(after.Value) : null), ["weather_damage"] = "unconfirmed" }; string result = (failed ? "Native wear calculation failed." : ((!observation.Owner) ? "Wear calculation remained with another owner or was unassigned." : (observation.Warmup ? "Native wear calculation waited for loading warmup." : ((!observation.GateReached) ? "Native weather contribution was not due." : (observation.Suppressed ? "Removed a due native weather contribution; its health outcome was observed." : "Allowed a due native weather contribution; its health outcome was observed."))))); Write(WeatherGuardLogTopics.Wear, result, fields, (LogLevel)(failed ? 2 : 32), error); if (base.VerboseEnabled) { Dictionary dictionary = new Dictionary(observation.Fields) { ["condition_source"] = "server_instance", ["protection_reason"] = (observation.Protected ? "eligible" : (object.Equals(value, "eligible") ? "not_acquired" : value)), ["action"] = (observation.Suppressed ? "weather_contribution_suppressed" : ((!observation.Owner) ? "left_to_native_owner" : ((!observation.GateReached) ? "weather_contribution_not_due" : "native_weather_contribution_allowed"))), ["health_change"] = ((!after.HasValue) ? "unavailable" : ((after.Value < observation.Before) ? "loss_observed" : ((after.Value > observation.Before) ? "increase_observed" : "unchanged"))), ["damage_source"] = "unobserved", ["managed"] = observation.Protected, ["warmup"] = observation.Warmup, ["native_weather_contribution_due"] = observation.GateReached, ["weather_contribution_suppressed"] = observation.Suppressed }; DiagnosticLog.Write(_logger, "WeatherGuard", WeatherGuardLogTopics.Wear, Subject(observation.Identity, "Native wear evidence"), dictionary, (LogLevel)32, verbose: true); } } } public void Coverage(CoverageSnapshot s) { string text = (s.Observed ? ($"Eligible {s.Eligible}, protected {s.Protected}, waiting {s.Waiting}, skipped {s.Skipped}, unloaded eligible {s.UnloadedEligible}. " + "Skip reasons: " + Counts(s.SkipReasons) + ". Wait reasons: " + Counts(s.WaitReasons) + ". ") : "Eligible, protected, waiting and skipped counts are unknown. "); DiagnosticLog.Write(_logger, "WeatherGuard", "Requested coverage report (" + s.State + "): " + text + $"Scope: retained nearby ready-player regions; observed {s.Observed}; scan age {DiagnosticLog.Value(s.ScanAge)} seconds; " + $"regions {s.Regions}, nearby records {s.NearbyRecords}, distant records unevaluated {s.DistantRecords}; capacity limited {s.Limited}. " + $"Rain protection {s.RainEnabled}; underwater protection {s.UnderwaterEnabled}. " + "The rest of the world is unobserved; weather-damage prevention is not verified.", (LogLevel)16); } public void Dispose() { Reset(); } public void Reset() { FlushPreventions(); _windowStart = DiagnosticLog.WallClock(); _capacityLimited = false; _budget.Reset(); _wearStreams.Clear(); _previous = null; _reported.Clear(); _wearPhases.Clear(); _lastSummary = 0f; } } public sealed class WeatherGuardExposureTracking { public const int MaximumObservationAgeSeconds = 30; public const int ProbeLimitPerScan = 12; private readonly Dictionary _observed = new Dictionary(); private readonly List _remove = new List(); public void Retain(HashSet eligible, HashSet managed) { //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_005c: Unknown result type (might be due to invalid IL or missing references) //IL_0061: Unknown result type (might be due to invalid IL or missing references) //IL_0063: Unknown result type (might be due to invalid IL or missing references) //IL_0080: Unknown result type (might be due to invalid IL or missing references) //IL_008b: Unknown result type (might be due to invalid IL or missing references) //IL_009c: 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) _remove.Clear(); foreach (KeyValuePair item in _observed) { _remove.Add(item.Key); } foreach (ZDOID item2 in _remove) { if (!eligible.Contains(item2)) { _observed.Remove(item2); continue; } (bool, bool, bool, bool, string, float) value = _observed[item2]; value.Item3 = managed.Contains(item2); _observed[item2] = value; } } public void Observe(ZDOID id, bool roof, bool underwater, bool managed, bool cachedRoof, string biome, float now) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) _observed[id] = (roof, underwater, managed, cachedRoof, biome, now); } public Dictionary Counts(int eligible, float now) { (bool, bool, bool, bool, string, float)[] array = _observed.Values.Where<(bool, bool, bool, bool, string, float)>(((bool Roof, bool Water, bool Managed, bool CachedRoof, string Biome, float At) item) => now >= item.At && now - item.At <= 30f).ToArray(); return new Dictionary { ["roof_sample_size"] = array.Length, ["roof_unchecked_or_stale"] = Math.Max(0, eligible - array.Length), ["roof_sample_covered"] = array.Count(((bool Roof, bool Water, bool Managed, bool CachedRoof, string Biome, float At) item) => item.Roof), ["roof_sample_exposed"] = array.Count(((bool Roof, bool Water, bool Managed, bool CachedRoof, string Biome, float At) item) => !item.Roof), ["roof_sample_exposed_managed"] = array.Count(((bool Roof, bool Water, bool Managed, bool CachedRoof, string Biome, float At) item) => !item.Roof && item.Managed), ["roof_sample_exposed_waiting"] = array.Count(((bool Roof, bool Water, bool Managed, bool CachedRoof, string Biome, float At) item) => !item.Roof && !item.Managed), ["roof_sample_underwater"] = array.Count(((bool Roof, bool Water, bool Managed, bool CachedRoof, string Biome, float At) item) => item.Water), ["roof_sample_cache_disagreements"] = array.Count(((bool Roof, bool Water, bool Managed, bool CachedRoof, string Biome, float At) item) => item.Roof != item.CachedRoof), ["roof_sample_biomes"] = string.Join(",", from item in array group item by item.Biome into @group orderby @group.Key select @group.Key + ":" + @group.Count()), ["roof_sample_oldest_check_age_s"] = ((array.Length == 0) ? ((float?)null) : new float?(array.Max(((bool Roof, bool Water, bool Managed, bool CachedRoof, string Biome, float At) item) => now - item.At))) }; } } public static class WeatherGuardLogTopics { public static readonly LogTopic Protection = new LogTopic("protection"); public static readonly LogTopic Ownership = new LogTopic("ownership"); public static readonly LogTopic Wear = new LogTopic("wear"); public static readonly LogTopic Rain = new LogTopic("rain"); public static readonly LogTopic Coverage = new LogTopic("coverage"); } public static class WeatherGuardNetworkFilter { public const int MaximumPacketBytes = 2097152; public const int MaximumRecords = 32768; internal static ZPackage ReadPackage(ZPackage packet) { //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_003b: Expected O, but got Unknown int num = packet.ReadInt(); if (num < 0 || num > 2097152 || num > packet.Size() - packet.GetPos()) { throw new InvalidDataException("Invalid embedded package length."); } return new ZPackage(packet.ReadByteArray(num)); } public static RoutedRPCData ReadRouted(ZPackage packet) { //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Unknown result type (might be due to invalid IL or missing references) //IL_003c: Unknown result type (might be due to invalid IL or missing references) //IL_0048: 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_004f: Unknown result type (might be due to invalid IL or missing references) //IL_0054: Unknown result type (might be due to invalid IL or missing references) //IL_0060: Unknown result type (might be due to invalid IL or missing references) //IL_0086: Expected O, but got Unknown int pos = packet.GetPos(); try { if (packet.Size() > 2097152) { throw new InvalidDataException("Oversized routed packet."); } RoutedRPCData val = new RoutedRPCData { m_msgID = packet.ReadLong(), m_senderPeerID = packet.ReadLong(), m_targetPeerID = packet.ReadLong(), m_targetZDO = packet.ReadZDOID(), m_methodHash = packet.ReadInt(), m_parameters = ReadPackage(packet) }; if (packet.GetPos() != packet.Size()) { throw new InvalidDataException("Trailing routed data."); } return val; } finally { packet.SetPos(pos); } } public static bool RelevantRouted(ZPackage packet, Func protectedId) { //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Unknown result type (might be due to invalid IL or missing references) int pos = packet.GetPos(); try { packet.ReadLong(); packet.ReadLong(); packet.ReadLong(); ZDOID arg = packet.ReadZDOID(); int num = packet.ReadInt(); return protectedId(arg) || (((ZDOID)(ref arg)).IsNone() && num == StringExtensionMethods.GetStableHashCode("DestroyZDO")); } finally { packet.SetPos(pos); } } public static ZPackage FilterData(ZPackage original, Func protectedId, out int blocked, Action? rejected = null) { //IL_0055: Unknown result type (might be due to invalid IL or missing references) //IL_005a: Unknown result type (might be due to invalid IL or missing references) //IL_005d: Unknown result type (might be due to invalid IL or missing references) //IL_00aa: Unknown result type (might be due to invalid IL or missing references) //IL_00af: Unknown result type (might be due to invalid IL or missing references) //IL_00ee: Unknown result type (might be due to invalid IL or missing references) //IL_0136: Unknown result type (might be due to invalid IL or missing references) //IL_0175: 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_0249: Expected O, but got Unknown //IL_0265: Unknown result type (might be due to invalid IL or missing references) int pos = original.GetPos(); blocked = 0; try { if (original.Size() > 2097152) { throw new InvalidDataException("Oversized ZDO packet."); } List<(int, int)> list = null; List<(ZDOID, uint, ushort)> list2 = null; int num = original.ReadInt(); if (num < 0 || num > 32768) { throw new InvalidDataException("Invalid sector count."); } int num2 = 0; for (int i = 0; i < num; i++) { int pos2 = original.GetPos(); ZDOID arg = original.ReadZDOID(); if (protectedId(arg)) { blocked++; num2++; (list ?? (list = new List<(int, int)>())).Add((pos2, original.GetPos() - pos2)); } } int num3 = 0; while (true) { int pos3 = original.GetPos(); ZDOID val = original.ReadZDOID(); if (((ZDOID)(ref val)).IsNone()) { break; } if (++num3 > 32768) { throw new InvalidDataException("Too many ZDO records."); } ushort item = original.ReadUShort(); uint item2 = original.ReadUInt(); original.ReadLong(); original.ReadVector3(); int num4 = original.ReadInt(); if (num4 < 0 || num4 > 2097152 || num4 > original.Size() - original.GetPos()) { throw new InvalidDataException("Invalid embedded package length."); } original.SetPos(original.GetPos() + num4); if (protectedId(val)) { blocked++; (list ?? (list = new List<(int, int)>())).Add((pos3, original.GetPos() - pos3)); (list2 ?? (list2 = new List<(ZDOID, uint, ushort)>())).Add((val, item2, item)); } } if (original.GetPos() != original.Size()) { throw new InvalidDataException("Trailing ZDO data."); } if (blocked == 0) { return original; } byte[] array = original.GetArray(); using MemoryStream memoryStream = new MemoryStream(); using BinaryWriter binaryWriter = new BinaryWriter(memoryStream); binaryWriter.Write(num - num2); int num5 = pos + 4; foreach (var item3 in list) { binaryWriter.Write(array, num5, item3.Item1 - num5); num5 = item3.Item1 + item3.Item2; } binaryWriter.Write(array, num5, array.Length - num5); ZPackage result = new ZPackage(memoryStream.ToArray()); if (rejected != null && list2 != null) { foreach (var item4 in list2) { rejected(item4.Item1, item4.Item2, item4.Item3); } } return result; } finally { original.SetPos(pos); } } public static ZPackage FilterDestroyed(ZPackage original, Func protectedId, out int blocked, Action? rejected = null) { //IL_0047: Unknown result type (might be due to invalid IL or missing references) //IL_004c: Unknown result type (might be due to invalid IL or missing references) //IL_004f: Unknown result type (might be due to invalid IL or missing references) //IL_0069: Unknown result type (might be due to invalid IL or missing references) //IL_005f: Unknown result type (might be due to invalid IL or missing references) //IL_0094: Unknown result type (might be due to invalid IL or missing references) //IL_009b: Expected O, but got Unknown //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) //IL_00bd: Unknown result type (might be due to invalid IL or missing references) //IL_00f4: Unknown result type (might be due to invalid IL or missing references) //IL_00f9: Unknown result type (might be due to invalid IL or missing references) //IL_00fc: Unknown result type (might be due to invalid IL or missing references) int pos = original.GetPos(); blocked = 0; try { int num = original.ReadInt(); if (num < 0 || num > 32768 || original.Size() > 2097152) { throw new InvalidDataException("Invalid destroyed-object list."); } List list = new List(); List list2 = new List(); for (int i = 0; i < num; i++) { ZDOID val = original.ReadZDOID(); if (protectedId(val)) { blocked++; list2.Add(val); } else { list.Add(val); } } if (original.GetPos() != original.Size()) { throw new InvalidDataException("Trailing destroyed-object data."); } ZPackage val2 = new ZPackage(); val2.Write(list.Count); foreach (ZDOID item in list) { val2.Write(item); } val2.SetPos(0); if (rejected != null) { foreach (ZDOID item2 in list2) { rejected(item2); } } return val2; } finally { original.SetPos(pos); } } } internal sealed class WeatherGuardPatches : IDisposable { private readonly Harmony _harmony = new Harmony("heimkit.weatherguard"); [ThreadStatic] private static int _protectedWearDepth; [ThreadStatic] private static WearObservation? _wearObservation; [ThreadStatic] private static bool _weatherSuppressed; [ThreadStatic] private static WeatherGuardWearPass? _wearPass; private static readonly Dictionary PendingWearSweeps = new Dictionary(); private static readonly FieldRef WearIndex = NativeAccess.Field("m_index"); private static readonly int Destroyed = StringExtensionMethods.GetStableHashCode("DestroyZDO"); public void Install() { Patch(typeof(ZoneSystem), "Update", null, "Terrain"); Patch(typeof(ZNetScene), "CreateObjects", "Instances"); Patch(typeof(ZNetScene), "RemoveObjects", "Instances"); Patch(typeof(ZDO), "SetOwner", "Owner"); Patch(typeof(ZDOMan), "RPC_ZDOData", "Data"); Patch(typeof(ZRoutedRpc), "RPC_RoutedRPC", "Routed"); MethodInfo methodInfo = AccessTools.Method(typeof(WearNTearUpdater), "UpdateWearNTear", new Type[2] { typeof(float), typeof(float) }, (Type[])null); if (methodInfo == null || WearIndex == null) { throw new MissingMemberException("WearNTearUpdater wear-sweep APIs"); } _harmony.Patch((MethodBase)methodInfo, Method("BeginWearPass"), (HarmonyMethod)null, (HarmonyMethod)null, Method("EndWearPass"), (HarmonyMethod)null); MethodInfo methodInfo2 = AccessTools.Method(typeof(WearNTear), "UpdateWear", new Type[1] { typeof(float) }, (Type[])null); if (methodInfo2 == null) { throw new MissingMethodException("WearNTear.UpdateWear"); } _harmony.Patch((MethodBase)methodInfo2, Method("Wear"), (HarmonyMethod)null, Method("WeatherDamage"), Method("RestoreWear"), (HarmonyMethod)null); MethodInfo methodInfo3 = AccessTools.Method(typeof(ZNetScene), "OutsideActiveArea", new Type[1] { typeof(Vector3) }, (Type[])null); if (methodInfo3 == null) { throw new MissingMethodException("ZNetScene.OutsideActiveArea"); } _harmony.Patch((MethodBase)methodInfo3, Method("ActiveArea"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); Patch(typeof(WearNTear), "UpdateSupport", null, "Support"); string[] array = new string[3] { "RPC_Damage", "RPC_Repair", "RPC_Remove" }; foreach (string text in array) { _harmony.Patch((MethodBase)(AccessTools.Method(typeof(WearNTear), text, (Type[])null, (Type[])null) ?? throw new MissingMethodException(text)), Method("Command"), (HarmonyMethod)null, (HarmonyMethod)null, Method("CommandComplete"), (HarmonyMethod)null); } } private static HarmonyMethod Method(string name) { //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Expected O, but got Unknown return new HarmonyMethod(typeof(WeatherGuardPatches), name, (Type[])null); } private void Patch(Type type, string name, string? prefix, string? postfix = null) { MethodInfo methodInfo = AccessTools.Method(type, name, (Type[])null, (Type[])null); if (methodInfo == null) { throw new MissingMethodException(type.Name + "." + name); } _harmony.Patch((MethodBase)methodInfo, (prefix == null) ? null : Method(prefix), (postfix == null) ? null : Method(postfix), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } private static void Terrain() { WeatherGuardController active = WeatherGuardController.Active; if (active == null || !active.Running) { return; } try { active.LoadTerrain(); } catch (Exception error) { active.Fail(error); } } private static void Instances(List currentNearObjects, List currentDistantObjects) { WeatherGuardController active = WeatherGuardController.Active; if (active == null || !active.Running) { return; } try { active.AddInstances(currentNearObjects, currentDistantObjects); } catch (Exception error) { active.Fail(error); } } private static void Owner(ZDO __instance, ref long uid) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) WeatherGuardController active = WeatherGuardController.Active; if (active != null && active.Protects(__instance.m_uid) && uid != active.ServerId) { active.OwnerBlocked(__instance, uid); uid = active.ServerId; } } private static bool Data(ZRpc rpc, ref ZPackage pkg) { WeatherGuardController active = WeatherGuardController.Active; if (active == null || !active.Running) { return true; } if (!Connected(rpc, null)) { return true; } try { int blocked; ZPackage val = WeatherGuardNetworkFilter.FilterData(pkg, active.Protects, out blocked, active.Reassert); if (blocked != 0) { pkg = val; active.DataBlocked(blocked); } return true; } catch (Exception error) { active.Fail(error); return false; } } private static bool Connected(ZRpc rpc, long? sender) { foreach (ZNetPeer peer in ZNet.instance.GetPeers()) { if (peer.m_rpc == rpc) { return peer.IsReady() && (!sender.HasValue || peer.m_uid == sender.Value); } } return false; } private static bool Routed(ZRpc rpc, ref ZPackage pkg) { //IL_011c: Unknown result type (might be due to invalid IL or missing references) //IL_016e: Unknown result type (might be due to invalid IL or missing references) //IL_0175: Expected O, but got Unknown //IL_00f7: Unknown result type (might be due to invalid IL or missing references) //IL_0101: Expected O, but got Unknown WeatherGuardController active = WeatherGuardController.Active; if (active == null || !active.Running) { return true; } int pos = pkg.GetPos(); try { if (!WeatherGuardNetworkFilter.RelevantRouted(pkg, active.Protects)) { return true; } RoutedRPCData val = WeatherGuardNetworkFilter.ReadRouted(pkg); if (!Connected(rpc, null)) { return true; } if (!Connected(rpc, val.m_senderPeerID)) { active.BroadcastBlocked(); return false; } bool flag = false; if (((ZDOID)(ref val.m_targetZDO)).IsNone() && val.m_methodHash == Destroyed) { ZPackage original = WeatherGuardNetworkFilter.ReadPackage(val.m_parameters); if (val.m_parameters.GetPos() != val.m_parameters.Size()) { throw new InvalidDataException("Trailing destruction parameters."); } int blocked; ZPackage val2 = WeatherGuardNetworkFilter.FilterDestroyed(original, active.Protects, out blocked, active.Resend); if (blocked == 0) { return true; } val.m_parameters = new ZPackage(); val.m_parameters.Write(val2); active.BroadcastBlocked(blocked); flag = true; } else if (active.Protects(val.m_targetZDO)) { switch (WeatherGuardRules.Route(val.m_methodHash, val.m_targetPeerID, active.ServerId)) { case Routing.Drop: active.BroadcastBlocked(); return false; case Routing.Server: val.m_targetPeerID = active.ServerId; active.CommandRouted(); flag = true; break; } } if (flag) { ZPackage val3 = new ZPackage(); val.Serialize(val3); val3.SetPos(0); pkg = val3; } return true; } catch (Exception error) { pkg.SetPos(pos); active.Fail(error); return false; } } internal static IEnumerable WeatherDamage(IEnumerable instructions) { //IL_01f3: Unknown result type (might be due to invalid IL or missing references) //IL_01f9: Expected O, but got Unknown //IL_0216: Unknown result type (might be due to invalid IL or missing references) //IL_021c: Expected O, but got Unknown List code = instructions.ToList(); FieldInfo flag = typeof(WearNTear).GetField("m_noRoofWear"); FieldInfo timer = typeof(WearNTear).GetField("m_rainTimer", BindingFlags.Instance | BindingFlags.NonPublic); int[] array = (from pair in code.Select((CodeInstruction instruction, int index) => (instruction: instruction, index: index)) where pair.instruction.opcode == OpCodes.Ldfld && object.Equals(pair.instruction.operand, flag) select pair.index).ToArray(); int num = code.FindIndex((CodeInstruction i) => i.operand is MethodInfo methodInfo && methodInfo.Name == "UpdateSupport"); if (array.Length != 2 || num <= array[1] || (code[array[1] + 1].opcode != OpCodes.Brfalse && code[array[1] + 1].opcode != OpCodes.Brfalse_S) || !code.Take(array[1]).Any((CodeInstruction i) => i.opcode == OpCodes.Stfld && object.Equals(i.operand, typeof(WearNTear).GetField("m_rainWet", BindingFlags.Instance | BindingFlags.NonPublic)))) { throw new MissingMethodException("WeatherGuard weather contribution does not match audited UpdateWear IL."); } int[] array2 = (from index in Enumerable.Range(array[1], num - array[1]) where index >= 2 && index + 2 < code.Count && code[index].opcode == OpCodes.Ldc_R4 && object.Equals(code[index].operand, 5f) && code[index + 1].opcode == OpCodes.Add && code[index - 2].opcode == OpCodes.Stfld && object.Equals(code[index - 2].operand, timer) && code[index - 1].opcode.Name.StartsWith("ldloc") && code[index + 2].opcode.Name.StartsWith("stloc") select index).ToArray(); if (array2.Length != 1 || !code.Skip(array[1]).Take(array2[0] - array[1]).Any((CodeInstruction i) => i.opcode == OpCodes.Ldc_R4 && object.Equals(i.operand, 60f))) { throw new MissingMethodException("WeatherGuard timed weather addition does not match audited UpdateWear IL."); } code.InsertRange(array2[0] + 1, (IEnumerable)(object)new CodeInstruction[2] { new CodeInstruction(OpCodes.Ldarg_0, (object)null), new CodeInstruction(OpCodes.Call, (object)typeof(WeatherGuardPatches).GetMethod("WeatherContribution", BindingFlags.Static | BindingFlags.NonPublic)) }); return code; } private static float WeatherContribution(float native, WearNTear wear) { //IL_0059: Unknown result type (might be due to invalid IL or missing references) if (_wearObservation != null) { _wearObservation.GateReached = true; } WeatherGuardController active = WeatherGuardController.Active; if (_protectedWearDepth == 0 || active == null || !active.Running) { return native; } ZNetView component = ((Component)wear).GetComponent(); if ((Object)(object)component == (Object)null || !component.IsValid() || !component.IsOwner() || !active.Protects(component.GetZDO().m_uid)) { return native; } try { bool flag = active.SuppressWeather(wear, wear.m_noRoofWear); active.WeatherGate(wear, flag); if (_wearObservation != null) { _wearObservation.Suppressed = flag; } _weatherSuppressed = flag && active.WeatherDamageMayApply(wear); return flag ? 0f : native; } catch (Exception error) { active.Fail(error); return native; } } private static void BeginWearPass(WearNTearUpdater __instance, out WeatherGuardWearPass? __state) { __state = _wearPass; _wearPass = null; WeatherGuardController? active = WeatherGuardController.Active; if (active != null && active.Running) { if (!PendingWearSweeps.TryGetValue(__instance, out WeatherGuardWearPass value)) { value = new WeatherGuardWearPass(); PendingWearSweeps.Add(__instance, value); } _wearPass = value; } } private static Exception? EndWearPass(WearNTearUpdater __instance, WeatherGuardWearPass? __state, Exception? __exception) { WeatherGuardWearPass wearPass = _wearPass; _wearPass = __state; WeatherGuardController active = WeatherGuardController.Active; try { if (wearPass != null && active != null && active.Running) { bool flag = __exception != null || WearIndex.Invoke(__instance) == 0; wearPass.CompleteFrame(__exception == null, flag, active.ConfirmedPiece); if (flag) { PendingWearSweeps.Remove(__instance); } } else { PendingWearSweeps.Remove(__instance); } } catch (Exception error) { active?.Fail(error); } if (__exception != null) { active?.Fail(__exception); } return __exception; } private static void Wear(WearNTear __instance, float time, out WearProcessingState __state) { //IL_005b: Unknown result type (might be due to invalid IL or missing references) //IL_0060: Unknown result type (might be due to invalid IL or missing references) //IL_0075: Unknown result type (might be due to invalid IL or missing references) __state = default(WearProcessingState); __state.PreviousSuppression = _weatherSuppressed; _weatherSuppressed = false; __state.PreviousObservation = _wearObservation; _wearObservation = null; WeatherGuardController active = WeatherGuardController.Active; if (active == null || !active.Running) { return; } ZNetView component = ((Component)__instance).GetComponent(); if ((Object)(object)component == (Object)null || !component.IsValid()) { return; } __state.Identity = component.GetZDO().m_uid; __state.Protected = component.IsOwner() && active.Protects(component.GetZDO().m_uid); try { if (__state.Protected) { __state.Prefab = active.PiecePrefab(component.GetZDO()); } if (__state.Protected) { active.WearConditions(__instance, time); } __state.Observation = active.BeginWear(__instance, component, __state.Protected, time); } catch (Exception error) { active.Fail(error); __state.Protected = false; return; } _wearObservation = __state.Observation; if (__state.Protected) { _protectedWearDepth++; active.WearPass(); } } private static Exception? RestoreWear(WearNTear __instance, WearProcessingState __state, Exception? __exception) { //IL_007d: Unknown result type (might be due to invalid IL or missing references) //IL_0063: Unknown result type (might be due to invalid IL or missing references) if (__state.Protected) { _protectedWearDepth = Math.Max(0, _protectedWearDepth - 1); } bool weatherSuppressed = _weatherSuppressed; _weatherSuppressed = __state.PreviousSuppression; _wearObservation = __state.PreviousObservation; try { if (__state.Protected && weatherSuppressed && __exception == null) { WeatherGuardController? active = WeatherGuardController.Active; if (active != null && active.Running) { if (_wearPass != null) { _wearPass.Record(__state.Identity, contributionSuppressed: true, nativeWearSucceeded: true, __state.Prefab); } else { WeatherGuardController.Active.WeatherDamageSuppressed(__state.Identity, __state.Prefab); } } } } catch (Exception error) { WeatherGuardController.Active?.Fail(error); } try { WeatherGuardController.Active?.EndWear(__instance, __state.Observation, __exception); } catch (Exception error2) { WeatherGuardController.Active?.Fail(error2); } if (__exception != null) { WeatherGuardController.Active?.Fail(__exception); } return __exception; } private static bool ActiveArea(ref bool __result) { if (_protectedWearDepth != 0) { WeatherGuardController? active = WeatherGuardController.Active; if (active != null && active.Running) { __result = false; return false; } } return true; } private static void Support(WearNTear __instance) { try { WeatherGuardController.Active?.SupportPass(__instance); } catch (Exception error) { WeatherGuardController.Active?.Fail(error); } } private static void Command(WearNTear __instance, MethodBase __originalMethod, out WearObservation? __state) { __state = null; try { __state = WeatherGuardController.Active?.BeginCommand(__instance, __originalMethod.Name); } catch (Exception error) { WeatherGuardController.Active?.Fail(error); } } private static Exception? CommandComplete(WearNTear __instance, WearObservation? __state, Exception? __exception) { try { WeatherGuardController.Active?.EndCommand(__instance, __state, __exception); } catch (Exception error) { WeatherGuardController.Active?.Fail(error); } return __exception; } public void Dispose() { PendingWearSweeps.Clear(); _wearPass = null; _harmony.UnpatchSelf(); } } public static class WeatherGuardRules { public const int MaximumRegions = 8; public const int MaximumObjects = 32768; public const int MaximumProtected = 8192; public static bool SuppressWeatherDamage(bool nativeWeather, bool protectRain, bool protectUnderwater, bool rainWet, bool underwater) { if (nativeWeather) { if (!(protectRain && protectUnderwater)) { if ((rainWet || underwater) && (!rainWet || protectRain)) { return !underwater || protectUnderwater; } return false; } return true; } return false; } public static HashSet ParseExcludedPrefabs(string value, out int rejected) { HashSet hashSet = new HashSet(StringComparer.Ordinal); rejected = 0; if (string.IsNullOrWhiteSpace(value)) { return hashSet; } string[] array = value.Split(','); for (int i = 0; i < array.Length; i++) { string text = array[i].Trim(); bool flag = text.Length > 0; string text2 = text; foreach (char c in text2) { if ((c < 'a' || c > 'z') && (c < 'A' || c > 'Z') && (c < '0' || c > '9') && c != '_') { flag = false; } } if (!flag || (hashSet.Count >= 1024 && !hashSet.Contains(text))) { rejected++; } else { hashSet.Add(text); } } return hashSet; } public static string SelectionReason(string nativeReason, string prefab, HashSet excluded, bool rain, bool underwater) { if (nativeReason != "eligible" && nativeReason != "world-created") { return nativeReason; } if (excluded.Contains(prefab)) { return "excluded_prefab"; } if (!rain && !underwater) { return "weather_protection_disabled"; } return nativeReason; } public static bool Eligible(long creator, bool persistent, bool staticPiece, bool hasWeatherWear, float health, bool buildingCategory, bool container) { return Exclusion(creator, persistent, staticPiece, hasWeatherWear, health, buildingCategory, container) == "eligible"; } public static string Exclusion(long creator, bool persistent, bool staticPiece, bool hasWeatherWear, float health, bool buildingCategory, bool container) { if (container) { return "container"; } if (!buildingCategory) { return "non-building category"; } if (!persistent) { return "nonpersistent"; } if (!staticPiece) { return "moving piece"; } if (!hasWeatherWear) { return "weather immune"; } if (health <= 0f || float.IsNaN(health) || float.IsInfinity(health)) { return "dead/invalid health"; } if (creator != 0L) { return "eligible"; } return "world-created"; } public static bool MayAcquire(bool instanceLoaded, bool terrainReady, bool surroundingObjectsReady, bool withinCapacity) { return instanceLoaded && terrainReady && surroundingObjectsReady && withinCapacity; } public static bool RequiresContext(int colliders, bool wear, bool shield) { return colliders != 0 || wear || shield; } public static Routing Route(int method, long target, long server) { if (method == StringExtensionMethods.GetStableHashCode("RPC_HealthChanged") || method == StringExtensionMethods.GetStableHashCode("RPC_SetSnow") || method == StringExtensionMethods.GetStableHashCode("RPC_CreateFragments")) { return Routing.Drop; } if (target == 0L || target == server) { return Routing.Forward; } return Routing.Server; } public static (uint Data, ushort Owner) ReassertRevisions(uint serverData, ushort serverOwner, uint clientData, ushort clientOwner) { if ((clientData >= serverData && clientData == uint.MaxValue) || (clientOwner >= serverOwner && clientOwner == ushort.MaxValue)) { throw new InvalidOperationException("Client revision overflow prevents authoritative handover."); } return (Data: (clientData >= serverData) ? (clientData + 1) : serverData, Owner: (clientOwner >= serverOwner) ? ((ushort)(clientOwner + 1)) : serverOwner); } } public sealed class WeatherGuardSettings { public ConfigEntry Enabled { get; } public ConfigEntry ProtectRain { get; } public ConfigEntry ProtectUnderwater { get; } public ConfigEntry ExcludedPrefabs { get; } public ConfigEntry DebugMode { get; } public ConfigEntry GlobalDebugMode { get; } public DebugLoggingPolicy DebugLogging { get; } public ConfigEntry DebugLogLevel { get; } public ConfigEntry LogWorldCreatedItems { get; } public WeatherGuardSettings(ConfigFile config, ManualLogSource? logger = null) { //IL_00dc: Unknown result type (might be due to invalid IL or missing references) //IL_00e6: Expected O, but got Unknown Enabled = config.Bind("WeatherGuard", "Enabled", true, "Enable automatic rain/water-wear protection for player-built structures using server processing. Preserve creators. World-created repair claims are inactive. Restart after edits."); ProtectRain = config.Bind("WeatherGuard", "ProtectRain", true, "Prevent rain wear on eligible structures. Restart after edits."); ProtectUnderwater = config.Bind("WeatherGuard", "ProtectUnderwater", true, "Prevent underwater wetness wear on eligible structures. Restart after edits."); ExcludedPrefabs = config.Bind("WeatherGuard", "ExcludedPrefabs", "", "Comma-separated exact case-sensitive prefab identifiers to leave under native processing; no wildcards. Restart after edits."); GlobalDebugMode = DiagnosticsSettings.Bind(config); DebugMode = config.Bind("WeatherGuard", "DebugMode", false, "Enable diagnostics for this feature even when global DebugMode is off. The hidden suppression override still takes precedence. Restart after edits."); DebugLogging = DebugLoggingResolver.Resolve(config, "WeatherGuard", GlobalDebugMode, logger, DebugMode); DebugLogLevel = config.Bind("WeatherGuard", "DebugLogLevel", HeimKit.Features.WeatherGuard.Models.DebugLogLevel.Detailed, new ConfigDescription("DebugMode output: Medium reports the grouped prevention path; Detailed adds native-condition, health-anomaly, loading, ownership and support evidence. Restart after edits.", (AcceptableValueBase)(object)new WeatherGuardDebugLogLevelValues(), Array.Empty())); LogWorldCreatedItems = config.Bind("WeatherGuard", "LogWorldCreatedItems", false, "Include otherwise qualifying world-created structures in debug logs. Logging only; these structures remain unprotected. Restart after edits."); } } public sealed class WeatherGuardWearPass { private readonly HashSet _pieces = new HashSet(); private ZDOID _firstId; private string? _firstPrefab; public void Record(ZDOID id, bool contributionSuppressed, bool nativeWearSucceeded, string? prefab = null) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Unknown result type (might be due to invalid IL or missing references) if (contributionSuppressed && nativeWearSucceeded && _pieces.Add(id) && _pieces.Count == 1) { _firstId = id; _firstPrefab = prefab; } } public int CompleteFrame(bool succeeded, bool sweepFinished, Action confirmed) { //IL_0076: Unknown result type (might be due to invalid IL or missing references) //IL_007b: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_0034: Unknown result type (might be due to invalid IL or missing references) //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Unknown result type (might be due to invalid IL or missing references) if (succeeded && !sweepFinished) { return 0; } int result = (succeeded ? _pieces.Count : 0); if (succeeded) { foreach (ZDOID piece in _pieces) { confirmed(piece, (piece == _firstId) ? _firstPrefab : null); } } _pieces.Clear(); _firstId = ZDOID.None; _firstPrefab = null; return result; } public int Complete(bool succeeded) { string singleId; string singlePrefab; return Complete(succeeded, out singleId, out singlePrefab); } public int CompleteFrame(bool succeeded, bool sweepFinished, out string? singleId, out string? singlePrefab) { if (!succeeded || sweepFinished) { return Complete(succeeded, out singleId, out singlePrefab); } singleId = (singlePrefab = null); return 0; } public int Complete(bool succeeded, out string? singleId, out string? singlePrefab) { //IL_0047: Unknown result type (might be due to invalid IL or missing references) //IL_004c: Unknown result type (might be due to invalid IL or missing references) int num = (succeeded ? _pieces.Count : 0); singleId = ((num == 1) ? ((object)Unsafe.As(ref _firstId)/*cast due to .constrained prefix*/).ToString() : null); singlePrefab = ((num == 1) ? _firstPrefab : null); _pieces.Clear(); _firstId = ZDOID.None; _firstPrefab = null; return num; } } } namespace HeimKit.Features.WeatherGuard.Models { public sealed class CoverageSnapshot { public string State { get; set; } = "not_observed"; public bool Observed { get; set; } public float? ScanAge { get; set; } public int NearbyRecords { get; set; } public int DistantRecords { get; set; } public int Regions { get; set; } public bool Limited { get; set; } public bool RainEnabled { get; set; } public bool UnderwaterEnabled { get; set; } public int Eligible { get; private set; } public int Protected { get; private set; } public int Skipped { get; private set; } public int Waiting { get; private set; } public int UnloadedEligible { get; private set; } public Dictionary SkipReasons { get; } = new Dictionary(); public Dictionary WaitReasons { get; } = new Dictionary(); public void Add(string eligibility, bool managed, bool loaded, string waitReason) { if (eligibility != "eligible") { Skipped++; Count(SkipReasons, eligibility); return; } Eligible++; if (managed && loaded) { Protected++; return; } Waiting++; if (!loaded) { UnloadedEligible++; } Count(WaitReasons, (!loaded) ? "waiting_instance" : waitReason); static void Count(Dictionary counts, string reason) { counts.TryGetValue(reason, out var value); counts[reason] = value + 1; } } } public enum DebugLogLevel { Medium, Detailed } public sealed class ProtectionObservation { public Dictionary Identity { get; set; } = new Dictionary(); public bool Protected { get; set; } public bool RainProtection { get; set; } = true; public bool UnderwaterProtection { get; set; } = true; public string Reason { get; set; } = ""; public string Origin { get; set; } = "player_built"; } public sealed class RainEvidence { public Dictionary Fields { get; set; } = new Dictionary(); public Dictionary Identity { get; set; } = new Dictionary(); public bool? FreshRoof { get; set; } public float FreshRoofAt { get; set; } public string Eligibility { get; set; } = ""; public float Started { get; set; } public float FirstHealth { get; set; } public float MaximumHealth { get; set; } public float Health { get; set; } public float MinimumHealth { get; set; } public float LastGateTime { get; set; } = -1f; public float WetSeconds { get; set; } public float LongestWetSeconds { get; set; } public long Gates { get; set; } public long WetGates { get; set; } public long WeatherBypasses { get; set; } public float HealthLost { get; set; } public long HealthLossObservations { get; set; } public string ProtectionReason { get; set; } = "not_observed"; public long Owner { get; set; } public int OwnerChanges { get; set; } public int ProtectionChanges { get; set; } public bool Protected { get; set; } public bool CreatorChanged { get; set; } public long Creator { get; set; } public void ObserveGate(float time, bool wet, bool branchBypassed = false) { Gates++; if (branchBypassed) { WeatherBypasses++; } if (wet) { WetGates++; } float num = time - LastGateTime; if (!wet) { WetSeconds = 0f; } else if (LastGateTime < 0f || num < 0f || num > 10f) { WetSeconds = 0f; } else { WetSeconds += num; } LastGateTime = (wet ? time : (-1f)); if (WetSeconds > LongestWetSeconds) { LongestWetSeconds = WetSeconds; } } public void ObserveState(float health, long owner, bool protectedPiece, long creator) { if (health < Health) { HealthLost += Health - health; HealthLossObservations++; } Health = health; if (health < MinimumHealth) { MinimumHealth = health; } if (Owner != owner) { OwnerChanges++; WetSeconds = 0f; LastGateTime = -1f; } if (Protected != protectedPiece) { ProtectionChanges++; WetSeconds = 0f; LastGateTime = -1f; } CreatorChanged |= Creator != creator; Owner = owner; Protected = protectedPiece; } } public enum Routing { Forward, Drop, Server } public sealed class WearObservation { public Dictionary Fields { get; set; } = new Dictionary(); public Dictionary Identity { get; set; } = new Dictionary(); public bool Protected { get; set; } public bool Owner { get; set; } public bool Warmup { get; set; } public bool GateReached { get; set; } public bool Suppressed { get; set; } public float Before { get; set; } } internal struct WearProcessingState { public bool Protected; public ZDOID Identity; public string? Prefab; public bool PreviousSuppression; public WearObservation? Observation; public WearObservation? PreviousObservation; } public sealed class WeatherGuardStatus { public bool RainProtection { get; set; } = true; public bool UnderwaterProtection { get; set; } = true; public Dictionary ReleaseTotals { get; set; } = new Dictionary(); public int Protected { get; set; } public int Eligible { get; set; } public int Waiting { get; set; } public int WaitingTerrain { get; set; } public int WaitingInstance { get; set; } public int WaitingObjects { get; set; } public int Regions { get; set; } public int Nearby { get; set; } public int Distant { get; set; } public long Acquired { get; set; } public long Released { get; set; } public long BlockedData { get; set; } public long BlockedOwner { get; set; } public long BlockedBroadcast { get; set; } public long Commands { get; set; } public long WearPasses { get; set; } public bool Limited { get; set; } public int Peers { get; set; } public int ReadyPeers { get; set; } public int CharacterWaits { get; set; } public Dictionary Exclusions { get; set; } = new Dictionary(); public Dictionary ReleaseReasons { get; set; } = new Dictionary(); public long OwnerLosses { get; set; } public long WeatherGates { get; set; } public Dictionary Decisions { get; set; } = new Dictionary(); public long WeatherSuppressed { get; set; } public long ConfirmedPreventions { get; set; } public long WetOpportunities { get; set; } public long NativeCommands { get; set; } public long SupportPasses { get; set; } } } namespace HeimKit.Features.TameTravel { public sealed class TameTravel : IServerModule { private readonly TameTravelSettings _settings; private readonly ManualLogSource _logger; private readonly GameVersionCompatibility _compatibility; private readonly PlayerServices _players; private TameTravelController? _controller; private TameTravelFollowRecovery? _followRecovery; private IDisposable? _presenceRegistration; private bool _occupied; private ZDOMan? _world; private long _worldUid; private readonly PlayerProcessingNotices _processing; public string Name => "TameTravel"; public bool IsActive { get; private set; } public TameTravel(ConfigFile config, ManualLogSource logger, PlayerServices players) { _logger = logger; _compatibility = GameVersionCompatibility.Resolve(config, logger); _settings = new TameTravelSettings(config, logger); _players = players; _processing = new PlayerProcessingNotices(logger, Name, () => _settings.DebugLogging.Enabled); } public void Initialize(string gameVersion) { Shutdown(); Log(_settings.Enabled.Value ? "Enabled." : "Disabled.", (LogLevel)16); _settings.DebugLogging.ReportStartup(_logger, Name, _settings.Enabled.Value); if (!_settings.Enabled.Value) { return; } if (!_compatibility.Supports(gameVersion)) { Log("DISABLED: unsupported game version " + gameVersion + "; required version " + _compatibility.RequiredVersion, (LogLevel)4); return; } IsActive = true; try { _followRecovery = new TameTravelFollowRecovery(_logger); } catch (Exception error) { Fail(error); return; } if (_settings.DebugLogging.Enabled) { Log("Waiting for joined players and dedicated-server world", (LogLevel)32); } try { _presenceRegistration = _players.Events.Subscribe(PresenceChanged, Fail, () => _processing.IsEmptyPaused, () => _processing.IsRunning, () => _processing.IsServerReady); } catch (Exception error2) { Fail(error2); } if (!IsActive) { IDisposable? presenceRegistration = _presenceRegistration; _presenceRegistration = null; presenceRegistration?.Dispose(); } } public void Tick(float now) { if (!IsActive) { return; } if (!_settings.Enabled.Value) { Shutdown(); return; } try { _followRecovery?.Report(); bool flag = WorldServices.Activity && WorldServices.Terrain; if (flag) { _processing.ServerReady(); } if (!_occupied) { StopController(); return; } if (!flag) { StopController(); _processing.Paused("world services unavailable"); return; } long worldUID = ZNet.instance.GetWorldUID(); if (_world != ZDOMan.instance || _worldUid != worldUID) { StopController(); _world = ZDOMan.instance; _worldUid = worldUID; } StartController(); _controller?.Tick(now); } catch (Exception error) { Fail(error); } } private void PresenceChanged(bool? occupied) { _occupied = occupied == true; if (IsActive && !_occupied) { StopController(); if (occupied.HasValue) { _processing.EmptyPaused(); } else { _processing.Unavailable("player presence unavailable"); } } } private void StartController() { if (_settings.Enabled.Value && _controller == null) { _controller = new TameTravelController(this, _settings, _logger, _players); _processing.Ready(); } } private void StopController() { TameTravelController controller = _controller; _controller = null; if (controller != null) { ModuleScheduler.Current.Forget(controller); } try { controller?.Dispose(); } finally { WorldObjectProvider.Current?.ReleaseOwner(Name); } } internal void Fail(Exception error) { if (IsActive) { DiagnosticLog.Write(_logger, Name, CoreLogTopics.Lifecycle, "Disabled after a runtime failure.", default(LogFields), (LogLevel)2, verbose: false, error); Shutdown(); } } private void Log(string message, LogLevel level = (LogLevel)16) { //IL_000d: Unknown result type (might be due to invalid IL or missing references) DiagnosticLog.Write(_logger, Name, message, level); } public void Shutdown() { IsActive = false; _occupied = false; _processing.Reset(); IDisposable registration = _presenceRegistration; _presenceRegistration = null; TameTravelFollowRecovery recovery = _followRecovery; _followRecovery = null; ModuleCleanup.Run(_logger, Name, delegate { registration?.Dispose(); }, StopController, delegate { recovery?.Dispose(); }); } } internal static class TameTravelCommandRules { internal static float SelectionRange(TameOrder order, float commandRange) { if (order != TameOrder.Stay) { return commandRange; } return 32f; } internal static bool AwaitingEarlierFollow(bool pending, TameOrder previous, bool sent) { return pending && previous == TameOrder.Follow && sent; } public static bool StopAssociated(string following, string player, bool bound, string reclaimName = "", bool pending = false) { if (player.Length != 0) { if (!(following == player)) { if (bound) { if (following.Length != 0) { if (pending && reclaimName.Length != 0) { return following == reclaimName; } return false; } return true; } return false; } return true; } return false; } public static bool Chat(string text, out TameOrder order) { order = TameOrder.Follow; switch (text.Trim().ToLowerInvariant()) { case "!follow": order = TameOrder.Follow; return true; case "!stay": order = TameOrder.Stay; return true; case "!wait": order = TameOrder.Wait; return true; default: return false; } } public static bool Emote(string text, out TameOrder order) { order = TameOrder.Follow; switch (text) { case "comehere": order = TameOrder.Follow; return true; case "nonono": order = TameOrder.Stay; return true; case "wave": order = TameOrder.Wait; return true; default: return false; } } public static string ExpectedFollow(TameOrder order, string player) { if (order != TameOrder.Follow) { return ""; } return player; } public static bool ConsentExpired(TameOrder order, float age, float lifetime) { if (PlayerWorldScope.Finite(age) && !(age < 0f)) { if (order != TameOrder.Follow) { return age > lifetime; } return false; } return true; } public static bool ConsentValid(TameOrder order, string follow, string player) { if (order != TameOrder.Stay) { return string.Equals(follow, ExpectedFollow(order, player), StringComparison.Ordinal); } return false; } } internal sealed class TameTravelCommands { private readonly TameTravelRules _rules; private readonly TameTravelSettings _settings; private readonly ManualLogSource _log; private readonly Func _reserved; private readonly Action _confirmed; private readonly TameTravelDiagnostics _diagnostics; private readonly TameTravelStops? _stops; public readonly Dictionary Bindings = new Dictionary(); private readonly List> _snapshot = new List>(); private readonly List _eligible = new List(); private readonly List _own = new List(); private readonly List<(ZDO Record, float Distance)> _supported = new List<(ZDO, float)>(); private static readonly Comparison AnimalOrder = (ZDO a, ZDO b) => NativeIdentity.Compare(a.m_uid, b.m_uid); private static readonly Comparison<(ZDO Record, float Distance)> DistanceOrder = ((ZDO Record, float Distance) a, (ZDO Record, float Distance) b) => (PlayerWorldScope.Finite(a.Distance) ? a.Distance : float.MaxValue).CompareTo(PlayerWorldScope.Finite(b.Distance) ? b.Distance : float.MaxValue); public bool FollowingAuthorized(ZDOID id, ZNetPeer peer, ZDOID character, string name) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Unknown result type (might be due to invalid IL or missing references) if (Bindings.TryGetValue(id, out FollowBinding value) && !value.Pending && value.Order == TameOrder.Follow && value.Peer == peer && value.Character == character) { return value.Name == name; } return false; } public TameTravelCommands(TameTravelRules rules, TameTravelSettings settings, ManualLogSource log, Func reserved, Action confirmed, TameTravelDiagnostics diagnostics, TameTravelStops? stops = null) { _rules = rules; _settings = settings; _log = log; _reserved = reserved; _confirmed = confirmed; _diagnostics = diagnostics; _stops = stops; } public void Observe(ZNetPeer peer, ZDOID target, int method, ZPackage parameters, float now) { //IL_0026: 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_0152: Unknown result type (might be due to invalid IL or missing references) //IL_0154: Unknown result type (might be due to invalid IL or missing references) //IL_004d: Unknown result type (might be due to invalid IL or missing references) //IL_0053: Unknown result type (might be due to invalid IL or missing references) //IL_0058: Unknown result type (might be due to invalid IL or missing references) //IL_005d: 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_009a: Unknown result type (might be due to invalid IL or missing references) //IL_0186: Unknown result type (might be due to invalid IL or missing references) //IL_00bd: Unknown result type (might be due to invalid IL or missing references) //IL_00c4: Unknown result type (might be due to invalid IL or missing references) if (!_rules.Actor(peer, out ZDO actor)) { return; } if (method == StringExtensionMethods.GetStableHashCode("Command")) { ZDO zDO = ZDOMan.instance.GetZDO(target); if (!_rules.Animal(zDO) || _reserved(target)) { return; } Vector3 val = zDO.GetPosition() - actor.GetPosition(); if (((Vector3)(ref val)).sqrMagnitude > _settings.CommandRangeMeters.Value * _settings.CommandRangeMeters.Value) { return; } ZDOID val2 = parameters.ReadZDOID(); parameters.ReadBool(); if (!(val2 != peer.m_characterID) && parameters.GetPos() == parameters.Size()) { Bindings.Remove(target); TameTravelFollowState.Untrack(target); if (zDO.GetString(ZDOVars.s_follow, "").Length == 0) { Bind(peer, zDO, now, pending: true, TameOrder.Follow); } else if (zDO.GetString(ZDOVars.s_follow, "") == peer.m_playerName) { _stops?.QueueCleanup(zDO, peer.m_playerName, now); } } } else { if ((method != StringExtensionMethods.GetStableHashCode("Say") && method != StringExtensionMethods.GetStableHashCode("ChatMessage")) || (method == StringExtensionMethods.GetStableHashCode("Say") && target != peer.m_characterID) || (method == StringExtensionMethods.GetStableHashCode("ChatMessage") && !((ZDOID)(ref target)).IsNone())) { return; } if (method == StringExtensionMethods.GetStableHashCode("ChatMessage")) { parameters.ReadVector3(); } int num = parameters.ReadInt(); parameters.ReadString(); parameters.ReadString(); string text = parameters.ReadString().Trim(); if (parameters.GetPos() == parameters.Size() && num >= 0 && num <= 2) { TameOrder order; if (text.Equals("!tame", StringComparison.OrdinalIgnoreCase)) { Feedback(peer, "!follow: follow. !stay: stop/cancel. !wait: stop/keep one portal trip. Solo input: /comehere, /nonono, /wave."); } else if (TameTravelCommandRules.Chat(text, out order)) { Request(peer, order, now); } } } } public void Request(ZNetPeer peer, TameOrder order, float now) { //IL_0055: Unknown result type (might be due to invalid IL or missing references) //IL_00c0: Unknown result type (might be due to invalid IL or missing references) //IL_00c6: Unknown result type (might be due to invalid IL or missing references) //IL_00cb: Unknown result type (might be due to invalid IL or missing references) //IL_00d0: Unknown result type (might be due to invalid IL or missing references) //IL_037f: Unknown result type (might be due to invalid IL or missing references) //IL_0385: 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_0406: Unknown result type (might be due to invalid IL or missing references) _diagnostics.Command(peer, "request_received", order.ToString()); ZDO actor; string text = _rules.ActorRejection(peer, out actor); if (text != null) { Reject(peer, text, "Your character is not ready for animal commands."); return; } CandidateView candidateView = TameTravelRules.Nearby(actor.GetPosition()); if (candidateView == null) { Reject(peer, "scope_over_capacity", "Animal scope is unavailable; try again outside this dense area."); return; } float num = TameTravelCommandRules.SelectionRange(order, _settings.CommandRangeMeters.Value); List eligible = _eligible; eligible.Clear(); foreach (ZDO item in candidateView) { if (_rules.Animal(item)) { Vector3 val = item.GetPosition() - actor.GetPosition(); if (((Vector3)(ref val)).sqrMagnitude <= num * num) { eligible.Add(item); } } } _own.Clear(); if (order == TameOrder.Stay) { foreach (ZDO item2 in eligible) { if (StopAssociated(peer, item2)) { _own.Add(item2); } } } if (_diagnostics.SelectionEnabled) { _supported.Clear(); foreach (ZDO item3 in candidateView) { if (_rules.Supported(item3)) { _supported.Add((item3, Vector3.Distance(item3.GetPosition(), actor.GetPosition()))); } } _supported.Sort(DistanceOrder); _diagnostics.Selection(peer, order, candidateView.Count, _supported.Count, (order == TameOrder.Stay) ? _own.Count : eligible.Count); for (int i = 0; i < Math.Min(3, _supported.Count); i++) { (ZDO, float) tuple = _supported[i]; _diagnostics.Candidate(peer, order, tuple.Item1, tuple.Item2, num, _rules.AnimalRejection(tuple.Item1) ?? ((tuple.Item2 > num) ? "outside_command_range" : ((order == TameOrder.Stay && !StopAssociated(peer, tuple.Item1)) ? ((tuple.Item1.GetString(ZDOVars.s_follow, "").Length == 0) ? "not_following_you" : "following_another_player") : "eligible"))); } } if (order == TameOrder.Stay) { _own.Sort(AnimalOrder); if (_own.Count == 0) { Reject(peer, "no_associated_animals", "No following or waiting animal associated with you is in command range."); return; } for (int j = 0; j < Math.Min(16, _own.Count); j++) { QueueStop(peer, _own[j], now); } if (_own.Count > 16) { Feedback(peer, "Stay addresses sixteen animals at a time; repeat /nonono for the remaining followers."); } return; } ZDO val2 = null; float num2 = float.MaxValue; float num3 = float.MaxValue; foreach (ZDO item4 in eligible) { float num4 = Vector3.Distance(item4.GetPosition(), actor.GetPosition()); if (num4 < num2) { num3 = num2; num2 = num4; val2 = item4; } else if (num4 < num3) { num3 = num4; } } if (val2 == null) { Reject(peer, "no_eligible_tame", "No eligible tame in command range."); } else if (num3 - num2 < 0.5f) { Reject(peer, "nearest_animal_ambiguous", "Move closer to one animal; selection is ambiguous."); } else if (_reserved(val2.m_uid)) { Reject(peer, "animal_handoff_busy", "That animal is changing ownership; wait for its result."); } else { Apply(peer, val2, order, now); } } private bool StopAssociated(ZNetPeer peer, ZDO animal) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Unknown result type (might be due to invalid IL or missing references) FollowBinding value; bool bound = Bindings.TryGetValue(animal.m_uid, out value) && value.Peer == peer && value.Character == peer.m_characterID; return TameTravelCommandRules.StopAssociated(animal.GetString(ZDOVars.s_follow, ""), peer.m_playerName, bound, value?.ReclaimName ?? "", value?.Pending ?? false); } private void Apply(ZNetPeer peer, ZDO selected, TameOrder order, float now) { //IL_000e: 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_004c: Unknown result type (might be due to invalid IL or missing references) //IL_0052: Unknown result type (might be due to invalid IL or missing references) //IL_0093: Unknown result type (might be due to invalid IL or missing references) //IL_01f8: Unknown result type (might be due to invalid IL or missing references) //IL_0254: Unknown result type (might be due to invalid IL or missing references) //IL_0267: Unknown result type (might be due to invalid IL or missing references) //IL_029d: Unknown result type (might be due to invalid IL or missing references) //IL_012d: 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) TameTravelStops? stops = _stops; if (stops != null && stops.Contains(selected.m_uid)) { Reject(peer, "stop_pending", "Waiting for the animal's stop handshake to finish."); return; } FollowBinding value; bool flag = Bindings.TryGetValue(selected.m_uid, out value) && value.Peer == peer && value.Character == peer.m_characterID; if (value != null && !flag) { if (_rules.ConnectedPeer(value.Peer)) { Reject(peer, "foreign_association", "That animal has another player's active command."); return; } Bindings.Remove(selected.m_uid); value = null; } if (value != null && value.Pending) { Reject(peer, "command_pending", "Waiting for the previous animal command to confirm."); return; } string text = selected.GetString(ZDOVars.s_follow, ""); if (text.Length != 0 && text != peer.m_playerName) { if (order != TameOrder.Follow || _rules.ConnectedName(text) || _stops == null) { Reject(peer, "foreign_following", "That animal is following another connected player, or its owner cannot be verified."); } else if (Bind(peer, selected, now, pending: true, order)) { FollowBinding followBinding = Bindings[selected.m_uid]; followBinding.ReclaimName = text; followBinding.CommandSent = false; TameTravelFollowState.Mark(selected, text); Feedback(peer, "Clearing the absent player's saved following before starting yours."); TameTravelDiagnostics diagnostics = _diagnostics; ZDOID? animal = selected.m_uid; diagnostics.Command(peer, "reclaim_queued", "Follow", "saved_follower_offline", null, animal); } return; } if (order != TameOrder.Follow && !flag && text != peer.m_playerName) { Reject(peer, "association_required", (order == TameOrder.Stay) ? "Animal is already staying; no portal travel authorized." : "Use !follow or /comehere to associate this animal first."); return; } if (order == TameOrder.Wait && _stops != null) { Bind(peer, selected, now, pending: true, order); return; } string text2 = TameTravelCommandRules.ExpectedFollow(order, peer.m_playerName); if (text == text2) { if (order == TameOrder.Stay) { Bindings.Remove(selected.m_uid); } else if (!Bind(peer, selected, now, pending: false, order)) { return; } Result(peer, selected, order); return; } long owner = selected.GetOwner(); if (owner == 0L) { Reject(peer, "owner_unassigned", "Animal ownership is not ready; try again shortly."); } else if (Bind(peer, selected, now, pending: true, order)) { ZRoutedRpc.instance.InvokeRoutedRPC(owner, selected.m_uid, "Command", new object[2] { peer.m_characterID, false }); TameTravelDiagnostics diagnostics2 = _diagnostics; string command = order.ToString(); ZDOID? animal = selected.m_uid; diagnostics2.Command(peer, "native_toggle_sent", command, null, null, animal); } } private bool Bind(ZNetPeer peer, ZDO animal, float now, bool pending, TameOrder order) { //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_0050: Unknown result type (might be due to invalid IL or missing references) //IL_0063: Unknown result type (might be due to invalid IL or missing references) //IL_0068: Unknown result type (might be due to invalid IL or missing references) //IL_006f: 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_00a5: Unknown result type (might be due to invalid IL or missing references) //IL_00aa: Unknown result type (might be due to invalid IL or missing references) if (Bindings.Count >= 512 && !Bindings.ContainsKey(animal.m_uid)) { Reject(peer, "binding_capacity", "Animal command capacity reached; try again later."); return false; } if (order == TameOrder.Follow) { TameTravelFollowState.Mark(animal, peer.m_playerName); } Bindings[animal.m_uid] = new FollowBinding { Peer = peer, Character = peer.m_characterID, Animal = animal.m_uid, Name = peer.m_playerName, Consent = now, Requested = now, Pending = pending, Order = order, WaitPosition = animal.GetPosition() }; return true; } private void QueueStop(ZNetPeer peer, ZDO animal, float now) { //IL_0007: 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_0027: Unknown result type (might be due to invalid IL or missing references) //IL_007b: Unknown result type (might be due to invalid IL or missing references) //IL_0092: Unknown result type (might be due to invalid IL or missing references) //IL_00bd: Unknown result type (might be due to invalid IL or missing references) //IL_0117: Unknown result type (might be due to invalid IL or missing references) //IL_0137: Unknown result type (might be due to invalid IL or missing references) Bindings.TryGetValue(animal.m_uid, out FollowBinding value); if (value != null && (value.Peer != peer || value.Character != peer.m_characterID)) { Reject(peer, "foreign_association", "That animal has another player's active command."); } else if (value != null && value.Pending && value.Order == TameOrder.Stay) { Feedback(peer, "The stop request is already pending."); } else if (Bind(peer, animal, now, pending: true, TameOrder.Stay)) { Bindings[animal.m_uid].CommandSent = false; Bindings[animal.m_uid].ReclaimName = value?.ReclaimName ?? ""; Bindings[animal.m_uid].AwaitingEarlierFollow = value != null && TameTravelCommandRules.AwaitingEarlierFollow(value.Pending, value.Order, value.CommandSent); if (_stops == null) { _confirmed(peer, animal, TameOrder.Stay); } TameTravelDiagnostics diagnostics = _diagnostics; string reason = (Bindings[animal.m_uid].AwaitingEarlierFollow ? "earlier_follow_pending" : "ownership_and_stop_pending"); ZDOID? animal2 = animal.m_uid; diagnostics.Command(peer, "stop_queued", "Stay", reason, null, animal2); Feedback(peer, "Following permission cancelled; confirming animal stay."); } } public void Tick(float now) { //IL_006f: 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_00a3: Unknown result type (might be due to invalid IL or missing references) //IL_0127: Unknown result type (might be due to invalid IL or missing references) //IL_062f: Unknown result type (might be due to invalid IL or missing references) //IL_02eb: Unknown result type (might be due to invalid IL or missing references) //IL_01ad: Unknown result type (might be due to invalid IL or missing references) //IL_0651: Unknown result type (might be due to invalid IL or missing references) //IL_0658: Unknown result type (might be due to invalid IL or missing references) //IL_065d: Unknown result type (might be due to invalid IL or missing references) //IL_0662: Unknown result type (might be due to invalid IL or missing references) //IL_0400: Unknown result type (might be due to invalid IL or missing references) //IL_02ff: Unknown result type (might be due to invalid IL or missing references) //IL_01dd: Unknown result type (might be due to invalid IL or missing references) //IL_0691: Unknown result type (might be due to invalid IL or missing references) //IL_05ed: Unknown result type (might be due to invalid IL or missing references) //IL_05c2: Unknown result type (might be due to invalid IL or missing references) //IL_03df: Unknown result type (might be due to invalid IL or missing references) //IL_01f1: Unknown result type (might be due to invalid IL or missing references) //IL_0383: Unknown result type (might be due to invalid IL or missing references) //IL_0358: 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_026d: Unknown result type (might be due to invalid IL or missing references) //IL_04ed: Unknown result type (might be due to invalid IL or missing references) //IL_0501: Unknown result type (might be due to invalid IL or missing references) //IL_0551: Unknown result type (might be due to invalid IL or missing references) //IL_044d: Unknown result type (might be due to invalid IL or missing references) //IL_04bc: Unknown result type (might be due to invalid IL or missing references) _snapshot.Clear(); foreach (KeyValuePair binding in Bindings) { _snapshot.Add(binding); } foreach (KeyValuePair item in _snapshot) { FollowBinding value = item.Value; ZDO zDO = ZDOMan.instance.GetZDO(item.Key); ZDO actor; string text = _rules.ActorRejection(value.Peer, out actor); if (text == null && value.Peer.m_characterID != value.Character) { text = "character_replaced"; } if (text == null && value.Name != value.Peer.m_playerName) { text = "player_name_changed"; } if (text == null) { text = _rules.AnimalRejection(zDO); } if (text == null && TameTravelCommandRules.ConsentExpired(value.Order, now - value.Consent, _settings.FollowConsentSeconds.Value)) { text = "consent_expired"; } if (text != null) { RemoveBinding(item.Key, value, text, now, zDO); continue; } string text2 = zDO.GetString(ZDOVars.s_follow, ""); if (value.Pending && value.ReclaimName.Length != 0 && _stops != null) { if (_rules.ConnectedName(value.ReclaimName) || (text2.Length != 0 && text2 != value.ReclaimName)) { Bindings.Remove(item.Key); Reject(value.Peer, "reclaim_owner_changed", "The former follower reconnected or the animal changed following; command cancelled."); } else { if (!_stops.Contains(item.Key) && _reserved(item.Key)) { continue; } if (_stops.TryStop(zDO, value.ReclaimName, now)) { value.ReclaimName = ""; value.Requested = now; if (value.Order == TameOrder.Follow) { TameTravelFollowState.Mark(zDO, value.Name); continue; } value.Pending = false; Result(value.Peer, zDO, value.Order); Bindings.Remove(item.Key); } else if (now - value.Requested > 15f) { Bindings.Remove(item.Key); Reject(value.Peer, "reclaim_stop_timeout", "The old following could not be cleared; follow was not started.", failed: true); } } } else if (value.Pending && value.Order != TameOrder.Follow && _stops != null) { if (!_stops.Contains(item.Key) && _reserved(item.Key)) { continue; } if (_stops.TryStop(zDO, value.Name, now)) { value.Pending = false; Result(value.Peer, zDO, value.Order); if (value.Order == TameOrder.Stay) { Bindings.Remove(item.Key); } } else if (now - value.Requested > 15f) { Bindings.Remove(item.Key); Reject(value.Peer, "stop_handshake_timeout", "Stay could not be confirmed; retry /nonono.", failed: true); } } else if (value.Pending) { if (!value.CommandSent) { if (text2.Length != 0 && text2 != value.Name) { RemoveBinding(item.Key, value, "follow_state_changed", now, zDO); continue; } if (_reserved(item.Key)) { continue; } if (value.AwaitingEarlierFollow) { if (!(text2 == value.Name)) { if (now - value.Requested > 5f) { Bindings.Remove(item.Key); Reject(value.Peer, "earlier_follow_unconfirmed", "Following permission cancelled, but the earlier command did not resolve; stay is unconfirmed. Try /nonono again.", failed: true); } continue; } value.AwaitingEarlierFollow = false; } if (text2 != TameTravelCommandRules.ExpectedFollow(value.Order, value.Name)) { long owner = zDO.GetOwner(); if (owner == 0L) { if (now - value.Requested > 5f) { Bindings.Remove(item.Key); Reject(value.Peer, "stop_owner_unavailable", "Portal travel cancelled, but stay could not be confirmed; try /nonono again.", failed: true); } continue; } ZRoutedRpc.instance.InvokeRoutedRPC(owner, item.Key, "Command", new object[2] { value.Character, false }); value.CommandSent = true; value.Requested = now; TameTravelDiagnostics diagnostics = _diagnostics; ZNetPeer peer = value.Peer; string command = value.Order.ToString(); ZDOID? animal = item.Key; diagnostics.Command(peer, "native_toggle_sent", command, null, null, animal); continue; } } if (text2 == TameTravelCommandRules.ExpectedFollow(value.Order, value.Name)) { value.Pending = false; Result(value.Peer, zDO, value.Order); if (value.Order == TameOrder.Stay) { Bindings.Remove(item.Key); } } else if (now - value.Requested > 5f) { Bindings.Remove(item.Key); Reject(value.Peer, "native_command_timeout", "Animal command was not confirmed; no toggle was retried.", failed: true); } } else if (!TameTravelCommandRules.ConsentValid(value.Order, text2, value.Name)) { RemoveBinding(item.Key, value, "follow_state_changed", now, zDO); } else if (value.Order == TameOrder.Wait) { Vector3 val = zDO.GetPosition() - value.WaitPosition; if (((Vector3)(ref val)).sqrMagnitude > _settings.FollowerRangeMeters.Value * _settings.FollowerRangeMeters.Value) { RemoveBinding(item.Key, value, "animal_left_wait_area", now, zDO); } } } } private void RemoveBinding(ZDOID id, FollowBinding binding, string reason, float now, ZDO? animal) { //IL_0064: 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_008b: Unknown result type (might be due to invalid IL or missing references) //IL_00ba: 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_0171: Unknown result type (might be due to invalid IL or missing references) if (_stops != null && animal != null && _rules.Animal(animal) && (binding.Order == TameOrder.Follow || binding.Pending) && reason != "follow_state_changed") { _stops.QueueCleanup(animal, (binding.ReclaimName.Length != 0) ? binding.ReclaimName : binding.Name, now); } else { TameTravelFollowState.Untrack(id); } Bindings.Remove(id); TameTravelDiagnostics diagnostics = _diagnostics; ZNetPeer peer = binding.Peer; ZDOID? animal2 = id; if (diagnostics.TraversalReady(peer, "consent_ended", reason, null, animal2, transition: true)) { TameTravelDiagnostics diagnostics2 = _diagnostics; ZNetPeer peer2 = binding.Peer; animal2 = id; (string, object)[] verboseFields = ((!_diagnostics.VerboseAfterNormalEnabled) ? null : new(string, object)[6] { ("order", binding.Order), ("consent_age_s", now - binding.Consent), ("following", (animal != null) ? animal.GetString(ZDOVars.s_follow, "") : null), ("wait_position", binding.WaitPosition), ("animal_position", (animal != null) ? new Vector3?(animal.GetPosition()) : ((Vector3?)null)), ("maximum_wait_range_m", _settings.FollowerRangeMeters.Value) }); diagnostics2.Traversal(peer2, "consent_ended", reason, null, animal2, null, transition: true, ready: true, verboseFields); } } internal void ClearForShutdown() { //IL_0031: Unknown result type (might be due to invalid IL or missing references) if (_stops == null || ZDOMan.instance == null) { return; } foreach (FollowBinding value in Bindings.Values) { ZDO zDO = ZDOMan.instance.GetZDO(value.Animal); if (zDO != null) { _stops.ClearForShutdown(zDO, (value.ReclaimName.Length != 0) ? value.ReclaimName : value.Name); } } } private void Result(ZNetPeer peer, ZDO animal, TameOrder order) { //IL_001d: Unknown result type (might be due to invalid IL or missing references) TameTravelDiagnostics diagnostics = _diagnostics; string command = order.ToString(); ZDOID? animal2 = animal.m_uid; diagnostics.Command(peer, "confirmed", command, null, null, animal2); string text = order switch { TameOrder.Stay => "stay", TameOrder.Follow => "follow", _ => "portal wait", }; DiagnosticLog.Write(_log, "TameTravel", "Confirmed " + text + " for " + peer.m_playerName + ".", (LogLevel)16); GameObject? obj = PrefabRegistry.Current.Prefab(animal.GetPrefab()); string text2 = ((obj != null) ? ((Object)obj).name : null) ?? "Animal"; Feedback(peer, order switch { TameOrder.Stay => text2 + " is staying; portal travel cancelled.", TameOrder.Follow => text2 + " is following, including through portals; /nonono stops following.", _ => text2 + " is waiting; one nearby portal trip authorized.", }); _confirmed(peer, animal, order); } private void Reject(ZNetPeer peer, string reason, string text, bool failed = false) { _diagnostics.Command(peer, "rejected", null, reason); if (failed) { DiagnosticLog.Write(_log, "TameTravel", "Animal command for " + peer.m_playerName + " was not confirmed; no toggle was retried.", (LogLevel)4); } Feedback(peer, text); } public static void Feedback(ZNetPeer peer, string text) { //IL_0029: Unknown result type (might be due to invalid IL or missing references) if (ZRoutedRpc.instance != null && peer.IsReady() && !((ZDOID)(ref peer.m_characterID)).IsNone()) { ZRoutedRpc.instance.InvokeRoutedRPC(peer.m_uid, peer.m_characterID, "Message", new object[3] { 1, "TameTravel: " + text, 0 }); } } } internal sealed class TameTravelController : IDisposable { private static TameTravelController? _current; private static readonly int PongMethod = StringExtensionMethods.GetStableHashCode("RPC_Pong"); private static readonly int TeleportMethod = StringExtensionMethods.GetStableHashCode("RPC_TeleportTo"); private static readonly int TeleportPlayerMethod = StringExtensionMethods.GetStableHashCode("RPC_TeleportPlayer"); private static readonly int CommandMethod = StringExtensionMethods.GetStableHashCode("Command"); private static readonly int SayMethod = StringExtensionMethods.GetStableHashCode("Say"); private static readonly int ChatMethod = StringExtensionMethods.GetStableHashCode("ChatMessage"); private readonly Harmony _hooks = new Harmony("heimkit.tametravel.traversal"); private readonly TameTravelSettings _settings; private readonly ManualLogSource _log; private readonly PlayerServices _players; private readonly Action _fail; private readonly TameTravelRules _rules; private readonly TameTravelCommands _commands; private readonly TameTravelStops _stops; private readonly ObjectTransferAuthority _authority; private readonly TameTravelPlacement _placement; private readonly TameTravelFollowing _following; private readonly TameTravelDiagnostics _diagnostics; private readonly IDisposable _messages; private readonly Dictionary _samples = new Dictionary(); private readonly Dictionary _transfers = new Dictionary(); private readonly HashSet _reserved = new HashSet(); private readonly Dictionary<(long Peer, long Message), float> _messagesSeen = new Dictionary<(long, long), float>(); private readonly List<(long Peer, long Message)> _expiredMessages = new List<(long, long)>(); private readonly List _readyPeers = new List(); private readonly List> _sampleSnapshot = new List>(); private readonly List _transferSnapshot = new List(); private readonly List _bindingSnapshot = new List(); private readonly List _portalSnapshot = new List(); private readonly List _orderedBindings = new List(); private static readonly Comparison BindingOrder = (FollowBinding a, FollowBinding b) => NativeIdentity.Compare(a.Animal, b.Animal); private int _cursor; private bool _disposed; private bool _placementUsed; private readonly List _cancelTransfers = new List(); public TameTravelController(TameTravel module, TameTravelSettings settings, ManualLogSource log, PlayerServices players) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Expected O, but got Unknown //IL_0226: Unknown result type (might be due to invalid IL or missing references) //IL_0234: Expected O, but got Unknown //IL_0261: Unknown result type (might be due to invalid IL or missing references) //IL_026f: Expected O, but got Unknown //IL_029c: Unknown result type (might be due to invalid IL or missing references) //IL_02b1: Unknown result type (might be due to invalid IL or missing references) //IL_02be: Expected O, but got Unknown //IL_02be: Expected O, but got Unknown _settings = settings; _log = log; _players = players; _fail = module.Fail; _rules = new TameTravelRules(players.Presence); _diagnostics = new TameTravelDiagnostics(log, settings.DebugLogging); _authority = new ObjectTransferAuthority(players.Presence, module.Fail); try { _placement = new TameTravelPlacement(_rules); } catch { _authority.Dispose(); throw; } try { _following = new TameTravelFollowing(_rules, settings, _authority, _diagnostics, log, module.Fail); } catch { ModuleCleanup.Run(log, "TameTravel", delegate { _placement.Dispose(); }, delegate { _authority.Dispose(); }); throw; } _stops = new TameTravelStops(_authority, _following, players.Presence, log); _commands = new TameTravelCommands(_rules, settings, log, (ZDOID id) => _reserved.Contains(id) || _following.ChangingOwners(id), _following.Command, _diagnostics, _stops); try { if (_current != null) { throw new InvalidOperationException("TameTravel traversal observer is already active."); } _current = this; _hooks.Patch((MethodBase)AccessTools.Method(typeof(Player), "TeleportTo", (Type[])null, (Type[])null), new HarmonyMethod(typeof(TameTravelController), "CompetingTeleport", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); _hooks.Patch((MethodBase)AccessTools.Method(typeof(Chat), "TeleportPlayer", (Type[])null, (Type[])null), new HarmonyMethod(typeof(TameTravelController), "AdministrativeTeleport", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); _hooks.Patch((MethodBase)AccessTools.Method(typeof(ZDOMan), "RPC_ZDOData", (Type[])null, (Type[])null), new HarmonyMethod(typeof(TameTravelController), "BeforePlayerData", (Type[])null), new HarmonyMethod(typeof(TameTravelController), "AfterPlayerData", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); _messages = players.RoutedMessages.Subscribe(Observe, module.Fail); } catch { if (_current == this) { _current = null; } ModuleCleanup.Run(log, "TameTravel", delegate { _hooks.UnpatchSelf(); }, delegate { _following.Dispose(); }, delegate { _placement.Dispose(); }, delegate { _authority.Dispose(); }); throw; } } public void Tick(float now) { //IL_01d7: Unknown result type (might be due to invalid IL or missing references) //IL_01e8: 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_02ff: Unknown result type (might be due to invalid IL or missing references) //IL_0307: Unknown result type (might be due to invalid IL or missing references) //IL_030c: Unknown result type (might be due to invalid IL or missing references) //IL_0345: Unknown result type (might be due to invalid IL or missing references) //IL_034c: Unknown result type (might be due to invalid IL or missing references) //IL_0378: Unknown result type (might be due to invalid IL or missing references) //IL_0416: Unknown result type (might be due to invalid IL or missing references) //IL_041d: Unknown result type (might be due to invalid IL or missing references) //IL_0564: Unknown result type (might be due to invalid IL or missing references) //IL_0569: Unknown result type (might be due to invalid IL or missing references) //IL_08b8: Unknown result type (might be due to invalid IL or missing references) //IL_08e1: Unknown result type (might be due to invalid IL or missing references) //IL_087a: Unknown result type (might be due to invalid IL or missing references) //IL_087f: Unknown result type (might be due to invalid IL or missing references) //IL_05be: Unknown result type (might be due to invalid IL or missing references) //IL_05a5: Unknown result type (might be due to invalid IL or missing references) //IL_0636: Unknown result type (might be due to invalid IL or missing references) //IL_063d: Unknown result type (might be due to invalid IL or missing references) //IL_0642: Unknown result type (might be due to invalid IL or missing references) //IL_0647: Unknown result type (might be due to invalid IL or missing references) //IL_05ff: Unknown result type (might be due to invalid IL or missing references) //IL_0604: Unknown result type (might be due to invalid IL or missing references) //IL_0a9d: Unknown result type (might be due to invalid IL or missing references) //IL_0aa2: Unknown result type (might be due to invalid IL or missing references) //IL_0aa9: Unknown result type (might be due to invalid IL or missing references) //IL_0ab9: Unknown result type (might be due to invalid IL or missing references) //IL_0a58: Unknown result type (might be due to invalid IL or missing references) //IL_0a5f: Unknown result type (might be due to invalid IL or missing references) //IL_0a64: Unknown result type (might be due to invalid IL or missing references) //IL_0a69: Unknown result type (might be due to invalid IL or missing references) //IL_0adf: Unknown result type (might be due to invalid IL or missing references) //IL_0aea: Unknown result type (might be due to invalid IL or missing references) //IL_0b3c: Unknown result type (might be due to invalid IL or missing references) //IL_0b43: Unknown result type (might be due to invalid IL or missing references) //IL_0b48: Unknown result type (might be due to invalid IL or missing references) //IL_0b4d: Unknown result type (might be due to invalid IL or missing references) //IL_0c87: Unknown result type (might be due to invalid IL or missing references) //IL_0c89: Unknown result type (might be due to invalid IL or missing references) //IL_0cb4: Unknown result type (might be due to invalid IL or missing references) //IL_0b96: Unknown result type (might be due to invalid IL or missing references) //IL_06f3: Unknown result type (might be due to invalid IL or missing references) //IL_0710: Unknown result type (might be due to invalid IL or missing references) //IL_0ce3: Unknown result type (might be due to invalid IL or missing references) //IL_0cf1: Unknown result type (might be due to invalid IL or missing references) //IL_0bc4: Unknown result type (might be due to invalid IL or missing references) //IL_0bce: Unknown result type (might be due to invalid IL or missing references) //IL_0d24: Unknown result type (might be due to invalid IL or missing references) //IL_0d2e: Unknown result type (might be due to invalid IL or missing references) //IL_0bf6: Unknown result type (might be due to invalid IL or missing references) //IL_0c00: Unknown result type (might be due to invalid IL or missing references) //IL_0d5b: Unknown result type (might be due to invalid IL or missing references) //IL_0d65: Unknown result type (might be due to invalid IL or missing references) //IL_0c39: Unknown result type (might be due to invalid IL or missing references) //IL_0c5b: Unknown result type (might be due to invalid IL or missing references) if (!ModuleScheduler.Current.Due(this, "processing", now, 0.25f)) { return; } using (_diagnostics.OptionalEnabled ? _diagnostics.Measure(now, () => _samples.Count + _following.Count) : null) { _expiredMessages.Clear(); foreach (KeyValuePair<(long, long), float> item in _messagesSeen) { if (now - item.Value > 30f) { _expiredMessages.Add(item.Key); } } foreach (var expiredMessage in _expiredMessages) { _messagesSeen.Remove(expiredMessage); } List readyPeers = _readyPeers; readyPeers.Clear(); for (int num = 0; num < _players.Presence.Peers.Count; num++) { ZNetPeer val = _players.Presence.Peers[num]; if (val.IsReady()) { readyPeers.Add(val); if (readyPeers.Count > 64) { break; } } } if (readyPeers.Count > 64) { ClearJourneys(); return; } _sampleSnapshot.Clear(); foreach (KeyValuePair sample in _samples) { _sampleSnapshot.Add(sample); } foreach (KeyValuePair item2 in _sampleSnapshot) { if (!ContainsPeer(readyPeers, item2.Value.Peer) || item2.Value.Character != item2.Value.Peer.m_characterID || !_rules.Actor(item2.Value.Peer, out ZDO _)) { Cancel(item2.Value, now); _samples.Remove(item2.Key); } } _stops.Tick(now); _commands.Tick(now); int num2 = Math.Min(8, readyPeers.Count); Vector3 val3; for (int num3 = 0; num3 < num2; num3++) { ZNetPeer val2 = readyPeers[(_cursor + num3) % readyPeers.Count]; ZDO actor2; string text = _rules.ActorRejection(val2, out actor2); _diagnostics.ActorGate(val2, text); if (text != null) { continue; } if (!_samples.TryGetValue(val2.m_uid, out PlayerSample value)) { _samples.Add(val2.m_uid, new PlayerSample { Peer = val2, Character = val2.m_characterID, Position = actor2.GetPosition(), Time = now, Emote = actor2.GetInt(ZDOVars.s_emoteID, 0) }); } else { if (value.Peer != val2 || value.Character != val2.m_characterID) { continue; } bool flag = value.Positions.Overflowed; if (flag) { Cancel(value, now, "position_history_overflow", actor2.GetPosition()); value.Positions.AcknowledgeOverflow(); if (_diagnostics.SelectionEnabled) { _diagnostics.Traversal(val2, "position_history", "overflow_reset", null, null, null, transition: true); } } List bindingSnapshot = _bindingSnapshot; bindingSnapshot.Clear(); foreach (FollowBinding value2 in _commands.Bindings.Values) { if (!value2.Pending && value2.Peer == val2 && value2.Character == value.Character) { bindingSnapshot.Add(value2); } } if (bindingSnapshot.Count > 0 && value.Journey == null && value.Positions.Count == 0 && _diagnostics.SelectionEnabled && _diagnostics.TraversalReady(val2, "source_observation", "awaiting_owner_position")) { TameTravelDiagnostics diagnostics = _diagnostics; (string, object)[] fields = new(string, object)[1] { ("followers", bindingSnapshot.Count) }; (string, object)[] verboseFields = ((!_diagnostics.VerboseAfterNormalEnabled) ? null : new(string, object)[1] { ("last_observation_age_s", now - value.Time) }); diagnostics.Traversal(val2, "source_observation", "awaiting_owner_position", null, null, fields, transition: false, ready: true, verboseFields); } List records = null; bool queried = false; PositionObservation observation; while (value.Positions.Take(out observation)) { if (flag) { value.Position = observation.Position; value.Time = observation.Time; flag = false; continue; } if (value.Journey != null) { if (now - observation.Time > 2f) { Cancel(value, now, "stale_position_observation", observation.Position); } else { UpdateJourney(value, observation.Position, observation.Time, now, fresh: true); } } else if (bindingSnapshot.Count > 0) { if (value.PendingPortal != null && ResolvePortal(value, observation, now, bindingSnapshot)) { value.Position = observation.Position; value.Time = observation.Time; continue; } float age = now - observation.Time; float gap = observation.Time - value.Time; val3 = observation.Position - value.Position; string text2 = TameTravelTraversalRules.SourceRejection(age, gap, ((Vector3)(ref val3)).sqrMagnitude); bool flag2 = text2 == "source_sample_gap" && observation.Time >= value.Time; if (text2 != null && _diagnostics.SelectionEnabled && _diagnostics.TraversalReady(val2, "source_observation", text2)) { TameTravelDiagnostics diagnostics2 = _diagnostics; (string, object)[] verboseFields = ((!_diagnostics.VerboseAfterNormalEnabled) ? null : new(string, object)[5] { ("before", value.Position), ("after", observation.Position), ("gap_s", observation.Time - value.Time), ("age_s", now - observation.Time), ("fresh_point_only", flag2) }); diagnostics2.Traversal(val2, "source_observation", text2, null, null, null, transition: false, ready: true, verboseFields); } if (text2 == null || flag2) { if (now >= value.BlockedUntil) { TryEnter(value, actor2, observation, now, bindingSnapshot, ref records, ref queried, flag2); } else if (_diagnostics.SelectionEnabled && _diagnostics.TraversalReady(val2, "source_observation", "cooldown")) { TameTravelDiagnostics diagnostics3 = _diagnostics; (string, object)[] verboseFields = ((!_diagnostics.VerboseAfterNormalEnabled) ? null : new(string, object)[1] { ("remaining_s", value.BlockedUntil - now) }); diagnostics3.Traversal(val2, "source_observation", "cooldown", null, null, null, transition: false, ready: true, verboseFields); } } } value.Position = observation.Position; value.Time = observation.Time; } if (bindingSnapshot.Count == 0) { value.PendingPortal = null; } else if (value.PendingPortal != null) { ResolvePortal(value, new PositionObservation(value.Position, value.Time, 0u), now, bindingSnapshot); } if (value.Journey != null) { UpdateJourney(value, actor2.GetPosition(), now, now, fresh: false); } } } if (readyPeers.Count > 0) { _cursor = (_cursor + num2) % readyPeers.Count; } _following.Tick(now); _authority.Tick(now); _placementUsed = false; _transferSnapshot.Clear(); foreach (AnimalTransfer value3 in _transfers.Values) { _transferSnapshot.Add(value3); } foreach (AnimalTransfer item3 in _transferSnapshot) { UpdateTransfer(item3, now); } foreach (PlayerSample value4 in _samples.Values) { PortalJourney journey = value4.Journey; if (journey == null) { continue; } if (journey.Followers.Count == 0) { if (!HasTransfer(journey)) { Complete(value4, now); } continue; } if (_transfers.Count >= 64) { break; } if (!_rules.Actor(journey.Peer, out ZDO actor3)) { continue; } if (journey.Arrived >= 0f) { val3 = actor3.GetPosition() - journey.Exit; if (TameTravelTraversalRules.DestinationRejection(((Vector3)(ref val3)).sqrMagnitude, now - journey.Entered, _settings.TravelWindowSeconds.Value) != null) { continue; } } ZDOID val4 = journey.Followers.Dequeue(); ZDO zDO = ZDOMan.instance.GetZDO(val4); bool flag3 = journey.Waiting.Contains(val4); string text3 = _rules.AnimalRejection(zDO); if (text3 == null && !flag3 && !_commands.FollowingAuthorized(val4, journey.Peer, journey.Character, journey.Name)) { text3 = "follow_authorization_ended"; } if (text3 == null && !TameTravelCommandRules.ConsentValid(flag3 ? TameOrder.Wait : TameOrder.Follow, zDO.GetString(ZDOVars.s_follow, ""), journey.Name)) { text3 = "follow_state_changed"; } if (text3 == null) { val3 = zDO.GetPosition() - journey.SourcePosition; if (((Vector3)(ref val3)).sqrMagnitude > _settings.FollowerRangeMeters.Value * _settings.FollowerRangeMeters.Value) { text3 = "animal_left_source_range"; } } if (text3 != null) { journey.EndReason = text3; _reserved.Remove(val4); if (_diagnostics.SelectionEnabled && _diagnostics.TraversalReady(journey.Peer, "transfer_start", text3, journey.Source, val4, transition: true)) { _diagnostics.Traversal(journey.Peer, "transfer_start", text3, journey.Source, val4, null, transition: true, ready: true, (!_diagnostics.VerboseAfterNormalEnabled) ? null : new(string, object)[2] { ("animal_position", (zDO != null) ? new Vector3?(zDO.GetPosition()) : ((Vector3?)null)), ("source_position", journey.SourcePosition) }); } continue; } AnimalTransfer animalTransfer = new AnimalTransfer { Record = zDO, Id = val4, Journey = journey, Started = now, PhaseTime = now, Waiting = flag3 }; _transfers.Add(val4, animalTransfer); if (!_authority.Acquire(animalTransfer, now)) { journey.EndReason = "authority_acquisition_unavailable"; _transfers.Remove(val4); _reserved.Remove(val4); if (_diagnostics.SelectionEnabled && _diagnostics.TraversalReady(journey.Peer, "transfer_start", journey.EndReason, journey.Source, val4, transition: true)) { _diagnostics.Traversal(journey.Peer, "transfer_start", journey.EndReason, journey.Source, val4, null, transition: true, ready: true, (!_diagnostics.VerboseAfterNormalEnabled) ? null : new(string, object)[2] { ("owner", zDO.GetOwner()), ("data_revision", zDO.DataRevision) }); } } break; } _diagnostics.Observe(now, _commands.Bindings.Count, _reserved.Count, _transfers.Count); } } private static bool ContainsPeer(List peers, ZNetPeer expected) { foreach (ZNetPeer peer in peers) { if (peer == expected) { return true; } } return false; } private bool HasTransfer(PortalJourney journey) { foreach (AnimalTransfer value in _transfers.Values) { if (value.Journey == journey) { return true; } } return false; } private static bool HasConsent(List bindings, float time) { foreach (FollowBinding binding in bindings) { if (binding.Consent <= time) { return true; } } return false; } private void TryEnter(PlayerSample sample, ZDO actor, PositionObservation observation, float now, List bindings, ref List? records, ref bool queried, bool pointOnly) { //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_011c: Unknown result type (might be due to invalid IL or missing references) //IL_0122: Unknown result type (might be due to invalid IL or missing references) //IL_0147: Unknown result type (might be due to invalid IL or missing references) //IL_014c: Unknown result type (might be due to invalid IL or missing references) //IL_014d: Unknown result type (might be due to invalid IL or missing references) //IL_0152: Unknown result type (might be due to invalid IL or missing references) //IL_0131: Unknown result type (might be due to invalid IL or missing references) //IL_0132: Unknown result type (might be due to invalid IL or missing references) //IL_013b: Unknown result type (might be due to invalid IL or missing references) //IL_0140: Unknown result type (might be due to invalid IL or missing references) //IL_018c: Unknown result type (might be due to invalid IL or missing references) //IL_0185: Unknown result type (might be due to invalid IL or missing references) //IL_018d: Unknown result type (might be due to invalid IL or missing references) //IL_0407: Unknown result type (might be due to invalid IL or missing references) //IL_040c: Unknown result type (might be due to invalid IL or missing references) //IL_0415: Unknown result type (might be due to invalid IL or missing references) //IL_041a: Unknown result type (might be due to invalid IL or missing references) //IL_0439: Unknown result type (might be due to invalid IL or missing references) //IL_043e: Unknown result type (might be due to invalid IL or missing references) //IL_0446: Unknown result type (might be due to invalid IL or missing references) //IL_044b: Unknown result type (might be due to invalid IL or missing references) //IL_0246: Unknown result type (might be due to invalid IL or missing references) //IL_02b3: Unknown result type (might be due to invalid IL or missing references) //IL_02ca: Unknown result type (might be due to invalid IL or missing references) if (!HasConsent(bindings, observation.Time)) { return; } Vector3 position = observation.Position; if (!queried) { CandidateView candidateView = TameTravelRules.Nearby(position); _portalSnapshot.Clear(); if (candidateView != null) { foreach (ZDO item in candidateView) { if (item.GetPrefab() == StringExtensionMethods.GetStableHashCode("portal_wood") || item.GetPrefab() == StringExtensionMethods.GetStableHashCode("portal_stone")) { _portalSnapshot.Add(item); } } } records = ((candidateView == null) ? null : _portalSnapshot); queried = true; } if (records == null) { if (_diagnostics.SelectionEnabled) { _diagnostics.Traversal(sample.Peer, "source_entry", "scope_over_capacity"); } return; } int num = 0; int num2 = 0; int num3 = 0; int num4 = 0; ZDO val = null; ZDO val2 = null; ZDO val3 = null; foreach (ZDO record in records) { if (record.m_uid == sample.ReentryPortal) { if (TameTravelRules.Crossed(record, actor, position, position)) { continue; } sample.ReentryPortal = ZDOID.None; } Vector3 val4 = record.GetPosition() - position; if (((Vector3)(ref val4)).sqrMagnitude >= 100f) { continue; } num++; val = record; if ((Object)(object)TameTravelRules.Portal(record) == (Object)null) { continue; } num2++; if (TameTravelRules.Crossed(record, actor, pointOnly ? position : sample.Position, position)) { num3++; val2 = record; if (PortalPairRejection(record, out ZDO _) == null) { num4++; val3 = record; } } } if (num4 == 1) { val2 = val3; } else if (num4 > 1 || num3 != 1) { if (_diagnostics.SelectionEnabled && _diagnostics.TraversalReady(sample.Peer, "source_entry", (num4 > 1 || num3 > 1) ? "ambiguous_trigger" : ((num2 > 0) ? "outside_trigger" : ((num > 0) ? "source_portal_ineligible" : "no_portal_nearby")), (num == 1) ? new ZDOID?(val.m_uid) : ((ZDOID?)null))) { TameTravelDiagnostics diagnostics = _diagnostics; ZNetPeer peer = sample.Peer; string reason = ((num4 > 1 || num3 > 1) ? "ambiguous_trigger" : ((num2 > 0) ? "outside_trigger" : ((num > 0) ? "source_portal_ineligible" : "no_portal_nearby"))); ZDOID? source = ((num == 1) ? new ZDOID?(val.m_uid) : ((ZDOID?)null)); (string, object)[] fields = new(string, object)[2] { ("pos", position), ("followers", bindings.Count) }; (string, object)[] verboseFields = ((!_diagnostics.VerboseAfterNormalEnabled) ? null : new(string, object)[5] { ("portals", num), ("supported_portals", num2), ("creator", (num == 1) ? new long?(val.GetLong(ZDOVars.s_creator, 0L)) : ((long?)null)), ("trigger_matches", num3), ("paired_trigger_matches", num4) }); diagnostics.Traversal(peer, "source_entry", reason, source, null, fields, transition: false, ready: true, verboseFields); } return; } ZDO val5 = val2; ZDO destination2; string text = PortalPairRejection(val5, out destination2); if (text != null) { _diagnostics.PortalPair(sample.Peer, val5, destination2, text); if (TameTravelPortalRules.CanWait(text)) { sample.PendingPortal = new PortalWitness { Source = val5, SourceId = val5.m_uid, Destination = val5.GetConnectionZDOID((ConnectionType)1), Tag = val5.GetString(ZDOVars.s_tag, ""), Position = val5.GetPosition(), Rotation = val5.GetRotation(), Observation = observation }; } } else { BeginJourney(sample, val5, destination2, observation, now, bindings, pointOnly ? "fresh_inside_after_gap" : "owner_position_history"); } } private void BeginJourney(PlayerSample sample, ZDO portalSource, ZDO destination, PositionObservation observation, float now, List bindings, string mode) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0022: 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_003f: Unknown result type (might be due to invalid IL or missing references) //IL_0044: Unknown result type (might be due to invalid IL or missing references) //IL_004b: Unknown result type (might be due to invalid IL or missing references) //IL_0050: Unknown result type (might be due to invalid IL or missing references) //IL_0057: Unknown result type (might be due to invalid IL or missing references) //IL_005c: Unknown result type (might be due to invalid IL or missing references) //IL_0063: Unknown result type (might be due to invalid IL or missing references) //IL_0068: Unknown result type (might be due to invalid IL or missing references) //IL_006f: 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_007b: Unknown result type (might be due to invalid IL or missing references) //IL_0080: Unknown result type (might be due to invalid IL or missing references) //IL_00aa: Unknown result type (might be due to invalid IL or missing references) //IL_00b0: Unknown result type (might be due to invalid IL or missing references) //IL_00b5: Unknown result type (might be due to invalid IL or missing references) //IL_00ba: Unknown result type (might be due to invalid IL or missing references) //IL_00c5: Unknown result type (might be due to invalid IL or missing references) //IL_00ca: Unknown result type (might be due to invalid IL or missing references) //IL_00cf: Unknown result type (might be due to invalid IL or missing references) //IL_00d4: Unknown result type (might be due to invalid IL or missing references) //IL_00d9: Unknown result type (might be due to invalid IL or missing references) //IL_01b4: Unknown result type (might be due to invalid IL or missing references) //IL_01d5: Unknown result type (might be due to invalid IL or missing references) //IL_022d: Unknown result type (might be due to invalid IL or missing references) //IL_025a: Unknown result type (might be due to invalid IL or missing references) //IL_025f: Unknown result type (might be due to invalid IL or missing references) //IL_0260: Unknown result type (might be due to invalid IL or missing references) //IL_0265: Unknown result type (might be due to invalid IL or missing references) //IL_0241: Unknown result type (might be due to invalid IL or missing references) //IL_0280: Unknown result type (might be due to invalid IL or missing references) //IL_0286: Unknown result type (might be due to invalid IL or missing references) //IL_028b: Unknown result type (might be due to invalid IL or missing references) //IL_0290: Unknown result type (might be due to invalid IL or missing references) //IL_03e4: Unknown result type (might be due to invalid IL or missing references) //IL_0413: Unknown result type (might be due to invalid IL or missing references) //IL_042b: Unknown result type (might be due to invalid IL or missing references) //IL_0400: Unknown result type (might be due to invalid IL or missing references) //IL_02d0: Unknown result type (might be due to invalid IL or missing references) //IL_02dc: Unknown result type (might be due to invalid IL or missing references) //IL_044d: Unknown result type (might be due to invalid IL or missing references) //IL_0305: Unknown result type (might be due to invalid IL or missing references) //IL_0311: Unknown result type (might be due to invalid IL or missing references) //IL_0328: Unknown result type (might be due to invalid IL or missing references) //IL_036c: Unknown result type (might be due to invalid IL or missing references) //IL_038d: Unknown result type (might be due to invalid IL or missing references) Vector3 position = observation.Position; TeleportWorld val = TameTravelRules.Portal(portalSource); PortalJourney portalJourney = new PortalJourney { Peer = sample.Peer, Character = sample.Character, Name = sample.Peer.m_playerName, Source = portalSource.m_uid, Destination = destination.m_uid, SourcePosition = portalSource.GetPosition(), DestinationPosition = destination.GetPosition(), SourceRotation = portalSource.GetRotation(), DestinationRotation = destination.GetRotation(), Tag = portalSource.GetString(ZDOVars.s_tag, ""), Entered = observation.Time, Exit = destination.GetPosition() + destination.GetRotation() * Vector3.forward * val.m_exitDistance + Vector3.up }; float value = _settings.FollowerRangeMeters.Value; _orderedBindings.Clear(); foreach (FollowBinding binding in bindings) { if (binding.Consent <= observation.Time) { _orderedBindings.Add(binding); } } _orderedBindings.Sort(BindingOrder); foreach (FollowBinding orderedBinding in _orderedBindings) { if (portalJourney.Followers.Count >= _settings.MaxFollowersPerTraversal.Value || _reserved.Count >= 512) { break; } if (!_commands.Bindings.TryGetValue(orderedBinding.Animal, out FollowBinding value2) || value2 != orderedBinding) { continue; } ZDO zDO = ZDOMan.instance.GetZDO(orderedBinding.Animal); string text = _rules.AnimalRejection(zDO); if (text == null && !TameTravelCommandRules.ConsentValid(orderedBinding.Order, zDO.GetString(ZDOVars.s_follow, ""), orderedBinding.Name)) { text = "follow_changed"; } if (text == null && (_reserved.Contains(orderedBinding.Animal) || _following.ChangingOwners(orderedBinding.Animal))) { text = "animal_handoff_busy"; } Vector3 val2; if (text == null) { val2 = zDO.GetPosition() - position; if (((Vector3)(ref val2)).sqrMagnitude > value * value) { text = "animal_outside_player_range"; } } if (text == null) { val2 = zDO.GetPosition() - portalSource.GetPosition(); if (((Vector3)(ref val2)).sqrMagnitude > value * value) { text = "animal_outside_portal_range"; } } if (text != null) { if (_diagnostics.SelectionEnabled && _diagnostics.TraversalReady(sample.Peer, "follower_entry", text, portalSource.m_uid, orderedBinding.Animal)) { _diagnostics.Traversal(sample.Peer, "follower_entry", text, portalSource.m_uid, orderedBinding.Animal, new(string, object)[1] { ("pos", position) }, transition: false, ready: true, (!_diagnostics.VerboseAfterNormalEnabled) ? null : new(string, object)[4] { ("animal_position", (zDO != null) ? new Vector3?(zDO.GetPosition()) : ((Vector3?)null)), ("portal_position", portalSource.GetPosition()), ("maximum_range_m", value), ("order", orderedBinding.Order) }); } } else { portalJourney.Followers.Enqueue(orderedBinding.Animal); if (orderedBinding.Order == TameOrder.Wait) { portalJourney.Waiting.Add(orderedBinding.Animal); } _following.Stop(orderedBinding.Animal, "portal_reserved"); _reserved.Add(orderedBinding.Animal); if (orderedBinding.Order == TameOrder.Wait) { _commands.Bindings.Remove(orderedBinding.Animal); } } } if (portalJourney.Followers.Count > 0) { sample.Journey = portalJourney; _diagnostics.Entry(portalJourney, mode); TameTravelCommands.Feedback(sample.Peer, "Portal trip detected; move clear and stay within 48 metres of the destination exit until animal arrival is confirmed."); } } private static string? PortalPairRejection(ZDO source, out ZDO? destination) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_003d: 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_004e: Unknown result type (might be due to invalid IL or missing references) //IL_005d: Unknown result type (might be due to invalid IL or missing references) //IL_0062: 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_00a5: Unknown result type (might be due to invalid IL or missing references) //IL_00aa: Unknown result type (might be due to invalid IL or missing references) //IL_00af: Unknown result type (might be due to invalid IL or missing references) ZDOID connectionZDOID = source.GetConnectionZDOID((ConnectionType)1); destination = ZDOMan.instance.GetZDO(connectionZDOID); bool linked = !((ZDOID)(ref connectionZDOID)).IsNone(); bool destinationPresent = destination != null; string? destinationRejection = TameTravelRules.PortalRejection(destination); ZDO? obj = destination; ZDOID? val = ((obj != null) ? new ZDOID?(obj.GetConnectionZDOID((ConnectionType)1)) : ((ZDOID?)null)); ZDOID uid = source.m_uid; bool reciprocal = val.HasValue && val.GetValueOrDefault() == uid; string sourceTag = source.GetString(ZDOVars.s_tag, ""); ZDO? obj2 = destination; string destinationTag = ((obj2 != null) ? obj2.GetString(ZDOVars.s_tag, "") : null) ?? ""; float separationSquared; if (destination != null) { Vector3 val2 = source.GetPosition() - destination.GetPosition(); separationSquared = ((Vector3)(ref val2)).sqrMagnitude; } else { separationSquared = float.NaN; } return TameTravelPortalRules.PairRejection(linked, destinationPresent, destinationRejection, reciprocal, sourceTag, destinationTag, separationSquared, ZoneSystem.instance.GetGlobalKey((GlobalKeys)32)); } private bool ResolvePortal(PlayerSample sample, PositionObservation current, float now, List bindings) { //IL_0030: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Unknown result type (might be due to invalid IL or missing references) //IL_0048: Unknown result type (might be due to invalid IL or missing references) //IL_00cb: Unknown result type (might be due to invalid IL or missing references) //IL_00c2: Unknown result type (might be due to invalid IL or missing references) //IL_00d0: Unknown result type (might be due to invalid IL or missing references) //IL_0081: Unknown result type (might be due to invalid IL or missing references) //IL_0087: 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_00a2: Unknown result type (might be due to invalid IL or missing references) //IL_00a8: Unknown result type (might be due to invalid IL or missing references) //IL_00e2: Unknown result type (might be due to invalid IL or missing references) //IL_00e7: 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_0155: 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_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_0258: Unknown result type (might be due to invalid IL or missing references) //IL_025d: Unknown result type (might be due to invalid IL or missing references) //IL_01c4: Unknown result type (might be due to invalid IL or missing references) //IL_01cb: Unknown result type (might be due to invalid IL or missing references) //IL_01d0: Unknown result type (might be due to invalid IL or missing references) //IL_01d5: 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_01ea: 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_01f4: Unknown result type (might be due to invalid IL or missing references) //IL_01f9: Unknown result type (might be due to invalid IL or missing references) //IL_01fc: Unknown result type (might be due to invalid IL or missing references) //IL_0201: Unknown result type (might be due to invalid IL or missing references) //IL_0203: Unknown result type (might be due to invalid IL or missing references) //IL_0208: Unknown result type (might be due to invalid IL or missing references) //IL_020a: Unknown result type (might be due to invalid IL or missing references) //IL_0211: Unknown result type (might be due to invalid IL or missing references) //IL_0218: Unknown result type (might be due to invalid IL or missing references) //IL_021d: Unknown result type (might be due to invalid IL or missing references) //IL_022d: Unknown result type (might be due to invalid IL or missing references) //IL_02e7: 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) PortalWitness pendingPortal = sample.PendingPortal; ZDO source = pendingPortal.Source; string text = null; Vector3 val; if (!TameTravelPortalRules.WitnessValid(now - pendingPortal.Observation.Time)) { text = "source_witness_expired"; } else { if (!(source.m_uid != pendingPortal.SourceId) && ZDOMan.instance.GetZDO(pendingPortal.SourceId) == source && !((Object)(object)TameTravelRules.Portal(source) == (Object)null) && !(source.GetString(ZDOVars.s_tag, "") != pendingPortal.Tag)) { val = source.GetPosition() - pendingPortal.Position; if (!(((Vector3)(ref val)).sqrMagnitude > 0.0001f) && !(Quaternion.Angle(source.GetRotation(), pendingPortal.Rotation) > 0.01f)) { goto IL_00bf; } } text = "witnessed_portal_changed"; } goto IL_00bf; IL_00bf: ZDOID val2 = ((text == null) ? source.GetConnectionZDOID((ConnectionType)1) : ZDOID.None); if (text == null && !((ZDOID)(ref pendingPortal.Destination)).IsNone() && pendingPortal.Destination != val2) { text = "witnessed_link_changed"; } if (text != null) { sample.PendingPortal = null; if (_diagnostics.SelectionEnabled) { _diagnostics.Traversal(sample.Peer, "source_pair_wait", text, pendingPortal.SourceId); } return true; } if (((ZDOID)(ref pendingPortal.Destination)).IsNone() && !((ZDOID)(ref val2)).IsNone()) { pendingPortal.Destination = val2; } ZDO destination; string text2 = PortalPairRejection(source, out destination); if (text2 != null) { _diagnostics.PortalPair(sample.Peer, source, destination, text2); } if (text2 != null && !TameTravelPortalRules.CanWait(text2)) { sample.PendingPortal = null; return true; } if (now - current.Time > 2f) { return true; } bool flag = false; if (destination != null && (Object)(object)TameTravelRules.Portal(destination) != (Object)null) { Vector3 val3 = destination.GetPosition() + destination.GetRotation() * Vector3.forward * TameTravelRules.Portal(source).m_exitDistance + Vector3.up; Vector3 val4 = current.Position - val3; Vector2 val5 = new Vector2(val4.x, val4.z); flag = ((Vector2)(ref val5)).sqrMagnitude <= 9f && Math.Abs(val4.y) <= 4f; } if (!flag) { val = current.Position - pendingPortal.Position; if (((Vector3)(ref val)).sqrMagnitude > 144f) { sample.PendingPortal = null; if (_diagnostics.SelectionEnabled) { _diagnostics.Traversal(sample.Peer, "source_pair_wait", "movement_outside_witnessed_endpoints", source.m_uid); } return true; } } if (text2 != null) { return true; } sample.PendingPortal = null; BeginJourney(sample, source, destination, pendingPortal.Observation, now, bindings, "retained_source_witness"); if (sample.Journey != null) { UpdateJourney(sample, current.Position, current.Time, now, fresh: true); } return true; } private bool Pair(PortalJourney j) { //IL_0006: 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_0046: Unknown result type (might be due to invalid IL or missing references) //IL_004c: Unknown result type (might be due to invalid IL or missing references) //IL_005d: Unknown result type (might be due to invalid IL or missing references) //IL_0063: 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_00be: Unknown result type (might be due to invalid IL or missing references) //IL_00c3: 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_00d9: Unknown result type (might be due to invalid IL or missing references) //IL_00de: Unknown result type (might be due to invalid IL or missing references) //IL_00e3: 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_00f9: Unknown result type (might be due to invalid IL or missing references) //IL_010b: Unknown result type (might be due to invalid IL or missing references) //IL_0111: Unknown result type (might be due to invalid IL or missing references) ZDO zDO = ZDOMan.instance.GetZDO(j.Source); ZDO zDO2 = ZDOMan.instance.GetZDO(j.Destination); if ((Object)(object)TameTravelRules.Portal(zDO) != (Object)null && (Object)(object)TameTravelRules.Portal(zDO2) != (Object)null && zDO.GetConnectionZDOID((ConnectionType)1) == j.Destination && zDO2.GetConnectionZDOID((ConnectionType)1) == j.Source && zDO.GetString(ZDOVars.s_tag, "") == j.Tag && zDO2.GetString(ZDOVars.s_tag, "") == j.Tag) { Vector3 val = zDO.GetPosition() - j.SourcePosition; if (((Vector3)(ref val)).sqrMagnitude < 0.0001f) { val = zDO2.GetPosition() - j.DestinationPosition; if (((Vector3)(ref val)).sqrMagnitude < 0.0001f && Quaternion.Angle(zDO.GetRotation(), j.SourceRotation) < 0.01f && Quaternion.Angle(zDO2.GetRotation(), j.DestinationRotation) < 0.01f) { return !ZoneSystem.instance.GetGlobalKey((GlobalKeys)32); } } } return false; } private void UpdateJourney(PlayerSample sample, Vector3 p, float observedAt, float now, bool fresh) { //IL_0049: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_0055: Unknown result type (might be due to invalid IL or missing references) //IL_0057: Unknown result type (might be due to invalid IL or missing references) //IL_005c: Unknown result type (might be due to invalid IL or missing references) //IL_0061: Unknown result type (might be due to invalid IL or missing references) //IL_0062: Unknown result type (might be due to invalid IL or missing references) //IL_0068: Unknown result type (might be due to invalid IL or missing references) //IL_006e: Unknown result type (might be due to invalid IL or missing references) //IL_0073: Unknown result type (might be due to invalid IL or missing references) //IL_0082: Unknown result type (might be due to invalid IL or missing references) //IL_0349: Unknown result type (might be due to invalid IL or missing references) //IL_00cf: Unknown result type (might be due to invalid IL or missing references) //IL_00e9: Unknown result type (might be due to invalid IL or missing references) //IL_00eb: Unknown result type (might be due to invalid IL or missing references) //IL_00f0: Unknown result type (might be due to invalid IL or missing references) //IL_00f5: Unknown result type (might be due to invalid IL or missing references) //IL_0373: Unknown result type (might be due to invalid IL or missing references) //IL_038d: Unknown result type (might be due to invalid IL or missing references) //IL_038f: Unknown result type (might be due to invalid IL or missing references) //IL_0208: Unknown result type (might be due to invalid IL or missing references) //IL_013a: Unknown result type (might be due to invalid IL or missing references) //IL_03c7: 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_0184: Unknown result type (might be due to invalid IL or missing references) //IL_03d9: Unknown result type (might be due to invalid IL or missing references) //IL_03de: Unknown result type (might be due to invalid IL or missing references) //IL_03df: Unknown result type (might be due to invalid IL or missing references) //IL_03e4: Unknown result type (might be due to invalid IL or missing references) //IL_0248: Unknown result type (might be due to invalid IL or missing references) //IL_01d2: Unknown result type (might be due to invalid IL or missing references) //IL_027e: 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_02c5: Unknown result type (might be due to invalid IL or missing references) //IL_045b: Unknown result type (might be due to invalid IL or missing references) PortalJourney journey = sample.Journey; if (!Pair(journey) || journey.Character != sample.Peer.m_characterID || journey.Name != sample.Peer.m_playerName) { Cancel(sample, now, "pair_or_actor_changed", p); return; } Vector3 val = p - journey.Exit; Vector2 val2 = new Vector2(val.x, val.z); bool flag = ((Vector2)(ref val2)).sqrMagnitude <= 9f && Math.Abs(val.y) <= 4f; Vector3 val3; if (journey.Arrived < 0f) { if (now - journey.Entered > _settings.TravelWindowSeconds.Value) { Cancel(sample, now, "arrival_timeout", p); } else { if (!fresh) { return; } float age = observedAt - journey.Entered; val3 = p - journey.SourcePosition; string text = TameTravelTraversalRules.ArrivalRejection(flag, age, ((Vector3)(ref val3)).sqrMagnitude); if (text == "arrival_too_early") { if (_diagnostics.SelectionEnabled && _diagnostics.TraversalReady(journey.Peer, "arrival", text, journey.Source)) { TameTravelDiagnostics diagnostics = _diagnostics; ZNetPeer peer = journey.Peer; ZDOID? source = journey.Source; (string, object)[] fields = new(string, object)[1] { ("pos", p) }; (string, object)[] verboseFields = ((!_diagnostics.VerboseAfterNormalEnabled) ? null : new(string, object)[2] { ("entry_age_s", observedAt - journey.Entered), ("expected_exit", journey.Exit) }); diagnostics.Traversal(peer, "arrival", text, source, null, fields, transition: false, ready: true, verboseFields); } } else if (text != null) { Cancel(sample, now, text, p); } else if (flag) { journey.Arrived = observedAt; if (_diagnostics.SelectionEnabled && _diagnostics.TraversalReady(journey.Peer, "arrival", "linked_exit_observed", journey.Source, null, transition: true)) { TameTravelDiagnostics diagnostics2 = _diagnostics; ZNetPeer peer2 = journey.Peer; ZDOID? source2 = journey.Source; (string, object)[] verboseFields = new(string, object)[1] { ("pos", p) }; (string, object)[] fields = ((!_diagnostics.VerboseAfterNormalEnabled) ? null : new(string, object)[2] { ("expected_exit", journey.Exit), ("entry_age_s", observedAt - journey.Entered) }); diagnostics2.Traversal(peer2, "arrival", "linked_exit_observed", source2, null, verboseFields, transition: true, ready: true, fields); } } } return; } string text2 = TameTravelTraversalRules.DestinationRejection(((Vector3)(ref val)).sqrMagnitude, now - journey.Entered, _settings.TravelWindowSeconds.Value, journey.Moved > 0); if (text2 != null) { Cancel(sample, now, text2, p); return; } if (!journey.Ready && now - journey.PathWarmed >= 1f && ZoneSystem.instance.IsZoneLoaded(journey.Exit)) { journey.PathWarmed = now; _placement.WarmAccess(p, journey.Exit); } if (journey.Ready || now - journey.Arrived < 2f || now - journey.Entered < 8f || !PlayerWorldScope.Finite(journey.Peer.m_refPos)) { return; } val3 = journey.Peer.m_refPos - p; if (((Vector3)(ref val3)).sqrMagnitude > 16f) { return; } if (journey.Barrier == 0f) { journey.Barrier = _authority.SendBarrier(journey.Peer, null, now); } else if (_authority.Echoed(journey.Barrier)) { journey.Ready = true; if (_diagnostics.SelectionEnabled) { _diagnostics.Traversal(journey.Peer, "destination", "readiness_confirmed", journey.Source, null, null, transition: true); } } } private void UpdateTransfer(AnimalTransfer t, float now) { //IL_00ec: Unknown result type (might be due to invalid IL or missing references) //IL_0095: Unknown result type (might be due to invalid IL or missing references) //IL_00a0: Unknown result type (might be due to invalid IL or missing references) //IL_00a5: Unknown result type (might be due to invalid IL or missing references) //IL_00aa: Unknown result type (might be due to invalid IL or missing references) //IL_0104: Unknown result type (might be due to invalid IL or missing references) //IL_010a: Unknown result type (might be due to invalid IL or missing references) //IL_014f: Unknown result type (might be due to invalid IL or missing references) //IL_0165: Unknown result type (might be due to invalid IL or missing references) //IL_02b9: Unknown result type (might be due to invalid IL or missing references) //IL_02bf: Unknown result type (might be due to invalid IL or missing references) //IL_02c4: Unknown result type (might be due to invalid IL or missing references) //IL_02c9: Unknown result type (might be due to invalid IL or missing references) //IL_0569: Unknown result type (might be due to invalid IL or missing references) //IL_0571: Unknown result type (might be due to invalid IL or missing references) //IL_0573: Unknown result type (might be due to invalid IL or missing references) //IL_05a6: Unknown result type (might be due to invalid IL or missing references) //IL_0307: Unknown result type (might be due to invalid IL or missing references) //IL_0312: Unknown result type (might be due to invalid IL or missing references) //IL_039c: Unknown result type (might be due to invalid IL or missing references) //IL_03a7: Unknown result type (might be due to invalid IL or missing references) //IL_03e3: Unknown result type (might be due to invalid IL or missing references) //IL_03ee: Unknown result type (might be due to invalid IL or missing references) //IL_0410: Unknown result type (might be due to invalid IL or missing references) //IL_042a: Unknown result type (might be due to invalid IL or missing references) //IL_04ab: Unknown result type (might be due to invalid IL or missing references) PlayerSample value; PlayerSample obj = (_samples.TryGetValue(t.Journey.Peer.m_uid, out value) ? value : null); string text = null; ZDO actor; Vector3 val; if (obj?.Journey != t.Journey) { text = "journey_changed"; } else if (!_rules.Actor(t.Journey.Peer, out actor)) { text = "traveller_unavailable"; } else if (!Pair(t.Journey)) { text = "portal_pair_changed"; } else { if (t.Journey.Arrived >= 0f) { val = actor.GetPosition() - t.Journey.Exit; string text2 = TameTravelTraversalRules.DestinationRejection(((Vector3)(ref val)).sqrMagnitude, now - t.Journey.Entered, _settings.TravelWindowSeconds.Value, t.Moved); if (text2 != null) { text = text2; goto IL_01e0; } } if (ZDOMan.instance.GetZDO(t.Id) != t.Record || t.Record.m_uid != t.Id) { text = "animal_record_replaced"; } else { string text3 = _rules.AnimalRejection(t.Record); if (text3 != null) { text = text3; } else if (!t.Waiting && !_commands.FollowingAuthorized(t.Id, t.Journey.Peer, t.Journey.Character, t.Journey.Name)) { text = "follow_authorization_ended"; } else if (!TameTravelCommandRules.ConsentValid(t.Waiting ? TameOrder.Wait : TameOrder.Follow, t.Record.GetString(ZDOVars.s_follow, ""), t.Journey.Name)) { text = "follow_changed"; } else if (TameTravelTraversalRules.PhaseExpired(t.Phase, t.PlacementStarted, now - t.PhaseTime)) { text = "phase_timeout"; } } } goto IL_01e0; IL_01e0: if (text != null) { FinishTransfer(t, confirmed: false, text); return; } if (t.Phase == 0) { if (t.PreviousPeer == null || !t.PreviousPeer.IsReady()) { FinishTransfer(t, confirmed: false, "source_owner_unavailable"); return; } if (!_authority.Echoed(t.Barrier)) { return; } if (!t.SourceStateObserved) { if (t.SourceEchoTime == 0f) { t.SourceEchoTime = now; } if (now - t.SourceEchoTime >= 2f) { _authority.RequestSourceState(t, now); } return; } t.Phase = 1; t.PhaseTime = now; } if (t.Phase == 1) { if (!t.Journey.Ready) { return; } if (!t.PlacementStarted) { t.PlacementStarted = true; t.PhaseTime = now; } if (_placementUsed) { return; } _placementUsed = true; val = t.Record.GetPosition() - t.Source; Vector3 position; if (((Vector3)(ref val)).sqrMagnitude > 144f) { if (_diagnostics.SelectionEnabled) { _diagnostics.Traversal(t.Journey.Peer, "placement", "animal_moved_from_drain_source", t.Journey.Source, t.Id); } } else if (!_placement.Find(t, _transfers.Values, _players.Presence.Peers, now, _settings.DebugLogging.Enabled, out position)) { if (_diagnostics.SelectionEnabled && _diagnostics.TraversalReady(t.Journey.Peer, "placement", _placement.WaitReason, t.Journey.Source, t.Id)) { TameTravelDiagnostics diagnostics = _diagnostics; ZNetPeer peer = t.Journey.Peer; string waitReason = _placement.WaitReason; ZDOID? source = t.Journey.Source; ZDOID? animal = t.Id; (string, object)[] array = new(string, object)[1]; ZDO zDO = ZDOMan.instance.GetZDO(t.Journey.Character); array[0] = ("pos", (zDO != null) ? new Vector3?(zDO.GetPosition()) : ((Vector3?)null)); diagnostics.Traversal(peer, "placement", waitReason, source, animal, array, transition: false, ready: true, (!_diagnostics.VerboseAfterNormalEnabled) ? null : new(string, object)[9] { ("blocking_object", _placement.BlockingObject), ("phase_age_s", now - t.PhaseTime), ("expected_exit", t.Journey.Exit), ("search_cursor", t.PlacementCursor), ("candidates", t.PlacementCandidates), ("rejections", TameTravelDiagnostics.PlacementReasons(t)), ("walkout_rejections", TameTravelDiagnostics.Reasons(t.PlacementWalkoutRejections)), ("surface_blocks", TameTravelDiagnostics.Reasons(t.PlacementSurfaceBlocks)), ("overlap_hits", TameTravelDiagnostics.Reasons(t.PlacementOverlapHits)) }); } } else { TameTravelPlacement.Move(t, position); t.Placement = position; t.Moved = true; t.Journey.Moved++; t.Phase = 2; t.PhaseTime = now; ZDOMan.instance.ForceSendZDO(t.Id); t.Barrier = _authority.SendBarrier(t.Journey.Peer, t.Record, now); } } else if (t.Phase == 2 && _authority.Echoed(t.Barrier) && now - t.PhaseTime >= 0.5f) { _authority.Handoff(t); t.PhaseTime = now; t.NextDestinationSend = now + 2f; } else { if (t.Phase == 3 && !t.OwnerObserved) { _authority.RefreshDestination(t, now); } if (t.Phase == 3 && t.OwnerObserved) { t.Phase = 4; t.PhaseTime = now; } else if (t.Phase == 4 && now - t.PhaseTime >= 2f) { FinishTransfer(t, confirmed: true); } } } private void FinishTransfer(AnimalTransfer t, bool confirmed, string reason = "journey_cancelled") { //IL_0210: 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_0234: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_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_025e: Unknown result type (might be due to invalid IL or missing references) //IL_0274: Unknown result type (might be due to invalid IL or missing references) //IL_00fd: Unknown result type (might be due to invalid IL or missing references) TransferSnapshot snapshot = null; if (_settings.DebugLogging.Enabled) { ZDOMan instance = ZDOMan.instance; bool flag = instance != null && instance.GetZDO(t.Id) == t.Record && t.Record.m_uid == t.Id && t.Record.IsValid(); float value = default(float); float num = default(float); snapshot = new TransferSnapshot { Reason = (confirmed ? "destination_owner_confirmed" : reason), SameRecord = flag, Owner = (flag ? new long?(t.Record.GetOwner()) : ((long?)null)), DataRevision = (flag ? new uint?(t.Record.DataRevision) : ((uint?)null)), OwnerRevision = (flag ? new ushort?(t.Record.OwnerRevision) : ((ushort?)null)), Position = (flag ? new Vector3?(t.Record.GetPosition()) : ((Vector3?)null)), Follow = (flag ? t.Record.GetString(ZDOVars.s_follow, "") : null), Health = ((flag && t.Record.GetFloat(ZDOVars.s_health, ref value)) ? new float?(value) : ((float?)null)), HealthSaved = (flag ? new bool?(t.Record.GetFloat(ZDOVars.s_health, ref num)) : ((bool?)null)), Tamed = (flag ? new bool?(t.Record.GetBool(ZDOVars.s_tamed, false)) : ((bool?)null)), Rider = (flag ? new long?(t.Record.GetLong(ZDOVars.s_user, 0L)) : ((long?)null)), PhaseAge = Time.unscaledTime - t.PhaseTime, BarrierEchoed = _authority.Echoed(t.Barrier) }; } _transfers.Remove(t.Id); _reserved.Remove(t.Id); _authority.Release(t.Id, keepServerOwner: false, t.Moved && !confirmed); t.FollowContinues = !t.Waiting && _commands.FollowingAuthorized(t.Id, t.Journey.Peer, t.Journey.Character, t.Journey.Name); if (!confirmed) { t.Journey.EndReason = reason; } if (confirmed) { t.Journey.Confirmed++; if (t.FollowContinues) { _following.Command(t.Journey.Peer, t.Record, TameOrder.Follow); } } _diagnostics.Transfer(t, confirmed, snapshot); } private void Complete(PlayerSample sample, float now, string? reason = null) { //IL_002e: 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_0033: 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) PortalJourney journey = sample.Journey; sample.Journey = null; sample.BlockedUntil = now + 3f; sample.ReentryPortal = ((journey.Moved > 0) ? journey.Destination : journey.Source); if (journey.Moved == 0) { if (reason == null) { reason = journey.EndReason ?? "no_animal_transfer_completed"; } if (_diagnostics.SelectionEnabled) { _diagnostics.Traversal(journey.Peer, "journey_ended", reason, journey.Source, null, null, transition: true); } DiagnosticLog.Write(_log, "TameTravel", "Portal travel for " + journey.Name + " ended before relocation.", (LogLevel)16); TameTravelCommands.Feedback(journey.Peer, TameTravelTraversalRules.CancellationMessage(reason) + " Following animals keep their permission; optional portal waits need a fresh command."); } else { DiagnosticLog.Write(_log, "TameTravel", (journey.Moved == journey.Confirmed) ? $"Moved {journey.Confirmed} follower(s) for {journey.Name}; destination ownership resumed." : $"Relocated {journey.Moved} follower(s) for {journey.Name}; destination ownership confirmed for {journey.Confirmed}.", (LogLevel)16); TameTravelCommands.Feedback(journey.Peer, (journey.Moved == journey.Confirmed) ? $"Portal arrival confirmed for {journey.Confirmed} animal(s)." : "Animal relocation was recorded but destination ownership was not fully confirmed; check the destination before retrying."); } } private void Cancel(PlayerSample sample, float now, string reason = "session_or_competing_teleport", Vector3? position = null) { //IL_0044: Unknown result type (might be due to invalid IL or missing references) //IL_0049: Unknown result type (might be due to invalid IL or missing references) //IL_0050: Unknown result type (might be due to invalid IL or missing references) sample.PendingPortal = null; PortalJourney journey = sample.Journey; if (journey == null) { sample.BlockedUntil = now + 3f; return; } _diagnostics.Cancel(journey, reason, position, now); foreach (ZDOID follower in journey.Followers) { _reserved.Remove(follower); } journey.Followers.Clear(); _cancelTransfers.Clear(); foreach (AnimalTransfer value in _transfers.Values) { if (value.Journey == journey) { _cancelTransfers.Add(value); } } foreach (AnimalTransfer cancelTransfer in _cancelTransfers) { FinishTransfer(cancelTransfer, confirmed: false, reason); } Complete(sample, now, reason); } private void ClearJourneys() { foreach (PlayerSample value in _samples.Values) { Cancel(value, Time.unscaledTime); } } private void Observe(ZRpc rpc, ZPackage packet) { //IL_00f6: Unknown result type (might be due to invalid IL or missing references) //IL_00fb: Unknown result type (might be due to invalid IL or missing references) //IL_0204: Unknown result type (might be due to invalid IL or missing references) if (_disposed) { return; } ZNetPeer val = PlayerPeerLookup.Ready(_players.Presence.Peers, rpc); if (val == null || !RoutedActivityReader.TryRead(packet, val.m_uid, out var target, out var method) || (method != PongMethod && method != TeleportMethod && method != TeleportPlayerMethod && method != CommandMethod && method != SayMethod && method != ChatMethod) || !RoutedActivityReader.TryReadParameters(packet, val.m_uid, out target, out method, out ZPackage parameters) || parameters == null) { return; } float unscaledTime = Time.unscaledTime; if (method == PongMethod && ((ZDOID)(ref target)).IsNone()) { float nonce = parameters.ReadSingle(); if (parameters.GetPos() == parameters.Size()) { _authority.ObservePong(val, nonce); } return; } if (method == TeleportMethod || method == TeleportPlayerMethod) { RoutedRPCData val2 = ZdoPackets.ReadRouted(packet); { foreach (PlayerSample value2 in _samples.Values) { if (value2.Character == target || (((ZDOID)(ref target)).IsNone() && (val2.m_targetPeerID == 0L || val2.m_targetPeerID == value2.Peer.m_uid))) { Cancel(value2, unscaledTime); } } return; } } if (method != CommandMethod && method != SayMethod && method != ChatMethod) { return; } RoutedRPCData val3 = ZdoPackets.ReadRouted(packet); (long, long) key = (val.m_uid, val3.m_msgID); if (_messagesSeen.ContainsKey(key) || _messagesSeen.Count >= 1024) { return; } _messagesSeen.Add(key, unscaledTime); if (!_samples.TryGetValue(val.m_uid, out PlayerSample value) || value.Peer != val || unscaledTime - value.CommandTime < 1f) { return; } value.CommandTime = unscaledTime; try { _commands.Observe(val, target, method, parameters, unscaledTime); } catch (EndOfStreamException) { } } private static void CompetingTeleport(Player __instance) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Unknown result type (might be due to invalid IL or missing references) TameTravelController current = _current; if (current == null) { return; } ZDOID zDOID = ((Character)__instance).GetZDOID(); foreach (PlayerSample value in current._samples.Values) { if (value.Character == zDOID) { current.Cancel(value, Time.unscaledTime); } } } private static void AdministrativeTeleport(long targetPeerID) { TameTravelController current = _current; if (current != null) { PlayerSample value; if (targetPeerID == 0L) { current.ClearJourneys(); } else if (current._samples.TryGetValue(targetPeerID, out value)) { current.Cancel(value, Time.unscaledTime); } } } private static void BeforePlayerData(ZRpc rpc, out (ZNetPeer? Peer, ZDO? Actor, uint Revision, int Emote) __state) { //IL_0047: Unknown result type (might be due to invalid IL or missing references) __state = default((ZNetPeer, ZDO, uint, int)); TameTravelController current = _current; if (current == null || current._disposed) { return; } try { ZNetPeer val = PlayerPeerLookup.Ready(current._players.Presence.Peers, rpc); if (val != null && !((ZDOID)(ref val.m_characterID)).IsNone()) { ZDO zDO = ZDOMan.instance.GetZDO(val.m_characterID); if (zDO != null && zDO.IsValid() && zDO.GetOwner() == val.m_uid) { __state = (Peer: val, Actor: zDO, Revision: zDO.DataRevision, Emote: zDO.GetInt(ZDOVars.s_emoteID, 0)); } } } catch (Exception obj) { current._fail(obj); } } private static void AfterPlayerData((ZNetPeer? Peer, ZDO? Actor, uint Revision, int Emote) __state) { TameTravelController current = _current; if (current == null || current._disposed) { return; } try { current.PlayerDataApplied(__state); } catch (Exception obj) { current._fail(obj); } } private void PlayerDataApplied((ZNetPeer? Peer, ZDO? Actor, uint Revision, int Emote) state) { //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_0051: Unknown result type (might be due to invalid IL or missing references) //IL_0139: 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_0247: Unknown result type (might be due to invalid IL or missing references) //IL_0266: Unknown result type (might be due to invalid IL or missing references) //IL_026b: Unknown result type (might be due to invalid IL or missing references) //IL_01f6: 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) var (val, val2, _, _) = state; if (val == null || val2 == null || !val2.IsValid() || val2.DataRevision <= state.Revision || val2.m_uid != val.m_characterID || val2.GetOwner() != val.m_uid || ZDOMan.instance.GetZDO(val.m_characterID) != val2) { return; } int num = val2.GetInt(ZDOVars.s_emoteID, 0); string text = val2.GetString(ZDOVars.s_emote, ""); TameOrder order; bool flag = TameTravelCommandRules.Emote(text, out order); if (num != state.Emote && flag) { _diagnostics.Command(val, "emote_applied", text, null, num); } ZDO actor; string text2 = _rules.ActorRejection(val, out actor); _diagnostics.ActorGate(val, text2); if (text2 != null || val2 != actor) { if (num != state.Emote && flag) { _diagnostics.Command(val, "rejected", text, text2, num); } return; } if (!_samples.TryGetValue(val.m_uid, out PlayerSample value) || value.Peer != val || value.Character != val.m_characterID) { if (num != state.Emote && flag) { _diagnostics.Command(val, "rejected", text, "player_sample_unavailable", num); } return; } if (!value.PlayerDataObserved) { value.PlayerDataObserved = true; _diagnostics.Command(val, "player_data_applied", text, null, num); } bool flag2 = value.Journey != null; if (!flag2) { foreach (FollowBinding value2 in _commands.Bindings.Values) { if (value2.Peer == val && value2.Character == value.Character) { flag2 = true; break; } } } if (flag2 || (num > value.Emote && TameTravelCommandRules.Emote(text, out order))) { value.Positions.Add(new PositionObservation(val2.GetPosition(), Time.unscaledTime, val2.DataRevision)); } else { value.Position = val2.GetPosition(); value.Time = Time.unscaledTime; } if (num <= value.Emote) { return; } value.Emote = num; float unscaledTime = Time.unscaledTime; if (TameTravelCommandRules.Emote(text, out var order2)) { if (unscaledTime - value.CommandTime < 1f) { _diagnostics.Command(val, "rejected", text, "command_rate_limited", num); return; } value.CommandTime = unscaledTime; _commands.Request(val, order2, unscaledTime); } } public void Dispose() { if (_disposed) { return; } _disposed = true; List list = new List(); Action[] array = new Action[8] { delegate { _messages.Dispose(); }, delegate { _hooks.UnpatchSelf(); }, ClearJourneys, delegate { _commands.ClearForShutdown(); }, delegate { _stops.ClearPendingForShutdown(); }, delegate { _following.Dispose(); }, delegate { _authority.Dispose(); }, delegate { _placement.Dispose(); } }; foreach (Action action in array) { try { action(); } catch (Exception item) { list.Add(item); } } if (_current == this) { _current = null; } _samples.Clear(); _commands.Bindings.Clear(); _reserved.Clear(); _messagesSeen.Clear(); _transfers.Clear(); if (list.Count <= 0) { return; } throw new AggregateException("TameTravel cleanup failed.", list); } } internal sealed class TameTravelDiagnostics : FeatureDiagnostics { private readonly ManualLogSource _log; private readonly ProcessingTiming _timing; private readonly DebugLoggingPolicy _policy; private readonly Func _clock; private readonly DiagnosticBudget _commands = new DiagnosticBudget(); private readonly DiagnosticBudget _selection = new DiagnosticBudget(); private readonly DiagnosticBudget _traversal = new DiagnosticBudget(); private readonly Dictionary _sourcePollTimes = new Dictionary(); private readonly Dictionary<(long Peer, string Stage, ZDOID Source, ZDOID Animal), (string Reason, float Time)> _gates = new Dictionary<(long, string, ZDOID, ZDOID), (string, float)>(); private readonly Dictionary _actorReasons = new Dictionary(); private readonly ScheduleToken _next = new ScheduleToken(); private int _samples; private int _followCalls; private double _followTotal; private double _followMaximum; private readonly ScheduleToken _followNext = new ScheduleToken(); private (int Bindings, int Reserved, int Transfers) _last; public bool SelectionEnabled => base.DiagnosticsEnabled; public IDisposable Measure(float now, Func scope) { return _timing.Measure(now, scope); } public TameTravelDiagnostics(ManualLogSource log, DebugLoggingPolicy policy, Func? clock = null) { _log = log; _policy = policy; ConfigureDiagnostics(() => policy.Enabled, log, "TameTravel"); _timing = new ProcessingTiming(log, "TameTravel", policy); _clock = clock ?? ((Func)(() => Time.unscaledTime)); } private bool Sample() { if (!base.DiagnosticsEnabled) { return false; } float now = _clock(); if (_next.Ready(now)) { _next.Postpone(now, 60f); _samples = 0; } return _samples++ < 2; } private bool TravelSample(string stream = "traversal") { if (base.DiagnosticsEnabled) { return _traversal.Reserve(_clock(), stream, 6); } return false; } public bool TraversalReady(ZNetPeer peer, string stage, string reason, ZDOID? source = null, ZDOID? animal = null, bool transition = false) { //IL_00a3: Unknown result type (might be due to invalid IL or missing references) //IL_009a: Unknown result type (might be due to invalid IL or missing references) //IL_00be: Unknown result type (might be due to invalid IL or missing references) //IL_00b5: Unknown result type (might be due to invalid IL or missing references) if (!base.DiagnosticsEnabled) { return false; } bool flag = ((stage == "source_entry" || stage == "source_observation") ? true : false); bool flag2 = flag; if (flag2) { bool flag3; switch (reason) { case "outside_trigger": case "no_portal_nearby": case "awaiting_owner_position": case "source_sample_gap": case "cooldown": flag3 = true; break; default: flag3 = false; break; } flag2 = flag3; } bool flag4 = flag2; (long, string, ZDOID, ZDOID) key = (peer.m_uid, stage, (ZDOID)(((??)source) ?? ZDOID.None), (ZDOID)(((??)animal) ?? ZDOID.None)); float num = _clock(); if (flag4 && _sourcePollTimes.TryGetValue(peer, out var value) && num >= value && num - value < 60f) { return false; } if (!transition && _gates.TryGetValue(key, out (string, float) value2) && value2.Item1 == reason && num >= value2.Item2 && num - value2.Item2 < 300f) { return false; } if (flag4) { if (_sourcePollTimes.Count >= 64 && !_sourcePollTimes.ContainsKey(peer)) { _sourcePollTimes.Clear(); } _sourcePollTimes[peer] = num; if (!_traversal.Reserve(num, "source_poll", 2)) { return false; } } else if (!TravelSample((stage == "placement") ? "placement_waits" : "traversal")) { return false; } if (!transition) { if (_gates.Count >= 256 && !_gates.ContainsKey(key)) { _gates.Clear(); } _gates[key] = (reason, num); } return true; } public void Traversal(ZNetPeer peer, string stage, string reason, ZDOID? source = null, ZDOID? animal = null, (string, object?)[]? fields = null, bool transition = false, bool ready = false, (string, object?)[]? verboseFields = null) { if (ready || TraversalReady(peer, stage, reason, source, animal, transition)) { string message = ((reason == "no_portal_nearby") ? ("No portal near " + peer.m_playerName + "; travel not started.") : ("Portal travel for " + peer.m_playerName + ": " + Reason(reason) + ".")); DiagnosticLog.Write(_log, "TameTravel", TameTravelLogTopics.Travel, message, new(string, object)[7] { ("pos", Evidence(fields, "pos")), ("followers", Evidence(fields, "followers")), ("stage", stage), ("peer", peer.m_uid), ("source", source), ("animal", animal), ("omitted", _traversal.TakeOmitted()) }, (LogLevel)32); if (base.VerboseEnabled && (verboseFields != null || fields != null)) { DiagnosticLog.Write(_log, "TameTravel", TameTravelLogTopics.Travel, "Travel evidence for " + peer.m_playerName + ".", verboseFields ?? fields, (LogLevel)32, verbose: true); } } } private static object? Evidence((string Key, object? Value)[]? fields, string key) { if (fields != null) { for (int i = 0; i < fields.Length; i++) { (string, object) tuple = fields[i]; if (tuple.Item1 == key) { return tuple.Item2; } } } return null; } private static string Reason(string? reason) { if (!(reason == "character_missing")) { if (!(reason == "destination_owner_confirmed")) { if (reason == null || (reason != null && reason.Length == 0) || reason == "unknown") { return "outcome unavailable"; } return reason.Replace('_', ' '); } return "destination owner confirmed"; } return "character not spawned yet"; } public void PortalPair(ZNetPeer peer, ZDO source, ZDO? destination, string reason) { //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_0199: Unknown result type (might be due to invalid IL or missing references) //IL_004b: 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_00ad: 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_015e: Unknown result type (might be due to invalid IL or missing references) //IL_0164: Unknown result type (might be due to invalid IL or missing references) if (TraversalReady(peer, "portal_pair", reason, source.m_uid)) { (string, object)[] array = null; if (base.VerboseAfterNormalEnabled) { TameTravelRules.Scale(source, out var scale); array = new(string, object)[8] { ("source_target", source.GetConnectionZDOID((ConnectionType)1)), ("source_tag", source.GetString(ZDOVars.s_tag, "")), ("source_scale", scale), ("destination", destination?.m_uid), ("destination_target", (destination != null) ? new ZDOID?(destination.GetConnectionZDOID((ConnectionType)1)) : ((ZDOID?)null)), ("destination_tag", (destination != null) ? destination.GetString(ZDOVars.s_tag, "") : null), ("destination_creator", (destination != null) ? new long?(destination.GetLong(ZDOVars.s_creator, 0L)) : ((long?)null)), ("separation_m", (destination == null) ? ((float?)null) : new float?(Vector3.Distance(source.GetPosition(), destination.GetPosition()))) }; } ZDOID? source2 = source.m_uid; (string, object)[] verboseFields = array; Traversal(peer, "portal_pair", reason, source2, null, null, transition: false, ready: true, verboseFields); } } public void Command(ZNetPeer peer, string stage, string? command, string? reason = null, int? counter = null, ZDOID? animal = null) { //IL_0074: Unknown result type (might be due to invalid IL or missing references) if (base.DiagnosticsEnabled && _commands.Reserve(_clock(), "commands", 32)) { string message = CommandMessage(peer.m_playerName, stage, command, reason); DiagnosticLog.Write(_log, "TameTravel", TameTravelLogTopics.Command, message, new(string, object)[7] { ("peer", peer.m_uid), ("character", peer.m_characterID), ("stage", stage), ("command", command), ("reason", reason), ("emote_counter", counter), ("animal", animal) }, (LogLevel)32); } } internal static string CommandMessage(string player, string stage, string? command, string? reason) { switch (stage) { case "player_data_applied": return "Observed fresh player data for " + player + "."; case "stop_queued": case "reclaim_queued": return "Queued " + player + "'s " + (command ?? "animal") + " command — " + Reason(reason ?? "pending") + "."; case "actor_gate": if (!(reason == "ready")) { return "Animal commands unavailable for " + player + " — " + Reason(reason ?? "unknown") + "."; } return player + "'s character is ready for animal commands."; default: if (reason != null) { return "Ignored " + player + "'s command — " + Reason(reason) + "."; } return "Received " + player + "'s " + (string.IsNullOrEmpty(command) ? "animal" : command) + " command."; } } public void ActorGate(ZNetPeer peer, string? reason) { if (base.DiagnosticsEnabled && (!_actorReasons.TryGetValue(peer.m_uid, out string value) || !(value == reason)) && (_actorReasons.Count < 64 || _actorReasons.ContainsKey(peer.m_uid))) { _actorReasons[peer.m_uid] = reason; Command(peer, "actor_gate", null, reason ?? "ready"); } } public void Selection(ZNetPeer peer, TameOrder order, int records, int supported, int eligible) { if (base.DiagnosticsEnabled && _selection.Reserve(_clock(), "selection", 8)) { DiagnosticLog.Write(_log, "TameTravel", TameTravelLogTopics.Command, $"Found {eligible} eligible animals for {peer.m_playerName}'s {order} command this pass.", new(string, object)[5] { ("peer", peer.m_uid), ("command", order), ("records", records), ("supported", supported), ("eligible", eligible) }, (LogLevel)32); } } public void Candidate(ZNetPeer peer, TameOrder order, ZDO animal, float distance, float range, string reason) { //IL_004c: 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_017e: Unknown result type (might be due to invalid IL or missing references) if (base.DiagnosticsEnabled && _selection.Reserve(_clock(), "selection", 8)) { float value = default(float); bool flag = animal.GetFloat(ZDOVars.s_health, ref value); DiagnosticLog.Write(_log, "TameTravel", TameTravelLogTopics.Command, $"Animal {animal.m_uid} for {peer.m_playerName}: {Reason(reason)}.", new(string, object)[8] { ("peer", peer.m_uid), ("command", order), ("animal", animal.m_uid), ("prefab", animal.GetPrefab()), ("distance_m", distance), ("range_m", range), ("health", flag ? new float?(value) : ((float?)null)), ("owner", animal.GetOwner()) }, (LogLevel)32); if (base.VerboseEnabled) { DiagnosticLog.Write(_log, "TameTravel", TameTravelLogTopics.Command, $"Selection evidence for animal {animal.m_uid}.", new LogField[3] { DiagnosticLog.FieldAlways("health_saved", flag), DiagnosticLog.FieldAlways("tamed", animal.GetBool(ZDOVars.s_tamed, false)), (Key: "following", Value: animal.GetString(ZDOVars.s_follow, "")) }, (LogLevel)32, verbose: true); } } } public void Entry(PortalJourney j, string mode = "owner_position_history") { //IL_0035: 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_0091: Unknown result type (might be due to invalid IL or missing references) if (TravelSample()) { DiagnosticLog.Write(_log, "TameTravel", TameTravelLogTopics.Travel, string.Format("{0} entered portal {1} → {2} with {3} {4}.", j.Name, j.Source, j.Destination, j.Followers.Count, (j.Followers.Count == 1) ? "follower" : "followers"), new(string, object)[2] { ("exit", j.Exit), ("mode", (mode == "owner_position_history") ? "position_history" : mode) }, (LogLevel)32); } } public void Transfer(AnimalTransfer t, bool confirmed, TransferSnapshot? snapshot) { //IL_0046: Unknown result type (might be due to invalid IL or missing references) //IL_0101: Unknown result type (might be due to invalid IL or missing references) //IL_0106: Unknown result type (might be due to invalid IL or missing references) //IL_010b: Unknown result type (might be due to invalid IL or missing references) //IL_0110: 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_0124: Unknown result type (might be due to invalid IL or missing references) //IL_0127: Unknown result type (might be due to invalid IL or missing references) //IL_0132: Unknown result type (might be due to invalid IL or missing references) //IL_013f: Unknown result type (might be due to invalid IL or missing references) //IL_014a: Unknown result type (might be due to invalid IL or missing references) //IL_014f: Unknown result type (might be due to invalid IL or missing references) //IL_0154: 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_0182: 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_016f: Unknown result type (might be due to invalid IL or missing references) //IL_018c: Unknown result type (might be due to invalid IL or missing references) //IL_01b0: Unknown result type (might be due to invalid IL or missing references) //IL_0384: Unknown result type (might be due to invalid IL or missing references) //IL_03b9: Unknown result type (might be due to invalid IL or missing references) //IL_03ba: Unknown result type (might be due to invalid IL or missing references) //IL_03f0: Unknown result type (might be due to invalid IL or missing references) //IL_03f1: Unknown result type (might be due to invalid IL or missing references) //IL_0445: Unknown result type (might be due to invalid IL or missing references) //IL_0447: Unknown result type (might be due to invalid IL or missing references) //IL_046f: Unknown result type (might be due to invalid IL or missing references) //IL_0471: Unknown result type (might be due to invalid IL or missing references) if (base.DiagnosticsEnabled && _traversal.Reserve(_clock(), "transfer_end", 8)) { DiagnosticLog.Write(_log, "TameTravel", TameTravelLogTopics.Travel, string.Format("Transfer of animal {0} for {1} {2} — {3} after {4} placement attempts ({5} candidates).", t.Id, t.Journey.Name, confirmed ? "finished" : "ended", Reason(snapshot?.Reason), t.PlacementAttempts, t.PlacementCandidates), new(string, object)[2] { ("search_ms", t.PlacementSearchMilliseconds), ("context_ms", t.PlacementContextMilliseconds) }, (LogLevel)32); if (base.VerboseEnabled) { Vector3 val = t.Journey.DestinationRotation * Vector3.forward; val.y = 0f; val = ((Vector3)(ref val)).normalized; Vector3 val2 = default(Vector3); ((Vector3)(ref val2))..ctor(val.z, 0f, 0f - val.x); Vector3 val3 = t.Placement - t.Journey.DestinationPosition; bool flag = t.Moved && t.PlacementTraveller.HasValue; Vector3 val4 = (flag ? (t.Placement - t.PlacementTraveller.Value) : Vector3.zero); val4.y = 0f; DiagnosticLog.Write(_log, "TameTravel", TameTravelLogTopics.Travel, $"Transfer evidence for animal {t.Id}.", new(string, object)[34] { ("phase", t.Phase), ("moved", t.Moved), ("owner_observed", confirmed), ("reason", snapshot?.Reason), ("source_state_observed", t.SourceStateObserved), ("previous_owner", t.PreviousOwner), ("destination_retries", t.DestinationRetries), ("follow_continues", t.FollowContinues), ("rejections", PlacementReasons(t)), ("walkout_rejections", Reasons(t.PlacementWalkoutRejections)), ("wait_reasons", Reasons(t.PlacementWaitReasons)), ("surface_blocks", Reasons(t.PlacementSurfaceBlocks)), ("overlap_hits", Reasons(t.PlacementOverlapHits)), ("last_probe", t.PlacementLastProbe), ("support_y_m", t.PlacementSupportHeight), ("pos", t.Moved ? new Vector3?(t.Placement) : ((Vector3?)null)), ("forward_m", t.Moved ? new float?(Vector3.Dot(val3, val)) : ((float?)null)), ("side_m", t.Moved ? new float?(Vector3.Dot(val3, val2)) : ((float?)null)), ("traveller_pos", flag ? t.PlacementTraveller : ((Vector3?)null)), ("traveller_forward_m", flag ? DiagnosticLog.Kept(Vector3.Dot(val4, val)) : null), ("traveller_side_m", flag ? DiagnosticLog.Kept(Vector3.Dot(val4, val2)) : null), ("traveller_distance_m", flag ? new float?(((Vector3)(ref val4)).magnitude) : ((float?)null)), ("same_record", snapshot?.SameRecord), ("owner", snapshot?.Owner), ("data_rev", snapshot?.DataRevision), ("owner_rev", snapshot?.OwnerRevision), ("position_before_release", snapshot?.Position), ("follow", snapshot?.Follow), ("health", snapshot?.Health), ("health_saved", snapshot?.HealthSaved), ("tamed", snapshot?.Tamed), ("rider", snapshot?.Rider), ("phase_age_s", snapshot?.PhaseAge), ("barrier_echoed", snapshot?.BarrierEchoed) }, (LogLevel)32, verbose: true); } } } internal static string PlacementReasons(AnimalTransfer t) { return Reasons(t.PlacementRejections); } internal static string Reasons(Dictionary counts) { return string.Join(",", from p in counts orderby p.Key select p.Key + ":" + p.Value); } public void Cancel(PortalJourney j, string reason, Vector3? position = null, float? now = null) { //IL_0061: 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_00b0: Unknown result type (might be due to invalid IL or missing references) //IL_00e1: Unknown result type (might be due to invalid IL or missing references) //IL_00e7: Unknown result type (might be due to invalid IL or missing references) //IL_00ec: Unknown result type (might be due to invalid IL or missing references) //IL_00f1: Unknown result type (might be due to invalid IL or missing references) if (TravelSample()) { ManualLogSource log = _log; LogTopic travel = TameTravelLogTopics.Travel; string message = "Cancelled portal travel for " + j.Name + " — " + Reason(reason) + "."; (string, object)[] obj = new(string, object)[8] { ("source", j.Source), ("destination", j.Destination), ("pos", position), ("exit", j.Exit), default((string, object)), default((string, object)), default((string, object)), default((string, object)) }; float? obj2; if (!position.HasValue) { obj2 = null; } else { Vector3 val = position.Value - j.Exit; obj2 = ((Vector3)(ref val)).magnitude; } obj[4] = ("distance_m", obj2); obj[5] = ("maximum_m", TameTravelTraversalRules.DestinationLimit(j.Moved > 0)); obj[6] = ("entry_age_s", now - j.Entered); obj[7] = ("arrival_age_s", (!(j.Arrived >= 0f)) ? ((float?)null) : (now - j.Arrived)); DiagnosticLog.Write(log, "TameTravel", travel, message, obj, (LogLevel)32); } } public void Following(AnimalTransfer t, string state, float distance, float stop, float resume) { //IL_0059: Unknown result type (might be due to invalid IL or missing references) //IL_007c: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Unknown result type (might be due to invalid IL or missing references) if (Sample()) { bool flag = t.Record != null && t.Record.IsValid() && t.Record.m_uid == t.Id; DiagnosticLog.Write(_log, "TameTravel", TameTravelLogTopics.Follow, $"Follow spacing for {t.Journey.Name}'s animal {t.Id}: {Reason(state)}.", new(string, object)[8] { ("animal", t.Id), ("phase", t.Phase), ("distance_m", distance), ("stop_m", stop), ("resume_m", resume), ("owner", flag ? new long?(t.Record.GetOwner()) : ((long?)null)), ("previous_owner", t.PreviousOwner), ("source_state_observed", t.SourceStateObserved) }, (LogLevel)32); } } public void FollowingEnded(AnimalTransfer t, string reason) { //IL_005e: Unknown result type (might be due to invalid IL or missing references) //IL_0081: Unknown result type (might be due to invalid IL or missing references) //IL_0029: 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) if (TravelSample()) { bool flag = t.Record != null && t.Record.IsValid() && t.Record.m_uid == t.Id; DiagnosticLog.Write(_log, "TameTravel", TameTravelLogTopics.Follow, $"Follow spacing for {t.Journey.Name}'s animal {t.Id} ended: {Reason(reason)}.", new(string, object)[6] { ("animal", t.Id), ("reason", reason), ("phase", t.Phase), ("peer", t.Journey.Peer.m_uid), ("owner", flag ? new long?(t.Record.GetOwner()) : ((long?)null)), ("omitted", _traversal.TakeOmitted()) }, (LogLevel)32); } } public long BeginFollowing() { if (!base.DiagnosticsEnabled) { return 0L; } return Stopwatch.GetTimestamp(); } public void EndFollowing(long started, int scope) { if (started != 0L && base.DiagnosticsEnabled) { double num = (double)(Stopwatch.GetTimestamp() - started) * 1000.0 / (double)Stopwatch.Frequency; _followCalls++; _followTotal += num; _followMaximum = Math.Max(_followMaximum, num); float now = _clock(); if (_followNext.Ready(now)) { _followNext.Postpone(now, 60f); DiagnosticLog.Write(_log, "TameTravel", CoreLogTopics.Timing, string.Format("{0} follow updates in the last minute, avg {1} ms, max {2} ms.", _followCalls, (_followTotal / (double)_followCalls).ToString("F2", CultureInfo.InvariantCulture), _followMaximum.ToString("F2", CultureInfo.InvariantCulture)), new(string, object)[1] { ("scope", scope) }, (LogLevel)32); _followCalls = 0; _followTotal = (_followMaximum = 0.0); } } } public void Observe(float now, int bindings, int reserved, int transfers) { (int, int, int) tuple = (bindings, reserved, transfers); (int, int, int) tuple2 = tuple; (int, int, int) last = _last; if ((tuple2.Item1 != last.Item1 || tuple2.Item2 != last.Item2 || tuple2.Item3 != last.Item3) && (reserved != 0 || transfers != 0) && Sample()) { _last = tuple; DiagnosticLog.Write(_log, "TameTravel", CoreLogTopics.Scope, "Portal processing scope changed this pass.", new(string, object)[3] { ("bindings", bindings), ("reservations", reserved), ("transfers", transfers) }, (LogLevel)32); } } } internal sealed class TameTravelFollowContext : IDisposable { private readonly TerrainContext _terrain = new TerrainContext(); public bool Prepare(ZDO animal, ZDO actor, float now) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0016: 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_004d: Unknown result type (might be due to invalid IL or missing references) //IL_0052: Unknown result type (might be due to invalid IL or missing references) CandidateView candidateView = TameTravelRules.Nearby(animal.GetPosition()); if (candidateView == null || !_terrain.Prepare(animal.GetPosition(), candidateView, now, 48f)) { return false; } bool flag = true; foreach (ZDO item in candidateView) { Vector3 val = item.GetPosition() - animal.GetPosition(); if (((Vector3)(ref val)).sqrMagnitude > 2304f && item != actor && item != animal) { continue; } if ((Object)(object)PrefabRegistry.Current.Prefab(item.GetPrefab()) == (Object)null) { return false; } if (PrefabRegistry.Current.Solid(item.GetPrefab()) || item == actor || item == animal) { if (!_terrain.Include(item, now)) { return false; } if ((Object)(object)ZNetScene.instance.FindInstance(item) == (Object)null) { flag = false; } } } if (!_terrain.Include(animal, now) || !_terrain.Include(actor, now)) { return false; } if (flag && (Object)(object)ZNetScene.instance.FindInstance(animal) != (Object)null) { return (Object)(object)ZNetScene.instance.FindInstance(actor) != (Object)null; } return false; } public void Dispose() { _terrain.Dispose(); } } internal sealed class TameTravelFollowing : IDisposable { private static TameTravelFollowing? _current; private static readonly int LoxPrefab = StringExtensionMethods.GetStableHashCode("Lox"); private readonly Harmony _hooks = new Harmony("heimkit.tametravel.following"); private readonly TameTravelFollowContext _context; private readonly TameTravelRules _rules; private readonly TameTravelSettings _settings; private readonly ObjectTransferAuthority _authority; private readonly TameTravelDiagnostics _diagnostics; private readonly ManualLogSource _log; private readonly Action _fail; private readonly Dictionary _sessions = new Dictionary(); private readonly List> _snapshot = new List>(); private readonly Dictionary _lapsed = new Dictionary(); private readonly List _lapsedIds = new List(); private const float RangeLimit = 32f; private const float CatchUpRange = 16f; private readonly Func _moveTo; private int _cursor; private bool _disposed; public int Count => _sessions.Count; internal OwnershipLease? TakeForStop(ZDOID id) { //IL_0006: 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_0025: Unknown result type (might be due to invalid IL or missing references) _lapsed.Remove(id); if (!_sessions.TryGetValue(id, out FollowingSession value)) { return null; } _sessions.Remove(id); _diagnostics.FollowingEnded(value.Lease, "stop_handshake"); if (!value.Acquired || !_authority.Holds(value.Lease)) { return null; } return value.Lease; } public bool ChangingOwners(ZDOID id) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) if (_sessions.TryGetValue(id, out FollowingSession value) && value.Acquired) { return value.Lease.Phase != 5; } return false; } internal static MethodInfo NativeMethod(string name, params Type[] parameters) { return typeof(BaseAI).GetMethod(name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, parameters, null) ?? throw new MissingMethodException(typeof(BaseAI).Name, name); } public TameTravelFollowing(TameTravelRules rules, TameTravelSettings settings, ObjectTransferAuthority authority, TameTravelDiagnostics diagnostics, ManualLogSource log, Action fail) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Expected O, but got Unknown //IL_0133: Unknown result type (might be due to invalid IL or missing references) //IL_0141: Expected O, but got Unknown _rules = rules; _settings = settings; _authority = authority; _diagnostics = diagnostics; _log = log; _fail = fail; _moveTo = NativeAccess.Method>(typeof(BaseAI), "MoveTo", new Type[4] { typeof(float), typeof(Vector3), typeof(float), typeof(bool) }); _context = new TameTravelFollowContext(); try { if (_current != null) { throw new InvalidOperationException("TameTravel following is already active."); } _current = this; if (settings.FollowSpacingEnabled.Value) { _hooks.Patch((MethodBase)NativeMethod("Follow", typeof(GameObject), typeof(float)), new HarmonyMethod(typeof(TameTravelFollowing), "Follow", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } } catch { if (_current == this) { _current = null; } _hooks.UnpatchSelf(); _context.Dispose(); throw; } } public void Command(ZNetPeer peer, ZDO animal, TameOrder order) { //IL_000a: 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_004f: Unknown result type (might be due to invalid IL or missing references) //IL_0132: Unknown result type (might be due to invalid IL or missing references) //IL_0137: Unknown result type (might be due to invalid IL or missing references) //IL_0167: Unknown result type (might be due to invalid IL or missing references) //IL_016c: 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_00c6: Unknown result type (might be due to invalid IL or missing references) //IL_00a6: Unknown result type (might be due to invalid IL or missing references) //IL_00ac: Unknown result type (might be due to invalid IL or missing references) if (order != TameOrder.Follow) { if (_sessions.TryGetValue(animal.m_uid, out FollowingSession value) && value.Acquired && value.Lease.Phase == 5 && _authority.Holds(value.Lease)) { value.StopRequested = Time.unscaledTime; } else { Stop(animal.m_uid, "stay_or_wait"); } } else { if (!_settings.FollowSpacingEnabled.Value) { return; } if (_sessions.TryGetValue(animal.m_uid, out FollowingSession value2)) { if (value2.Lease.Journey.Peer == peer && value2.Lease.Journey.Character == peer.m_characterID) { value2.StopRequested = -1f; return; } Stop(animal.m_uid, "new_player_session"); } if (_sessions.Count >= _settings.MaxControlledFollowers.Value) { DiagnosticLog.Write(_log, "TameTravel", "Follow spacing unavailable for " + peer.m_playerName + ": controlled-follower capacity reached; native following remains.", (LogLevel)4); Feedback(peer, "Follow spacing capacity reached; native following remains. Try /comehere again later."); return; } float unscaledTime = Time.unscaledTime; AnimalTransfer animalTransfer = new AnimalTransfer { Id = animal.m_uid, Record = animal, FollowControl = true, Started = unscaledTime, PhaseTime = unscaledTime, Journey = new PortalJourney { Peer = peer, Character = peer.m_characterID, Name = peer.m_playerName } }; _sessions.Add(animal.m_uid, new FollowingSession { Lease = animalTransfer, Requested = unscaledTime }); _diagnostics.Following(animalTransfer, "requested", 0f, 0f, 0f); } } private bool Valid(FollowingSession s, out ZDO actor) { return InvalidReason(s.Lease, out actor) == null; } private string? InvalidReason(AnimalTransfer t, out ZDO actor) { //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Unknown result type (might be due to invalid IL or missing references) //IL_0073: Unknown result type (might be due to invalid IL or missing references) //IL_008b: Unknown result type (might be due to invalid IL or missing references) //IL_0091: 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_00f4: Unknown result type (might be due to invalid IL or missing references) //IL_00f9: Unknown result type (might be due to invalid IL or missing references) //IL_00fe: Unknown result type (might be due to invalid IL or missing references) string text = _rules.ActorRejection(t.Journey.Peer, out actor); if (text != null) { return text; } if (t.Journey.Character != t.Journey.Peer.m_characterID) { return "character_replaced"; } if (t.Journey.Name != t.Journey.Peer.m_playerName) { return "player_name_changed"; } if (ZDOMan.instance.GetZDO(t.Id) != t.Record || t.Record.m_uid != t.Id) { return "animal_record_replaced"; } text = _rules.AnimalRejection(t.Record); if (text != null) { return text; } if (t.Record.GetString(ZDOVars.s_follow, "") != t.Journey.Name) { return "follow_state_changed"; } Vector3 val = t.Record.GetPosition() - actor.GetPosition(); if (!(((Vector3)(ref val)).sqrMagnitude > 1024f)) { return null; } return "follower_range_exceeded"; } private void Resume() { //IL_0034: Unknown result type (might be due to invalid IL or missing references) //IL_0039: Unknown result type (might be due to invalid IL or missing references) //IL_0040: 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_0096: Unknown result type (might be due to invalid IL or missing references) //IL_00a6: Unknown result type (might be due to invalid IL or missing references) _lapsedIds.Clear(); _lapsedIds.AddRange(_lapsed.Keys); foreach (ZDOID lapsedId in _lapsedIds) { AnimalTransfer animalTransfer = _lapsed[lapsedId]; ZDO actor; string text = InvalidReason(animalTransfer, out actor); if (text == "follower_range_exceeded") { continue; } float num = ((text == null) ? Vector3.Distance(animalTransfer.Record.GetPosition(), actor.GetPosition()) : 0f); if (text != null || !(num > 16f)) { _lapsed.Remove(lapsedId); if (text == null && !_sessions.ContainsKey(lapsedId)) { _diagnostics.Following(animalTransfer, "caught_up", num, 0f, 0f); Command(animalTransfer.Journey.Peer, animalTransfer.Record, TameOrder.Follow); } } } } public void Tick(float now) { //IL_00a6: 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_0166: 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_01ec: Unknown result type (might be due to invalid IL or missing references) //IL_01f6: 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_0205: Unknown result type (might be due to invalid IL or missing references) //IL_0364: Unknown result type (might be due to invalid IL or missing references) //IL_036b: Unknown result type (might be due to invalid IL or missing references) //IL_0370: Unknown result type (might be due to invalid IL or missing references) //IL_0375: Unknown result type (might be due to invalid IL or missing references) //IL_0338: Unknown result type (might be due to invalid IL or missing references) //IL_0276: Unknown result type (might be due to invalid IL or missing references) //IL_0433: Unknown result type (might be due to invalid IL or missing references) //IL_053d: Unknown result type (might be due to invalid IL or missing references) //IL_048e: Unknown result type (might be due to invalid IL or missing references) //IL_0401: Unknown result type (might be due to invalid IL or missing references) //IL_0576: Unknown result type (might be due to invalid IL or missing references) if (_lapsed.Count > 0) { Resume(); } Snapshot(); foreach (KeyValuePair item in _snapshot) { FollowingSession value = item.Value; ZDO actor; string text = InvalidReason(value.Lease, out actor); if (text == null && value.Acquired && !_authority.Holds(value.Lease)) { text = "follower_ownership_changed"; } if (text == null && value.StopRequested >= 0f && now - value.StopRequested > 6f) { text = "stay_unconfirmed"; } if (text != null) { Stop(item.Key, text); } } Snapshot(); List> snapshot = _snapshot; if (snapshot.Count == 0) { return; } FollowingSession value2 = snapshot[_cursor % snapshot.Count].Value; _cursor = (_cursor + 1) % snapshot.Count; if (now >= value2.NextContext && Valid(value2, out ZDO actor2)) { if (_context.Prepare(value2.Lease.Record, actor2, now)) { value2.ContextAt = now; value2.ContextPosition = value2.Lease.Record.GetPosition(); value2.UnreadySince = -1f; CapsuleCollider val = PrefabRegistry.Component(_rules.Prefab(value2.Lease.Record)); TameTravelRules.Scale(value2.Lease.Record, out var scale); float num = val.radius + ((val.direction == 1) ? 0f : Math.Max(0f, val.height * 0.5f - val.radius)); Vector2 val2 = new Vector2(val.center.x, val.center.z); float animalExtent = (num + ((Vector2)(ref val2)).magnitude) * scale.x; ZNetView obj = ZNetScene.instance.FindInstance(actor2); CapsuleCollider val3 = ((obj != null) ? ((Component)obj).GetComponent() : null); if (!((Object)(object)val3 == (Object)null)) { (value2.StopDistance, value2.ResumeDistance) = TameTravelFollowRules.Distances(_settings.FollowStopDistanceMeters.Value, _settings.FollowResumeDistanceMeters.Value, animalExtent, val3.radius * Math.Abs(((Component)val3).transform.lossyScale.x), value2.Lease.Record.GetPrefab() == LoxPrefab); } else { value2.ContextAt = float.NegativeInfinity; } } else { value2.ContextAt = float.NegativeInfinity; } value2.NextContext = now + (float.IsNegativeInfinity(value2.ContextAt) ? 0.25f : 1f); } foreach (KeyValuePair item2 in snapshot) { FollowingSession value3 = item2.Value; AnimalTransfer lease = value3.Lease; if (value3.Acquired && lease.Phase == 0 && now - lease.PhaseTime > 10f) { Stop(item2.Key, "source_drain_timeout", warning: true); continue; } if (now - value3.ContextAt <= 3f) { Vector3 val4 = lease.Record.GetPosition() - value3.ContextPosition; if (((Vector3)(ref val4)).sqrMagnitude <= 256f) { if (!value3.Acquired) { if (!_authority.Acquire(lease, now)) { Stop(item2.Key, "acquisition_unavailable", warning: true); continue; } value3.Acquired = true; lease.PhaseTime = now; } if (lease.Phase == 0) { if (now - lease.PhaseTime > 10f || lease.PreviousPeer == null || !lease.PreviousPeer.IsReady()) { Stop(item2.Key, "source_drain_timeout", warning: true); continue; } if (!_authority.Echoed(lease.Barrier)) { continue; } if (!lease.SourceStateObserved) { if (lease.SourceEchoTime == 0f) { lease.SourceEchoTime = now; } if (now - lease.SourceEchoTime >= 2f) { _authority.RequestSourceState(lease, now); } continue; } lease.Phase = 1; } if (lease.Phase != 1 && lease.Phase != 6) { continue; } ZNetView val5 = ZNetScene.instance.FindInstance(lease.Record); GameObject val6 = ZNetScene.instance.FindInstance(lease.Journey.Character); MonsterAI val7 = (((Object)(object)val5 == (Object)null) ? null : ((Component)val5).GetComponent()); if ((Object)(object)val7 == (Object)null || (Object)(object)val6 == (Object)null) { Stop(item2.Key, "instance_unavailable", warning: true); continue; } val7.SetFollowTarget(val6); ((BaseAI)val7).StopMoving(); _authority.RunFollow(lease); ((Component)val5).GetComponent().SyncNow(); if (!value3.Started) { value3.Started = true; DiagnosticLog.Write(_log, "TameTravel", "Server follow spacing active for " + lease.Journey.Name + ".", (LogLevel)16); Feedback(lease.Journey.Peer, "Follow spacing active: stop " + value3.StopDistance.ToString("0.0") + "m, resume " + value3.ResumeDistance.ToString("0.0") + "m."); } _diagnostics.Following(lease, "simulation_started", 0f, value3.StopDistance, value3.ResumeDistance); continue; } } if (value3.UnreadySince < 0f) { value3.UnreadySince = now; } if (value3.Acquired && lease.Phase == 5) { _authority.PauseFollow(lease); _diagnostics.Following(lease, "context_paused", 0f, value3.StopDistance, value3.ResumeDistance); } if (now - value3.UnreadySince > 10f) { Stop(item2.Key, "context_timeout", warning: true); } } } private static bool Follow(BaseAI __instance, GameObject go, float dt) { TameTravelFollowing current = _current; if (current == null || current._disposed || current._sessions.Count == 0) { return true; } try { return current.Apply(__instance, go, dt); } catch (Exception obj) { current._fail(obj); return false; } } private bool Apply(BaseAI ai, GameObject target, float dt) { //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_0077: 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_0092: Unknown result type (might be due to invalid IL or missing references) //IL_00a2: Unknown result type (might be due to invalid IL or missing references) //IL_00a7: Unknown result type (might be due to invalid IL or missing references) //IL_00d4: Unknown result type (might be due to invalid IL or missing references) //IL_00da: Unknown result type (might be due to invalid IL or missing references) //IL_00df: 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_011f: Unknown result type (might be due to invalid IL or missing references) //IL_012a: 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_0134: Unknown result type (might be due to invalid IL or missing references) //IL_0136: Unknown result type (might be due to invalid IL or missing references) //IL_013d: 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_014c: Unknown result type (might be due to invalid IL or missing references) //IL_01d4: Unknown result type (might be due to invalid IL or missing references) ZNetView component = ((Component)ai).GetComponent(); ZDO val = ((component != null) ? component.GetZDO() : null); if (val == null || !_sessions.TryGetValue(val.m_uid, out FollowingSession value) || !_authority.RunningFollow(val.m_uid)) { return true; } if (!((Object)(object)target == (Object)null)) { ZNetView component2 = target.GetComponent(); ZDOID? val2 = ((component2 == null) ? ((ZDOID?)null) : component2.GetZDO()?.m_uid); ZDOID character = value.Lease.Journey.Character; if (val2.HasValue && !(val2.GetValueOrDefault() != character) && Valid(value, out ZDO _) && !(Time.unscaledTime - value.ContextAt > 3f)) { Vector3 val3 = ((Component)ai).transform.position - value.ContextPosition; if (!(((Vector3)(ref val3)).sqrMagnitude > 256f)) { long started = _diagnostics.BeginFollowing(); try { Vector3 val4 = target.transform.position - ((Component)ai).transform.position; float num = val4.x * val4.x + val4.z * val4.z; bool flag = TameTravelFollowRules.Stopped(value.Stopped, num, value.StopDistance, value.ResumeDistance); if (flag != value.Stopped) { value.Stopped = flag; _diagnostics.Following(value.Lease, flag ? "stopped" : "resumed", (float)Math.Sqrt(num), value.StopDistance, value.ResumeDistance); } if (flag) { ai.StopMoving(); } else { _moveTo(ai, dt, target.transform.position, value.StopDistance, num > Math.Max(10f, value.ResumeDistance + 3f) * Math.Max(10f, value.ResumeDistance + 3f)); } return false; } finally { _diagnostics.EndFollowing(started, _sessions.Count); } } } } ai.StopMoving(); _authority.PauseFollow(value.Lease); return false; } public void Stop(ZDOID id, string reason, bool warning = false) { //IL_0006: 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_0024: Unknown result type (might be due to invalid IL or missing references) //IL_004d: Unknown result type (might be due to invalid IL or missing references) //IL_00da: 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) _lapsed.Remove(id); if (_sessions.TryGetValue(id, out FollowingSession value)) { _sessions.Remove(id); if (reason == "follower_range_exceeded" && _lapsed.Count < 64) { _lapsed[id] = value.Lease; } _diagnostics.FollowingEnded(value.Lease, reason); if (value.Acquired && _authority.Holds(value.Lease)) { _authority.Release(id); } if (value.Started || warning) { DiagnosticLog.Write(_log, "TameTravel", TameTravelLogTopics.Follow, "Server follow spacing released for " + value.Lease.Journey.Name + ".", new(string, object)[2] { ("animal", id), ("reason", reason) }, (LogLevel)(warning ? 4 : 16)); } if (warning) { Feedback(value.Lease.Journey.Peer, "Follow spacing unavailable (" + reason + "); native following remains. Try /comehere again later."); } } } private void Snapshot() { _snapshot.Clear(); foreach (KeyValuePair session in _sessions) { _snapshot.Add(session); } } private static void Feedback(ZNetPeer peer, string text) { //IL_0021: Unknown result type (might be due to invalid IL or missing references) if (peer.IsReady() && !((ZDOID)(ref peer.m_characterID)).IsNone()) { ZRoutedRpc.instance.InvokeRoutedRPC(peer.m_uid, peer.m_characterID, "Message", new object[3] { 1, "TameTravel: " + text, 0 }); } } public void Dispose() { //IL_003b: 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_0042: Unknown result type (might be due to invalid IL or missing references) if (_disposed) { return; } _disposed = true; if (_current == this) { _current = null; } List list = new List(); ZDOID[] array = _sessions.Keys.ToArray(); foreach (ZDOID id in array) { try { Stop(id, "controller_stopped"); } catch (Exception item) { list.Add(item); } } _lapsed.Clear(); Action[] array2 = new Action[2] { delegate { _hooks.UnpatchSelf(); }, delegate { _context.Dispose(); } }; foreach (Action action in array2) { try { action(); } catch (Exception item2) { list.Add(item2); } } if (list.Count <= 0) { return; } throw new AggregateException("Following cleanup failed.", list); } } internal sealed class TameTravelFollowRecovery : IDisposable { private static TameTravelFollowRecovery? _current; private readonly Harmony _hooks = new Harmony("heimkit.tametravel.follow_recovery"); private readonly ManualLogSource _log; private int _cleared; internal TameTravelFollowRecovery(ManualLogSource log) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Expected O, but got Unknown //IL_00ac: Unknown result type (might be due to invalid IL or missing references) //IL_00b9: Expected O, but got Unknown //IL_0104: Unknown result type (might be due to invalid IL or missing references) //IL_0112: Expected O, but got Unknown _log = log; if (_current != null) { throw new InvalidOperationException("Follow recovery is already active."); } _current = this; try { string[] array = new string[2] { "Load", "LoadOldFormat" }; foreach (string text in array) { _hooks.Patch((MethodBase)(AccessTools.Method(typeof(ZDO), text, new Type[2] { typeof(ZPackage), typeof(World) }, (Type[])null) ?? throw new MissingMethodException("ZDO", text)), (HarmonyMethod)null, new HarmonyMethod(typeof(TameTravelFollowRecovery), "Loaded", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } _hooks.Patch((MethodBase)(AccessTools.Method(typeof(ZDOMan), "PrepareSave", (Type[])null, (Type[])null) ?? throw new MissingMethodException("ZDOMan", "PrepareSave")), new HarmonyMethod(typeof(TameTravelFollowRecovery), "Saving", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } catch { _current = null; _hooks.UnpatchSelf(); throw; } } private static void Saving(ZDOMan __instance) { TameTravelFollowState.PrepareSave(__instance); } private static void Loaded(ZDO __instance) { TameTravelFollowRecovery current = _current; if (current != null && __instance.Persistent && __instance.GetBool(ZDOVars.s_tamed, false) && !__instance.GetBool(ZDOVars.s_dead, false) && __instance.GetLong(ZDOVars.s_user, 0L) == 0L && TameTravelFollowState.Recoverable(__instance.GetPrefab(), __instance.GetString(ZDOVars.s_follow, ""), __instance.GetString(TameTravelFollowState.OwnerKey, ""), __instance.GetString(TameTravelFollowState.SessionKey, ""))) { TameTravelFollowState.ClearSaved(__instance); Interlocked.Increment(ref current._cleared); } } internal void Report() { int num = Interlocked.Exchange(ref _cleared, 0); if (num > 0) { DiagnosticLog.Write(_log, "TameTravel", $"Cleared stale following on {num} animal(s) loaded from disk.", (LogLevel)16); } } public void Dispose() { try { Report(); _hooks.UnpatchSelf(); } finally { if (_current == this) { _current = null; } TameTravelFollowState.ResetTracking(); } } } internal static class TameTravelFollowRules { public static (float Stop, float Resume) Distances(float stop, float resume, float animalExtent, float playerExtent, bool lox = false) { float[] array = new float[4] { stop, resume, animalExtent, playerExtent }; foreach (float num in array) { if (float.IsNaN(num) || float.IsInfinity(num) || num < 0f) { throw new ArgumentOutOfRangeException("stop"); } } float num2 = Math.Max(Math.Max(stop, lox ? 6 : 0), animalExtent + playerExtent + 1f); return (Stop: num2, Resume: Math.Max(Math.Max(resume, lox ? 8 : 0), num2 + (float)((!lox) ? 1 : 2))); } public static bool Stopped(bool stopped, float distanceSquared, float stop, float resume) { if (!stopped) { return distanceSquared <= stop * stop; } return distanceSquared <= resume * resume; } } internal static class TameTravelFollowState { internal static readonly int OwnerKey = StringExtensionMethods.GetStableHashCode("heimkit_tametravel_follow_owner"); internal static readonly int SessionKey = StringExtensionMethods.GetStableHashCode("heimkit_tametravel_follow_session"); internal static readonly string Session = Guid.NewGuid().ToString("N"); private static readonly Dictionary Tracked = new Dictionary(); private static readonly int Wolf = StringExtensionMethods.GetStableHashCode("Wolf"); private static readonly int[] Legacy = new int[5] { StringExtensionMethods.GetStableHashCode("Boar"), StringExtensionMethods.GetStableHashCode("Lox"), StringExtensionMethods.GetStableHashCode("Asksvin"), StringExtensionMethods.GetStableHashCode("Hen"), StringExtensionMethods.GetStableHashCode("Moose") }; internal static void Untrack(ZDOID id) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) Tracked.Remove(id); } internal static void ResetTracking() { Tracked.Clear(); } internal static void Mark(ZDO animal, string name) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) Tracked[animal.m_uid] = (animal, name); animal.Set(OwnerKey, name); animal.Set(SessionKey, Session); } internal static void PrepareSave(ZDOMan world) { //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_0044: Unknown result type (might be due to invalid IL or missing references) foreach (KeyValuePair item2 in Tracked) { ZDO item = item2.Value.Item1; if (item.IsValid() && !(item.m_uid != item2.Key) && world.GetZDO(item2.Key) == item) { string text = item.GetString(ZDOVars.s_follow, ""); if (text.Length == 0 || !(text != item2.Value.Item2)) { item.Set(OwnerKey, item2.Value.Item2); item.Set(SessionKey, Session); } } } } internal static void Forget(ZDO animal) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) Tracked.Remove(animal.m_uid); animal.Set(OwnerKey, ""); animal.Set(SessionKey, Session); } internal static bool Recoverable(int prefab, string follow, string owner, string session) { bool flag = prefab == Wolf; int[] legacy = Legacy; foreach (int num in legacy) { flag = flag || num == prefab; } if (!flag) { return false; } if (owner.Length != 0) { if (session != Session) { if (follow.Length != 0) { return follow == owner; } return true; } return false; } if (session.Length != 0 || follow.Length == 0 || prefab == Wolf) { return false; } legacy = Legacy; for (int i = 0; i < legacy.Length; i++) { if (legacy[i] == prefab) { return true; } } return false; } internal static void ClearSaved(ZDO animal, bool forget = true) { //IL_0017: Unknown result type (might be due to invalid IL or missing references) animal.Set(ZDOVars.s_follow, ""); animal.Set(ZDOVars.s_patrolPoint, animal.GetPosition()); animal.Set(ZDOVars.s_patrol, true); if (forget) { Forget(animal); } } internal static bool ClearLive(ZDO animal, bool forget = true) { ZNetView val = (((Object)(object)ZNetScene.instance == (Object)null) ? null : ZNetScene.instance.FindInstance(animal)); MonsterAI val2 = (((Object)(object)val == (Object)null) ? null : ((Component)val).GetComponent()); if ((Object)(object)val2 != (Object)null) { val2.SetFollowTarget((GameObject)null); ((BaseAI)val2).SetPatrolPoint(); ((BaseAI)val2).StopMoving(); } ClearSaved(animal, forget); if (!((Object)(object)val2 == (Object)null)) { return (Object)(object)val2.GetFollowTarget() == (Object)null; } return true; } } public static class TameTravelLogTopics { public static readonly LogTopic Command = new LogTopic("command"); public static readonly LogTopic Follow = new LogTopic("follow"); public static readonly LogTopic Travel = new LogTopic("travel"); } internal sealed class TameTravelPlacement : IDisposable { private static readonly Vector3[] FootprintOffsets = (Vector3[])(object)new Vector3[9] { Vector3.zero, Vector3.right, -Vector3.right, Vector3.forward, -Vector3.forward, new Vector3(0.70710677f, 0f, 0.70710677f), new Vector3(-0.70710677f, 0f, 0.70710677f), new Vector3(0.70710677f, 0f, -0.70710677f), new Vector3(-0.70710677f, 0f, -0.70710677f) }; private static readonly Action ResetGround = NativeAccess.Method>(typeof(Character), "ResetGroundContact", Array.Empty()); private static readonly FieldRef MaxAltitude = NativeAccess.Field("m_maxAirAltitude"); private static readonly FieldRef LastGroundTouch = NativeAccess.Field("m_lastGroundTouch"); private static readonly FieldRef FallTimer = NativeAccess.Field("m_fallTimer"); private static readonly FieldRef> Path = NativeAccess.Field>("m_path"); private static readonly FieldRef SpawnPoint = NativeAccess.Field("m_spawnPoint"); private readonly TerrainContext _context = new TerrainContext(); private readonly TameTravelPlacementSurfaces _surfaces = new TameTravelPlacementSurfaces(); private readonly TameTravelPlacementAccess _access = new TameTravelPlacementAccess(); private readonly TameTravelRules _rules; private readonly List<(Vector3 Position, float Clearance)> _creatures = new List<(Vector3, float)>(); private readonly List _players = new List(); private readonly List _placements = new List(); private readonly int _solid = LayerMask.GetMask(new string[9] { "Default", "static_solid", "Default_small", "piece", "terrain", "vehicle", "character", "character_net", "character_ghost" }); private readonly int _building = LayerMask.GetMask(new string[1] { "piece" }); private readonly int _obstacles = LayerMask.GetMask(new string[5] { "Default", "static_solid", "Default_small", "piece", "vehicle" }); private readonly Collider[] _overlaps = (Collider[])(object)new Collider[32]; private readonly RaycastHit[] _roofs = (RaycastHit[])(object)new RaycastHit[32]; private CapsuleCollider? _padding; private readonly Func _groundProbe; private readonly Func _clearProbe; private AnimalTransfer _probeTransfer; private bool _probeEvidence; private bool _probeWalkout; private string? _candidateReason; private Vector3 _probeCenterOffset; private Vector3 _probeAxis; private Quaternion _probeRotation; private int _probeDirection; private float _probeExtent; private float _probeHorizontalExtent; private float _probeHalfLine; private float _probeRadius; public string WaitReason { get; private set; } = "no_safe_ground_position"; public ZDOID? BlockingObject { get; private set; } public TameTravelPlacement(TameTravelRules rules) { _rules = rules; _groundProbe = ProbeGround; _clearProbe = ProbeClear; } public void WarmAccess(Vector3 traveller, Vector3 exit) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) _access.Warm(traveller, exit); } public bool Find(AnimalTransfer t, Dictionary.ValueCollection transfers, IReadOnlyList peers, float now, bool evidence, out Vector3 position) { long num = (evidence ? Stopwatch.GetTimestamp() : 0); double placementContextMilliseconds = t.PlacementContextMilliseconds; try { return FindPosition(t, transfers, peers, now, evidence, out position); } finally { if (evidence) { t.PlacementAttempts++; t.PlacementSearchMilliseconds += (double)(Stopwatch.GetTimestamp() - num) * 1000.0 / (double)Stopwatch.Frequency - (t.PlacementContextMilliseconds - placementContextMilliseconds); if (WaitReason != "placed") { Count(t.PlacementWaitReasons, WaitReason); } } } } private bool FindPosition(AnimalTransfer t, Dictionary.ValueCollection transfers, IReadOnlyList peers, float now, bool evidence, out Vector3 position) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_0066: 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_00f4: 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_0134: Unknown result type (might be due to invalid IL or missing references) //IL_015e: Unknown result type (might be due to invalid IL or missing references) //IL_0195: Unknown result type (might be due to invalid IL or missing references) //IL_027b: Unknown result type (might be due to invalid IL or missing references) //IL_028e: Unknown result type (might be due to invalid IL or missing references) //IL_02c3: Unknown result type (might be due to invalid IL or missing references) //IL_01d9: Unknown result type (might be due to invalid IL or missing references) //IL_02c8: Unknown result type (might be due to invalid IL or missing references) //IL_02d0: Unknown result type (might be due to invalid IL or missing references) //IL_02d5: 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) //IL_02dc: Unknown result type (might be due to invalid IL or missing references) //IL_02e4: Unknown result type (might be due to invalid IL or missing references) //IL_02ea: Unknown result type (might be due to invalid IL or missing references) //IL_02ef: Unknown result type (might be due to invalid IL or missing references) //IL_02f5: 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_02ff: Unknown result type (might be due to invalid IL or missing references) //IL_0304: Unknown result type (might be due to invalid IL or missing references) //IL_0317: Unknown result type (might be due to invalid IL or missing references) //IL_031e: Unknown result type (might be due to invalid IL or missing references) //IL_0325: Unknown result type (might be due to invalid IL or missing references) //IL_032a: Unknown result type (might be due to invalid IL or missing references) //IL_033d: Unknown result type (might be due to invalid IL or missing references) //IL_0342: Unknown result type (might be due to invalid IL or missing references) //IL_0347: Unknown result type (might be due to invalid IL or missing references) //IL_034c: Unknown result type (might be due to invalid IL or missing references) //IL_02bc: Unknown result type (might be due to invalid IL or missing references) //IL_02b5: Unknown result type (might be due to invalid IL or missing references) //IL_0377: Unknown result type (might be due to invalid IL or missing references) //IL_037c: Unknown result type (might be due to invalid IL or missing references) //IL_0396: Unknown result type (might be due to invalid IL or missing references) //IL_0398: Unknown result type (might be due to invalid IL or missing references) //IL_03a6: Unknown result type (might be due to invalid IL or missing references) //IL_03a8: Unknown result type (might be due to invalid IL or missing references) //IL_03c3: Unknown result type (might be due to invalid IL or missing references) //IL_03c8: Unknown result type (might be due to invalid IL or missing references) //IL_0400: Unknown result type (might be due to invalid IL or missing references) //IL_0418: Unknown result type (might be due to invalid IL or missing references) //IL_0497: Unknown result type (might be due to invalid IL or missing references) //IL_0453: Unknown result type (might be due to invalid IL or missing references) //IL_04b6: Unknown result type (might be due to invalid IL or missing references) //IL_04bb: Unknown result type (might be due to invalid IL or missing references) //IL_04ed: Unknown result type (might be due to invalid IL or missing references) //IL_04ca: Unknown result type (might be due to invalid IL or missing references) //IL_04d2: Unknown result type (might be due to invalid IL or missing references) //IL_04d7: Unknown result type (might be due to invalid IL or missing references) //IL_04dc: Unknown result type (might be due to invalid IL or missing references) //IL_0506: Unknown result type (might be due to invalid IL or missing references) //IL_050b: Unknown result type (might be due to invalid IL or missing references) //IL_055c: Unknown result type (might be due to invalid IL or missing references) //IL_0561: Unknown result type (might be due to invalid IL or missing references) //IL_0563: Unknown result type (might be due to invalid IL or missing references) //IL_0565: Unknown result type (might be due to invalid IL or missing references) //IL_056a: Unknown result type (might be due to invalid IL or missing references) //IL_0591: Unknown result type (might be due to invalid IL or missing references) //IL_0571: Unknown result type (might be due to invalid IL or missing references) //IL_05c6: Unknown result type (might be due to invalid IL or missing references) //IL_05cb: Unknown result type (might be due to invalid IL or missing references) //IL_05cd: Unknown result type (might be due to invalid IL or missing references) //IL_05d2: Unknown result type (might be due to invalid IL or missing references) //IL_05ee: Unknown result type (might be due to invalid IL or missing references) //IL_05f0: Unknown result type (might be due to invalid IL or missing references) //IL_05f9: Unknown result type (might be due to invalid IL or missing references) //IL_0606: Unknown result type (might be due to invalid IL or missing references) //IL_062b: Unknown result type (might be due to invalid IL or missing references) //IL_0630: Unknown result type (might be due to invalid IL or missing references) //IL_066a: Unknown result type (might be due to invalid IL or missing references) //IL_066f: Unknown result type (might be due to invalid IL or missing references) //IL_0676: Unknown result type (might be due to invalid IL or missing references) //IL_0684: Unknown result type (might be due to invalid IL or missing references) //IL_0689: Unknown result type (might be due to invalid IL or missing references) //IL_068e: Unknown result type (might be due to invalid IL or missing references) //IL_06cf: Unknown result type (might be due to invalid IL or missing references) //IL_06d4: Unknown result type (might be due to invalid IL or missing references) //IL_06e3: Unknown result type (might be due to invalid IL or missing references) //IL_06e8: Unknown result type (might be due to invalid IL or missing references) //IL_06f0: Unknown result type (might be due to invalid IL or missing references) position = default(Vector3); WaitReason = "no_safe_ground_position"; BlockingObject = null; long num = (evidence ? Stopwatch.GetTimestamp() : 0); try { CandidateView candidateView = TameTravelRules.Nearby(t.Journey.Exit); if (candidateView == null) { WaitReason = "destination_scope_over_capacity"; return false; } if (!_context.Prepare(t.Journey.Exit, candidateView, now, 56f)) { WaitReason = _context.WaitReason ?? "destination_terrain_unready"; BlockingObject = _context.WaitObject; return false; } bool flag = true; List<(Vector3, float)> creatures = _creatures; creatures.Clear(); _players.Clear(); _placements.Clear(); foreach (ZDO item in candidateView) { if (item.m_uid == t.Id) { continue; } GameObject val = PrefabRegistry.Current.Prefab(item.GetPrefab()); if ((Object)(object)val == (Object)null) { WaitReason = "destination_prefab_unavailable"; BlockingObject = item.m_uid; return false; } if ((Object)(object)PrefabRegistry.Component(val) != (Object)null) { creatures.Add((item.GetPosition(), BodyClearance(item))); continue; } if (!_context.Include(item, now)) { WaitReason = "destination_context_capacity"; BlockingObject = item.m_uid; return false; } if (PrefabRegistry.Current.Solid(item.GetPrefab()) && (Object)(object)ZNetScene.instance.FindInstance(item) == (Object)null) { flag = false; BlockingObject = item.m_uid; } } if (!flag) { WaitReason = "destination_collision_instances_unready"; return false; } Physics.SyncTransforms(); } finally { if (evidence) { t.PlacementContextMilliseconds += (double)(Stopwatch.GetTimestamp() - num) * 1000.0 / (double)Stopwatch.Frequency; } } if (!TameTravelRules.Scale(t.Record, out var scale)) { return false; } CapsuleCollider val2 = PrefabRegistry.Component(_rules.Prefab(t.Record)); float num2 = val2.radius * scale.x; float num3 = Mathf.Max(0f, val2.height * scale.x * 0.5f - num2); Vector3 val3 = ((val2.direction == 0) ? Vector3.right : ((val2.direction == 1) ? Vector3.up : Vector3.forward)); val3 = t.Journey.DestinationRotation * val3; Vector3 val4 = t.Journey.DestinationRotation * (val2.center * scale.x); float num4 = num2 + num3 * Math.Abs(val3.y); Vector2 val5 = new Vector2(val3.x, val3.z); float num5 = num2 + num3 * ((Vector2)(ref val5)).magnitude; Vector3 val6 = t.Journey.DestinationRotation * Vector3.forward; val6.y = 0f; if (((Vector3)(ref val6)).sqrMagnitude < 0.001f) { WaitReason = "destination_facing_unsupported"; return false; } val6 = ((Vector3)(ref val6)).normalized; _probeTransfer = t; _probeEvidence = evidence; _probeExtent = num4; _probeCenterOffset = val4; _probeHorizontalExtent = num5; _probeAxis = val3; _probeHalfLine = num3; _probeRadius = num2; _probeRotation = t.Journey.DestinationRotation; _probeDirection = val2.direction; for (int i = 0; i < peers.Count; i++) { ZNetPeer val7 = peers[i]; if (val7.IsReady()) { ZDO zDO = ZDOMan.instance.GetZDO(val7.m_characterID); if (zDO != null) { _players.Add(zDO.GetPosition()); } } } foreach (AnimalTransfer transfer in transfers) { if (transfer != t && transfer.Moved) { _placements.Add(transfer.Placement); } } Func groundProbe = _groundProbe; Func clearProbe = _clearProbe; int probes = 0; int num6 = 0; ZDO zDO2 = ZDOMan.instance.GetZDO(t.Journey.Character); if (zDO2 == null) { WaitReason = "traveller_unavailable"; return false; } Vector3 position2 = zDO2.GetPosition(); if (t.PlacementAnchor.HasValue) { Vector3 val8 = position2 - t.PlacementAnchor.Value; if (!(((Vector3)(ref val8)).sqrMagnitude > 1f)) { goto IL_0500; } } t.PlacementAnchor = position2; t.PlacementCursor = 0; goto IL_0500; IL_0500: Vector3 value = t.PlacementAnchor.Value; int num7 = TameTravelPlacementRules.CandidateCount(num5); int num8 = t.PlacementCursor % num7; for (int j = 0; j < 64; j++) { int num9 = (num8 + j) % num7; t.PlacementCursor = (num9 + 1) % num7; if (evidence) { t.PlacementCandidates++; } Vector3 val9 = TameTravelPlacementRules.Candidate(num9, num5, t.Journey.Exit, value, val6); if (evidence) { t.PlacementLastProbe = val9; t.PlacementSupportHeight = null; } _candidateReason = null; Vector3? val10 = ProbeLanding(val9); if (!val10.HasValue) { if (evidence) { Reject(t, _candidateReason ?? "no_safe_ground_position"); } continue; } Vector3 outward = val10.Value - value; outward.y = 0f; if (((Vector3)(ref outward)).sqrMagnitude < 0.001f) { outward = val6; } if (evidence) { t.PlacementSupportHeight = val10.Value.y - num4 + val4.y - 0.15f; } int probesBefore = probes; _probeWalkout = true; bool flag2; try { flag2 = TameTravelPlacementRules.HasEscape(val10.Value, outward, Math.Max(3f, num5 + 2f), groundProbe, clearProbe, ref probes); } finally { _probeWalkout = false; } if (flag2) { num6++; Vector3 landing = val10.Value - Vector3.up * (num4 - val4.y + 0.15f); float valueOrDefault = t.PlacementAccessWarmupUntil.GetValueOrDefault(); if (!t.PlacementAccessWarmupUntil.HasValue) { valueOrDefault = now + 4f; t.PlacementAccessWarmupUntil = valueOrDefault; } if (_access.Reachable(zDO2.GetPosition(), landing, out string reason)) { position = val10.Value; t.PlacementTraveller = zDO2.GetPosition(); WaitReason = "placed"; return true; } if (evidence) { Reject(t, reason); } WaitReason = reason; if (reason == "access_path_unready_or_blocked" && now < t.PlacementAccessWarmupUntil.Value) { t.PlacementCursor = num9; return false; } if (num6 >= 4) { return false; } } else { bool flag3 = TameTravelPlacementRules.EscapeDeferred(probesBefore, probes); WaitReason = (flag3 ? "destination_escape_search_deferred" : "destination_escape_route_blocked"); if (evidence) { Reject(t, WaitReason); } if (flag3) { t.PlacementCursor = num9; return false; } } } return false; } private Vector3? ProbeLanding(Vector3 candidate) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_000e: 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_0018: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_001f: 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_002c: Unknown result type (might be due to invalid IL or missing references) //IL_0052: Unknown result type (might be due to invalid IL or missing references) //IL_0070: Unknown result type (might be due to invalid IL or missing references) //IL_00aa: Unknown result type (might be due to invalid IL or missing references) //IL_00b1: Unknown result type (might be due to invalid IL or missing references) //IL_00c3: Unknown result type (might be due to invalid IL or missing references) //IL_00c8: Unknown result type (might be due to invalid IL or missing references) //IL_00cd: 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) int num = 0; while (true) { Vector3 val = candidate - _probeTransfer.Journey.Exit; if (val.x * val.x + val.z * val.z > 2304f) { Note("landing_range"); return null; } Vector3? result = ProbeGround(candidate); if (!result.HasValue) { return null; } if (!Crowded(result.Value, out var away)) { return result; } Note("obstacle_padding"); if (num == 3 || ((Vector3)(ref away)).sqrMagnitude < 0.0001f) { break; } candidate = result.Value + ((Vector3)(ref away)).normalized * (((Vector3)(ref away)).magnitude + 0.05f); if (_probeEvidence) { _probeTransfer.PlacementLastProbe = candidate; } num++; } return null; } private bool Crowded(Vector3 root, out Vector3 away) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_001a: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_003c: Unknown result type (might be due to invalid IL or missing references) //IL_003d: 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_004a: Unknown result type (might be due to invalid IL or missing references) //IL_004f: Unknown result type (might be due to invalid IL or missing references) //IL_0054: Unknown result type (might be due to invalid IL or missing references) //IL_0056: 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_0066: Unknown result type (might be due to invalid IL or missing references) //IL_00f1: Unknown result type (might be due to invalid IL or missing references) //IL_00f3: Unknown result type (might be due to invalid IL or missing references) //IL_0101: Unknown result type (might be due to invalid IL or missing references) //IL_010d: 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_0124: 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_012d: Unknown result type (might be due to invalid IL or missing references) //IL_0132: Unknown result type (might be due to invalid IL or missing references) away = Vector3.zero; float num = 0.75f; float num2 = _probeRadius + num; Vector3 val = root + _probeCenterOffset + Vector3.up * (num - 0.05f); int num3 = Physics.OverlapCapsuleNonAlloc(val + _probeAxis * _probeHalfLine, val - _probeAxis * _probeHalfLine, num2, _overlaps, _obstacles, (QueryTriggerInteraction)1); if (num3 == 0) { return false; } if (num3 == _overlaps.Length) { return true; } CapsuleCollider val2 = PaddingProbe(); val2.radius = num2; val2.height = 2f * (_probeHalfLine + num2); val2.direction = _probeDirection; ((Collider)val2).enabled = true; try { Vector3 val4 = default(Vector3); float num4 = default(float); for (int i = 0; i < num3; i++) { Collider val3 = _overlaps[i]; _overlaps[i] = null; if ((Object)(object)val3 != (Object)null && Physics.ComputePenetration((Collider)(object)val2, val, _probeRotation, val3, ((Component)val3).transform.position, ((Component)val3).transform.rotation, ref val4, ref num4)) { away += val4 * num4; } } } finally { ((Collider)val2).enabled = false; } away.y = 0f; return true; } private CapsuleCollider PaddingProbe() { //IL_001a: Unknown result type (might be due to invalid IL or missing references) //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: Expected O, but got Unknown //IL_0059: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)_padding != (Object)null) { return _padding; } GameObject val = new GameObject("HeimKit TameTravel padding probe") { hideFlags = (HideFlags)61, layer = 2 }; _padding = val.AddComponent(); ((Collider)_padding).isTrigger = true; ((Collider)_padding).enabled = false; _padding.center = Vector3.zero; return _padding; } private Vector3? ProbeGround(Vector3 p) { //IL_0006: 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_00a3: 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_00df: Unknown result type (might be due to invalid IL or missing references) //IL_00eb: Unknown result type (might be due to invalid IL or missing references) //IL_00f0: Unknown result type (might be due to invalid IL or missing references) //IL_00f5: Unknown result type (might be due to invalid IL or missing references) //IL_0121: 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) //IL_012e: 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_0137: Unknown result type (might be due to invalid IL or missing references) //IL_013c: Unknown result type (might be due to invalid IL or missing references) //IL_0151: Unknown result type (might be due to invalid IL or missing references) //IL_0159: Unknown result type (might be due to invalid IL or missing references) //IL_015e: Unknown result type (might be due to invalid IL or missing references) //IL_0191: Unknown result type (might be due to invalid IL or missing references) //IL_0196: Unknown result type (might be due to invalid IL or missing references) //IL_0197: Unknown result type (might be due to invalid IL or missing references) //IL_019c: Unknown result type (might be due to invalid IL or missing references) //IL_01fc: Unknown result type (might be due to invalid IL or missing references) //IL_0201: 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_0270: Unknown result type (might be due to invalid IL or missing references) //IL_0275: Unknown result type (might be due to invalid IL or missing references) //IL_0276: Unknown result type (might be due to invalid IL or missing references) //IL_027b: Unknown result type (might be due to invalid IL or missing references) //IL_02ce: Unknown result type (might be due to invalid IL or missing references) //IL_02d0: Unknown result type (might be due to invalid IL or missing references) //IL_02d5: Unknown result type (might be due to invalid IL or missing references) //IL_02da: Unknown result type (might be due to invalid IL or missing references) //IL_02dc: Unknown result type (might be due to invalid IL or missing references) //IL_02df: Unknown result type (might be due to invalid IL or missing references) //IL_02ea: Unknown result type (might be due to invalid IL or missing references) //IL_02ef: 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_02f7: Unknown result type (might be due to invalid IL or missing references) //IL_0302: Unknown result type (might be due to invalid IL or missing references) //IL_0307: Unknown result type (might be due to invalid IL or missing references) //IL_0326: Unknown result type (might be due to invalid IL or missing references) //IL_034a: Unknown result type (might be due to invalid IL or missing references) if (!_surfaces.Probe(p, out float height, out Vector3 normal, out string reason)) { if (_surfaces.Unsupported != null) { Name(_probeTransfer.PlacementSurfaceBlocks, _surfaces.Unsupported); } return Rejected(reason); } if (Math.Abs(height - _probeTransfer.Journey.Exit.y) > 24f) { return Rejected("vertical_range"); } p.y = height + _probeExtent - _probeCenterOffset.y + 0.15f; string text = Roof(new Vector3(p.x, height + 0.1f, p.z)); if (text != null) { Name(_probeTransfer.PlacementSurfaceBlocks, text + ":building_overhead"); return Rejected("building_overhead"); } Vector3 normal2 = p - _probeTransfer.Journey.Exit; if (((Vector3)(ref normal2)).sqrMagnitude > 3136f) { return Rejected("walkout_range"); } Vector3[] footprintOffsets = FootprintOffsets; foreach (Vector3 val in footprintOffsets) { if (!_surfaces.Probe(p + val * _probeHorizontalExtent, out float height2, out normal2, out string _) || !TameTravelPlacementRules.SupportedFootprint(height, height2, val * _probeHorizontalExtent, normal)) { return Rejected("footprint_support"); } } foreach (Vector3 player in _players) { normal2 = player - p; if (((Vector3)(ref normal2)).sqrMagnitude < (_probeHorizontalExtent + 1.5f) * (_probeHorizontalExtent + 1.5f)) { return Rejected("player_clearance"); } } foreach (Vector3 placement in _placements) { normal2 = placement - p; if (((Vector3)(ref normal2)).sqrMagnitude < (_probeHorizontalExtent + 6f) * (_probeHorizontalExtent + 6f)) { return Rejected("follower_clearance"); } } foreach (var creature in _creatures) { normal2 = creature.Position - p; if (((Vector3)(ref normal2)).sqrMagnitude < (_probeHorizontalExtent + creature.Clearance) * (_probeHorizontalExtent + creature.Clearance)) { return Rejected("creature_clearance"); } } Vector3 val2 = p + _probeCenterOffset; if (!Physics.CheckCapsule(val2 + _probeAxis * _probeHalfLine, val2 - _probeAxis * _probeHalfLine, _probeRadius + 0.05f, _solid, (QueryTriggerInteraction)1)) { return p; } if (_probeEvidence && !_probeWalkout) { Name(_probeTransfer.PlacementOverlapHits, Overlapping(val2)); } return Rejected("solid_overlap"); Vector3? Rejected(string reason3) { Note(reason3); return null; } } private string? Roof(Vector3 point) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0057: Unknown result type (might be due to invalid IL or missing references) int num = Physics.RaycastNonAlloc(point, Vector3.up, _roofs, 64f, _building, (QueryTriggerInteraction)1); string text = ((num == _roofs.Length) ? "roof_probe_capacity" : null); for (int i = 0; i < num; i++) { Collider collider = ((RaycastHit)(ref _roofs[i])).collider; _roofs[i] = default(RaycastHit); if (text == null && !((Object)(object)collider == (Object)null)) { ZNetView componentInParent = ((Component)collider).GetComponentInParent(); ZDO val = (((Object)(object)componentInParent != (Object)null) ? componentInParent.GetZDO() : null); if (val == null || val.GetLong(ZDOVars.s_creator, 0L) != 0L) { text = (((Object)(object)componentInParent != (Object)null) ? Utils.GetPrefabName(((Component)componentInParent).gameObject) : ((Object)collider).name); } } } return text; } private string Overlapping(Vector3 center) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Unknown result type (might be due to invalid IL or missing references) int num = Physics.OverlapCapsuleNonAlloc(center + _probeAxis * _probeHalfLine, center - _probeAxis * _probeHalfLine, _probeRadius + 0.05f, _overlaps, _solid, (QueryTriggerInteraction)1); string text = null; string text2 = null; for (int i = 0; i < num; i++) { Collider val = _overlaps[i]; _overlaps[i] = null; if ((Object)(object)val == (Object)null || text != null) { continue; } string text3 = LayerMask.LayerToName(((Component)val).gameObject.layer); ZNetView componentInParent = ((Component)val).GetComponentInParent(); string text4 = text3 + ":" + (((Object)(object)componentInParent != (Object)null) ? Utils.GetPrefabName(((Component)componentInParent).gameObject) : ((Object)val).name); if (text3 == "terrain") { if (text2 == null) { text2 = text4; } } else { text = text4; } } return text ?? text2 ?? "unknown"; } private void Name(Dictionary counts, string key) { if (_probeEvidence && !_probeWalkout) { Count(counts, (counts.Count >= 16 && !counts.ContainsKey(key)) ? "other" : key); } } private bool ProbeClear(Vector3 before, Vector3 after) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_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_0022: 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_002c: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_0039: 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_0051: Unknown result type (might be due to invalid IL or missing references) Vector3 val = before + _probeCenterOffset; Vector3 val2 = after - before; RaycastHit val3 = default(RaycastHit); bool num = !Physics.CapsuleCast(val + _probeAxis * _probeHalfLine, val - _probeAxis * _probeHalfLine, _probeRadius + 0.05f, ((Vector3)(ref val2)).normalized, ref val3, ((Vector3)(ref val2)).magnitude, _solid, (QueryTriggerInteraction)1); if (!num) { Note("walkout_collision"); } return num; } private void Note(string reason) { if (_probeEvidence) { if (_probeWalkout) { Count(_probeTransfer.PlacementWalkoutRejections, reason); } else { _candidateReason = reason; } } } private static void Reject(AnimalTransfer t, string reason) { Count(t.PlacementRejections, reason); } private static void Count(Dictionary counts, string reason) { counts[reason] = ((!counts.TryGetValue(reason, out var value)) ? 1 : (value + 1)); } public static void Move(AnimalTransfer t, Vector3 position) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0009: Unknown result type (might be due to invalid IL or missing references) //IL_000e: 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_0021: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_0067: Unknown result type (might be due to invalid IL or missing references) //IL_0074: 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_0094: 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_0051: Unknown result type (might be due to invalid IL or missing references) //IL_0056: Unknown result type (might be due to invalid IL or missing references) //IL_005b: Unknown result type (might be due to invalid IL or missing references) //IL_005c: 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_00f0: 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_011c: 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_0131: Unknown result type (might be due to invalid IL or missing references) //IL_013d: Unknown result type (might be due to invalid IL or missing references) //IL_01d8: Unknown result type (might be due to invalid IL or missing references) //IL_01d9: Unknown result type (might be due to invalid IL or missing references) //IL_01de: Unknown result type (might be due to invalid IL or missing references) //IL_01ee: Unknown result type (might be due to invalid IL or missing references) ZDO record = t.Record; Vector3 val = position - record.GetPosition(); record.Set(ZDOVars.s_spawnPoint, record.GetVec3(ZDOVars.s_spawnPoint, record.GetPosition()) + val); if (record.GetBool(ZDOVars.s_patrol, false)) { record.Set(ZDOVars.s_patrolPoint, record.GetVec3(ZDOVars.s_patrolPoint, record.GetPosition()) + val); } record.SetPosition(position); record.SetRotation(t.Journey.DestinationRotation); record.Set(ZDOVars.s_velHash, Vector3.zero); record.Set(ZDOVars.s_bodyVelHash, Vector3.zero); record.Set(ZDOVars.s_bodyAVelHash, Vector3.zero); record.Set("heimkit_tametravel_stamp", ZNet.instance.GetTime().Ticks); ZNetView val2 = ZNetScene.instance.FindInstance(record); if ((Object)(object)val2 != (Object)null) { ((Component)val2).transform.SetPositionAndRotation(position, t.Journey.DestinationRotation); Rigidbody component = ((Component)val2).GetComponent(); if ((Object)(object)component != (Object)null) { component.position = position; component.rotation = t.Journey.DestinationRotation; if (!component.isKinematic) { component.linearVelocity = Vector3.zero; component.angularVelocity = Vector3.zero; } } Character component2 = ((Component)val2).GetComponent(); if ((Object)(object)component2 != (Object)null) { ResetGround(component2); MaxAltitude.Invoke(component2) = position.y; LastGroundTouch.Invoke(component2) = 1f; FallTimer.Invoke(component2) = 0f; } MonsterAI component3 = ((Component)val2).GetComponent(); if ((Object)(object)component3 != (Object)null) { Path.Invoke((BaseAI)(object)component3)?.Clear(); SpawnPoint.Invoke((BaseAI)(object)component3) = record.GetVec3(ZDOVars.s_spawnPoint, position); GameObject val3 = ZNetScene.instance.FindInstance(t.Journey.Character); if (t.Waiting) { component3.SetFollowTarget((GameObject)null); ((BaseAI)component3).SetPatrolPoint(); } else if ((Object)(object)val3 != (Object)null) { component3.SetFollowTarget(val3); } } } Physics.SyncTransforms(); } private static float BodyClearance(ZDO z) { //IL_0052: Unknown result type (might be due to invalid IL or missing references) CapsuleCollider val = PrefabRegistry.Component(PrefabRegistry.Current.Prefab(z.GetPrefab())); if ((Object)(object)val == (Object)null || !TameTravelRules.Scale(z, out var scale)) { return 32f; } return (val.radius + ((val.direction == 1) ? 0f : (val.height * 0.5f))) * scale.x + 1f; } public void Dispose() { _context.Dispose(); if ((Object)(object)_padding != (Object)null) { Object.Destroy((Object)(object)((Component)_padding).gameObject); _padding = null; } } } internal sealed class TameTravelPlacementAccess { private readonly List _path = new List(); private readonly int _walls = LayerMask.GetMask(new string[6] { "Default", "static_solid", "Default_small", "piece", "terrain", "vehicle" }); internal void Warm(Vector3 traveller, Vector3 exit) { //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) if (!((Object)(object)Pathfinding.instance == (Object)null)) { Pathfinding.instance.GetPath(traveller, exit, _path, (AgentType)5, false, false, false); _path.Clear(); } } internal bool Reachable(Vector3 traveller, Vector3 landing, out string reason) { //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_001a: Unknown result type (might be due to invalid IL or missing references) //IL_003b: Unknown result type (might be due to invalid IL or missing references) //IL_003c: Unknown result type (might be due to invalid IL or missing references) reason = "access_path_unready_or_blocked"; if ((Object)(object)Pathfinding.instance == (Object)null || !Pathfinding.instance.GetPath(traveller, landing, _path, (AgentType)5, true, false, true) || _path.Count == 0) { return false; } return Validate(traveller, landing, _path, Clear, out reason); } internal static bool Validate(Vector3 traveller, Vector3 landing, IReadOnlyList path, Func clear, out string reason) { //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_0035: 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_0052: Unknown result type (might be due to invalid IL or missing references) //IL_0053: Unknown result type (might be due to invalid IL or missing references) //IL_0069: Unknown result type (might be due to invalid IL or missing references) //IL_0064: Unknown result type (might be due to invalid IL or missing references) //IL_006e: Unknown result type (might be due to invalid IL or missing references) //IL_006f: Unknown result type (might be due to invalid IL or missing references) //IL_0082: Unknown result type (might be due to invalid IL or missing references) //IL_0083: 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_008d: Unknown result type (might be due to invalid IL or missing references) //IL_00ad: Unknown result type (might be due to invalid IL or missing references) //IL_00ae: Unknown result type (might be due to invalid IL or missing references) //IL_00af: 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_00d8: Unknown result type (might be due to invalid IL or missing references) //IL_00d9: Unknown result type (might be due to invalid IL or missing references) //IL_00c5: Unknown result type (might be due to invalid IL or missing references) //IL_00c6: Unknown result type (might be due to invalid IL or missing references) reason = "access_endpoint_snap"; if (path.Count == 0 || path.Count > 128 || !Near(path[0], traveller) || !Near(path[path.Count - 1], landing)) { reason = "access_endpoint_snap"; return false; } float num = 0f; Vector3 val = traveller; for (int i = 0; i <= path.Count; i++) { Vector3 val2 = ((i < path.Count) ? path[i] : landing); if (!PlayerWorldScope.Finite(val2)) { reason = "access_path_invalid"; return false; } num += Vector3.Distance(val, val2); if (num > Vector3.Distance(traveller, landing) + 12f || num > 96f) { reason = "access_route_detour"; return false; } Vector3 val3 = val2 - val; if (((Vector3)(ref val3)).sqrMagnitude > 0.0001f && !clear(val, val2)) { reason = "access_wall_collision"; return false; } val = val2; } reason = "accessible"; return true; } private bool Clear(Vector3 start, Vector3 end) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_000a: 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_0016: Unknown result type (might be due to invalid IL or missing references) //IL_0028: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Unknown result type (might be due to invalid IL or missing references) if (!Occupied(start) && !Occupied(end) && !Blocked(start, end - start, 0.8f)) { return !Blocked(start, end - start, 1.5f); } return false; } private bool Occupied(Vector3 point) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0028: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Unknown result type (might be due to invalid IL or missing references) //IL_0038: Unknown result type (might be due to invalid IL or missing references) if (!Physics.CheckSphere(point + Vector3.up * 0.8f, 0.2f, _walls, (QueryTriggerInteraction)1)) { return Physics.CheckSphere(point + Vector3.up * 1.5f, 0.2f, _walls, (QueryTriggerInteraction)1); } return true; } private bool Blocked(Vector3 start, Vector3 delta, float height) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0007: 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_0018: Unknown result type (might be due to invalid IL or missing references) RaycastHit val = default(RaycastHit); return Physics.SphereCast(start + Vector3.up * height, 0.2f, ((Vector3)(ref delta)).normalized, ref val, ((Vector3)(ref delta)).magnitude, _walls, (QueryTriggerInteraction)1); } private static bool Near(Vector3 point, Vector3 target) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_0028: Unknown result type (might be due to invalid IL or missing references) Vector3 val = point - target; Vector2 val2 = new Vector2(val.x, val.z); if (((Vector2)(ref val2)).sqrMagnitude <= 1f) { return Mathf.Abs(val.y) <= 1f; } return false; } } internal static class TameTravelPlacementRules { internal const int MaximumEscapeProbes = 64; internal const int MaximumCandidatesPerPass = 64; internal const int MaximumPushes = 3; internal const float LandingRadius = 48f; internal const float ContextRadius = 56f; internal const float ObstaclePadding = 0.75f; internal const float ArcStep = 0.25f; internal const float SweepLimit = 12f; internal static float GridSpacing(float extent) { return Math.Max(2f, Math.Min(3f, extent)); } internal static float ArcStart(float extent) { return extent + 1.55f; } internal static float ArcSpacing(float extent) { return Math.Max(0.25f, extent * 0.5f); } internal static int Arcs(float extent) { return Math.Max(1, (int)Math.Floor((double)((12f - ArcStart(extent)) / 0.25f) + 0.0001) + 1); } internal static int CandidateCount(float extent) { int num = 2 * (int)Math.Ceiling(48f / GridSpacing(extent)) + 1; return ArcCandidates(extent) + num * num * 2; } internal static int ArcCandidates(float extent) { int num = 0; int i = 0; for (int num2 = Arcs(extent); i < num2; i++) { num += ArcPoints(i, num2, extent); } return num; } private static void Divisions(int arc, int arcs, float extent, out float radius, out int front, out int behind, out float extra, out bool full) { radius = ArcStart(extent) + (float)arc * 0.25f; float num = ArcSpacing(extent); extra = ((arcs > 1) ? (MathF.PI / 2f * (float)arc / (float)(arcs - 1)) : 0f); front = Math.Max(1, (int)Math.Ceiling(Math.PI * (double)radius / (double)num)); behind = ((!(extra <= 0f)) ? ((int)Math.Ceiling(extra * radius / num)) : 0); full = arc == arcs - 1 && arcs > 1; } private static int ArcPoints(int arc, int arcs, float extent) { Divisions(arc, arcs, extent, out var _, out var front, out var behind, out var _, out var full); return front + 1 + 2 * behind - (full ? 1 : 0); } internal static Vector3 Candidate(int index, float extent, Vector3 exit, Vector3 traveller, Vector3 forward) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_000e: 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_00fd: Unknown result type (might be due to invalid IL or missing references) //IL_0101: Unknown result type (might be due to invalid IL or missing references) //IL_00b9: Unknown result type (might be due to invalid IL or missing references) //IL_00ba: Unknown result type (might be due to invalid IL or missing references) //IL_00c4: Unknown result type (might be due to invalid IL or missing references) //IL_00c9: Unknown result type (might be due to invalid IL or missing references) //IL_00d2: 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_00de: 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_0109: Unknown result type (might be due to invalid IL or missing references) //IL_0190: Unknown result type (might be due to invalid IL or missing references) //IL_0191: Unknown result type (might be due to invalid IL or missing references) //IL_0195: Unknown result type (might be due to invalid IL or missing references) //IL_019a: Unknown result type (might be due to invalid IL or missing references) //IL_019f: Unknown result type (might be due to invalid IL or missing references) //IL_01a4: Unknown result type (might be due to invalid IL or missing references) //IL_01af: Unknown result type (might be due to invalid IL or missing references) //IL_01b4: Unknown result type (might be due to invalid IL or missing references) Vector3 val = default(Vector3); ((Vector3)(ref val))..ctor(forward.z, 0f, 0f - forward.x); int i = 0; for (int num = Arcs(extent); i < num; i++) { Divisions(i, num, extent, out var radius, out var front, out var behind, out var extra, out var _); int num2 = ArcPoints(i, num, extent); if (index >= num2) { index -= num2; continue; } double num3 = ((index <= front) ? (Math.PI / 2.0 - (double)index * Math.PI / (double)front) : ((index <= front + behind) ? (Math.PI / 2.0 + (double)((float)(index - front) * extra / (float)behind)) : (-Math.PI / 2.0 - (double)((float)(index - front - behind) * extra / (float)behind)))); return traveller + (forward * (float)Math.Cos(num3) + val * (float)Math.Sin(num3)) * radius; } Vector3 val2 = ((index % 2 == 0) ? exit : traveller); int num4 = index / 2; if (num4 == 0) { return val2; } int num5 = (int)Math.Ceiling((Math.Sqrt(num4 + 1) - 1.0) / 2.0); int num6 = 2 * num5; int num7 = num4 - (2 * num5 - 1) * (2 * num5 - 1); int num8 = num7 / num6; int num9 = num7 % num6; return val2 + (val * (float)(num8 switch { 2 => num5 - num9, 1 => num5, 0 => -num5 + num9, _ => -num5, }) + forward * (float)(num8 switch { 2 => num5, 1 => -num5 + num9, 0 => -num5, _ => num5 - num9, })) * GridSpacing(extent); } internal static bool SupportedFootprint(float centerHeight, float sampleHeight, Vector3 offset, Vector3 normal) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Unknown result type (might be due to invalid IL or missing references) if (normal.y < 0.8f || !PlayerWorldScope.Finite(sampleHeight)) { return false; } float num = centerHeight - (normal.x * offset.x + normal.z * offset.z) / normal.y; return Math.Abs(sampleHeight - num) <= 0.5f; } internal static bool EscapeDeferred(int probesBefore, int probesAfter) { if (probesBefore > 0) { return probesAfter >= 64; } return false; } internal static bool HasEscape(Vector3 start, Vector3 outward, float distance, Func ground, Func clear, ref int probes) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_0048: Unknown result type (might be due to invalid IL or missing references) //IL_004d: Unknown result type (might be due to invalid IL or missing references) //IL_0051: Unknown result type (might be due to invalid IL or missing references) //IL_005c: Unknown result type (might be due to invalid IL or missing references) //IL_008f: Unknown result type (might be due to invalid IL or missing references) //IL_0097: 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_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_00ae: Unknown result type (might be due to invalid IL or missing references) //IL_00b0: Unknown result type (might be due to invalid IL or missing references) //IL_00b1: Unknown result type (might be due to invalid IL or missing references) //IL_00cd: Unknown result type (might be due to invalid IL or missing references) //IL_00ce: 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_00dd: Unknown result type (might be due to invalid IL or missing references) //IL_00f4: 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_010c: Unknown result type (might be due to invalid IL or missing references) //IL_012d: Unknown result type (might be due to invalid IL or missing references) //IL_0131: 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_0144: Unknown result type (might be due to invalid IL or missing references) if (!PlayerWorldScope.Finite(start) || !PlayerWorldScope.Finite(outward) || !PlayerWorldScope.Finite(distance) || distance < 3f || distance > 32f) { return false; } outward.y = 0f; if (((Vector3)(ref outward)).sqrMagnitude < 0.001f) { return false; } outward = ((Vector3)(ref outward)).normalized; Vector3 val = default(Vector3); ((Vector3)(ref val))..ctor(outward.z, 0f, 0f - outward.x); int num = (int)Math.Ceiling(distance); for (int i = 0; i < 8; i++) { double num2 = (double)i * Math.PI / 4.0; Vector3 val2 = outward * (float)Math.Cos(num2) + val * (float)Math.Sin(num2); Vector3 val3 = start; for (int j = 1; j <= num; j++) { if (probes >= 64) { return false; } probes++; Vector3? val4 = ground(start + val2 * (distance * (float)j / (float)num)); if (!val4.HasValue || !PlayerWorldScope.Finite(val4.Value) || Math.Abs(val4.Value.y - val3.y) > 0.75f * distance / (float)num + 0.05f || !clear(val3, val4.Value)) { break; } val3 = val4.Value; if (j == num) { return true; } } } return false; } } internal sealed class TameTravelPlacementSurfaces { internal const float MaximumSlabThickness = 1.25f; private readonly RaycastHit[] _hits = (RaycastHit[])(object)new RaycastHit[32]; private readonly int _pieces = LayerMask.GetMask(new string[1] { "piece" }); public string? Unsupported { get; private set; } internal bool Probe(Vector3 point, out float height, out Vector3 normal, out string reason) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_001a: 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) //IL_0059: Unknown result type (might be due to invalid IL or missing references) //IL_0073: Unknown result type (might be due to invalid IL or missing references) //IL_0080: Unknown result type (might be due to invalid IL or missing references) //IL_0086: Unknown result type (might be due to invalid IL or missing references) //IL_008b: Unknown result type (might be due to invalid IL or missing references) //IL_00d2: Unknown result type (might be due to invalid IL or missing references) //IL_00ec: Unknown result type (might be due to invalid IL or missing references) //IL_0151: 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_010f: 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) //IL_01cf: Unknown result type (might be due to invalid IL or missing references) //IL_01d4: Unknown result type (might be due to invalid IL or missing references) //IL_01d8: 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_0204: Unknown result type (might be due to invalid IL or missing references) //IL_025c: 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_026f: Unknown result type (might be due to invalid IL or missing references) normal = Vector3.up; reason = "terrain_missing"; Unsupported = null; if (!Heightmap.GetHeight(point, ref height)) { return false; } Vector3 val = default(Vector3); ((Vector3)(ref val))..ctor(point.x, height, point.z); Biome val2 = default(Biome); BiomeArea val3 = default(BiomeArea); Heightmap val4 = default(Heightmap); ZoneSystem.instance.GetGroundData(ref val, ref normal, ref val2, ref val3, ref val4); if ((Object)(object)val4 == (Object)null) { return false; } if (val4.GetLava(val) > 0f) { reason = "lava"; return false; } float num = height; int num2 = Physics.RaycastNonAlloc(new Vector3(point.x, num + 3.5f, point.z), Vector3.down, _hits, 3.6f, _pieces, (QueryTriggerInteraction)1); if (num2 == _hits.Length) { reason = "surface_probe_capacity"; return false; } int num3 = -1; for (int i = 0; i < num2; i++) { if (((RaycastHit)(ref _hits[i])).point.y > num && ((RaycastHit)(ref _hits[i])).normal.y >= 0.8f && (num3 < 0 || ((RaycastHit)(ref _hits[i])).point.y > ((RaycastHit)(ref _hits[num3])).point.y)) { num3 = i; } } if (num3 >= 0) { RaycastHit val5 = _hits[num3]; Piece componentInParent = ((Component)((RaycastHit)(ref val5)).collider).GetComponentInParent(); WearNTear val6 = (((Object)(object)componentInParent == (Object)null) ? null : ((Component)componentInParent).GetComponent()); bool piece = (Object)(object)componentInParent != (Object)null; int comfort = (((Object)(object)componentInParent != (Object)null) ? componentInParent.m_comfort : 0); bool structural = (Object)(object)val6 != (Object)null; bool isStatic = (Object)(object)val6 != (Object)null && val6.m_staticPosition; bool supports = (Object)(object)val6 != (Object)null && val6.m_supports; Bounds bounds = ((RaycastHit)(ref val5)).collider.bounds; string text = SurfaceRejection(piece, comfort, structural, isStatic, supports, ((Bounds)(ref bounds)).size, ((RaycastHit)(ref val5)).point.y - num); for (int j = 0; j < num2; j++) { _hits[j] = default(RaycastHit); } if (text != null) { Unsupported = (((Object)(object)componentInParent != (Object)null) ? Utils.GetPrefabName(((Component)componentInParent).gameObject) : ((Object)((RaycastHit)(ref val5)).collider).name) + ":" + text; reason = "unsupported_surface"; return false; } height = ((RaycastHit)(ref val5)).point.y; normal = ((RaycastHit)(ref val5)).normal; } reason = ((normal.y < 0.8f) ? "slope" : ((height <= ZoneSystem.instance.m_waterLevel + 0.5f) ? "water" : "supported")); return reason == "supported"; } internal static bool LowSlab(Vector3 size, float aboveTerrain) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) return SlabRejection(size, aboveTerrain) == null; } internal static string? SurfaceRejection(bool piece, int comfort, bool structural, bool isStatic, bool supports, Vector3 size, float aboveTerrain) { //IL_0010: Unknown result type (might be due to invalid IL or missing references) if (piece) { if (comfort == 0) { if (structural) { if (isStatic) { if (supports) { return SlabRejection(size, aboveTerrain); } return "not_supporting"; } return "not_static"; } return "not_structural"; } return "furniture"; } return "not_a_piece"; } internal static string? SlabRejection(Vector3 size, float aboveTerrain) { //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_002a: 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) if (!(aboveTerrain < 0f) && !(aboveTerrain > 3f)) { if (!(size.y <= 0f) && !(size.y > 1.25f)) { if (!(size.x < 0.5f) && !(size.z < 0.5f)) { return null; } return "too_narrow"; } return "too_thick"; } return "raised_construction"; } } internal static class TameTravelPortalRules { internal const float WitnessLifetime = 6f; internal static string? PairRejection(bool linked, bool destinationPresent, string? destinationRejection, bool reciprocal, string sourceTag, string destinationTag, float separationSquared, bool portalsDisabled) { if (portalsDisabled) { return "portals_disabled"; } if (!linked) { return "source_unlinked"; } if (!destinationPresent) { return "destination_record_missing"; } if (destinationRejection != null) { return "destination_" + destinationRejection; } if (!reciprocal) { return "destination_link_not_reciprocal"; } if (!string.Equals(sourceTag, destinationTag, StringComparison.Ordinal)) { return "portal_tag_mismatch"; } if (!PlayerWorldScope.Finite(separationSquared) || separationSquared < 400f) { return "portal_separation_invalid"; } return null; } internal static bool CanWait(string reason) { switch (reason) { case "source_unlinked": case "destination_record_missing": case "destination_link_not_reciprocal": return true; default: return false; } } internal static bool WitnessValid(float age) { if (PlayerWorldScope.Finite(age) && age >= 0f) { return age <= 6f; } return false; } } internal sealed class TameTravelPositionHistory { public const int Capacity = 32; private readonly Queue _positions = new Queue(); private uint _revision; public int Count => _positions.Count; public bool Overflowed { get; private set; } public void Add(PositionObservation observation) { if (observation.Revision > _revision) { _revision = observation.Revision; if (_positions.Count == 32) { _positions.Clear(); Overflowed = true; } _positions.Enqueue(observation); } } public bool Take(out PositionObservation observation) { if (_positions.Count == 0) { observation = default(PositionObservation); return false; } observation = _positions.Dequeue(); return true; } public void AcknowledgeOverflow() { Overflowed = false; } } internal sealed class TameTravelRules { private readonly IPlayerPresence _presence; private readonly PrefabCatalog _animals = PrefabRegistry.Current.Catalog("TameTravelRules._animals"); public TameTravelRules(IPlayerPresence presence) { _presence = presence; string[] array = new string[6] { "Wolf", "Boar", "Lox", "Asksvin", "Hen", "Moose" }; int num = 0; while (num < array.Length) { string text = array[num]; GameObject val = PrefabRegistry.Current.Prefab(text); ZSyncTransform val2 = PrefabRegistry.Component(val); if (!((Object)(object)val == (Object)null) && !((Object)(object)PrefabRegistry.Component(val) == (Object)null) && !((Object)(object)PrefabRegistry.Component(val) == (Object)null) && !((Object)(object)PrefabRegistry.Component(val) == (Object)null)) { ZNetView? obj = PrefabRegistry.Component(val); if (obj != null && obj.m_persistent && !((Object)(object)val2 == (Object)null) && val2.m_syncPosition && !val2.m_characterParentSync && !((Object)(object)PrefabRegistry.Component(val) == (Object)null)) { _animals.Add(StringExtensionMethods.GetStableHashCode(text), val); num++; continue; } } throw new InvalidOperationException("Unsupported native tame definition: " + text); } } public bool Actor(ZNetPeer peer, out ZDO actor) { return ActorRejection(peer, out actor) == null; } internal bool ConnectedName(string name) { return ConnectedName(_presence, name); } internal static bool ConnectedName(IPlayerPresence presence, string name) { if (!presence.ConnectedCount.HasValue) { return true; } foreach (ZNetPeer peer in presence.Peers) { if (string.Equals(peer.m_playerName, name, StringComparison.Ordinal)) { return true; } } return false; } internal bool ConnectedPeer(ZNetPeer peer) { if (!_presence.ConnectedCount.HasValue) { return true; } foreach (ZNetPeer peer2 in _presence.Peers) { if (peer2 == peer) { return true; } } return false; } public string? ActorRejection(ZNetPeer peer, out ZDO actor) { //IL_008d: 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_00df: Unknown result type (might be due to invalid IL or missing references) actor = null; bool flag = false; int num = 0; IReadOnlyList peers = _presence.Peers; for (int i = 0; i < peers.Count; i++) { if (peers[i] == peer) { flag = true; } if (peers[i].IsReady() && string.Equals(peers[i].m_playerName, peer.m_playerName, StringComparison.Ordinal)) { num++; } } if (!peer.IsReady() || !flag) { return "peer_not_ready"; } if (((ZDOID)(ref peer.m_characterID)).IsNone()) { return "character_not_ready"; } ZDO zDO = ZDOMan.instance.GetZDO(peer.m_characterID); if (zDO == null || !zDO.IsValid()) { return "character_missing"; } if (zDO.GetOwner() != peer.m_uid) { return "character_owner_changed"; } if (!NativeCharacterHealth.IsAlive(zDO)) { return "character_not_alive"; } if (!PlayerWorldScope.Finite(zDO.GetPosition())) { return "character_position_invalid"; } if (Character.InInterior(zDO.GetPosition())) { return "character_interior"; } if (string.IsNullOrEmpty(peer.m_playerName)) { return "player_name_unavailable"; } if (num != 1) { return "player_name_ambiguous"; } if (zDO.GetString(ZDOVars.s_playerName, "") != peer.m_playerName) { return "character_name_mismatch"; } actor = zDO; return null; } public bool Animal(ZDO? z) { return AnimalRejection(z) == null; } public string? AnimalRejection(ZDO? z) { //IL_007c: Unknown result type (might be due to invalid IL or missing references) //IL_008f: Unknown result type (might be due to invalid IL or missing references) if (z == null) { return "animal_missing"; } if (!z.IsValid()) { return "animal_invalid"; } if (!z.Persistent) { return "animal_not_persistent"; } if (!_animals.ContainsKey(z.GetPrefab())) { return "animal_prefab_changed"; } if (!z.GetBool(ZDOVars.s_tamed, false)) { return "animal_not_tamed"; } if (z.GetBool(ZDOVars.s_dead, false)) { return "animal_dead"; } if (z.GetLong(ZDOVars.s_user, 0L) != 0L) { return "animal_ridden"; } if (!PlayerWorldScope.Finite(z.GetPosition())) { return "animal_position_invalid"; } if (Character.InInterior(z.GetPosition())) { return "animal_interior"; } if (!NativeCharacterHealth.IsAlive(z)) { return "animal_health_invalid"; } if (!Scale(z, out var _)) { return "animal_scale_unsupported"; } return null; } public GameObject Prefab(ZDO z) { return _animals[z.GetPrefab()]; } public bool Supported(ZDO z) { return _animals.ContainsKey(z.GetPrefab()); } public static bool Scale(ZDO z, out Vector3 scale) { //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_0028: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_0077: Unknown result type (might be due to invalid IL or missing references) //IL_0055: Unknown result type (might be due to invalid IL or missing references) //IL_0066: Unknown result type (might be due to invalid IL or missing references) //IL_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) GameObject val = PrefabRegistry.Current.Prefab(z.GetPrefab()); scale = z.GetVec3(ZDOVars.s_scaleHash, Vector3.zero); if (scale == Vector3.zero) { float num = z.GetFloat(ZDOVars.s_scaleScalarHash, ((Object)(object)val != (Object)null) ? val.transform.localScale.x : 1f); scale = Vector3.one * num; } if (PlayerWorldScope.Finite(scale) && scale.x >= 0.25f && scale.x <= 4f && Math.Abs(scale.x - scale.y) < 0.001f) { return Math.Abs(scale.x - scale.z) < 0.001f; } return false; } public static CandidateView? Nearby(Vector3 point) { //IL_000f: Unknown result type (might be due to invalid IL or missing references) return WorldObjectProvider.Current.For("TameTravel").Nearby(point); } public static TeleportWorld? Portal(ZDO? z) { if (PortalRejection(z) != null) { return null; } return PrefabRegistry.Component(PrefabRegistry.Current.Prefab(z.GetPrefab())); } public static string? PortalRejection(ZDO? z) { //IL_0051: Unknown result type (might be due to invalid IL or missing references) //IL_005e: Unknown result type (might be due to invalid IL or missing references) //IL_007a: Unknown result type (might be due to invalid IL or missing references) //IL_007b: Unknown result type (might be due to invalid IL or missing references) //IL_0080: 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) if (z == null || !z.IsValid()) { return "record_missing"; } if (z.GetPrefab() != StringExtensionMethods.GetStableHashCode("portal_wood") && z.GetPrefab() != StringExtensionMethods.GetStableHashCode("portal_stone")) { return "prefab_unsupported"; } if (z.GetLong(ZDOVars.s_creator, 0L) == 0L) { return "not_player_built"; } if (!PlayerWorldScope.Finite(z.GetPosition()) || Character.InInterior(z.GetPosition())) { return "position_unsupported"; } if (Scale(z, out var scale)) { Vector3 val = scale - Vector3.one; if (!(((Vector3)(ref val)).sqrMagnitude > 0.0001f)) { if (!((Object)(object)PrefabRegistry.Component(PrefabRegistry.Current.Prefab(z.GetPrefab())) == (Object)null)) { return null; } return "definition_unavailable"; } } return "scale_unsupported"; } public static bool Trigger(ZDO portal, ZDO actor, out Bounds box) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0084: Unknown result type (might be due to invalid IL or missing references) //IL_0089: Unknown result type (might be due to invalid IL or missing references) //IL_008e: Unknown result type (might be due to invalid IL or missing references) //IL_0093: Unknown result type (might be due to invalid IL or missing references) //IL_0096: Unknown result type (might be due to invalid IL or missing references) //IL_0098: Unknown result type (might be due to invalid IL or missing references) //IL_009d: Unknown result type (might be due to invalid IL or missing references) //IL_00a2: Unknown result type (might be due to invalid IL or missing references) //IL_00a8: Unknown result type (might be due to invalid IL or missing references) //IL_00b2: Unknown result type (might be due to invalid IL or missing references) //IL_00b7: 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_013c: Unknown result type (might be due to invalid IL or missing references) //IL_0142: Unknown result type (might be due to invalid IL or missing references) //IL_0147: Unknown result type (might be due to invalid IL or missing references) //IL_0170: Unknown result type (might be due to invalid IL or missing references) //IL_017b: Unknown result type (might be due to invalid IL or missing references) //IL_0180: 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_00d7: Unknown result type (might be due to invalid IL or missing references) //IL_00f7: Unknown result type (might be due to invalid IL or missing references) //IL_00ee: 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_0105: Unknown result type (might be due to invalid IL or missing references) //IL_0116: Unknown result type (might be due to invalid IL or missing references) //IL_011b: Unknown result type (might be due to invalid IL or missing references) //IL_0120: Unknown result type (might be due to invalid IL or missing references) //IL_0125: Unknown result type (might be due to invalid IL or missing references) box = default(Bounds); GameObject val = PrefabRegistry.Current.Prefab(portal.GetPrefab()); if ((Object)(object)val == (Object)null) { return false; } TeleportWorldTrigger[] array = PrefabRegistry.Children(val, inactive: true); if (array.Length != 1) { return false; } BoxCollider val2 = PrefabRegistry.Component((Component?)(object)array[0]); CapsuleCollider val3 = PrefabRegistry.Component(PrefabRegistry.Current.Prefab(actor.GetPrefab())); if ((Object)(object)val2 == (Object)null || !((Collider)val2).isTrigger || (Object)(object)val3 == (Object)null || val3.direction != 1) { return false; } Vector3 val4 = val.transform.InverseTransformPoint(((Component)val2).transform.TransformPoint(val2.center)); box = new Bounds(val4, Vector3.zero); Vector3 val5 = val2.size * 0.5f; for (int i = 0; i < 8; i++) { ((Bounds)(ref box)).Encapsulate(val.transform.InverseTransformPoint(((Component)val2).transform.TransformPoint(val2.center + new Vector3(((i & 1) == 0) ? (0f - val5.x) : val5.x, ((i & 2) == 0) ? (0f - val5.y) : val5.y, ((i & 4) == 0) ? (0f - val5.z) : val5.z)))); } ((Bounds)(ref box)).center = ((Bounds)(ref box)).center - val3.center; ((Bounds)(ref box)).Expand(new Vector3(val3.radius * 2f, val3.height, val3.radius * 2f)); Vector3 size = ((Bounds)(ref box)).size; return ((Vector3)(ref size)).sqrMagnitude > 0f; } public static bool Crossed(ZDO portal, ZDO actor, Vector3 before, Vector3 after) { //IL_000e: 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_0018: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Unknown result type (might be due to invalid IL or missing references) //IL_0038: Unknown result type (might be due to invalid IL or missing references) //IL_003d: 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_0040: Unknown result type (might be due to invalid IL or missing references) //IL_0041: Unknown result type (might be due to invalid IL or missing references) if (!Trigger(portal, actor, out var box)) { return false; } Quaternion val = Quaternion.Inverse(portal.GetRotation()); before = val * (before - portal.GetPosition()); after = val * (after - portal.GetPosition()); return TameTravelTraversalRules.Touches(box, before, after); } } public sealed class TameTravelSettings { public ConfigEntry Enabled { get; } public ConfigEntry DebugMode { get; } public DebugLoggingPolicy DebugLogging { get; } public ConfigEntry CommandRangeMeters { get; } public ConfigEntry FollowSpacingEnabled { get; } public ConfigEntry FollowStopDistanceMeters { get; } public ConfigEntry FollowResumeDistanceMeters { get; } public ConfigEntry MaxControlledFollowers { get; } public ConfigEntry FollowerRangeMeters { get; } public ConfigEntry FollowConsentSeconds { get; } public ConfigEntry TravelWindowSeconds { get; } public ConfigEntry MaxFollowersPerTraversal { get; } public TameTravelSettings(ConfigFile config, ManualLogSource logger) { //IL_0068: Unknown result type (might be due to invalid IL or missing references) //IL_0072: Expected O, but got Unknown //IL_00bd: Unknown result type (might be due to invalid IL or missing references) //IL_00c7: Expected O, but got Unknown //IL_00f6: Unknown result type (might be due to invalid IL or missing references) //IL_0100: Expected O, but got Unknown //IL_0124: Unknown result type (might be due to invalid IL or missing references) //IL_012e: Expected O, but got Unknown //IL_015d: Unknown result type (might be due to invalid IL or missing references) //IL_0167: Expected O, but got Unknown //IL_0196: Unknown result type (might be due to invalid IL or missing references) //IL_01a0: Expected O, but got Unknown //IL_01cf: Unknown result type (might be due to invalid IL or missing references) //IL_01d9: Expected O, but got Unknown //IL_01fd: Unknown result type (might be due to invalid IL or missing references) //IL_0207: Expected O, but got Unknown Enabled = config.Bind("TameTravel", "Enabled", true, "Enable validated portal travel for explicitly following tames. Restart after edits."); DebugMode = config.Bind("TameTravel", "DebugMode", false, "Enable feature diagnostics through the shared debug policy."); CommandRangeMeters = config.Bind("TameTravel", "CommandRangeMeters", 8f, new ConfigDescription("Maximum follow/wait selection distance. Stay addresses your associated animals within 32 metres.", (AcceptableValueBase)(object)new AcceptableValueRange(2f, 12f), Array.Empty())); FollowSpacingEnabled = config.Bind("TameTravel", "FollowSpacingEnabled", true, "Use bounded server ownership to apply follow spacing after an explicit follow command. Restart after edits."); FollowStopDistanceMeters = config.Bind("TameTravel", "FollowStopDistanceMeters", 4f, new ConfigDescription("Horizontal follow stopping distance; enlarged when needed for animal and player clearance.", (AcceptableValueBase)(object)new AcceptableValueRange(3f, 12f), Array.Empty())); FollowResumeDistanceMeters = config.Bind("TameTravel", "FollowResumeDistanceMeters", 5f, new ConfigDescription("Horizontal distance to resume following; effective value is at least the stop distance plus one metre.", (AcceptableValueBase)(object)new AcceptableValueRange(4f, 16f), Array.Empty())); MaxControlledFollowers = config.Bind("TameTravel", "MaxControlledFollowers", 8, new ConfigDescription("Global cap on server-controlled followers; native following remains when capacity is unavailable.", (AcceptableValueBase)(object)new AcceptableValueRange(1, 16), Array.Empty())); FollowerRangeMeters = config.Bind("TameTravel", "FollowerRangeMeters", 20f, new ConfigDescription("Maximum follower distance from player and source portal at entry.", (AcceptableValueBase)(object)new AcceptableValueRange(5f, 32f), Array.Empty())); FollowConsentSeconds = config.Bind("TameTravel", "FollowConsentSeconds", 300f, new ConfigDescription("Optional portal-wait consent lifetime; one traversal consumes it. Active follow permission lasts for the current player session until stopped or invalidated.", (AcceptableValueBase)(object)new AcceptableValueRange(30f, 1800f), Array.Empty())); TravelWindowSeconds = config.Bind("TameTravel", "TravelWindowSeconds", 30f, new ConfigDescription("Maximum time to observe corresponding portal arrival.", (AcceptableValueBase)(object)new AcceptableValueRange(15f, 60f), Array.Empty())); MaxFollowersPerTraversal = config.Bind("TameTravel", "MaxFollowersPerTraversal", 8, new ConfigDescription("Maximum tames reserved for one traversal.", (AcceptableValueBase)(object)new AcceptableValueRange(1, 16), Array.Empty())); float[] array = new float[6] { CommandRangeMeters.Value, FollowStopDistanceMeters.Value, FollowResumeDistanceMeters.Value, FollowerRangeMeters.Value, FollowConsentSeconds.Value, TravelWindowSeconds.Value }; foreach (float f in array) { if (float.IsNaN(f) || float.IsInfinity(f)) { throw new ArgumentException("TameTravel settings must be finite."); } } DebugLogging = DebugLoggingResolver.Resolve(config, "TameTravel", DiagnosticsSettings.Bind(config), logger, DebugMode); } } internal sealed class TameTravelStops { private sealed class StopLease : OwnershipLease { public override ZNetPeer DestinationPeer => PreviousPeer; } private sealed class Stop { internal OwnershipLease Lease; internal string Name = ""; internal float Started; internal float ResetAt; internal bool Reset; internal bool Complete; internal readonly List<(ZNetPeer Peer, float Barrier)> Echoes = new List<(ZNetPeer, float)>(); } private readonly ObjectTransferAuthority _authority; private readonly TameTravelFollowing _following; private readonly IPlayerPresence _presence; private readonly ManualLogSource _log; private readonly Dictionary _stops = new Dictionary(); private readonly Dictionary _cleanup = new Dictionary(); private readonly List _expired = new List(); internal TameTravelStops(ObjectTransferAuthority authority, TameTravelFollowing following, IPlayerPresence presence, ManualLogSource log) { _authority = authority; _following = following; _presence = presence; _log = log; } internal bool Contains(ZDOID id) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) return _stops.ContainsKey(id); } internal void QueueCleanup(ZDO animal, string name, float now) { //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Unknown result type (might be due to invalid IL or missing references) if (_cleanup.Count < 512 || _cleanup.ContainsKey(animal.m_uid)) { _cleanup[animal.m_uid] = (animal, name); TryStop(animal, name, now); } } internal bool TryStop(ZDO animal, string name, float now) { //IL_0007: 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_0036: Unknown result type (might be due to invalid IL or missing references) //IL_0092: Unknown result type (might be due to invalid IL or missing references) //IL_00e8: Unknown result type (might be due to invalid IL or missing references) //IL_00a7: Unknown result type (might be due to invalid IL or missing references) //IL_00ac: Unknown result type (might be due to invalid IL or missing references) if (_stops.TryGetValue(animal.m_uid, out Stop value)) { if (value.Name != name) { return false; } if (!value.Complete) { return false; } _stops.Remove(animal.m_uid); return true; } string text = animal.GetString(ZDOVars.s_follow, ""); if ((text.Length != 0 && text != name) || _stops.Count >= 64) { return false; } OwnershipLease ownershipLease = _following.TakeForStop(animal.m_uid); if (ownershipLease == null) { if (_authority.Contains(animal.m_uid)) { return false; } ownershipLease = new StopLease { Id = animal.m_uid, Record = animal, FollowControl = true }; if (!_authority.Acquire(ownershipLease, now, allowDisconnectedOwner: true)) { return false; } } if (ownershipLease.Phase != 0) { ownershipLease.Phase = 1; } _stops.Add(animal.m_uid, new Stop { Lease = ownershipLease, Name = name, Started = now }); return false; } internal void Tick(float now) { //IL_0092: Unknown result type (might be due to invalid IL or missing references) //IL_00a6: Unknown result type (might be due to invalid IL or missing references) //IL_0078: Unknown result type (might be due to invalid IL or missing references) //IL_0055: Unknown result type (might be due to invalid IL or missing references) //IL_00fb: Unknown result type (might be due to invalid IL or missing references) //IL_04d3: Unknown result type (might be due to invalid IL or missing references) //IL_04d8: Unknown result type (might be due to invalid IL or missing references) //IL_04e0: Unknown result type (might be due to invalid IL or missing references) //IL_0149: Unknown result type (might be due to invalid IL or missing references) //IL_015d: Unknown result type (might be due to invalid IL or missing references) //IL_027c: Unknown result type (might be due to invalid IL or missing references) //IL_0290: Unknown result type (might be due to invalid IL or missing references) //IL_05ae: Unknown result type (might be due to invalid IL or missing references) //IL_0545: Unknown result type (might be due to invalid IL or missing references) //IL_0415: Unknown result type (might be due to invalid IL or missing references) //IL_0463: Unknown result type (might be due to invalid IL or missing references) //IL_05e5: Unknown result type (might be due to invalid IL or missing references) //IL_05ea: Unknown result type (might be due to invalid IL or missing references) //IL_05f2: Unknown result type (might be due to invalid IL or missing references) _expired.Clear(); foreach (KeyValuePair stop in _stops) { Stop value = stop.Value; OwnershipLease lease = value.Lease; if (value.Complete) { if (now - value.ResetAt > 15f) { _expired.Add(stop.Key); } continue; } if (!lease.Record.IsValid() || ZDOMan.instance.GetZDO(stop.Key) != lease.Record) { _authority.Release(stop.Key); _expired.Add(stop.Key); continue; } if (now - value.Started > 12f) { DiagnosticLog.Write(_log, "TameTravel", TameTravelLogTopics.Command, "Stay for " + value.Name + " could not be confirmed; client refresh or ownership drain timed out.", new(string, object)[2] { ("animal", stop.Key), ("stage", value.Reset ? "client_refresh" : "owner_drain") }, (LogLevel)4); _authority.Release(stop.Key); _expired.Add(stop.Key); continue; } if (lease.Phase == 0) { bool flag = false; foreach (ZNetPeer peer in _presence.Peers) { if (peer == lease.PreviousPeer && peer.IsReady()) { flag = true; break; } } if (flag && (!_authority.Echoed(lease.Barrier) || !lease.SourceStateObserved)) { if (_authority.Echoed(lease.Barrier)) { if (lease.SourceEchoTime == 0f) { lease.SourceEchoTime = now; } if (now - lease.SourceEchoTime >= 2f) { _authority.RequestSourceState(lease, now); } } continue; } lease.Phase = 1; } if (!value.Reset) { string text = lease.Record.GetString(ZDOVars.s_follow, ""); if (text.Length != 0 && text != value.Name) { _authority.Release(stop.Key); _expired.Add(stop.Key); continue; } if (!TameTravelFollowState.ClearLive(lease.Record, forget: false)) { continue; } foreach (ZNetPeer peer2 in _presence.Peers) { if (peer2.IsReady() && peer2.m_uid != ZDOMan.GetSessionID()) { value.Echoes.Add((peer2, _authority.ResetClientInstance(peer2, lease, now))); } } value.Reset = true; value.ResetAt = now; } bool flag2 = now - value.ResetAt >= 0.5f; foreach (var echo in value.Echoes) { bool flag3 = false; foreach (ZNetPeer peer3 in _presence.Peers) { if (peer3 == echo.Peer && peer3.IsReady()) { flag3 = true; break; } } if (flag3 && !_authority.Echoed(echo.Barrier)) { flag2 = false; break; } } if (flag2 && lease.Record.GetString(ZDOVars.s_follow, "").Length == 0) { TameTravelFollowState.Forget(lease.Record); _authority.Release(stop.Key); value.Complete = true; value.ResetAt = now; DiagnosticLog.Write(_log, "TameTravel", TameTravelLogTopics.Command, "Cleared native following for " + value.Name + ".", new(string, object)[2] { ("animal", stop.Key), ("client_caches", value.Echoes.Count) }, (LogLevel)16); } } foreach (ZDOID item2 in _expired) { _stops.Remove(item2); } _expired.Clear(); foreach (KeyValuePair item3 in _cleanup) { ZDO item = item3.Value.Item1; if (!item.IsValid() || ZDOMan.instance.GetZDO(item3.Key) != item || (item.GetString(ZDOVars.s_follow, "").Length != 0 && item.GetString(ZDOVars.s_follow, "") != item3.Value.Item2) || TryStop(item, item3.Value.Item2, now)) { _expired.Add(item3.Key); } } foreach (ZDOID item4 in _expired) { _cleanup.Remove(item4); } } internal void ClearPendingForShutdown() { foreach (Stop value in _stops.Values) { if (!value.Complete) { ClearForShutdown(value.Lease.Record, value.Name); } } foreach (var value2 in _cleanup.Values) { ClearForShutdown(value2.Record, value2.Name); } _stops.Clear(); _cleanup.Clear(); } internal void ClearForShutdown(ZDO animal, string name) { //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_0046: Unknown result type (might be due to invalid IL or missing references) //IL_005d: Unknown result type (might be due to invalid IL or missing references) //IL_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_011f: Unknown result type (might be due to invalid IL or missing references) //IL_010d: Unknown result type (might be due to invalid IL or missing references) if (!animal.IsValid() || ZDOMan.instance.GetZDO(animal.m_uid) != animal) { return; } string text = animal.GetString(ZDOVars.s_follow, ""); if (text.Length != 0 && text != name) { return; } _following.Stop(animal.m_uid, "session_ended"); _authority.Release(animal.m_uid); animal.SetOwner(ZDOMan.GetSessionID()); TameTravelFollowState.ClearLive(animal); StopLease stopLease = new StopLease { Id = animal.m_uid, Record = animal, FollowControl = true }; if (_authority.Acquire(stopLease, Time.unscaledTime, allowDisconnectedOwner: true)) { foreach (ZNetPeer peer in _presence.Peers) { if (peer.IsReady() && peer.m_uid != ZDOMan.GetSessionID()) { _authority.ResetClientInstance(peer, stopLease, Time.unscaledTime); } } _authority.Release(animal.m_uid); } ZDOMan.instance.ForceSendZDO(animal.m_uid); animal.SetOwner(0L); } } internal static class TameTravelTraversalRules { public static string CancellationMessage(string reason) { switch (reason) { case "traveller_left_destination": case "destination_distance_exceeded": return "Portal attempt ended: stay within 48 metres of the destination exit."; case "arrival_timeout": case "traversal_timeout": return "Portal attempt ended: the linked arrival did not finish in time."; case "pair_or_actor_changed": case "portal_pair_changed": return "Portal attempt ended: the portal link or character changed."; case "stale_position_observation": case "position_history_overflow": return "Portal attempt ended: player position updates were incomplete."; case "animal_left_source_range": return "Portal attempt ended: the animal moved too far from the source portal."; default: return "Portal attempt ended before animal relocation."; } } public static string? SourceRejection(float age, float gap, float distanceSquared) { if (!PlayerWorldScope.Finite(age) || age < 0f || age > 2f) { return "stale_position_observation"; } if (!PlayerWorldScope.Finite(distanceSquared) || distanceSquared > 144f) { return "jump_without_trigger_witness"; } if (!PlayerWorldScope.Finite(gap) || gap < 0f || gap > 2f) { return "source_sample_gap"; } return null; } public static float DestinationLimit(bool relocated) { return 48f; } public static bool PhaseExpired(int phase, bool placementStarted, float age) { if (phase != 1) { return age > 10f; } if (placementStarted) { return age > 30f; } return false; } public static string? DestinationRejection(float distanceSquared, float age, float window, bool relocated = false) { float num = DestinationLimit(relocated); if (!PlayerWorldScope.Finite(distanceSquared) || distanceSquared > num * num) { return "destination_distance_exceeded"; } if (!(age > window + 30f)) { return null; } return "traversal_timeout"; } public static string? ArrivalRejection(bool atExit, float age, float sourceDistanceSquared) { if (atExit) { if (!(age < 2f)) { return null; } return "arrival_too_early"; } if (!(sourceDistanceSquared > 144f)) { return null; } return "movement_outside_linked_endpoints"; } public static bool Touches(Bounds box, Vector3 before, Vector3 after) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_0028: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Unknown result type (might be due to invalid IL or missing references) if (!PlayerWorldScope.Finite(before) || !PlayerWorldScope.Finite(after)) { return false; } float num = 0f; float num2 = 1f; Vector3 min = ((Bounds)(ref box)).min; Vector3 max = ((Bounds)(ref box)).max; bool flag = true; bool flag2 = true; for (int i = 0; i < 3; i++) { flag &= ((Vector3)(ref before))[i] >= ((Vector3)(ref min))[i] && ((Vector3)(ref before))[i] <= ((Vector3)(ref max))[i]; flag2 &= ((Vector3)(ref after))[i] >= ((Vector3)(ref min))[i] && ((Vector3)(ref after))[i] <= ((Vector3)(ref max))[i]; } if (flag2) { return true; } if (flag) { return false; } for (int j = 0; j < 3; j++) { float num3 = ((Vector3)(ref after))[j] - ((Vector3)(ref before))[j]; if (Math.Abs(num3) < 1E-05f) { if (((Vector3)(ref before))[j] < ((Vector3)(ref min))[j] || ((Vector3)(ref before))[j] > ((Vector3)(ref max))[j]) { return false; } continue; } float val = (((Vector3)(ref min))[j] - ((Vector3)(ref before))[j]) / num3; float val2 = (((Vector3)(ref max))[j] - ((Vector3)(ref before))[j]) / num3; num = Math.Max(num, Math.Min(val, val2)); num2 = Math.Min(num2, Math.Max(val, val2)); if (num > num2) { return false; } } return true; } } } namespace HeimKit.Features.TameTravel.Models { internal sealed class AnimalTransfer : OwnershipLease { public PortalJourney Journey; public float Started; public float PhaseTime; public int PlacementCursor; public Vector3? PlacementAnchor; public int PlacementAttempts; public int PlacementCandidates; public Vector3? PlacementLastProbe; public float? PlacementSupportHeight; public float? PlacementAccessWarmupUntil; public double PlacementContextMilliseconds; public double PlacementSearchMilliseconds; public readonly Dictionary PlacementRejections = new Dictionary(); public readonly Dictionary PlacementWalkoutRejections = new Dictionary(); public readonly Dictionary PlacementWaitReasons = new Dictionary(); public readonly Dictionary PlacementSurfaceBlocks = new Dictionary(); public readonly Dictionary PlacementOverlapHits = new Dictionary(); public Vector3? PlacementTraveller; public bool Waiting; public bool PlacementStarted; public bool FollowContinues; public override ZNetPeer DestinationPeer => Journey.Peer; } internal sealed class FollowBinding { public ZNetPeer Peer; public ZDOID Character; public ZDOID Animal; public string Name = ""; public float Consent; public float Requested; public bool Pending; public bool CommandSent = true; public bool AwaitingEarlierFollow; public string ReclaimName = ""; public TameOrder Order; public Vector3 WaitPosition; } internal sealed class FollowingSession { public AnimalTransfer Lease; public bool Acquired; public bool Started; public bool Stopped; public float Requested; public float StopRequested = -1f; public float ContextAt = float.NegativeInfinity; public float NextContext; public float UnreadySince = -1f; public float StopDistance; public float ResumeDistance; public Vector3 ContextPosition; } internal sealed class PlayerSample { public ZNetPeer Peer; public ZDOID Character; public Vector3 Position; public float Time; public float CommandTime = -10f; public float BlockedUntil; public int Emote; public bool PlayerDataObserved; public readonly TameTravelPositionHistory Positions = new TameTravelPositionHistory(); public PortalJourney? Journey; public ZDOID ReentryPortal; public PortalWitness? PendingPortal; } internal sealed class PortalJourney { public ZNetPeer Peer; public ZDOID Character; public string Name = ""; public ZDOID Source; public ZDOID Destination; public Vector3 SourcePosition; public Vector3 DestinationPosition; public Vector3 Exit; public Quaternion SourceRotation; public Quaternion DestinationRotation; public string Tag = ""; public float Entered; public float Arrived = -1f; public float Barrier; public float PathWarmed = float.NegativeInfinity; public bool Ready; public string? EndReason; public readonly Queue Followers = new Queue(); public readonly HashSet Waiting = new HashSet(); public int Moved; public int Confirmed; } internal sealed class PortalWitness { public ZDO Source; public ZDOID SourceId; public ZDOID Destination; public string Tag = ""; public Vector3 Position; public Quaternion Rotation; public PositionObservation Observation; } internal readonly struct PositionObservation { public readonly Vector3 Position; public readonly float Time; public readonly uint Revision; public PositionObservation(Vector3 position, float time, uint revision) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Unknown result type (might be due to invalid IL or missing references) Position = position; Time = time; Revision = revision; } } internal enum TameOrder { Follow, Stay, Wait } internal sealed class TransferSnapshot { public string Reason = ""; public bool SameRecord; public long? Owner; public uint? DataRevision; public ushort? OwnerRevision; public Vector3? Position; public string? Follow; public float? Health; public bool? HealthSaved; public bool? Tamed; public long? Rider; public float PhaseAge; public bool BarrierEchoed; } } namespace HeimKit.Features.SharedMap { public sealed class SharedMap : IServerModule { private readonly SharedMapSettings _settings; private readonly ManualLogSource _logger; private readonly GameVersionCompatibility _compatibility; private readonly PlayerServices _players; private readonly PlayerProcessingNotices _processing; private IDisposable? _presenceRegistration; private bool _occupied; private SharedMapController? _controller; private SharedMapExploration? _exploration; private ZDOMan? _world; private long _worldUid; private readonly string _storeDirectory; private readonly SharedMapDiagnostics _diagnostics; private SharedMapStore? _store; private SharedMapBootstrap? _bootstrap; private SharedMapMarkerRefresh? _portalRefresh; private SharedMapResourceStore? _resources; private SharedMapMarkerRefresh? _resourceRefresh; private SharedMapDungeonStore? _dungeons; private SharedMapPinState? _pinState; private SharedMapLandmarkStore? _runestones; private SharedMapLandmarkStore? _spawners; internal string StoreDirectory => _storeDirectory; public string Name => "SharedMap"; public bool IsActive { get; private set; } public SharedMap(ConfigFile config, ManualLogSource logger, PlayerServices players) { _settings = new SharedMapSettings(config, logger); _logger = logger; _compatibility = GameVersionCompatibility.Resolve(config, logger); _players = players; _storeDirectory = Path.Combine(Path.GetDirectoryName(config.ConfigFilePath), "HeimKit", "SharedMap"); _diagnostics = new SharedMapDiagnostics(logger, _settings.DebugLogging); _processing = new PlayerProcessingNotices(logger, Name, () => _settings.DebugLogging.Enabled); } public void Initialize(string gameVersion) { Shutdown(); Log(_settings.Enabled.Value ? "Enabled." : "Disabled.", (LogLevel)16); _settings.DebugLogging.ReportStartup(_logger, Name, _settings.Enabled.Value); if (!_settings.Enabled.Value) { return; } if (!_compatibility.Supports(gameVersion)) { Log("DISABLED: unsupported game version " + gameVersion + "; required version " + _compatibility.RequiredVersion, (LogLevel)4); return; } IsActive = true; try { SharedMapPatches.CheckCompatibility(); if (_settings.ResourceMarkerSync.Value) { SharedMapResources.CheckCompatibility(); } if (_settings.DungeonMarkerSync.Value) { SharedMapDungeons.CheckCompatibility(); } if (_settings.RunestoneMarkerSync.Value || _settings.SpawnerMarkerSync.Value) { SharedMapLandmarks.CheckCompatibility(); } _presenceRegistration = _players.Events.Subscribe(PresenceChanged, Fail, () => _processing.IsEmptyPaused, () => _processing.IsRunning, () => _processing.IsServerReady); } catch (Exception error) { Fail(error); } } public void Tick(float now) { if (!IsActive) { return; } if (!_settings.Enabled.Value) { Shutdown(); return; } try { SaveIfDue(now); int num; if (PlayerServices.Ready && (Object)(object)ZoneSystem.instance != (Object)null && ZRoutedRpc.instance != null && (Object)(object)ZNetScene.instance != (Object)null) { num = (((Object)(object)Minimap.instance != (Object)null) ? 1 : 0); if (num != 0) { _processing.ServerReady(); } } else { num = 0; } if (num == 0) { StopController(); if (_occupied) { _processing.Paused("world or minimap services unavailable"); } return; } Minimap instance = Minimap.instance; if ((Object)(object)instance == (Object)null) { StopController(); return; } long worldUID = ZNet.instance.GetWorldUID(); if (_world != ZDOMan.instance || _worldUid != worldUID || _exploration == null || !_exploration.Matches(instance.m_textureSize, instance.m_pixelSize, instance.m_exploreRadius, instance.m_exploreInterval)) { StopController(); FlushStore(); FlushPortalState(); FlushResourceState(); FlushDungeonState(); SharedMapExploration sharedMapExploration = new SharedMapExploration(instance.m_textureSize, instance.m_pixelSize, instance.m_exploreRadius, instance.m_exploreInterval); SharedMapStore sharedMapStore = new SharedMapStore(_storeDirectory, worldUID, sharedMapExploration); bool flag = sharedMapStore.Load(); SharedMapMarkerRefresh sharedMapMarkerRefresh = new SharedMapMarkerRefresh(_storeDirectory, worldUID, _diagnostics.PortalPublished, _diagnostics.PortalRemoved); bool loaded = sharedMapMarkerRefresh.Load(); SharedMapResourceStore sharedMapResourceStore = null; SharedMapMarkerRefresh sharedMapMarkerRefresh2 = null; if (_settings.ResourceMarkerSync.Value) { sharedMapResourceStore = new SharedMapResourceStore(_storeDirectory, worldUID); bool discoveriesLoaded = sharedMapResourceStore.Load(); sharedMapMarkerRefresh2 = new SharedMapMarkerRefresh(_storeDirectory, worldUID, _diagnostics.ResourcePublished, null, resourcePins: true); bool publicationsLoaded = sharedMapMarkerRefresh2.Load(); _diagnostics.ResourceStateOpened(discoveriesLoaded, publicationsLoaded, sharedMapResourceStore.Deposits.Count); } _resources = sharedMapResourceStore; _resourceRefresh = sharedMapMarkerRefresh2; SharedMapDungeonStore sharedMapDungeonStore = null; if (_settings.DungeonMarkerSync.Value) { sharedMapDungeonStore = new SharedMapDungeonStore(_storeDirectory, worldUID); bool loaded2 = sharedMapDungeonStore.Load(); _diagnostics.DungeonStateOpened(loaded2, sharedMapDungeonStore.Count); } _dungeons = sharedMapDungeonStore; _runestones = (_settings.RunestoneMarkerSync.Value ? new SharedMapLandmarkStore(_storeDirectory, worldUID, spawners: false) : null); _spawners = (_settings.SpawnerMarkerSync.Value ? new SharedMapLandmarkStore(_storeDirectory, worldUID, spawners: true) : null); _runestones?.Load(); _spawners?.Load(); _pinState = new SharedMapPinState(_storeDirectory, worldUID, _diagnostics.PinStateChanged); _pinState.Load(); _exploration = sharedMapExploration; _store = sharedMapStore; _portalRefresh = sharedMapMarkerRefresh; _bootstrap = (flag ? null : new SharedMapBootstrap(ZDOMan.instance, sharedMapExploration)); _world = ZDOMan.instance; _worldUid = worldUID; _diagnostics.StoreOpened(flag, worldUID, sharedMapStore.FilePath, sharedMapExploration.ExploredPixels); _diagnostics.PortalStateOpened(loaded, sharedMapMarkerRefresh.FilePath, sharedMapMarkerRefresh.Count); } if (_bootstrap != null) { if (!_bootstrap.Tick(_settings.MaxTablesPerPass.Value)) { return; } _store.Save(initialize: true); SharedMapBootstrap bootstrap = _bootstrap; _bootstrap = null; _diagnostics.Bootstrapped(bootstrap.Tables, bootstrap.Imported, bootstrap.Invalid, _exploration.ExploredPixels); } if (_occupied) { if (_controller == null) { _controller = new SharedMapController(this, _settings, _players.Presence, _exploration, _portalRefresh, _logger, _resources, _resourceRefresh, _players.RoutedMessages, _dungeons, _pinState, _runestones, _spawners); _controller.Install(); } _processing.Ready(); _controller.Tick(now); SaveIfDue(now); } } catch (Exception error) { Fail(error); } } private void PresenceChanged(bool? occupied) { _occupied = occupied == true; if (IsActive && !_occupied) { StopController(); FlushStore(); FlushPortalState(); FlushResourceState(); FlushDungeonState(); if (occupied.HasValue) { _processing.EmptyPaused(); } else { _processing.Unavailable("player presence unavailable"); } } } internal void Fail(Exception error) { if (IsActive) { DiagnosticLog.Write(_logger, Name, CoreLogTopics.Lifecycle, "Disabled after a runtime failure.", default(LogFields), (LogLevel)2, verbose: false, error); Shutdown(); } } private void Log(string message, LogLevel level = (LogLevel)16) { //IL_000d: Unknown result type (might be due to invalid IL or missing references) DiagnosticLog.Write(_logger, Name, message, level); } private void StopController() { SharedMapController controller = _controller; _controller = null; if (controller != null) { ModuleScheduler.Current.Forget(controller); } try { controller?.Dispose(); } finally { WorldObjectProvider.Current?.ReleaseOwner(Name); } } private void FlushStore() { if (_bootstrap == null) { SharedMapStore? store = _store; if (store != null && store.Save()) { _diagnostics.Saved(Time.unscaledTime, _exploration.ExploredPixels); } } } private void SaveIfDue(float now) { if (_bootstrap == null) { SharedMapStore? store = _store; if (store != null && store.SaveIfDue(now, _settings.SaveIntervalSeconds.Value)) { _diagnostics.Saved(now, _exploration.ExploredPixels); } } if (_bootstrap == null) { SharedMapMarkerRefresh? portalRefresh = _portalRefresh; if (portalRefresh != null && portalRefresh.SaveIfDue(now, _settings.SaveIntervalSeconds.Value)) { _diagnostics.PortalStateSaved(now, _portalRefresh.Count); } } bool num = _resources?.SaveIfDue(now, _settings.SaveIntervalSeconds.Value) ?? false; bool flag = _resourceRefresh?.SaveIfDue(now, _settings.SaveIntervalSeconds.Value) ?? false; if (num || flag) { _diagnostics.ResourceStateSaved(now, _resources?.Deposits.Count ?? 0); } SharedMapDungeonStore? dungeons = _dungeons; if (dungeons != null && dungeons.SaveIfDue(now, _settings.SaveIntervalSeconds.Value)) { _diagnostics.DungeonStateSaved(now, _dungeons.Count); } _pinState?.SaveIfDue(now, _settings.SaveIntervalSeconds.Value); _runestones?.SaveIfDue(now, _settings.SaveIntervalSeconds.Value); _spawners?.SaveIfDue(now, _settings.SaveIntervalSeconds.Value); } private void FlushPortalState() { if (_bootstrap == null) { SharedMapMarkerRefresh? portalRefresh = _portalRefresh; if (portalRefresh != null && portalRefresh.Save()) { _diagnostics.PortalStateSaved(Time.unscaledTime, _portalRefresh.Count); } } } private void FlushResourceState() { if (!ModuleCleanup.Run(_logger, Name, delegate { _resources?.Save(); }, delegate { _resourceRefresh?.Save(); })) { throw new IOException("Resource state could not be flushed; prior files were retained."); } } private void FlushDungeonState() { if (!ModuleCleanup.Run(_logger, Name, delegate { SharedMapDungeonStore? dungeons = _dungeons; if (dungeons != null && dungeons.Save()) { _diagnostics.DungeonStateSaved(Time.unscaledTime, _dungeons.Count); } }, delegate { _pinState?.Save(); }, delegate { _runestones?.Save(); }, delegate { _spawners?.Save(); })) { throw new IOException("Dungeon/pin/landmark state could not be flushed."); } } public void Shutdown() { IsActive = false; _occupied = false; _processing.Reset(); IDisposable registration = _presenceRegistration; _presenceRegistration = null; ModuleCleanup.Run(_logger, Name, delegate { registration?.Dispose(); }, StopController, FlushStore, FlushPortalState, FlushResourceState, FlushDungeonState); _exploration = null; _store = null; _bootstrap = null; _portalRefresh = null; _world = null; _worldUid = 0L; _resources = null; _resourceRefresh = null; _dungeons = null; _pinState = null; _runestones = null; _spawners = null; } } internal sealed class SharedMapBootstrap { private readonly ZDOMan _world; private readonly SharedMapExploration _map; private readonly List _batch = new List(); private readonly HashSet _seen = new HashSet(); private int _sector; private int _cursor; private bool _finishedScan; public int Tables { get; private set; } public int Imported { get; private set; } public int Invalid { get; private set; } public SharedMapBootstrap(ZDOMan world, SharedMapExploration map) { _world = world; _map = map; } public bool Tick(int budget) { //IL_0097: Unknown result type (might be due to invalid IL or missing references) if (_cursor == _batch.Count) { if (_finishedScan) { return true; } _batch.Clear(); _cursor = 0; _finishedScan = _world.GetAllZDOsWithPrefabIterative("piece_cartographytable", _batch, ref _sector); } for (int i = 0; i < budget; i++) { if (_cursor >= _batch.Count) { break; } ZDO val = _batch[_cursor++]; if (!val.IsValid() || val.GetPrefab() != SharedMapController.TablePrefab || !_seen.Add(val.m_uid)) { continue; } Tables++; byte[] byteArray = val.GetByteArray(ZDOVars.s_data, (byte[])null); if (byteArray != null && byteArray.Length != 0) { try { SharedMapTableData.Import(_map, byteArray); Imported++; } catch (Exception ex) when (ex is IOException || ex is DecoderFallbackException || ex is ArgumentException) { Invalid++; } } } if (_finishedScan) { return _cursor == _batch.Count; } return false; } } internal sealed class SharedMapController : IDisposable { internal static readonly int TablePrefab = StringExtensionMethods.GetStableHashCode("piece_cartographytable"); private const int MaximumCandidates = 1024; private readonly SharedMap _module; private readonly SharedMapSettings _settings; private readonly IPlayerPresence _presence; private readonly SharedMapExploration _exploration; private readonly SharedMapDiagnostics _diagnostics; private readonly SharedMapPatches _patches = new SharedMapPatches(); private readonly ZDOMan _manager; private readonly SharedMapPortals _portals; private readonly SharedMapMarkerRefresh _portalRefresh; private readonly SharedMapResources? _resources; private readonly SharedMapDungeons? _dungeons; private readonly SharedMapLandmarks? _landmarks; private readonly SharedMapPinState _pinState; private readonly SharedMapPinAdministration _pinAdministration; private long _playerPixels; private long _tablePixels; private readonly List _sector = new List(); private readonly List _distant = new List(); private readonly List _tables = new List(); private readonly HashSet _seen = new HashSet(); private readonly HashSet _changedTables = new HashSet(); private int _cursor; private int _batchDepth; private int _removed; private int _invalidExisting; private int _rejectedIncoming; private int _rejectedPlayerWrites; private int _acceptedChecks; private readonly Dictionary _reconciled = new Dictionary(); private int _reconciledBytes; private const int ReconciliationBytes = 16777216; private IReadOnlyList? _portalPins; private long _portalPinsRevision = -1L; private IReadOnlyList? _portalInput; private SharedMapReconciliationState? _inputs; internal static SharedMapController? Active { get; private set; } internal bool Running { get { if (Active == this && _module.IsActive && _manager == ZDOMan.instance && _presence.HasJoinedPlayers == true && (Object)(object)ZNet.instance != (Object)null && ZNet.instance.IsServer()) { return ZNet.instance.IsDedicated(); } return false; } } private SharedMapReconciliationState Inputs() { IReadOnlyList readOnlyList = PortalPins(); IReadOnlyList readOnlyList2 = _resources?.Read() ?? Array.Empty(); IReadOnlyList readOnlyList3 = _dungeons?.Read() ?? Array.Empty(); IReadOnlyList readOnlyList4 = _landmarks?.Runestones() ?? Array.Empty(); IReadOnlyList readOnlyList5 = _landmarks?.Spawners() ?? Array.Empty(); if (_inputs != null && _inputs.Pixels == _exploration.ExploredPixels && _inputs.Pins == _pinState.Revision && _inputs.Removals == _pinAdministration.Removals.Revision && _inputs.PortalPublications == _portalRefresh.Revision && _inputs.HideDistance == _settings.ResourceMarkerHideDistanceMeters.Value && SharedMapReconciliationState.SameMarkers(_inputs.Portals, readOnlyList) && SharedMapReconciliationState.SameMarkers(_inputs.Resources, readOnlyList2) && SharedMapReconciliationState.SameMarkers(_inputs.Dungeons, readOnlyList3) && SharedMapReconciliationState.SameMarkers(_inputs.Runestones, readOnlyList4) && SharedMapReconciliationState.SameMarkers(_inputs.Spawners, readOnlyList5)) { return _inputs; } return _inputs = new SharedMapReconciliationState(_exploration.ExploredPixels, _pinState.Revision, _pinAdministration.Removals.Revision, _portalRefresh.Revision, _settings.ResourceMarkerHideDistanceMeters.Value, readOnlyList, readOnlyList2, readOnlyList3, readOnlyList4, readOnlyList5); } public SharedMapController(SharedMap module, SharedMapSettings settings, IPlayerPresence presence, SharedMapExploration exploration, SharedMapMarkerRefresh portalRefresh, ManualLogSource logger, SharedMapResourceStore? resourceStore = null, SharedMapMarkerRefresh? resourceRefresh = null, PlayerRoutedMessages? routedMessages = null, SharedMapDungeonStore? dungeonStore = null, SharedMapPinState? pinState = null, SharedMapLandmarkStore? runestones = null, SharedMapLandmarkStore? spawners = null) { SharedMapController sharedMapController = this; _module = module; _settings = settings; _presence = presence; _exploration = exploration; _manager = ZDOMan.instance; _pinAdministration = new SharedMapPinAdministration(_manager, exploration.Size, module.StoreDirectory, ZNet.instance.GetWorldUID(), logger, () => settings.MaxTablesPerPass.Value, delegate(ZDO table) { sharedMapController.Reconcile(table, "selected_pin_cleanup"); }); _portals = new SharedMapPortals(_manager, exploration); _portalRefresh = portalRefresh; _diagnostics = new SharedMapDiagnostics(logger, settings.DebugLogging, () => settings.PinDebugNameFilter.Value); _pinState = pinState ?? new SharedMapPinState(module.StoreDirectory, ZNet.instance.GetWorldUID(), _diagnostics.PinStateChanged); _diagnostics.ProgressReady(settings.DungeonLootProgress.Value, settings.SharePinCheckmarks.Value, settings.AllowPlayerMapWrites.Value); if (settings.ResourceMarkerSync.Value && resourceStore != null && resourceRefresh != null) { _resources = new SharedMapResources(_manager, resourceStore, resourceRefresh, exploration, settings, _diagnostics, Fail, presence, routedMessages ?? throw new InvalidOperationException("SharedMap resource discovery requires shared player message observations.")); } if (settings.DungeonMarkerSync.Value && dungeonStore != null) { _dungeons = new SharedMapDungeons(_manager, dungeonStore, exploration, settings, _diagnostics); } if (settings.RunestoneMarkerSync.Value || settings.SpawnerMarkerSync.Value) { _landmarks = new SharedMapLandmarks(_manager, runestones, spawners, exploration, settings, _diagnostics, Fail); } } public void Install() { if (Active != null) { throw new InvalidOperationException("SharedMap already has an active controller."); } if (_settings.PortalMarkerSync.Value) { _portals.Refresh(); } Active = this; try { _resources?.Install(); _landmarks?.Install(); _patches.Install(); } catch { Dispose(); throw; } } internal ZNetPeer? ReadyPeer(ZRpc rpc) { return PlayerPeerLookup.Ready(_presence.Peers, rpc); } internal float ResourceHealthBaseline(ZDO zdo) { return _resources?.HealthBaseline(zdo) ?? float.NaN; } internal bool ObservesResourceRecord(int prefab) { return _resources?.Observes(prefab) ?? false; } internal void AcceptedResourceRecord(ZDO zdo, MapReplicationSnapshot before) { _resources?.Accepted(zdo, before); } internal void Fail(Exception error) { _module.Fail(error); } internal static bool Equal(byte[]? left, byte[]? right) { if (left != right) { if (left != null && right != null) { return ((ReadOnlySpan)left).SequenceEqual((ReadOnlySpan)right); } return false; } return true; } private static bool PayloadError(Exception error) { if (!(error is IOException) && !(error is InvalidDataException) && !(error is DecoderFallbackException)) { return error is ArgumentException; } return true; } private static bool TryCharacter(ZNetPeer peer, out Vector3 position, bool allowInterior = false) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_007d: Unknown result type (might be due to invalid IL or missing references) //IL_0082: Unknown result type (might be due to invalid IL or missing references) //IL_00b2: Unknown result type (might be due to invalid IL or missing references) position = default(Vector3); if (!peer.IsReady() || ((ZDOID)(ref peer.m_characterID)).IsNone()) { return false; } ZDO zDO = ZDOMan.instance.GetZDO(peer.m_characterID); if (zDO == null || !zDO.IsValid() || zDO.GetOwner() != peer.m_uid) { return false; } float num = zDO.GetFloat(ZDOVars.s_health, float.NaN); if (!SharedMapExploration.Finite(num) || num <= 0f || zDO.GetBool(ZDOVars.s_dead, false)) { return false; } position = zDO.GetPosition(); if (SharedMapExploration.Finite(position.x) && SharedMapExploration.Finite(position.y) && SharedMapExploration.Finite(position.z)) { if (!allowInterior) { return !Character.InInterior(position); } return true; } return false; } public void Tick(float now) { //IL_007d: Unknown result type (might be due to invalid IL or missing references) //IL_00ad: Unknown result type (might be due to invalid IL or missing references) //IL_00b3: 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_0091: 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_0101: Unknown result type (might be due to invalid IL or missing references) if (!Running) { return; } BeginBatch(); try { _pinAdministration.Tick(now); } finally { EndBatch(); } if (ModuleScheduler.Current.Due(this, "sampling", now, _exploration.Interval)) { for (int i = 0; i < _presence.Peers.Count; i++) { ZNetPeer val = _presence.Peers[i]; if (TryCharacter(val, out var position, allowInterior: true)) { if (Character.InInterior(position)) { _dungeons?.SampleInterior(position, val.m_uid, now); continue; } _playerPixels += _exploration.Reveal(position.x, position.z); _resources?.Sample(val.m_uid, position); _dungeons?.Sample(position); _landmarks?.Sample(val.m_uid, position); } } } _resources?.Tick(now); _dungeons?.Tick(now); _landmarks?.Tick(now); if (!ModuleScheduler.Current.Due(this, "tables", now, _settings.TableIntervalSeconds.Value)) { return; } if (_settings.PortalMarkerSync.Value) { _portals.Refresh(); } CollectTables(out var usablePlayers); BeginBatch(); try { if (_tables.Count > 0) { _cursor %= _tables.Count; } int j; for (j = 0; j < _tables.Count && j < _settings.MaxTablesPerPass.Value; j++) { ZDO table = _tables[_cursor]; _cursor = (_cursor + 1) % _tables.Count; Reconcile(table); } _diagnostics.Report(now, _exploration, usablePlayers, _tables.Count, j, _settings.PortalMarkerSync.Value, PortalPins().Count, _playerPixels, _tablePixels); _resources?.Report(now); _dungeons?.Report(now); _landmarks?.Report(); } finally { EndBatch(); } } internal byte[]? Normalize(byte[]? incoming, byte[]? previous, out int removedDeaths) { if (!_settings.AllowPlayerMapWrites.Value) { if (!Equal(incoming, previous)) { if (_batchDepth > 0) { _rejectedPlayerWrites++; } else { _diagnostics.PlayerWritesRejected(1); } } try { return MergeTable(previous, out removedDeaths) ?? previous; } catch (Exception error) when (PayloadError(error)) { removedDeaths = 0; return previous; } } SharedMapTableData.ValidatedTable table = null; if (previous != null && !Equal(previous, incoming)) { try { int exploredPixels = _exploration.ExploredPixels; table = SharedMapTableData.Decode(_exploration.Size, previous); SharedMapTableData.ImportValidated(_exploration, table); _tablePixels += _exploration.ExploredPixels - exploredPixels; } catch (Exception error2) when (PayloadError(error2)) { } } try { SharedMapTableData.ValidatedTable validatedTable = SharedMapTableData.Decode(_exploration.Size, incoming); byte[] array = MergeTable(incoming, out removedDeaths, validatedTable) ?? incoming; if (!Equal(incoming, previous)) { IReadOnlyList incoming2 = SharedMapTableData.ReadValidatedPins(_exploration.Size, validatedTable); IReadOnlyList previous2; try { previous2 = SharedMapTableData.ReadValidatedPins(_exploration.Size, table); } catch (Exception error3) when (PayloadError(error3)) { previous2 = Array.Empty(); } int num = _pinState.Accept(incoming2, previous2, _settings.SharePinCheckmarks.Value); if (_batchDepth > 0) { _acceptedChecks += num; } else { _diagnostics.CheckmarksAccepted(num); } array = MergeTable(incoming, out removedDeaths, validatedTable) ?? array; } return array; } catch (Exception error4) when (PayloadError(error4)) { removedDeaths = 0; if (_batchDepth > 0) { _rejectedIncoming++; } else { _diagnostics.InvalidTables(Time.unscaledTime, 1, incoming: true); } return previous; } } internal void Incoming(ZDO table, TableMapSnapshot snapshot) { //IL_0073: Unknown result type (might be due to invalid IL or missing references) //IL_00ad: Unknown result type (might be due to invalid IL or missing references) //IL_00e0: Unknown result type (might be due to invalid IL or missing references) if (Running && table.GetPrefab() == TablePrefab) { byte[] byteArray = table.GetByteArray(ZDOVars.s_data, (byte[])null); byte[] array; int removedDeaths; try { array = Normalize(byteArray, snapshot.Previous, out removedDeaths); } catch { SharedMapPatches.Write(table, snapshot.Previous); throw; } if (!Equal(byteArray, array)) { SharedMapPatches.Write(table, array); } byte[] byteArray2 = table.GetByteArray(ZDOVars.s_data, (byte[])null); _diagnostics.PinChanges(_exploration.Size, table.m_uid, table.DataRevision, snapshot.Previous, byteArray, "received_update", snapshot.SenderPeer, snapshot.SenderName); _diagnostics.PinChanges(_exploration.Size, table.m_uid, table.DataRevision, byteArray, byteArray2, "server_normalization", snapshot.SenderPeer, snapshot.SenderName); if (!Equal(snapshot.Previous, byteArray2)) { RecordChange(table.m_uid, removedDeaths, "accepted_client_update", table.DataRevision); } } } internal void AcceptedServerWrite(ZDO table, TableMapSnapshot snapshot) { //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_005e: Unknown result type (might be due to invalid IL or missing references) //IL_0096: Unknown result type (might be due to invalid IL or missing references) byte[] byteArray = table.GetByteArray(ZDOVars.s_data, (byte[])null); _diagnostics.PinChanges(_exploration.Size, table.m_uid, table.DataRevision, snapshot.Previous, snapshot.Received, "server_local_input", snapshot.SenderPeer, snapshot.SenderName); _diagnostics.PinChanges(_exploration.Size, table.m_uid, table.DataRevision, snapshot.Received, byteArray, "server_normalization", snapshot.SenderPeer, snapshot.SenderName); if (!Equal(snapshot.Previous, byteArray)) { RecordChange(table.m_uid, snapshot.RemovedDeaths, "server_map_field_write", table.DataRevision); } } internal void Reconcile(ZDO table, string reason = "nearby_reconciliation") { //IL_0039: 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_01b2: Unknown result type (might be due to invalid IL or missing references) //IL_01e2: 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_0155: Unknown result type (might be due to invalid IL or missing references) if (!Running || !table.IsValid() || table.GetPrefab() != TablePrefab) { return; } byte[] byteArray = table.GetByteArray(ZDOVars.s_data, (byte[])null); SharedMapReconciliationState sharedMapReconciliationState = Inputs(); if (_reconciled.TryGetValue(table.m_uid, out (byte[], SharedMapReconciliationState) value) && Equal(byteArray, value.Item1) && sharedMapReconciliationState.Same(value.Item2)) { return; } byte[] array; int removed; try { array = MergeTable(byteArray, out removed); } catch (Exception error) when (PayloadError(error)) { if (_batchDepth > 0) { _invalidExisting++; } else { _diagnostics.InvalidTables(Time.unscaledTime, 1, incoming: false); } return; } byte[] array2 = array ?? byteArray; int num = ((array2 != null) ? array2.Length : 0); if (_reconciled.TryGetValue(table.m_uid, out (byte[], SharedMapReconciliationState) value2)) { int reconciledBytes = _reconciledBytes; byte[] item = value2.Item1; _reconciledBytes = reconciledBytes - ((item != null) ? item.Length : 0); _reconciled.Remove(table.m_uid); } if (num <= 16777216) { if (_reconciled.Count >= 64 || _reconciledBytes + num > 16777216) { _reconciled.Clear(); _reconciledBytes = 0; } _reconciled[table.m_uid] = ((array2 == null) ? null : ((byte[])array2.Clone()), sharedMapReconciliationState); _reconciledBytes += num; } if (array != null) { byte[] byteArray2 = table.GetByteArray(ZDOVars.s_data, (byte[])null); SharedMapPatches.Write(table, array); _diagnostics.PinChanges(_exploration.Size, table.m_uid, table.DataRevision, byteArray2, table.GetByteArray(ZDOVars.s_data, (byte[])null), reason); RecordChange(table.m_uid, removed, reason, table.DataRevision); } } private IReadOnlyList PortalPins() { if (!_settings.PortalMarkerSync.Value) { return Array.Empty(); } IReadOnlyList readOnlyList = _portals.Read(_settings.PortalClusterDistanceMeters.Value); IReadOnlyList readOnlyList2; if (readOnlyList == _portalInput && _portalPins != null && _portalPinsRevision == _portalRefresh.Revision) { readOnlyList2 = _portalPins; } else { readOnlyList2 = _portalRefresh.Apply(readOnlyList); _portalInput = readOnlyList; _portalPins = readOnlyList2; _portalPinsRevision = _portalRefresh.Revision; } _diagnostics.PortalCatalog(_portals.RegisteredCount, _portals.EligibleCount, readOnlyList2, _settings.PortalClusterDistanceMeters.Value); return readOnlyList2; } private byte[]? MergeTable(byte[]? data, out int removed, SharedMapTableData.ValidatedTable? decoded = null) { if (decoded == null) { decoded = SharedMapTableData.Decode(_exploration.Size, data); } int exploredPixels = _exploration.ExploredPixels; bool repositioned = false; byte[] result = SharedMapTableData.MergeValidated(_exploration, decoded, out removed, PortalPins(), _settings.PortalMarkerSync.Value, delegate(string name, int type, long owner, float x, float z, bool obsolete) { if (obsolete) { repositioned |= _portalRefresh.AvoidObsoletePin(name, x, z); } _diagnostics.PortalPinConflict(name, type, owner, x, z, obsolete); }, _resources?.Read() ?? Array.Empty(), _pinAdministration.Removals.Contains, _dungeons?.Read() ?? Array.Empty(), PublishPin, _landmarks?.Runestones() ?? Array.Empty(), _landmarks?.Spawners() ?? Array.Empty(), _diagnostics.DungeonPinCleanup, _settings.ResourceMarkerHideDistanceMeters.Value); if (repositioned) { result = SharedMapTableData.MergeValidated(_exploration, decoded, out removed, PortalPins(), _settings.PortalMarkerSync.Value, null, _resources?.Read() ?? Array.Empty(), _pinAdministration.Removals.Contains, _dungeons?.Read() ?? Array.Empty(), PublishPin, _landmarks?.Runestones() ?? Array.Empty(), _landmarks?.Spawners() ?? Array.Empty(), _diagnostics.DungeonPinCleanup, _settings.ResourceMarkerHideDistanceMeters.Value); } _tablePixels += _exploration.ExploredPixels - exploredPixels; return result; } private MapPin? PublishPin(MapPin pin, string? identity) { if (identity != null || !_pinState.Adopted(pin)) { return _pinState.Publish(pin, identity, _settings.SharePinCheckmarks.Value); } return null; } internal void BeginBatch() { if (_batchDepth++ == 0) { _changedTables.Clear(); _removed = (_invalidExisting = (_rejectedIncoming = (_rejectedPlayerWrites = (_acceptedChecks = 0)))); } } internal void EndBatch() { if (_batchDepth != 0 && --_batchDepth == 0) { _diagnostics.Changed(_changedTables.Count, _removed); _diagnostics.InvalidTables(Time.unscaledTime, _invalidExisting, incoming: false); _diagnostics.InvalidTables(Time.unscaledTime, _rejectedIncoming, incoming: true); _diagnostics.PlayerWritesRejected(_rejectedPlayerWrites); _diagnostics.CheckmarksAccepted(_acceptedChecks); _acceptedChecks = 0; _changedTables.Clear(); _removed = (_invalidExisting = (_rejectedIncoming = (_rejectedPlayerWrites = 0))); } } internal void RecordChange(ZDOID table, int removedDeaths, string reason = "server_map_field_write", uint? revision = null) { //IL_000f: 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) if (_batchDepth > 0) { _changedTables.Add(table); _removed += removedDeaths; } else { _diagnostics.Changed(1, removedDeaths); } _diagnostics.TableChanged(Time.unscaledTime, table, revision, reason); } private void CollectTables(out int usablePlayers) { //IL_007c: 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_0083: Unknown result type (might be due to invalid IL or missing references) //IL_00e1: Unknown result type (might be due to invalid IL or missing references) _tables.Clear(); _seen.Clear(); usablePlayers = 0; for (int i = 0; i < _presence.Peers.Count; i++) { ZNetPeer val = _presence.Peers[i]; if (!TryCharacter(val, out var position)) { continue; } usablePlayers++; _sector.Clear(); _distant.Clear(); WorldObjectProvider.Current.For("SharedMap").Query(ZoneSystem.GetZone(position), val.m_simulationDistance, _sector, _distant); foreach (ZDO item in _sector) { if (_tables.Count < 1024 && item.IsValid() && item.GetPrefab() == TablePrefab && _seen.Add(item.m_uid)) { _tables.Add(item); } } } } public void Dispose() { if (Active == this) { Active = null; } try { try { try { _resources?.Dispose(); } finally { try { _dungeons?.Dispose(); } finally { _landmarks?.Dispose(); } } } finally { try { _pinAdministration.Dispose(); } finally { _patches.Dispose(); } } } finally { _reconciled.Clear(); _portalPins = null; _portalInput = null; _tables.Clear(); _sector.Clear(); _distant.Clear(); _seen.Clear(); _changedTables.Clear(); _batchDepth = 0; } } } internal sealed class SharedMapDiagnostics : FeatureDiagnostics { private readonly ManualLogSource _logger; private readonly DebugLoggingPolicy _policy; private int _portalSampleCursor; private readonly Func _pinNameFilter; private int _lastDungeonCount = -1; private bool? _lastDungeonRetrospective; private (int Sources, int Pins)? _lastDungeonCleanup; private readonly Dictionary _dungeonLoot = new Dictionary(StringComparer.Ordinal); private readonly Dictionary _dungeonLayouts = new Dictionary(StringComparer.Ordinal); public SharedMapDiagnostics(ManualLogSource logger, DebugLoggingPolicy policy, Func? pinNameFilter = null) { _logger = logger; _policy = policy; ConfigureDiagnostics(() => policy.Enabled, logger, "SharedMap"); _pinNameFilter = pinNameFilter ?? ((Func)(() => "")); } public void StoreOpened(bool loaded, long world, string path, int pixels) { DiagnosticLog.Write(_logger, "SharedMap", loaded ? $"Loaded existing community map with {pixels} explored pixels; first-run table import skipped." : "No saved community map found; starting first-run cartography table import before player capture.", (LogLevel)16); if (base.DiagnosticsEnabled && DiagnosticLog.DebugAvailable(_logger, "SharedMap")) { DiagnosticLog.Write(_logger, "SharedMap", SharedMapLogTopics.Save, "Selected community map storage.", new(string, object)[4] { ("world_uid", world), ("map_path", path), ("loaded_existing", loaded), ("explored_pixels_loaded", pixels) }, (LogLevel)32); } } public void LandmarkResults(int runestones, int spawners, int retired) { if (runestones + spawners > 0) { DiagnosticLog.Write(_logger, "SharedMap", $"Discovered {runestones} runestones and {spawners} recurring spawner sources.", (LogLevel)16); } if (retired > 0) { DiagnosticLog.Write(_logger, "SharedMap", $"Recorded confirmed destruction of {retired} discovered spawner sources.", (LogLevel)16); } } public void DungeonPinCleanup(int sources, int pins) { (int, int) tuple = (sources, pins); (int, int)? lastDungeonCleanup = _lastDungeonCleanup; (int, int) tuple2 = tuple; bool hasValue = lastDungeonCleanup.HasValue; if (hasValue) { if (!hasValue) { return; } (int, int) valueOrDefault = lastDungeonCleanup.GetValueOrDefault(); if (valueOrDefault.Item1 == tuple2.Item1 && valueOrDefault.Item2 == tuple2.Item2) { return; } } _lastDungeonCleanup = tuple; if (sources + pins != 0 && base.DiagnosticsEnabled && _budget.Reserve(Time.unscaledTime, "dungeon_pin_cleanup", 6) && DiagnosticLog.DebugAvailable(_logger, "SharedMap")) { DiagnosticLog.Write(_logger, "SharedMap", SharedMapLogTopics.Dungeons, "Prepared cleanup of obsolete dungeon publications.", new(string, object)[4] { ("nearby_sources_suppressed", sources), ("obsolete_uploaded_pins", pins), ("duplicate_distance_m", 10f), ("client_read_confirmed", false) }, (LogLevel)32); } } public void LandmarkCatalog(int runestones, int spawners, IReadOnlyList unavailable, bool runestonesEnabled, bool spawnersEnabled, int spawnerCandidates, string spawnerRejections) { if (unavailable.Count > 0) { DiagnosticLog.Write(_logger, "SharedMap", $"Skipped {unavailable.Count} incompatible runestone prefabs; review the supported game metadata.", (LogLevel)4); } if (spawnersEnabled && spawners == 0) { DiagnosticLog.Write(_logger, "SharedMap", "Spawner markers are enabled, but no compatible physical spawner types were registered; new spawner discovery is unavailable. Enable SharedMap.DebugMode for catalog rejection details.", (LogLevel)4); } if (base.DiagnosticsEnabled && DiagnosticLog.DebugAvailable(_logger, "SharedMap")) { DiagnosticLog.Write(_logger, "SharedMap", SharedMapLogTopics.Landmarks, "Completed the landmark prefab audit.", new(string, object)[8] { ("runestone_families", runestones), ("spawner_families", spawners), ("runestone_marker_sync", runestonesEnabled), ("spawner_marker_sync", spawnersEnabled), ("spawner_candidates", spawnerCandidates), ("spawner_rejections", spawnerRejections), ("interior_sources", "omitted_without_verified_layout_and_gateway"), ("pin_type", 3) }, (LogLevel)32); } } public void LandmarkEvidence(string identity, Vector3 point, string reason, Vector3? player = null, float? radius = null) { //IL_00a2: Unknown result type (might be due to invalid IL or missing references) //IL_00be: Unknown result type (might be due to invalid IL or missing references) //IL_00da: Unknown result type (might be due to invalid IL or missing references) //IL_011e: Unknown result type (might be due to invalid IL or missing references) //IL_0200: Unknown result type (might be due to invalid IL or missing references) //IL_0208: 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_022a: Unknown result type (might be due to invalid IL or missing references) //IL_0159: Unknown result type (might be due to invalid IL or missing references) if (base.DiagnosticsEnabled && _budget.Reserve(Time.unscaledTime, "landmark_" + reason, 6)) { if (DiagnosticLog.DebugAvailable(_logger, "SharedMap")) { DiagnosticLog.Write(_logger, "SharedMap", SharedMapLogTopics.Landmarks, "Landmark source " + identity + ": " + reason.Replace('_', ' ') + ".", new(string, object)[8] { ("source_id", identity), ("x_m", point.x), ("y_m", point.y), ("z_m", point.z), ("reason", reason), ("sample_x_m", player?.x), ("sample_z_m", player?.z), ("radius_m", radius) }, (LogLevel)32); } if (base.VerboseEnabled && DiagnosticLog.DebugAvailable(_logger, "SharedMap", verbose: true)) { DiagnosticLog.Write(_logger, "SharedMap", SharedMapLogTopics.Landmarks, "Landmark evidence for source " + identity + ".", new(string, object)[2] { ("distance_m", player.HasValue ? new double?(Math.Sqrt(Math.Pow(point.x - player.Value.x, 2.0) + Math.Pow(point.z - player.Value.z, 2.0))) : ((double?)null)), ("client_read_confirmed", false) }, (LogLevel)32, verbose: true); } } } public void Bootstrapped(int tables, int imported, int invalid, int pixels) { DiagnosticLog.Write(_logger, "SharedMap", $"Initialized community map from {imported} of {tables} existing cartography tables; saved {pixels} explored pixels.", (LogLevel)16); if (invalid > 0) { DiagnosticLog.Write(_logger, "SharedMap", $"First-run import skipped {invalid} invalid table map payloads; existing tables were preserved. Review their data and supported environment.", (LogLevel)4); } } public void Changed(int count, int removedDeaths) { if (count != 0) { DiagnosticLog.Write(_logger, "SharedMap", string.Format("Updated shared map data for {0} cartography {1}; removed {2} shared death {3}.", count, (count == 1) ? "table" : "tables", removedDeaths, (removedDeaths == 1) ? "pin" : "pins"), (LogLevel)16); } } public void InvalidTables(float now, int count, bool incoming) { if (count != 0 && _budget.Reserve(now, incoming ? "rejected_incoming" : "invalid_tables", 1, countOmitted: false)) { DiagnosticLog.Write(_logger, "SharedMap", incoming ? string.Format("Rejected {0} invalid incoming table map {1}; prior data was retained. Review the table data and supported environment.", count, (count == 1) ? "field" : "fields") : string.Format("Skipped {0} unsupported or invalid cartography {1}; existing data was preserved. Review the table data and supported game environment.", count, (count == 1) ? "table" : "tables"), (LogLevel)4); } } public void Report(float now, SharedMapExploration exploration, int players, int tables, int prepared, bool markerSync, int portalCount, long playerPixels, long tablePixels) { if (base.DiagnosticsEnabled && _budget.Reserve(now, "summary", 1, countOmitted: false)) { if (DiagnosticLog.DebugAvailable(_logger, "SharedMap")) { DiagnosticLog.Write(_logger, "SharedMap", CoreLogTopics.Scope, "Observed community exploration and table reconciliation in the last minute.", new(string, object)[8] { ("radius_m", exploration.Radius), ("pixel_size_m", exploration.PixelSize), ("grid_size", exploration.Size), ("sample_interval_s", exploration.Interval), ("explored_pixels", exploration.ExploredPixels), ("usable_players", players), ("table_candidates", tables), ("tables_prepared", prepared) }, (LogLevel)32); } if (base.VerboseEnabled && DiagnosticLog.DebugAvailable(_logger, "SharedMap", verbose: true)) { DiagnosticLog.Write(_logger, "SharedMap", CoreLogTopics.Scope, "Exploration and portal marker evidence for the last minute.", new(string, object)[4] { ("portal_marker_sync", markerSync), ("eligible_portal_markers", portalCount), ("player_pixels_added_controller", playerPixels), ("table_pixels_added_controller", tablePixels) }, (LogLevel)32, verbose: true); } } } public void Saved(float now, int pixels) { if (base.DiagnosticsEnabled && _budget.Reserve(now, "saved", 1, countOmitted: false) && DiagnosticLog.DebugAvailable(_logger, "SharedMap")) { DiagnosticLog.Write(_logger, "SharedMap", SharedMapLogTopics.Save, "Saved community terrain.", new(string, object)[1] { ("explored_pixels", pixels) }, (LogLevel)32); } } public void PortalCatalog(int registered, int eligible, IReadOnlyList markers, float clusterDistance) { if (!base.DiagnosticsEnabled || !_budget.Reserve(Time.unscaledTime, "portal_catalog", 1, countOmitted: false)) { return; } if (DiagnosticLog.DebugAvailable(_logger, "SharedMap")) { DiagnosticLog.Write(_logger, "SharedMap", CoreLogTopics.Scope, "Reconciled the portal catalog this pass.", new(string, object)[8] { ("registered_portals", registered), ("eligible_explored_portals", eligible), ("excluded_portals", registered - eligible), ("grouped_markers", markers.Count), ("cluster_distance_m", clusterDistance), ("eligibility_source", "persisted_community_exploration"), ("pin_type", 6), ("pin_type_name", "Icon4") }, (LogLevel)32); } for (int i = 0; i < Math.Min(6, markers.Count); i++) { _portalSampleCursor %= markers.Count; MapMarker mapMarker = markers[_portalSampleCursor++]; if (DiagnosticLog.DebugAvailable(_logger, "SharedMap")) { DiagnosticLog.Write(_logger, "SharedMap", SharedMapLogTopics.Portals, "Observed a rotating portal publication sample.", new(string, object)[6] { ("marker_id", mapMarker.Identity), ("name", mapMarker.Name), ("published_x_m", mapMarker.X), ("published_z_m", mapMarker.Z), ("pin_type", 6), ("client_read_confirmed", false) }, (LogLevel)32); } } } public void PortalRemoved(string identity, string name) { if (base.DiagnosticsEnabled && _budget.Reserve(Time.unscaledTime, "portal_removals", 6) && DiagnosticLog.DebugAvailable(_logger, "SharedMap")) { DiagnosticLog.Write(_logger, "SharedMap", SharedMapLogTopics.Portals, "Removed a portal marker from publication state.", new(string, object)[4] { ("marker_id", identity), ("old_name", name), ("reason", "no_longer_eligible_or_regrouped"), ("client_read_confirmed", false) }, (LogLevel)32); } } public void PortalPinConflict(string name, int type, long owner, float x, float z, bool removed) { if (base.DiagnosticsEnabled && _budget.Reserve(Time.unscaledTime, "portal_pin_conflicts", 6) && DiagnosticLog.DebugAvailable(_logger, "SharedMap")) { DiagnosticLog.Write(_logger, "SharedMap", SharedMapLogTopics.Portals, removed ? "Removed obsolete table pin matching a portal" : "Preserved table pin shares a generated portal label", new(string, object)[8] { ("name", name), ("preserved_pin_type", type), ("owner_id", owner), ("x_m", x), ("z_m", z), ("generated_pin_type", 6), ("removed_from_table", removed), ("client_read_confirmed", false) }, (LogLevel)32); } } public void PortalPublished(MapMarker? previous, MapMarker actual, MapMarker published, int slot) { if (!base.DiagnosticsEnabled) { return; } float unscaledTime = Time.unscaledTime; if (_budget.Reserve(unscaledTime, "portal_publications", 6)) { double num = ((previous == null) ? 0.0 : ((double)published.X - (double)previous.X)); double num2 = ((previous == null) ? 0.0 : ((double)published.Z - (double)previous.Z)); if (DiagnosticLog.DebugAvailable(_logger, "SharedMap")) { DiagnosticLog.Write(_logger, "SharedMap", SharedMapLogTopics.Portals, "Selected publication of portal marker " + published.Name + ".", new(string, object)[8] { ("marker_id", actual.Identity), ("reason", (previous == null) ? "new_marker" : ((previous.Name != actual.Name) ? "label_changed" : "position_changed")), ("old_name", previous?.Name), ("new_name", published.Name), ("slot", slot), ("actual_x_m", actual.X), ("actual_z_m", actual.Z), ("published_x_m", published.X) }, (LogLevel)32); } if (base.VerboseEnabled && DiagnosticLog.DebugAvailable(_logger, "SharedMap", verbose: true)) { DiagnosticLog.Write(_logger, "SharedMap", SharedMapLogTopics.Portals, "Portal marker evidence for " + published.Name + ".", new(string, object)[5] { ("published_z_m", published.Z), ("previous_x_m", previous?.X), ("previous_z_m", previous?.Z), ("previous_distance_m", (previous == null) ? ((double?)null) : new double?(Math.Sqrt(num * num + num2 * num2))), ("client_read_confirmed", false) }, (LogLevel)32, verbose: true); } } } public void PinChanges(int size, ZDOID table, uint revision, byte[]? before, byte[]? after, string stage, long? sender = null, string senderName = "") { //IL_039b: Unknown result type (might be due to invalid IL or missing references) //IL_00b2: Unknown result type (might be due to invalid IL or missing references) //IL_0278: Unknown result type (might be due to invalid IL or missing references) //IL_01c4: Unknown result type (might be due to invalid IL or missing references) //IL_02c0: Unknown result type (might be due to invalid IL or missing references) //IL_0309: Unknown result type (might be due to invalid IL or missing references) if (!base.DiagnosticsEnabled || SharedMapController.Equal(before, after)) { return; } float unscaledTime = Time.unscaledTime; try { if (!_budget.Reserve(unscaledTime, "pin_comparisons", 60)) { return; } MapPinChanges mapPinChanges = SharedMapPinChanges.Compare(SharedMapTableData.ReadPins(size, before, includeDeaths: true), SharedMapTableData.ReadPins(size, after, includeDeaths: true)); if (!mapPinChanges.Any) { return; } if (_budget.Reserve(unscaledTime, "pin_summary_" + stage, 6)) { if (DiagnosticLog.DebugAvailable(_logger, "SharedMap")) { DiagnosticLog.Write(_logger, "SharedMap", CoreLogTopics.Scope, "Observed changes to the table pin list.", new(string, object)[8] { ("table_id", table), ("data_revision", revision), ("stage", stage), ("added_pins", mapPinChanges.Added.Count), ("removed_pins", mapPinChanges.Removed.Count), ("updated_pins", mapPinChanges.Updated.Count), ("sender_peer_id", sender), ("sender_character_name", CleanPinText(senderName)) }, (LogLevel)32); } if (base.VerboseEnabled && DiagnosticLog.DebugAvailable(_logger, "SharedMap", verbose: true)) { DiagnosticLog.Write(_logger, "SharedMap", CoreLogTopics.Scope, $"Pin list evidence for table {table}.", new(string, object)[4] { ("sender_role", sender.HasValue ? "replication_peer" : "unknown"), ("writer_confirmed", false), ("omitted_debug", _budget.TakeOmitted()), ("client_read_confirmed", false) }, (LogLevel)32, verbose: true); } } string filter = _pinNameFilter(); foreach (MapPin item in mapPinChanges.Removed) { PinDetail(unscaledTime, table, revision, stage, "removed", item, null, sender, senderName, filter); } foreach (MapPin item2 in mapPinChanges.Added) { PinDetail(unscaledTime, table, revision, stage, "added", item2, null, sender, senderName, filter); } foreach (var item3 in mapPinChanges.Updated) { PinDetail(unscaledTime, table, revision, stage, "updated", item3.After, item3.Before, sender, senderName, filter); } } catch (Exception ex) { try { if (_budget.Reserve(unscaledTime, "pin_comparison_unavailable", 1) && DiagnosticLog.DebugAvailable(_logger, "SharedMap")) { DiagnosticLog.Write(_logger, "SharedMap", SharedMapLogTopics.Tables, "Could not compare table pins.", new(string, object)[4] { ("table_id", table), ("stage", stage), ("error_type", ex.GetType().FullName), ("removal_inferred", false) }, (LogLevel)32); } } catch { } } } private static string CleanPinText(string value) { return new string((from c in value.Take(128) select (!char.IsControl(c)) ? c : ' ').ToArray()); } private void PinDetail(float now, ZDOID table, uint revision, string stage, string action, MapPin pin, MapPin? previous, long? sender, string senderName, string filter) { //IL_00d7: 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) if (filter.Length > 0 && !string.Equals(pin.Name, filter, StringComparison.Ordinal)) { return; } bool flag = SharedMapTableData.ManagedOwner(pin.Owner); if (_budget.Reserve(now, "pin_" + stage + "_" + action + (flag ? "_generated" : "_player"), 6)) { if (DiagnosticLog.DebugAvailable(_logger, "SharedMap")) { DiagnosticLog.Write(_logger, "SharedMap", SharedMapLogTopics.Tables, "Table pin " + pin.Name + " was " + action + ".", new(string, object)[8] { ("table_id", table), ("data_revision", revision), ("stage", stage), ("pin_name", CleanPinText(pin.Name)), ("pin_owner_id", pin.Owner), ("pin_type", pin.Icon), ("x_m", pin.X), ("y_m", pin.Y) }, (LogLevel)32); } if (base.VerboseEnabled && DiagnosticLog.DebugAvailable(_logger, "SharedMap", verbose: true)) { DiagnosticLog.Write(_logger, "SharedMap", SharedMapLogTopics.Tables, $"Pin evidence for {pin.Name} on table {table}.", new(string, object)[11] { ("z_m", pin.Z), ("checked", pin.Checked), ("author", CleanPinText(pin.Author)), ("previous_checked", previous?.Checked), ("previous_author", (previous == null) ? null : CleanPinText(previous.Author)), ("sender_peer_id", sender), ("sender_character_name", CleanPinText(senderName)), ("sender_role", sender.HasValue ? "replication_peer" : "unknown"), ("writer_confirmed", false), ("pin_source", flag ? "generated" : "player"), ("client_read_confirmed", false) }, (LogLevel)32, verbose: true); } } } public void TableChanged(float now, ZDOID table, uint? revision, string reason) { //IL_0057: Unknown result type (might be due to invalid IL or missing references) if (base.DiagnosticsEnabled && _budget.Reserve(now, "table_fields", 6) && DiagnosticLog.DebugAvailable(_logger, "SharedMap")) { DiagnosticLog.Write(_logger, "SharedMap", SharedMapLogTopics.Tables, "Observed a changed table map field on the server.", new(string, object)[5] { ("table_id", table), ("data_revision", revision), ("reason", reason), ("client_read_confirmed", false), ("omitted_debug", _budget.TakeOmitted()) }, (LogLevel)32); } } public void PortalStateOpened(bool loaded, string path, int count) { if (base.DiagnosticsEnabled && DiagnosticLog.DebugAvailable(_logger, "SharedMap")) { DiagnosticLog.Write(_logger, "SharedMap", SharedMapLogTopics.Save, "Selected portal publication state.", new(string, object)[3] { ("loaded_existing", loaded), ("state_path", path), ("marker_states_loaded", count) }, (LogLevel)32); } } public void PortalStateSaved(float now, int count) { if (base.DiagnosticsEnabled && _budget.Reserve(now, "portal_state_saved", 1, countOmitted: false) && DiagnosticLog.DebugAvailable(_logger, "SharedMap")) { DiagnosticLog.Write(_logger, "SharedMap", SharedMapLogTopics.Save, "Saved portal publication state.", new(string, object)[1] { ("marker_states", count) }, (LogLevel)32); } } public void UnsupportedResources(IReadOnlyList names) { if (names.Count != 0) { DiagnosticLog.Write(_logger, "SharedMap", string.Format("Excluded {0} unavailable or incompatible resource prefabs ({1}); other resources remain eligible. Review the supported environment.", names.Count, string.Join(", ", names)), (LogLevel)4); } } public void ResourceResults(int added, int retired) { if (added != 0 || retired != 0) { DiagnosticLog.Write(_logger, "SharedMap", $"Recorded {added} resource discoveries and {retired} confirmed resource removals.", (LogLevel)16); } } public void ResourceCatalog(float now, int deposits, int markers, bool retrospective) { if (base.DiagnosticsEnabled && _budget.Reserve(now, "resource_catalog", 1, countOmitted: false) && DiagnosticLog.DebugAvailable(_logger, "SharedMap")) { DiagnosticLog.Write(_logger, "SharedMap", CoreLogTopics.Scope, "Observed resource discovery and publication scope this pass.", new(string, object)[5] { ("discovery_records", deposits), ("resource_markers_last_preparation", markers), ("discover_previously_explored", retrospective), ("pin_type", 3), ("client_read_confirmed", false) }, (LogLevel)32); } } public void ResourcePublished(MapMarker? previous, MapMarker actual, MapMarker published, int slot) { if (base.DiagnosticsEnabled && _budget.Reserve(Time.unscaledTime, "resource_publications", 6)) { if (DiagnosticLog.DebugAvailable(_logger, "SharedMap")) { DiagnosticLog.Write(_logger, "SharedMap", SharedMapLogTopics.Resources, "Selected publication of resource marker " + published.Name + ".", new(string, object)[8] { ("marker_id", actual.Identity), ("old_name", previous?.Name), ("new_name", published.Name), ("slot", slot), ("actual_x_m", actual.X), ("actual_z_m", actual.Z), ("published_x_m", published.X), ("published_z_m", published.Z) }, (LogLevel)32); } if (base.VerboseEnabled && DiagnosticLog.DebugAvailable(_logger, "SharedMap", verbose: true)) { DiagnosticLog.Write(_logger, "SharedMap", SharedMapLogTopics.Resources, "Resource marker evidence for " + published.Name + ".", new(string, object)[1] { ("client_read_confirmed", false) }, (LogLevel)32, verbose: true); } } } public void ResourceStateOpened(bool discoveriesLoaded, bool publicationsLoaded, int count) { if (base.DiagnosticsEnabled && DiagnosticLog.DebugAvailable(_logger, "SharedMap")) { DiagnosticLog.Write(_logger, "SharedMap", SharedMapLogTopics.Save, "Selected resource storage.", new(string, object)[3] { ("loaded_discoveries", discoveriesLoaded), ("loaded_publications", publicationsLoaded), ("discovery_records", count) }, (LogLevel)32); } } public void ResourceStateSaved(float now, int count) { if (base.DiagnosticsEnabled && _budget.Reserve(now, "resource_state_saved", 1, countOmitted: false) && DiagnosticLog.DebugAvailable(_logger, "SharedMap")) { DiagnosticLog.Write(_logger, "SharedMap", SharedMapLogTopics.Save, "Saved resource state.", new(string, object)[1] { ("discovery_records", count) }, (LogLevel)32); } } public void UnsupportedDungeons(IReadOnlyList names) { if (names.Count != 0) { DiagnosticLog.Write(_logger, "SharedMap", string.Format("Excluded {0} incompatible dungeon prefabs ({1}); other supported dungeons remain eligible. Review the supported environment.", names.Count, string.Join(", ", names)), (LogLevel)4); } } public void DungeonResults(int added) { if (added != 0) { DiagnosticLog.Write(_logger, "SharedMap", $"Recorded {added} dungeon entrance discoveries.", (LogLevel)16); } } public void DungeonReady(int prefabs, int gateways, int discoveries, float radius, float interval, bool retrospective, bool allowWrites) { if (base.DiagnosticsEnabled && DiagnosticLog.DebugAvailable(_logger, "SharedMap")) { DiagnosticLog.Write(_logger, "SharedMap", SharedMapLogTopics.Dungeons, "Prepared dungeon discovery metadata.", new(string, object)[8] { ("supported_location_prefabs", prefabs), ("validated_exterior_gateways", gateways), ("discovery_records", discoveries), ("radius_m", radius), ("sample_interval_s", interval), ("discover_previously_explored", retrospective), ("allow_player_map_writes", allowWrites), ("pin_type", 2) }, (LogLevel)32); } } public void DungeonDiscovered(MapMarker marker, string prefab, Vector3 root, Vector3? player, float radius) { //IL_003f: Unknown result type (might be due to invalid IL or missing references) //IL_0062: Unknown result type (might be due to invalid IL or missing references) //IL_01f3: Unknown result type (might be due to invalid IL or missing references) //IL_020f: Unknown result type (might be due to invalid IL or missing references) //IL_017b: Unknown result type (might be due to invalid IL or missing references) //IL_0241: Unknown result type (might be due to invalid IL or missing references) //IL_027c: Unknown result type (might be due to invalid IL or missing references) //IL_02b7: Unknown result type (might be due to invalid IL or missing references) if (base.DiagnosticsEnabled && _budget.Reserve(Time.unscaledTime, "dungeon_discoveries", 6)) { double? num = (player.HasValue ? new double?(Math.Sqrt(Math.Pow((double)marker.X - (double)player.Value.x, 2.0) + Math.Pow((double)marker.Z - (double)player.Value.z, 2.0))) : ((double?)null)); if (DiagnosticLog.DebugAvailable(_logger, "SharedMap")) { DiagnosticLog.Write(_logger, "SharedMap", SharedMapLogTopics.Dungeons, "Discovered an exterior dungeon entrance.", new(string, object)[8] { ("marker_id", marker.Identity), ("name", marker.Name), ("location_prefab", prefab), ("discovery_source", player.HasValue ? "usable_player_sample" : "persisted_community_exploration"), ("x_m", marker.X), ("y_m", marker.Y), ("z_m", marker.Z), ("location_root_x_m", root.x) }, (LogLevel)32); } if (base.VerboseEnabled && DiagnosticLog.DebugAvailable(_logger, "SharedMap", verbose: true)) { DiagnosticLog.Write(_logger, "SharedMap", SharedMapLogTopics.Dungeons, "Dungeon entrance evidence for " + marker.Name + ".", new(string, object)[9] { ("location_root_y_m", root.y), ("location_root_z_m", root.z), ("sample_player_x_m", player?.x), ("sample_player_y_m", player?.y), ("sample_player_z_m", player?.z), ("sample_distance_m", num), ("radius_m", radius), ("pin_type", 2), ("client_read_confirmed", false) }, (LogLevel)32, verbose: true); } } } public void DungeonCatalog(float now, int count, int pending, bool retrospective) { if (base.DiagnosticsEnabled && (count != _lastDungeonCount || retrospective != _lastDungeonRetrospective) && _budget.Reserve(now, "dungeon_catalog", 1, countOmitted: false)) { _lastDungeonCount = count; _lastDungeonRetrospective = retrospective; if (DiagnosticLog.DebugAvailable(_logger, "SharedMap")) { DiagnosticLog.Write(_logger, "SharedMap", CoreLogTopics.Scope, "Observed a changed dungeon discovery scope.", new(string, object)[5] { ("discovery_records", count), ("pending_encounters", pending), ("discover_previously_explored", retrospective), ("pin_type", 2), ("client_read_confirmed", false) }, (LogLevel)32); } } } public void DungeonStateOpened(bool loaded, int count) { if (base.DiagnosticsEnabled && DiagnosticLog.DebugAvailable(_logger, "SharedMap")) { DiagnosticLog.Write(_logger, "SharedMap", SharedMapLogTopics.Save, "Selected dungeon storage.", new(string, object)[2] { ("loaded_discoveries", loaded), ("discovery_records", count) }, (LogLevel)32); } } public void DungeonStateSaved(float now, int count) { if (base.DiagnosticsEnabled && _budget.Reserve(now, "dungeon_state_saved", 1, countOmitted: false) && DiagnosticLog.DebugAvailable(_logger, "SharedMap")) { DiagnosticLog.Write(_logger, "SharedMap", SharedMapLogTopics.Save, "Saved dungeon discoveries.", new(string, object)[1] { ("discovery_records", count) }, (LogLevel)32); } } public void PlayerWritesRejected(int count) { if (count != 0 && base.DiagnosticsEnabled && _budget.Reserve(Time.unscaledTime, "player_writes_rejected", 6) && DiagnosticLog.DebugAvailable(_logger, "SharedMap")) { DiagnosticLog.Write(_logger, "SharedMap", SharedMapLogTopics.Tables, "Rejected table map-field changes under the player-write policy.", new(string, object)[4] { ("rejected_fields", count), ("allow_player_map_writes", false), ("writer_confirmed", false), ("client_read_confirmed", false) }, (LogLevel)32); } } private static bool NewResult(Dictionary seen, string key, T value) { if (seen.TryGetValue(key, out T value2) && EqualityComparer.Default.Equals(value2, value)) { return false; } if (seen.Count >= 8192 && !seen.ContainsKey(key)) { seen.Clear(); } seen[key] = value; return true; } private static string Dungeon(string location) { if (!SharedMapDungeonPrefab.Labels.TryGetValue(location, out string value)) { return location; } return value + " (" + location + ")"; } public void DungeonLoot(float now, string identity, string location, Vector3 position, int total, int picked, bool changed, string reason) { //IL_00c2: Unknown result type (might be due to invalid IL or missing references) if (base.DiagnosticsEnabled && NewResult(_dungeonLoot, identity, (total, picked, reason)) && _budget.Reserve(now, "dungeon_loot", 6)) { bool flag = picked >= 0; if (DiagnosticLog.DebugAvailable(_logger, "SharedMap")) { DiagnosticLog.Write(_logger, "SharedMap", SharedMapLogTopics.Dungeons, Dungeon(location) + " pickups: " + reason.Replace('_', ' ') + ".", new LogField[8] { (Key: "location", Value: location), (Key: "gateway", Value: identity), (Key: "pos", Value: position), DiagnosticLog.FieldAlways("total_pickups", total), (Key: "picked_pickups", Value: flag ? DiagnosticLog.Kept(picked) : null), (Key: "remaining_percent", Value: flag ? DiagnosticLog.Kept((total != 0) ? ((int)Math.Ceiling(100.0 * (double)(total - picked) / (double)total)) : 0) : null), DiagnosticLog.FieldAlways("changed", changed), (Key: "reason", Value: reason) }, (LogLevel)32); } } } public void DungeonVisited(float now, string location, long peer, int gateways) { if (base.DiagnosticsEnabled && _budget.Reserve(now, "dungeon_visit", 6) && DiagnosticLog.DebugAvailable(_logger, "SharedMap")) { DiagnosticLog.Write(_logger, "SharedMap", SharedMapLogTopics.Dungeons, "Observed an interior dungeon visit.", new(string, object)[4] { ("location", location), ("peer_id", peer), ("visited_gateways", gateways), ("evidence", "unique_saved_location_zone") }, (LogLevel)32); } } public void DungeonPriorVisit(float now, string gateway, int total, int picked) { if (base.DiagnosticsEnabled && _budget.Reserve(now, "dungeon_visit", 6) && DiagnosticLog.DebugAvailable(_logger, "SharedMap")) { DiagnosticLog.Write(_logger, "SharedMap", SharedMapLogTopics.Dungeons, "Inferred a prior dungeon visit from saved pickup evidence.", new(string, object)[4] { ("gateway", gateway), ("total_pickups", total), ("picked_pickups", picked), ("evidence", "matched_saved_pickup_flags") }, (LogLevel)32); } } public void DungeonLayout(float now, string gateway, string location, Vector3 position, int bytes, int rooms, bool valid, string reason) { //IL_00e8: Unknown result type (might be due to invalid IL or missing references) if (base.DiagnosticsEnabled && NewResult(_dungeonLayouts, gateway, (bytes, rooms, valid, reason)) && _budget.Reserve(now, "dungeon_layout", 6) && DiagnosticLog.DebugAvailable(_logger, "SharedMap")) { DiagnosticLog.Write(_logger, "SharedMap", SharedMapLogTopics.Dungeons, Dungeon(location) + " layout " + (valid ? "is ready" : "was rejected") + " — " + reason.Replace('_', ' ') + ".", new LogField[8] { (Key: "location", Value: location), (Key: "gateway", Value: gateway), (Key: "pos", Value: position), DiagnosticLog.FieldAlways("layout_bytes", bytes), DiagnosticLog.FieldAlways("room_count", rooms), (Key: "expected_layout_bytes", Value: 4 + (long)rooms * 28L), DiagnosticLog.FieldAlways("layout_valid", valid), (Key: "reason", Value: reason) }, (LogLevel)32); } } public void DungeonLootResults(int count) { if (count > 0) { DiagnosticLog.Write(_logger, "SharedMap", $"Updated pickup progress for {count} dungeon markers.", (LogLevel)16); } } public void PinStateChanged(string identity, MapPin pin, string reason) { string text = _pinNameFilter(); if ((text.Length <= 0 || string.Equals(text, pin.Name, StringComparison.Ordinal)) && base.DiagnosticsEnabled && _budget.Reserve(Time.unscaledTime, reason, 6) && DiagnosticLog.DebugAvailable(_logger, "SharedMap")) { DiagnosticLog.Write(_logger, "SharedMap", SharedMapLogTopics.Tables, "Shared pin " + pin.Name + " changed — " + reason.Replace('_', ' ') + ".", new(string, object)[8] { ("identity", identity), ("label", pin.Name), ("owner", pin.Owner), ("checked", pin.Checked), ("x", pin.X), ("y", pin.Y), ("z", pin.Z), ("reason", reason) }, (LogLevel)32); } } public void CheckmarksAccepted(int count) { if (count > 0) { DiagnosticLog.Write(_logger, "SharedMap", $"Accepted {count} shared pin checkmark changes.", (LogLevel)16); } } public void ProgressReady(bool loot, bool checks, bool uploads) { if (base.DiagnosticsEnabled && DiagnosticLog.DebugAvailable(_logger, "SharedMap")) { DiagnosticLog.Write(_logger, "SharedMap", CoreLogTopics.Config, "Loaded dungeon progress and shared checkmark policy.", new(string, object)[3] { ("dungeon_loot_progress", loot), ("share_pin_checkmarks", checks), ("allow_player_map_writes", uploads) }, (LogLevel)32); } } } public static class SharedMapDungeonIdentity { public static string Create(string prefab, float x, float y, float z, string gateway) { if (prefab.Length == 0 || prefab.Length > 128 || gateway.Length == 0 || gateway.Length > 512 || !SharedMapExploration.Finite(x) || !SharedMapExploration.Finite(y) || !SharedMapExploration.Finite(z)) { throw new ArgumentException("Invalid dungeon source identity."); } using MemoryStream memoryStream = new MemoryStream(); using (BinaryWriter binaryWriter = new BinaryWriter(memoryStream, Encoding.UTF8, leaveOpen: true)) { binaryWriter.Write(prefab); binaryWriter.Write((x == 0f) ? 0f : x); binaryWriter.Write((y == 0f) ? 0f : y); binaryWriter.Write((z == 0f) ? 0f : z); binaryWriter.Write(gateway); } using SHA256 sHA = SHA256.Create(); return BitConverter.ToString(sHA.ComputeHash(memoryStream.ToArray())).Replace("-", "").ToLowerInvariant(); } } public static class SharedMapDungeonLayout { public const int RoomBytes = 28; public const int MaximumRooms = 1024; public static bool TryRead(byte[]? data, out DungeonRoomPlacement[] rooms, out string reason) { //IL_00a4: Unknown result type (might be due to invalid IL or missing references) //IL_00ad: Unknown result type (might be due to invalid IL or missing references) //IL_00c6: Unknown result type (might be due to invalid IL or missing references) //IL_00c8: Unknown result type (might be due to invalid IL or missing references) rooms = Array.Empty(); reason = "layout_not_saved"; if (data == null || data.Length < 4) { return false; } reason = "invalid_layout"; if (data.Length > 28676) { return false; } using BinaryReader binaryReader = new BinaryReader(new MemoryStream(data, writable: false)); int num = binaryReader.ReadInt32(); if (num < 1 || num > 1024 || data.Length != 4 + num * 28) { return false; } DungeonRoomPlacement[] array = new DungeonRoomPlacement[num]; Vector3 val = default(Vector3); Vector3 val2 = default(Vector3); for (int i = 0; i < num; i++) { int hash = binaryReader.ReadInt32(); ((Vector3)(ref val))..ctor(binaryReader.ReadSingle(), binaryReader.ReadSingle(), binaryReader.ReadSingle()); ((Vector3)(ref val2))..ctor(binaryReader.ReadSingle(), binaryReader.ReadSingle(), binaryReader.ReadSingle()); if (!Finite(val) || !Finite(val2)) { reason = "invalid_room_transform"; return false; } array[i] = new DungeonRoomPlacement(hash, val, val2); } rooms = array; reason = "saved_room_layout"; return true; } private static bool Finite(Vector3 point) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_001a: Unknown result type (might be due to invalid IL or missing references) if (SharedMapExploration.Finite(point.x) && SharedMapExploration.Finite(point.y)) { return SharedMapExploration.Finite(point.z); } return false; } } internal sealed class SharedMapDungeonLoot { private sealed class Target { public SharedMapDungeonPrefab Prefab; public Vector3 Root; public Vector3 Interior; public Quaternion Rotation; public readonly HashSet Gateways = new HashSet(); public readonly ScheduleToken Next = new ScheduleToken(); public float EmptySince = -1f; } private readonly ZDOMan _world; private readonly SharedMapDungeonStore _store; private readonly SharedMapDiagnostics _diagnostics; private readonly Dictionary _targets = new Dictionary(); private readonly Dictionary<(string Name, Vector3 Root), string> _targetIdentities = new Dictionary<(string, Vector3), string>(); private readonly List _order = new List(); private readonly PrefabCatalog<(int Hash, Vector3 Offset, string Item)[]> _rooms = PrefabRegistry.Current.Catalog<(int, Vector3, string)[]>("SharedMapDungeonLoot._rooms"); private readonly Dictionary _claims = new Dictionary(); private readonly List _near = new List(); private readonly List _objects = new List(); private readonly List<(int Hash, Vector3 Position)> _points = new List<(int, Vector3)>(); private readonly Dictionary<(int Hash, int X, int Y, int Z), List> _cells = new Dictionary<(int, int, int, int), List>(); private readonly Stack> _cellLists = new Stack>(); private readonly HashSet _pickupHashes = new HashSet(); private readonly HashSet _seen = new HashSet(); private readonly HashSet<(int Hash, float X, float Y, float Z)> _matchedSites = new HashSet<(int, float, float, float)>(); private int _cursor; private int _changed; public SharedMapDungeonLoot(ZDOMan world, SharedMapDungeonStore store, SharedMapDiagnostics diagnostics) { _world = world; _store = store; _diagnostics = diagnostics; } internal static bool Objective(string location, string item) { switch (location) { case "Crypt2": case "Crypt3": case "Crypt4": case "Hildir_crypt": return item == "SurtlingCore"; case "Mistlands_DvergrTownEntrance1": case "Mistlands_DvergrTownEntrance2": return item == "BlackCore"; case "MountainCave02": case "Hildir_cave": return item == "WolfHairBundle"; case "TheHole01": return item == "FrostCore"; case "MorkBorg": return item.StartsWith("AncientGemstone", StringComparison.Ordinal); default: return false; } } internal static (int Hash, Vector3 Offset, string Item)[] Points(GameObject root, Transform? exclude = null) { //IL_00aa: Unknown result type (might be due to invalid IL or missing references) //IL_00af: Unknown result type (might be due to invalid IL or missing references) //IL_00ba: Unknown result type (might be due to invalid IL or missing references) //IL_00c5: Unknown result type (might be due to invalid IL or missing references) //IL_00ca: Unknown result type (might be due to invalid IL or missing references) //IL_00cf: Unknown result type (might be due to invalid IL or missing references) //IL_00d4: Unknown result type (might be due to invalid IL or missing references) //IL_00d6: Unknown result type (might be due to invalid IL or missing references) //IL_00f0: Unknown result type (might be due to invalid IL or missing references) PrefabRegistry.Current.Observe(root); List<(int, Vector3, string)> list = new List<(int, Vector3, string)>(); Pickable[] array = PrefabRegistry.Children(root, inactive: true); foreach (Pickable val in array) { if ((Object)(object)exclude != (Object)null && ((Component)val).transform.IsChildOf(exclude)) { continue; } ZNetView val2 = PrefabRegistry.Component((Component?)(object)val); if (!((Behaviour)val).enabled || val.m_defaultPicked || (Object)(object)val2 == (Object)null || !val2.m_persistent || (Object)(object)val.m_itemPrefab == (Object)null || (Object)(object)val.m_hideWhenPicked == (Object)null || val.m_respawnTimeMinutes != 0f) { continue; } Vector3 val3 = Quaternion.Inverse(root.transform.rotation) * (((Component)val).transform.position - root.transform.position); if (SharedMapDungeonPrefab.Finite(val3)) { list.Add((StringExtensionMethods.GetStableHashCode(Utils.GetPrefabName(((Component)val).gameObject)), val3, ((Object)val.m_itemPrefab).name)); if (list.Count > 4096) { throw new InvalidDataException("Dungeon pickup template limit exceeded."); } } } return list.ToArray(); } public void Track(string gateway, SharedMapDungeonPrefab prefab, Vector3 root, Quaternion rotation, Vector3 interior) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_0041: Unknown result type (might be due to invalid IL or missing references) //IL_0047: Unknown result type (might be due to invalid IL or missing references) //IL_004d: Unknown result type (might be due to invalid IL or missing references) //IL_00a5: Unknown result type (might be due to invalid IL or missing references) //IL_00a6: Unknown result type (might be due to invalid IL or missing references) //IL_00ac: Unknown result type (might be due to invalid IL or missing references) //IL_00ae: Unknown result type (might be due to invalid IL or missing references) //IL_00b4: 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) (string, Vector3) key = (prefab.Name, root); if (!_targetIdentities.TryGetValue(key, out string value)) { if (_targetIdentities.Count >= 4096) { throw new InvalidDataException("Dungeon pickup target limit exceeded."); } value = SharedMapDungeonIdentity.Create(prefab.Name, root.x, root.y, root.z, "loot"); _targetIdentities.Add(key, value); } if (!_targets.TryGetValue(value, out Target value2)) { if (_targets.Count >= 4096) { throw new InvalidDataException("Dungeon pickup target limit exceeded."); } value2 = new Target { Prefab = prefab, Root = root, Rotation = rotation, Interior = interior }; _targets.Add(value, value2); _order.Add(value); } value2.Gateways.Add(gateway); } public void Tick(float now, float interval) { //IL_00f1: 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_00fb: Unknown result type (might be due to invalid IL or missing references) //IL_0106: Unknown result type (might be due to invalid IL or missing references) //IL_010b: Unknown result type (might be due to invalid IL or missing references) //IL_0110: Unknown result type (might be due to invalid IL or missing references) //IL_0125: Unknown result type (might be due to invalid IL or missing references) //IL_00bc: Unknown result type (might be due to invalid IL or missing references) //IL_00c2: Unknown result type (might be due to invalid IL or missing references) //IL_00c9: Unknown result type (might be due to invalid IL or missing references) //IL_00ce: Unknown result type (might be due to invalid IL or missing references) //IL_00d3: Unknown result type (might be due to invalid IL or missing references) //IL_0173: 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_017c: Unknown result type (might be due to invalid IL or missing references) //IL_01ae: Unknown result type (might be due to invalid IL or missing references) //IL_01a7: Unknown result type (might be due to invalid IL or missing references) //IL_01b0: Unknown result type (might be due to invalid IL or missing references) //IL_01cc: Unknown result type (might be due to invalid IL or missing references) //IL_01ce: Unknown result type (might be due to invalid IL or missing references) //IL_01d6: Unknown result type (might be due to invalid IL or missing references) //IL_034b: Unknown result type (might be due to invalid IL or missing references) //IL_026f: Unknown result type (might be due to invalid IL or missing references) //IL_02a0: Unknown result type (might be due to invalid IL or missing references) //IL_0282: Unknown result type (might be due to invalid IL or missing references) //IL_0288: 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_0294: Unknown result type (might be due to invalid IL or missing references) //IL_0299: Unknown result type (might be due to invalid IL or missing references) //IL_02a2: Unknown result type (might be due to invalid IL or missing references) //IL_02a7: Unknown result type (might be due to invalid IL or missing references) //IL_05a3: Unknown result type (might be due to invalid IL or missing references) //IL_03a3: Unknown result type (might be due to invalid IL or missing references) //IL_03a8: Unknown result type (might be due to invalid IL or missing references) //IL_03aa: Unknown result type (might be due to invalid IL or missing references) //IL_03af: Unknown result type (might be due to invalid IL or missing references) //IL_03b4: Unknown result type (might be due to invalid IL or missing references) //IL_05f5: Unknown result type (might be due to invalid IL or missing references) //IL_062f: Unknown result type (might be due to invalid IL or missing references) //IL_0631: Unknown result type (might be due to invalid IL or missing references) //IL_0691: Unknown result type (might be due to invalid IL or missing references) //IL_0696: Unknown result type (might be due to invalid IL or missing references) //IL_069f: Unknown result type (might be due to invalid IL or missing references) //IL_03fe: Unknown result type (might be due to invalid IL or missing references) //IL_0403: Unknown result type (might be due to invalid IL or missing references) //IL_0488: Unknown result type (might be due to invalid IL or missing references) //IL_048a: Unknown result type (might be due to invalid IL or missing references) //IL_048e: Unknown result type (might be due to invalid IL or missing references) //IL_0493: Unknown result type (might be due to invalid IL or missing references) //IL_0498: Unknown result type (might be due to invalid IL or missing references) //IL_0407: Unknown result type (might be due to invalid IL or missing references) //IL_073e: Unknown result type (might be due to invalid IL or missing references) //IL_074f: Unknown result type (might be due to invalid IL or missing references) //IL_0754: Unknown result type (might be due to invalid IL or missing references) //IL_0756: Unknown result type (might be due to invalid IL or missing references) //IL_076f: Unknown result type (might be due to invalid IL or missing references) //IL_07af: Unknown result type (might be due to invalid IL or missing references) //IL_0832: Unknown result type (might be due to invalid IL or missing references) //IL_080c: Unknown result type (might be due to invalid IL or missing references) if (_order.Count == 0) { return; } string text = _order[_cursor++ % _order.Count]; if (_cursor == int.MaxValue) { _cursor = 0; } Target target = _targets[text]; if (!target.Next.Ready(now)) { return; } List<(int, Vector3)> points = _points; points.Clear(); (int, Vector3, string)[] pickups = target.Prefab.Pickups; for (int i = 0; i < pickups.Length; i++) { (int, Vector3, string) tuple = pickups[i]; if (Objective(target.Prefab.Name, tuple.Item3)) { points.Add((tuple.Item1, target.Root + target.Rotation * tuple.Item2)); } } Vector3 val = ZoneSystem.GetZonePos(ZoneSystem.GetZone(target.Root)) + target.Prefab.CustomInteriorShift; val.y = target.Root.y + target.Prefab.CustomInteriorShift.y; pickups = target.Prefab.CustomPickups; for (int i = 0; i < pickups.Length; i++) { (int, Vector3, string) tuple2 = pickups[i]; if (Objective(target.Prefab.Name, tuple2.Item3)) { points.Add((tuple2.Item1, val + tuple2.Item2)); } } Vector3 val2 = (target.Prefab.CustomInterior ? val : target.Interior); _near.Clear(); WorldObjectProvider.Current.For("SharedMap").Query(ZoneSystem.GetZone(val2), new SimulationDistance(2, 0, true), _near); if (_near.Count > 65536) { Unknown(target, now, "interior_record_limit"); return; } ZDO val3 = null; int num = 0; foreach (ZDO item in _near) { if (!item.IsValid() || !item.Persistent) { continue; } (int, Vector3)[] generatorPoints = target.Prefab.GeneratorPoints; for (int i = 0; i < generatorPoints.Length; i++) { (int, Vector3) tuple3 = generatorPoints[i]; if (tuple3.Item1 == item.GetPrefab()) { Vector3 val4 = item.GetPosition() - (target.Prefab.CustomInterior ? val : (target.Root + target.Rotation * tuple3.Item2)); if (((Vector3)(ref val4)).sqrMagnitude <= 0.01f) { val3 = item; num++; break; } } } } if (target.Prefab.Generators.Length != 0) { if (num != 1) { Unknown(target, now, "layout_not_unique_or_unavailable"); return; } byte[] byteArray = val3.GetByteArray(ZDOVars.s_roomData, (byte[])null); DungeonRoomPlacement[] rooms; string reason; bool flag = SharedMapDungeonLayout.TryRead(byteArray, out rooms, out reason); _diagnostics.DungeonLayout(now, target.Gateways.First(), target.Prefab.Name, target.Root, (byteArray != null) ? byteArray.Length : 0, (byteArray != null && byteArray.Length >= 4) ? BitConverter.ToInt32(byteArray, 0) : 0, flag, reason); if (!flag) { Unknown(target, now, reason); return; } DungeonRoomPlacement[] array = rooms; foreach (DungeonRoomPlacement obj in array) { int hash = obj.Hash; Vector3 position = obj.Position; Quaternion val5 = Quaternion.Euler(obj.RotationEuler); if (!_rooms.TryGetValue(hash, out (int, Vector3, string)[] value)) { RoomData room = DungeonDB.instance.GetRoom(hash); if (room == null || _rooms.Count >= 2048) { Unknown(target, now, "room_metadata_unavailable"); return; } SoftReference prefab = room.m_prefab; try { prefab.Load(); if ((Object)(object)prefab.Asset == (Object)null) { Unknown(target, now, "room_asset_unavailable"); } else { _rooms[hash] = Points(prefab.Asset); } return; } finally { prefab.Release(); } } pickups = value; for (int j = 0; j < pickups.Length; j++) { (int, Vector3, string) tuple4 = pickups[j]; if (Objective(target.Prefab.Name, tuple4.Item3)) { points.Add((tuple4.Item1, position + val5 * tuple4.Item2)); } } if (points.Count > 65536) { Unknown(target, now, "pickup_point_limit"); return; } } } target.Next.Postpone(now, interval); if (points.Count == 0) { Record(target, now, 0, 0, "verified_empty_layout", verifiedEmpty: true); return; } foreach (List value4 in _cells.Values) { value4.Clear(); if (_cellLists.Count < 4096 && value4.Capacity <= 64) { _cellLists.Push(value4); } } _cells.Clear(); _pickupHashes.Clear(); foreach (var item2 in points) { (int, int, int, int) key = Cell(item2.Item1, item2.Item2); if (!_cells.TryGetValue(key, out List value2)) { value2 = ((_cellLists.Count > 0) ? _cellLists.Pop() : new List()); _cells.Add(key, value2); } value2.Add(item2.Item2); _pickupHashes.Add(item2.Item1); } Vector3 centre = val2; float zoneSize = ZoneSystem.instance.m_zoneSize; int num2 = (int)Math.Ceiling(points.Max<(int, Vector3)>(((int Hash, Vector3 Position) p) => Math.Max(Math.Abs(p.Position.x - centre.x), Math.Abs(p.Position.z - centre.z))) / zoneSize) + 1; if (num2 > 16) { Unknown(target, now, "pickup_extent_limit"); return; } _objects.Clear(); WorldObjectProvider.Current.For("SharedMap").Query(ZoneSystem.GetZone(centre), new SimulationDistance(num2, 0, true), _objects); if (_objects.Count > 65536) { Unknown(target, now, "pickup_record_limit"); return; } int num3 = 0; int num4 = 0; _seen.Clear(); _matchedSites.Clear(); foreach (ZDO @object in _objects) { if (!@object.IsValid() || !@object.Persistent || !_pickupHashes.Contains(@object.GetPrefab()) || !_seen.Add(@object.m_uid)) { continue; } Vector3 position2 = @object.GetPosition(); if (!SharedMapDungeonPrefab.Finite(position2)) { continue; } (int, float, float, float) site; int num5 = FindSite(_cells, @object.GetPrefab(), position2, out site); if (num5 != 0) { if (num5 != 1 || !_matchedSites.Add(site)) { Unknown(target, now, "ambiguous_pickup_site"); return; } if (_claims.TryGetValue(@object.m_uid, out string value3) && value3 != text) { Unknown(_targets[value3], now, "ambiguous_pickup_membership"); Unknown(target, now, "ambiguous_pickup_membership"); return; } if (_claims.Count >= 65536 && !_claims.ContainsKey(@object.m_uid)) { Unknown(target, now, "pickup_identity_limit"); return; } _claims[@object.m_uid] = text; num3++; if (@object.GetBool(ZDOVars.s_picked, false)) { num4++; } } } if (num3 == 0) { bool flag2 = false; foreach (string gateway in target.Gateways) { if (_store.Visited(gateway)) { flag2 = true; break; } } if (!flag2) { Record(target, now, 0, 0, "unvisited_empty_inventory"); return; } if (target.EmptySince < 0f) { target.EmptySince = now; } if (now - target.EmptySince < 30f) { Pending(target, now); return; } } else { target.EmptySince = -1f; } Record(target, now, num3, num4, (num3 == 0) ? "observed_empty_inventory" : "saved_pickup_flags", num3 == 0); } private void Record(Target target, float now, int total, int picked, string reason, bool verifiedEmpty = false) { //IL_007e: Unknown result type (might be due to invalid IL or missing references) foreach (string gateway in target.Gateways) { bool flag = _store.Progress(gateway, total, picked, verifiedEmpty); if (flag) { _changed++; } if (_store.VisitFromPickups(gateway, total, picked)) { _diagnostics.DungeonPriorVisit(now, gateway, total, picked); } (int, int) tuple = _store.ProgressState(gateway); _diagnostics.DungeonLoot(now, gateway, target.Prefab.Name, target.Root, tuple.Item1, tuple.Item2, flag, (tuple.Item2 < 0) ? "missing_or_unestablished_pickups" : reason); } } private void Pending(Target target, float now) { //IL_0037: Unknown result type (might be due to invalid IL or missing references) foreach (string gateway in target.Gateways) { (int, int) tuple = _store.ProgressState(gateway); _diagnostics.DungeonLoot(now, gateway, target.Prefab.Name, target.Root, tuple.Item1, tuple.Item2, changed: false, "empty_inventory_pending"); } } internal static int FindSite(IReadOnlyDictionary<(int Hash, int X, int Y, int Z), List> cells, int hash, Vector3 position, out (int Hash, float X, float Y, float Z) site) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0069: Unknown result type (might be due to invalid IL or missing references) //IL_006e: 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_0072: Unknown result type (might be due to invalid IL or missing references) //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_0090: Unknown result type (might be due to invalid IL or missing references) //IL_0097: 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) (int, int, int, int) tuple = Cell(hash, position); site = default((int, float, float, float)); bool flag = false; bool flag2 = false; for (int i = -1; i <= 1; i++) { for (int j = -1; j <= 1; j++) { for (int k = -1; k <= 1; k++) { if (!cells.TryGetValue((tuple.Item1, tuple.Item2 + i, tuple.Item3 + j, tuple.Item4 + k), out List value)) { continue; } foreach (Vector3 item in value) { Vector3 val = item - position; if (((Vector3)(ref val)).sqrMagnitude <= 0.01f) { (int, float, float, float) tuple2 = (tuple.Item1, item.x, item.y, item.z); if (flag && !site.Equals(tuple2)) { flag2 = true; } site = tuple2; flag = true; } } } } } if (!flag2) { return flag ? 1 : 0; } return 2; } private static (int Hash, int X, int Y, int Z) Cell(int hash, Vector3 p) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Unknown result type (might be due to invalid IL or missing references) return (Hash: hash, X: (int)Math.Floor(p.x), Y: (int)Math.Floor(p.y), Z: (int)Math.Floor(p.z)); } private void Unknown(Target target, float now, string reason) { //IL_0074: Unknown result type (might be due to invalid IL or missing references) target.EmptySince = -1f; target.Next.Postpone(now, 10f); foreach (string gateway in target.Gateways) { bool flag = _store.Progress(gateway, 0, 0); if (flag) { _changed++; } (int, int) tuple = _store.ProgressState(gateway); _diagnostics.DungeonLoot(now, gateway, target.Prefab.Name, target.Root, tuple.Item1, -1, flag, reason); } } public int TakeChanges() { int changed = _changed; _changed = 0; return changed; } } public sealed class SharedMapDungeonPins { public const float DuplicateDistanceMeters = 10f; private readonly Dictionary<(int X, int Z), List> _anchors = new Dictionary<(int, int), List>(); public IReadOnlyList Markers { get; } public int Suppressed { get; } public SharedMapDungeonPins(IReadOnlyList markers) { List list = new List(); int num = 0; foreach (MapMarker item in markers.OrderBy((MapMarker p) => p.Identity, StringComparer.Ordinal).ThenBy((MapMarker p) => p.X).ThenBy((MapMarker p) => p.Z) .ThenBy((MapMarker p) => p.Name, StringComparer.Ordinal)) { if (!SharedMapExploration.Finite(item.X) || !SharedMapExploration.Finite(item.Y) || !SharedMapExploration.Finite(item.Z)) { throw new InvalidDataException("Invalid dungeon publication point."); } if (Near(item.X, item.Z).Any()) { num++; continue; } list.Add(item); (int, int) key = Cell(item.X, item.Z); if (!_anchors.TryGetValue(key, out List value)) { _anchors.Add(key, value = new List()); } value.Add(item); } Markers = list; Suppressed = num; } private static (int X, int Z) Cell(float x, float z) { return (X: (int)Math.Floor(x / 10f), Z: (int)Math.Floor(z / 10f)); } private IEnumerable Near(float x, float z) { (int X, int Z) cell = Cell(x, z); for (int dx = -1; dx <= 1; dx++) { for (int dz = -1; dz <= 1; dz++) { if (!_anchors.TryGetValue((cell.X + dx, cell.Z + dz), out List value)) { continue; } foreach (MapMarker item in value) { double num = (double)item.X - (double)x; double num2 = (double)item.Z - (double)z; if (num * num + num2 * num2 <= 100.0) { yield return item; } } } } } public static string? Family(string label) { string name = label.Trim(); int num = name.LastIndexOf(' '); if (num > 0 && name.EndsWith("%", StringComparison.Ordinal) && int.TryParse(name.Substring(num + 1, name.Length - num - 2), NumberStyles.None, CultureInfo.InvariantCulture, out var result) && result >= 0 && result <= 100) { name = name.Substring(0, num); } return SharedMapDungeonPrefab.Labels.Values.FirstOrDefault((string n) => string.Equals(n, name, StringComparison.OrdinalIgnoreCase)); } public bool Obsolete(MapPin pin) { if (pin.Icon == 2 && Family(pin.Name) != null) { return Near(pin.X, pin.Z).Any(); } return false; } } internal sealed class SharedMapDungeonPrefab { internal static readonly IReadOnlyDictionary Labels = new Dictionary(StringComparer.Ordinal) { ["Crypt2"] = "Burial Chamber", ["Crypt3"] = "Burial Chamber", ["Crypt4"] = "Burial Chamber", ["SunkenCrypt4"] = "Sunken Crypt", ["TrollCave02"] = "Troll Cave", ["MountainCave02"] = "Frost Cave", ["Mistlands_DvergrTownEntrance1"] = "Infested Mine", ["Mistlands_DvergrTownEntrance2"] = "Infested Mine", ["Mistlands_DvergrBossEntrance1"] = "Infested Citadel", ["Hildir_crypt"] = "Smouldering Tomb", ["Hildir_cave"] = "Howling Cavern", ["MorgenHole1"] = "Putrid Hole", ["MorgenHole2"] = "Putrid Hole", ["MorgenHole3"] = "Putrid Hole", ["PlaceofMystery3"] = "Reto's Tomb", ["BearCave"] = "Bear Cave", ["TheHole01"] = "Winding Tunnels", ["MorkBorg"] = "Mörkhalla" }; public string Name { get; } public string Label { get; } public IReadOnlyList Gateways { get; } public float MaximumOffset { get; } public (int Hash, Vector3 Offset, string Item)[] Pickups { get; } public int[] Generators { get; } public (int Hash, Vector3 Offset)[] GeneratorPoints { get; } public bool CustomInterior { get; } public Vector3 CustomInteriorShift { get; } public (int Hash, Vector3 Offset, string Item)[] CustomPickups { get; } public SharedMapDungeonPrefab(GameObject prefab) { //IL_00c3: 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_00b6: 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_00ec: Unknown result type (might be due to invalid IL or missing references) //IL_00fc: Unknown result type (might be due to invalid IL or missing references) //IL_0107: Unknown result type (might be due to invalid IL or missing references) //IL_0111: Unknown result type (might be due to invalid IL or missing references) //IL_0116: Unknown result type (might be due to invalid IL or missing references) //IL_026b: 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_027c: Unknown result type (might be due to invalid IL or missing references) //IL_0283: Unknown result type (might be due to invalid IL or missing references) //IL_0288: Unknown result type (might be due to invalid IL or missing references) //IL_028d: Unknown result type (might be due to invalid IL or missing references) //IL_0292: Unknown result type (might be due to invalid IL or missing references) //IL_0296: Unknown result type (might be due to invalid IL or missing references) //IL_029b: Unknown result type (might be due to invalid IL or missing references) //IL_02a7: Unknown result type (might be due to invalid IL or missing references) //IL_02ae: Unknown result type (might be due to invalid IL or missing references) //IL_02b3: Unknown result type (might be due to invalid IL or missing references) //IL_02b8: Unknown result type (might be due to invalid IL or missing references) //IL_02bd: Unknown result type (might be due to invalid IL or missing references) //IL_02bf: Unknown result type (might be due to invalid IL or missing references) //IL_02cb: 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) //IL_02ed: Unknown result type (might be due to invalid IL or missing references) //IL_03f9: Unknown result type (might be due to invalid IL or missing references) //IL_0400: Unknown result type (might be due to invalid IL or missing references) //IL_0408: Unknown result type (might be due to invalid IL or missing references) //IL_040f: Unknown result type (might be due to invalid IL or missing references) //IL_0452: Unknown result type (might be due to invalid IL or missing references) //IL_0454: Unknown result type (might be due to invalid IL or missing references) PrefabRegistry.Current.Observe(prefab); Name = ((Object)prefab).name; if (!Labels.TryGetValue(Name, out string value)) { throw new InvalidDataException("Unsupported dungeon prefab."); } Label = value; Location val = PrefabRegistry.Component(prefab); if ((Object)(object)val == (Object)null || !val.m_hasInterior) { throw new InvalidDataException("Dungeon has no native interior metadata."); } CustomInterior = val.m_useCustomInteriorTransform && (Object)(object)val.m_interiorTransform != (Object)null && (Object)(object)val.m_generator != (Object)null; CustomInteriorShift = (CustomInterior ? (val.m_interiorTransform.localPosition + ((Component)val.m_generator).transform.localPosition) : Vector3.zero); if (CustomInterior) { CustomInteriorShift = new Vector3(CustomInteriorShift.x, val.m_interiorTransform.localPosition.y, CustomInteriorShift.z); } Pickups = SharedMapDungeonLoot.Points(prefab, CustomInterior ? val.m_interiorTransform : null); CustomPickups = ((int Hash, Vector3 Offset, string Item)[])(CustomInterior ? ((Array)SharedMapDungeonLoot.Points(((Component)val.m_interiorTransform).gameObject)) : ((Array)Array.Empty<(int, Vector3, string)>())); GeneratorPoints = (from g in PrefabRegistry.Children(prefab, inactive: true) select (StringExtensionMethods.GetStableHashCode(Utils.GetPrefabName(((Component)g).gameObject)), Quaternion.Inverse(prefab.transform.rotation) * (((Component)g).transform.position - prefab.transform.position))).ToArray(); Generators = GeneratorPoints.Select(((int Hash, Vector3 Offset) g) => g.Hash).Distinct().ToArray(); List list = new List(); Transform transform = prefab.transform; Teleport[] array = PrefabRegistry.Children(prefab, inactive: true); foreach (Teleport val2 in array) { Teleport targetPoint = val2.m_targetPoint; if (!((Behaviour)val2).enabled || val2.m_hoverText != "$location_enter" || (Object)(object)targetPoint == (Object)null || (Object)(object)targetPoint.m_targetPoint != (Object)(object)val2 || targetPoint.m_hoverText != "$location_exit" || !((Component)targetPoint).transform.IsChildOf(transform)) { continue; } Vector3 val3 = Quaternion.Inverse(transform.rotation) * (((Component)val2).transform.position - transform.position); Vector3 val4 = Quaternion.Inverse(transform.rotation) * (((Component)targetPoint).transform.position - transform.position); if (!Finite(val3) || !Finite(val4) || Math.Abs(val3.y) >= 1000f || val4.y < 4000f) { continue; } List list2 = new List(); bool flag = true; Transform val5 = ((Component)val2).transform; while ((Object)(object)val5 != (Object)null) { if (!((Component)val5).gameObject.activeSelf) { flag = false; break; } MonoBehaviour[] array2 = PrefabRegistry.Components((Component)(object)val5); foreach (MonoBehaviour val6 in array2) { if ((Object)(object)val6 == (Object)null || ((Object)(object)val6 != (Object)(object)val2 && (Object)(object)val6 != (Object)(object)val && ((Behaviour)val6).enabled)) { flag = false; } } if ((Object)(object)val5 == (Object)(object)transform) { break; } list2.Insert(0, val5.GetSiblingIndex().ToString(CultureInfo.InvariantCulture)); val5 = val5.parent; } if (flag) { string text = string.Join("/", list2); if (text.Length == 0 || text.Length > 512 || list.Count >= 16) { throw new InvalidDataException("Unsupported dungeon gateway hierarchy."); } float num3 = Mathf.Sqrt(val3.x * val3.x + val3.z * val3.z); if (!SharedMapExploration.Finite(num3) || num3 > 128f) { throw new InvalidDataException("Unsupported dungeon exterior offset."); } MaximumOffset = Math.Max(MaximumOffset, num3); list.Add(new DungeonGateway(text, val3, val4)); } } if (list.Count == 0) { throw new InvalidDataException("No validated static exterior gateway."); } Gateways = list; } internal static bool Finite(Vector3 p) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_001a: Unknown result type (might be due to invalid IL or missing references) if (SharedMapExploration.Finite(p.x) && SharedMapExploration.Finite(p.y)) { return SharedMapExploration.Finite(p.z); } return false; } } internal sealed class SharedMapDungeons : IDisposable { private readonly ZDOMan _world; private CandidateSubscription? _index; private readonly SharedMapDungeonStore _store; private readonly SharedMapExploration _map; private readonly SharedMapSettings _settings; private readonly SharedMapDiagnostics _diagnostics; private readonly PrefabCatalog _prefabs = PrefabRegistry.Current.Catalog("SharedMapDungeons._prefabs"); private readonly List _near = new List(); private readonly List _scan = new List(); private readonly Queue<(SharedMapDungeonPrefab Prefab, DungeonGateway Gateway, Vector3 Root, Quaternion Rotation, Vector3? Player)> _pending = new Queue<(SharedMapDungeonPrefab, DungeonGateway, Vector3, Quaternion, Vector3?)>(); private readonly string _proxyName; private readonly int _proxyHash; private float _maximumOffset; private readonly ScheduleToken _nextScan = new ScheduleToken(); private int _sector; private int _scanCursor; private int _added; private bool _scanComplete; private readonly SharedMapDungeonLoot? _loot; private readonly Dictionary<(string Name, Vector3 Root), string[]> _gatewayIdentities = new Dictionary<(string, Vector3), string[]>(); public SharedMapDungeons(ZDOMan world, SharedMapDungeonStore store, SharedMapExploration map, SharedMapSettings settings, SharedMapDiagnostics diagnostics) { //IL_015a: Unknown result type (might be due to invalid IL or missing references) //IL_015f: Unknown result type (might be due to invalid IL or missing references) //IL_0179: Unknown result type (might be due to invalid IL or missing references) //IL_017e: Unknown result type (might be due to invalid IL or missing references) //IL_0180: Unknown result type (might be due to invalid IL or missing references) _world = world; _store = store; _map = map; _settings = settings; _diagnostics = diagnostics; if (settings.DungeonLootProgress.Value) { _loot = new SharedMapDungeonLoot(world, store, diagnostics); } GameObject locationProxyPrefab = ZoneSystem.instance.m_locationProxyPrefab; if ((Object)(object)locationProxyPrefab == (Object)null || (Object)(object)PrefabRegistry.Component(locationProxyPrefab) == (Object)null || (Object)(object)PrefabRegistry.Component(locationProxyPrefab) == (Object)null) { throw new InvalidOperationException("Native dungeon location-proxy metadata is unavailable."); } _proxyName = ((Object)locationProxyPrefab).name; _proxyHash = StringExtensionMethods.GetStableHashCode(_proxyName); List list = new List(); HashSet hashSet = new HashSet(StringComparer.Ordinal); foreach (ZoneLocation location in ZoneSystem.instance.m_locations) { if (!location.m_prefab.IsValid) { continue; } string name = location.m_prefab.Name; if (!SharedMapDungeonPrefab.Labels.ContainsKey(name) || !hashSet.Add(name)) { continue; } SoftReference prefab = location.m_prefab; if (!prefab.IsValid) { list.Add(name); continue; } LoadResult val = prefab.Load(); try { if ((int)val != 0 || (Object)(object)prefab.Asset == (Object)null) { throw new InvalidDataException("Dungeon prefab could not be loaded for metadata inspection."); } SharedMapDungeonPrefab sharedMapDungeonPrefab = new SharedMapDungeonPrefab(prefab.Asset); int stableHashCode = StringExtensionMethods.GetStableHashCode(name); if (_prefabs.ContainsKey(stableHashCode)) { throw new InvalidDataException("Ambiguous dungeon location hash."); } _prefabs.Add(stableHashCode, sharedMapDungeonPrefab); _maximumOffset = Math.Max(_maximumOffset, sharedMapDungeonPrefab.MaximumOffset); } catch (InvalidDataException) { list.Add(name); } finally { prefab.Release(); } } _diagnostics.UnsupportedDungeons(list); _diagnostics.DungeonReady(_prefabs.Count, _prefabs.Values.Sum((SharedMapDungeonPrefab p) => p.Gateways.Count), _store.Count, _map.Radius, _map.Interval, _settings.DungeonDiscoverPreviouslyExplored.Value, _settings.AllowPlayerMapWrites.Value); } public static void CheckCompatibility() { if (typeof(ZoneSystem).GetField("m_locations")?.FieldType != typeof(List) || typeof(ZoneSystem).GetField("m_locationProxyPrefab")?.FieldType != typeof(GameObject) || typeof(Teleport).GetField("m_targetPoint")?.FieldType != typeof(Teleport) || typeof(ZDOMan).GetMethod("FindSectorObjects", new Type[4] { typeof(Vector2s), typeof(SimulationDistance), typeof(List), typeof(List) }) == null) { throw new MissingMemberException("Native dungeon entrance discovery APIs are unavailable."); } } public void Sample(Vector3 player) { //IL_007f: Unknown result type (might be due to invalid IL or missing references) //IL_00a6: Unknown result type (might be due to invalid IL or missing references) float zoneSize = ZoneSystem.instance.m_zoneSize; if (!SharedMapExploration.Finite(zoneSize) || zoneSize < 16f) { throw new InvalidOperationException("Unsupported native dungeon-sector geometry."); } _near.Clear(); int radius = (int)Math.Ceiling((_map.Radius + _maximumOffset) / zoneSize) + 1; if (_index == null) { _index = WorldObjectProvider.Current.Subscribe("SharedMap", (ZDO z) => z.GetPrefab() == _proxyHash); } _index.Read(player, radius, _near, classic: true); foreach (ZDO item in _near) { Enqueue(item, player); } } public void SampleInterior(Vector3 player, long peer, float now) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_0053: Unknown result type (might be due to invalid IL or missing references) //IL_00b2: Unknown result type (might be due to invalid IL or missing references) //IL_0124: Unknown result type (might be due to invalid IL or missing references) //IL_0129: Unknown result type (might be due to invalid IL or missing references) //IL_012b: Unknown result type (might be due to invalid IL or missing references) //IL_0130: Unknown result type (might be due to invalid IL or missing references) //IL_0132: Unknown result type (might be due to invalid IL or missing references) //IL_00c0: Unknown result type (might be due to invalid IL or missing references) //IL_0140: Unknown result type (might be due to invalid IL or missing references) //IL_00ce: Unknown result type (might be due to invalid IL or missing references) //IL_00d3: Unknown result type (might be due to invalid IL or missing references) //IL_00d8: Unknown result type (might be due to invalid IL or missing references) //IL_014e: Unknown result type (might be due to invalid IL or missing references) //IL_015c: Unknown result type (might be due to invalid IL or missing references) //IL_0188: Unknown result type (might be due to invalid IL or missing references) //IL_01bf: Unknown result type (might be due to invalid IL or missing references) //IL_01c0: Unknown result type (might be due to invalid IL or missing references) if (!SharedMapDungeonPrefab.Finite(player) || !Character.InInterior(player)) { return; } Vector2s zone = ZoneSystem.GetZone(player); _near.Clear(); if (_index == null) { _index = WorldObjectProvider.Current.Subscribe("SharedMap", (ZDO z) => z.GetPrefab() == _proxyHash); } _index.Read(player, 0, _near, classic: true); if (_near.Count > 65536) { return; } ZDO val = null; foreach (ZDO item in _near) { if (item.IsValid() && item.Persistent && item.GetPrefab() == _proxyHash && SharedMapDungeonPrefab.Finite(item.GetPosition()) && !Character.InInterior(item.GetPosition()) && !(ZoneSystem.GetZone(item.GetPosition()) != zone)) { if (val != null) { return; } val = item; } } if (val == null || !_prefabs.TryGetValue(val.GetInt(ZDOVars.s_location, 0), out SharedMapDungeonPrefab value)) { return; } Vector3 position = val.GetPosition(); Quaternion rotation = val.GetRotation(); if (!SharedMapExploration.Finite(rotation.x) || !SharedMapExploration.Finite(rotation.y) || !SharedMapExploration.Finite(rotation.z) || !SharedMapExploration.Finite(rotation.w)) { return; } int num = 0; foreach (DungeonGateway gateway in value.Gateways) { string identity = GatewayIdentity(value, position, gateway.Path); if (_store.Visit(identity)) { num++; } if (_store.Contains(identity)) { TrackLoot(identity, value, position, rotation, gateway); } } if (num > 0) { _diagnostics.DungeonVisited(now, value.Name, peer, num); } } private void Enqueue(ZDO zdo, Vector3? player) { //IL_003b: 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_0042: Unknown result type (might be due to invalid IL or missing references) //IL_0047: Unknown result type (might be due to invalid IL or missing references) //IL_0048: Unknown result type (might be due to invalid IL or missing references) //IL_0050: Unknown result type (might be due to invalid IL or missing references) //IL_0058: Unknown result type (might be due to invalid IL or missing references) //IL_0065: Unknown result type (might be due to invalid IL or missing references) //IL_0072: 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_0096: 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_00ab: 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_0122: Unknown result type (might be due to invalid IL or missing references) //IL_0123: Unknown result type (might be due to invalid IL or missing references) if (!zdo.IsValid() || !zdo.Persistent || zdo.GetPrefab() != _proxyHash || !_prefabs.TryGetValue(zdo.GetInt(ZDOVars.s_location, 0), out SharedMapDungeonPrefab value)) { return; } Vector3 position = zdo.GetPosition(); Quaternion rotation = zdo.GetRotation(); if (!SharedMapDungeonPrefab.Finite(position) || Character.InInterior(position) || !SharedMapExploration.Finite(rotation.x) || !SharedMapExploration.Finite(rotation.y) || !SharedMapExploration.Finite(rotation.z) || !SharedMapExploration.Finite(rotation.w)) { return; } if (player.HasValue) { double num = (double)position.x - (double)player.Value.x; double num2 = (double)position.z - (double)player.Value.z; double num3 = _map.Radius + value.MaximumOffset; if (num * num + num2 * num2 > num3 * num3) { return; } } foreach (DungeonGateway gateway in value.Gateways) { if (_pending.Count >= 65536) { throw new InvalidOperationException("Dungeon encounter queue limit exceeded; discoveries and prior table data were retained."); } _pending.Enqueue((value, gateway, position, rotation, player)); } } public void Tick(float now) { //IL_0166: 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_0179: Unknown result type (might be due to invalid IL or missing references) //IL_017e: Unknown result type (might be due to invalid IL or missing references) //IL_0183: Unknown result type (might be due to invalid IL or missing references) //IL_0188: 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_0196: Unknown result type (might be due to invalid IL or missing references) //IL_01ac: Unknown result type (might be due to invalid IL or missing references) //IL_01df: 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_020a: Unknown result type (might be due to invalid IL or missing references) //IL_0219: Unknown result type (might be due to invalid IL or missing references) //IL_0225: Unknown result type (might be due to invalid IL or missing references) //IL_0234: Unknown result type (might be due to invalid IL or missing references) //IL_0285: Unknown result type (might be due to invalid IL or missing references) //IL_028c: Unknown result type (might be due to invalid IL or missing references) //IL_02a9: Unknown result type (might be due to invalid IL or missing references) //IL_02b0: Unknown result type (might be due to invalid IL or missing references) //IL_02b7: Unknown result type (might be due to invalid IL or missing references) //IL_030e: Unknown result type (might be due to invalid IL or missing references) //IL_031f: Unknown result type (might be due to invalid IL or missing references) //IL_0347: Unknown result type (might be due to invalid IL or missing references) //IL_034e: Unknown result type (might be due to invalid IL or missing references) //IL_0383: Unknown result type (might be due to invalid IL or missing references) if ((_settings.DungeonDiscoverPreviouslyExplored.Value || (_store.Count > 0 && _loot != null)) && _nextScan.Ready(now) && _pending.Count < 32768) { if (_scanCursor == _scan.Count) { if (_scanComplete) { _scanComplete = false; _sector = 0; _nextScan.Postpone(now, _settings.TableIntervalSeconds.Value); } else { _scan.Clear(); _scanCursor = 0; _scanComplete = _world.GetAllZDOsWithPrefabIterative(_proxyName, _scan, ref _sector); if (_scan.Count > 65536) { throw new InvalidOperationException("Dungeon scan candidate limit exceeded; discoveries were retained."); } } } for (int i = 0; i < 256; i++) { if (_scanCursor >= _scan.Count) { break; } if (_pending.Count >= 32768) { break; } Enqueue(_scan[_scanCursor++], null); } } for (int j = 0; j < 256 && _pending.Count > 0; j++) { (SharedMapDungeonPrefab, DungeonGateway, Vector3, Quaternion, Vector3?) tuple = _pending.Dequeue(); Vector3 val = tuple.Item3 + tuple.Item4 * tuple.Item2.Offset; if (!SharedMapDungeonPrefab.Finite(val) || Character.InInterior(val)) { continue; } string identity = GatewayIdentity(tuple.Item1, tuple.Item3, tuple.Item2.Path); if (_store.Contains(identity)) { TrackLoot(identity, tuple.Item1, tuple.Item3, tuple.Item4, tuple.Item2); continue; } if (tuple.Item5.HasValue) { double num = (double)val.x - (double)tuple.Item5.Value.x; double num2 = (double)val.z - (double)tuple.Item5.Value.z; if (num * num + num2 * num2 > (double)_map.Radius * (double)_map.Radius) { continue; } } else if (!_settings.DungeonDiscoverPreviouslyExplored.Value || !_map.IsExplored(val.x, val.z)) { continue; } MapMarker marker = new MapMarker(tuple.Item1.Label, val.x, val.y, val.z, identity); bool num3; if (!tuple.Item5.HasValue) { if (!_settings.DungeonDiscoverPreviouslyExplored.Value) { continue; } num3 = _store.DiscoverExplored(marker, _map); } else { num3 = _store.DiscoverNearby(marker, tuple.Item5.Value.x, tuple.Item5.Value.z, _map.Radius); } if (num3) { TrackLoot(identity, tuple.Item1, tuple.Item3, tuple.Item4, tuple.Item2); _added++; _diagnostics.DungeonDiscovered(marker, tuple.Item1.Name, tuple.Item3, tuple.Item5, _map.Radius); } } if ((Object)(object)DungeonDB.instance != (Object)null) { _loot?.Tick(now, _settings.TableIntervalSeconds.Value); } } private string[] GatewayIdentities(SharedMapDungeonPrefab prefab, Vector3 root) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_005a: Unknown result type (might be due to invalid IL or missing references) //IL_0060: Unknown result type (might be due to invalid IL or missing references) //IL_0066: Unknown result type (might be due to invalid IL or missing references) (string, Vector3) key = (prefab.Name, root); if (_gatewayIdentities.TryGetValue(key, out string[] value)) { return value; } if (_gatewayIdentities.Count >= 65536) { throw new InvalidOperationException("Dungeon placed-source cache limit exceeded."); } value = new string[prefab.Gateways.Count]; for (int i = 0; i < value.Length; i++) { value[i] = SharedMapDungeonIdentity.Create(prefab.Name, root.x, root.y, root.z, prefab.Gateways[i].Path); } _gatewayIdentities.Add(key, value); return value; } private string GatewayIdentity(SharedMapDungeonPrefab prefab, Vector3 root, string path) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) string[] array = GatewayIdentities(prefab, root); for (int i = 0; i < prefab.Gateways.Count; i++) { if (prefab.Gateways[i].Path == path) { return array[i]; } } throw new InvalidOperationException("Dungeon gateway is outside its validated template."); } private void TrackLoot(string identity, SharedMapDungeonPrefab prefab, Vector3 root, Quaternion rotation, DungeonGateway gateway) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_0086: Unknown result type (might be due to invalid IL or missing references) //IL_0087: 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_008a: 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_0093: Unknown result type (might be due to invalid IL or missing references) //IL_0098: Unknown result type (might be due to invalid IL or missing references) _store.ShareVisits(GatewayIdentities(prefab, root)); if (new string[10] { "Crypt2", "Crypt3", "Crypt4", "Hildir_crypt", "Mistlands_DvergrTownEntrance1", "Mistlands_DvergrTownEntrance2", "MountainCave02", "Hildir_cave", "TheHole01", "MorkBorg" }.Contains(prefab.Name)) { _loot?.Track(identity, prefab, root, rotation, root + rotation * gateway.InteriorOffset); } } public IReadOnlyList Read() { return _store.Read(_settings.DungeonLootProgress.Value); } public void Report(float now) { _diagnostics.DungeonResults(_added); _diagnostics.DungeonLootResults(_loot?.TakeChanges() ?? 0); _added = 0; _diagnostics.DungeonCatalog(now, _store.Count, _pending.Count, _settings.DungeonDiscoverPreviouslyExplored.Value); } public void Dispose() { _index?.Dispose(); _index = null; _pending.Clear(); _gatewayIdentities.Clear(); _scan.Clear(); _near.Clear(); _prefabs.Clear(); _added = 0; } } public sealed class SharedMapDungeonStore { private const uint Magic = 1195658056u; public const int MaximumDiscoveries = 65536; public const int MaximumMarkers = 4096; private readonly long _world; private Dictionary _discoveries = new Dictionary(StringComparer.Ordinal); private readonly Dictionary _progress = new Dictionary(StringComparer.Ordinal); private readonly HashSet _visited = new HashSet(StringComparer.Ordinal); private long _revision; private long _savedRevision; private readonly ScheduleToken _nextSave = new ScheduleToken(); private IReadOnlyList? _markers; public string FilePath { get; } public int Count => _discoveries.Count; public SharedMapDungeonStore(string directory, long world) { _world = world; FilePath = Path.Combine(directory, "world-" + world.ToString("X16", CultureInfo.InvariantCulture) + ".entrances"); } public bool Contains(string identity) { return _discoveries.ContainsKey(identity); } public bool Visited(string identity) { return _visited.Contains(identity); } public bool Visit(string identity) { if (!_discoveries.ContainsKey(identity) || !_visited.Add(identity)) { return false; } _revision++; _markers = null; return true; } public bool VisitFromPickups(string identity, int total, int picked) { (int, int) tuple = ProgressState(identity); if (total > 0 && picked > 0 && picked <= total && tuple.Item1 == total && tuple.Item2 == picked) { return Visit(identity); } return false; } public int ShareVisits(IReadOnlyList locationGateways) { bool flag = false; for (int i = 0; i < locationGateways.Count; i++) { if (Visited(locationGateways[i])) { flag = true; break; } } if (!flag) { return 0; } int num = 0; for (int j = 0; j < locationGateways.Count; j++) { if (Visit(locationGateways[j])) { num++; } } return num; } public (int Total, int Picked) ProgressState(string identity) { if (!_progress.TryGetValue(identity, out (int, int) value)) { return (Total: 0, Picked: -1); } return value; } private static bool Valid(MapMarker marker) { if (SharedMapPinRemovals.ValidId(marker.Identity) && marker.Name.Length > 0 && Encoding.UTF8.GetByteCount(marker.Name) <= 128 && SharedMapExploration.Finite(marker.X) && SharedMapExploration.Finite(marker.Y) && SharedMapExploration.Finite(marker.Z) && Math.Abs(marker.X) <= 100000f && Math.Abs(marker.Z) <= 100000f) { return Math.Abs(marker.Y) < 4000f; } return false; } public bool Discover(MapMarker marker) { if (!Valid(marker)) { throw new InvalidDataException("Invalid dungeon discovery."); } if (_discoveries.ContainsKey(marker.Identity)) { return false; } if (Count >= 65536) { throw new InvalidOperationException("Dungeon discovery storage limit exceeded; existing discoveries were retained."); } _discoveries.Add(marker.Identity, marker); _revision++; _markers = null; return true; } public bool DiscoverNearby(MapMarker marker, float playerX, float playerZ, float radius) { if (!SharedMapExploration.Finite(playerX) || !SharedMapExploration.Finite(playerZ) || !SharedMapExploration.Finite(radius) || radius <= 0f) { return false; } double num = (double)marker.X - (double)playerX; double num2 = (double)marker.Z - (double)playerZ; if (num * num + num2 * num2 <= (double)radius * (double)radius) { return Discover(marker); } return false; } public bool DiscoverExplored(MapMarker marker, SharedMapExploration map) { if (map.IsExplored(marker.X, marker.Z)) { return Discover(marker); } return false; } public bool Progress(string identity, int total, int picked, bool verifiedEmpty = false) { if (!_discoveries.ContainsKey(identity) || total < 0 || total > 65536 || picked < 0 || picked > total) { return false; } (int, int) value; bool num = _progress.TryGetValue(identity, out value); (int, int) tuple = ((total < value.Item1 || (total == 0 && !verifiedEmpty)) ? (value.Item1, -1) : (total, picked)); if (num) { (int, int) tuple2 = tuple; (int, int) tuple3 = value; if (tuple2.Item1 == tuple3.Item1 && tuple2.Item2 == tuple3.Item2) { return false; } } _progress[identity] = tuple; _revision++; _markers = null; return true; } public static string ProgressLabel(string name, int total, int picked) { if (total < 0 || picked < 0 || picked > total) { return name; } return name + " " + ((total != 0) ? ((int)Math.Ceiling(100.0 * (double)(total - picked) / (double)total)) : 0).ToString(CultureInfo.InvariantCulture) + "%"; } public IReadOnlyList Read(bool progress = true) { if (Count > 4096) { throw new InvalidOperationException("Dungeon marker limit exceeded; prior table data must be retained."); } if (!progress) { return (from p in _discoveries.OrderBy, string>((KeyValuePair p) => p.Key, StringComparer.Ordinal) select p.Value).ToArray(); } return _markers ?? (_markers = _discoveries.OrderBy, string>((KeyValuePair p) => p.Key, StringComparer.Ordinal).Select(delegate(KeyValuePair p) { MapMarker value = p.Value; (int, int) tuple = ProgressState(p.Key); return new MapMarker(Visited(p.Key) ? ProgressLabel(value.Name, tuple.Item1, tuple.Item2) : value.Name, value.X, value.Y, value.Z, value.Identity); }).ToArray()); } public bool Load() { if (!File.Exists(FilePath)) { if (File.Exists(FilePath + ".bak")) { throw new InvalidDataException("Dungeon discoveries are missing but their backup exists."); } return false; } using FileStream fileStream = new FileStream(FilePath, FileMode.Open, FileAccess.Read, FileShare.Read); if (fileStream.Length < 52 || fileStream.Length > 11993140) { throw new InvalidDataException("Invalid dungeon discovery file length."); } using BinaryReader binaryReader = new BinaryReader(fileStream); byte[] buffer = binaryReader.ReadBytes((int)fileStream.Length - 32); byte[] array = binaryReader.ReadBytes(32); using SHA256 sHA = SHA256.Create(); if (!((ReadOnlySpan)sHA.ComputeHash(buffer)).SequenceEqual((ReadOnlySpan)array)) { throw new InvalidDataException("Dungeon discovery checksum mismatch."); } using BinaryReader binaryReader2 = new BinaryReader(new MemoryStream(buffer, writable: false), new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true)); uint num = binaryReader2.ReadUInt32(); int num2 = binaryReader2.ReadInt32(); if (num != 1195658056 || (num2 != 1 && num2 != 2 && num2 != 3) || binaryReader2.ReadInt64() != _world) { throw new InvalidDataException("Unsupported dungeon discovery format or world."); } int num3 = binaryReader2.ReadInt32(); if (num3 < 0 || num3 > 65536) { throw new InvalidDataException("Invalid dungeon discovery count."); } Dictionary dictionary = new Dictionary(StringComparer.Ordinal); Dictionary dictionary2 = new Dictionary(); HashSet hashSet = new HashSet(StringComparer.Ordinal); for (int i = 0; i < num3; i++) { byte[] array2 = binaryReader2.ReadBytes(32); if (array2.Length != 32) { throw new InvalidDataException("Truncated dungeon identity."); } int num4 = binaryReader2.ReadUInt16(); if (num4 < 1 || num4 > 128) { throw new InvalidDataException("Invalid dungeon label length."); } byte[] array3 = binaryReader2.ReadBytes(num4); if (array3.Length != num4) { throw new InvalidDataException("Truncated dungeon label."); } MapMarker mapMarker = new MapMarker(new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true).GetString(array3), binaryReader2.ReadSingle(), binaryReader2.ReadSingle(), binaryReader2.ReadSingle(), BitConverter.ToString(array2).Replace("-", "").ToLowerInvariant()); if (!Valid(mapMarker) || dictionary.ContainsKey(mapMarker.Identity)) { throw new InvalidDataException("Invalid or duplicate dungeon discovery."); } dictionary.Add(mapMarker.Identity, mapMarker); if (num2 >= 2) { int num5 = binaryReader2.ReadInt32(); int num6 = binaryReader2.ReadInt32(); if (num5 < 0 || num5 > 65536 || num6 < -1 || num6 > num5) { throw new InvalidDataException("Invalid dungeon pickup progress."); } if (num2 == 2 && num5 == 0) { num6 = -1; } dictionary2[mapMarker.Identity] = (num5, num6); } if (num2 >= 3) { byte num7 = binaryReader2.ReadByte(); if (num7 > 1) { throw new InvalidDataException("Invalid dungeon visit state."); } if (num7 == 1) { hashSet.Add(mapMarker.Identity); } } } if (binaryReader2.BaseStream.Position != binaryReader2.BaseStream.Length) { throw new InvalidDataException("Trailing dungeon discovery data."); } _discoveries = dictionary; _progress.Clear(); foreach (KeyValuePair item in dictionary2) { _progress.Add(item.Key, item.Value); } _visited.Clear(); foreach (string item2 in hashSet) { _visited.Add(item2); } _revision = (_savedRevision = 0L); _markers = null; return true; } public bool SaveIfDue(float now, float interval) { if (!_nextSave.Ready(now)) { return false; } _nextSave.Postpone(now, interval); return Save(); } public bool Save() { if (_revision == _savedRevision) { return false; } Directory.CreateDirectory(Path.GetDirectoryName(FilePath)); string text = FilePath + "." + Guid.NewGuid().ToString("N") + ".tmp"; try { using MemoryStream memoryStream = new MemoryStream(); using (BinaryWriter binaryWriter = new BinaryWriter(memoryStream, Encoding.UTF8, leaveOpen: true)) { binaryWriter.Write(1195658056u); binaryWriter.Write(3); binaryWriter.Write(_world); binaryWriter.Write(Count); foreach (MapMarker item in from p in _discoveries.OrderBy, string>((KeyValuePair p) => p.Key, StringComparer.Ordinal) select p.Value) { for (int num = 0; num < 64; num += 2) { binaryWriter.Write(byte.Parse(item.Identity.Substring(num, 2), NumberStyles.HexNumber, CultureInfo.InvariantCulture)); } byte[] bytes = Encoding.UTF8.GetBytes(item.Name); binaryWriter.Write((ushort)bytes.Length); binaryWriter.Write(bytes); binaryWriter.Write(item.X); binaryWriter.Write(item.Y); binaryWriter.Write(item.Z); (int, int) tuple = ProgressState(item.Identity); binaryWriter.Write(tuple.Item1); binaryWriter.Write(tuple.Item2); binaryWriter.Write(Visited(item.Identity) ? ((byte)1) : ((byte)0)); } } byte[] array = memoryStream.ToArray(); using SHA256 sHA = SHA256.Create(); using (FileStream fileStream = new FileStream(text, FileMode.CreateNew, FileAccess.Write, FileShare.None)) { fileStream.Write(array, 0, array.Length); byte[] array2 = sHA.ComputeHash(array); fileStream.Write(array2, 0, array2.Length); fileStream.Flush(flushToDisk: true); } if (File.Exists(FilePath)) { File.Replace(text, FilePath, FilePath + ".bak"); } else { File.Move(text, FilePath); } _savedRevision = _revision; return true; } finally { if (File.Exists(text)) { File.Delete(text); } } } } public sealed class SharedMapExploration { public int Size { get; } public float PixelSize { get; } public float Radius { get; } public float Interval { get; } public int ExploredPixels { get; private set; } internal byte[] Pixels { get; } public SharedMapExploration(int size, float pixelSize, float radius, float interval) { if (size < 16 || size > 4096 || (size & (size - 1)) != 0 || !Finite(pixelSize) || pixelSize < 1f || pixelSize > 128f || !Finite(radius) || radius <= 0f || radius > 1000f || !Finite(interval) || interval < 0.1f || interval > 60f) { throw new ArgumentOutOfRangeException("size", "Unsupported native minimap geometry."); } Size = size; PixelSize = pixelSize; Radius = radius; Interval = interval; Pixels = new byte[size * size]; } public bool Matches(int size, float pixelSize, float radius, float interval) { if (Size == size && PixelSize == pixelSize && Radius == radius) { return Interval == interval; } return false; } public static bool Finite(float value) { if (!float.IsNaN(value)) { return !float.IsInfinity(value); } return false; } private bool TryPixel(float x, float z, out int px, out int py) { px = (py = 0); if (!Finite(x) || !Finite(z)) { return false; } float num = (float)(Size / 2) * PixelSize; if (x < 0f - num || x >= num || z < 0f - num || z >= num) { return false; } px = Utils.RoundToInt(x / PixelSize + (float)(Size / 2)); py = Utils.RoundToInt(z / PixelSize + (float)(Size / 2)); if (px >= 0 && px < Size && py >= 0) { return py < Size; } return false; } public bool IsExplored(float x, float z) { if (TryPixel(x, z, out var px, out var py)) { return Pixels[py * Size + px] != 0; } return false; } public bool IsExploredPixel(int x, int y) { if (x >= 0 && x < Size && y >= 0 && y < Size) { return Pixels[y * Size + x] != 0; } return false; } internal int Import(byte[] source, int offset) { if (offset < 0 || source.Length - offset < Pixels.Length) { throw new ArgumentException("Invalid terrain array."); } int num = 0; for (int i = 0; i < Pixels.Length; i++) { if (source[offset + i] != 0 && Pixels[i] == 0) { Pixels[i] = 1; num++; } } ExploredPixels += num; return num; } public byte[] ExportPacked() { byte[] array = new byte[(Pixels.Length + 7) / 8]; for (int i = 0; i < Pixels.Length; i++) { if (Pixels[i] != 0) { array[i / 8] |= (byte)(1 << i % 8); } } return array; } public void ImportPacked(byte[] packed) { if (packed.Length != (Pixels.Length + 7) / 8) { throw new ArgumentException("Invalid packed terrain length."); } int num = 0; for (int i = 0; i < Pixels.Length; i++) { if ((packed[i / 8] & (1 << i % 8)) != 0 && Pixels[i] == 0) { Pixels[i] = 1; num++; } } ExploredPixels += num; } public int Reveal(float x, float z) { if (!TryPixel(x, z, out var px, out var py)) { return 0; } int num = (int)Math.Ceiling(Radius / PixelSize); int num2 = 0; for (int i = Math.Max(0, py - num); i <= Math.Min(Size - 1, py + num); i++) { for (int j = Math.Max(0, px - num); j <= Math.Min(Size - 1, px + num); j++) { int num3 = j - px; int num4 = i - py; if (num3 * num3 + num4 * num4 <= num * num) { int num5 = i * Size + j; if (Pixels[num5] == 0) { Pixels[num5] = 1; num2++; } } } } ExploredPixels += num2; return num2; } } internal sealed class SharedMapLandmarkPrefab { internal static readonly IReadOnlyDictionary Runestones = new Dictionary(StringComparer.Ordinal) { ["Runestone_Boars"] = "Boar Runestone", ["Runestone_Greydwarfs"] = "Greydwarf Runestone", ["Runestone_Draugr"] = "Draugr Runestone", ["Runestone_Meadows"] = "Meadows Runestone", ["Runestone_BlackForest"] = "Black Forest Runestone", ["Runestone_Swamps"] = "Swamp Runestone", ["Runestone_Mountains"] = "Mountain Runestone", ["Runestone_Plains"] = "Plains Runestone", ["Runestone_Mistlands"] = "Mistlands Runestone", ["Runestone_Ashlands"] = "Ashlands Runestone", ["Runestone_DeepNorth"] = "Deep North Runestone" }; private static readonly IReadOnlyDictionary SourceLabels = new Dictionary(StringComparer.Ordinal) { ["Spawner_GreydwarfNest"] = "Greydwarf Nest", ["BonePileSpawner"] = "Skeleton Bone Pile", ["BonePileSpawner_swamp"] = "Swamp Skeleton Bone Pile", ["Spawner_DraugrPile"] = "Draugr Pile", ["Spawner_CharredStone"] = "Charred Stone", ["Spawner_CharredStone_Elite"] = "Charred Elite Stone", ["Spawner_CharredStone_event"] = "Charred Event Stone", ["Spawner_CharredCross"] = "Charred Cross", ["BlackIce_Core"] = "Jotun Core", ["Spawner_Hole"] = "Elaking Hole", ["BlobMorkBig"] = "Mork Blob Source", ["Spawner_Hole_double"] = "Elaking Double Hole", ["EvilHeart_Forest"] = "Greydwarf Heart" }; private static readonly HashSet PhysicalSpawnerLabels = new HashSet(SourceLabels.Values, StringComparer.Ordinal); public string Name { get; } public (string Path, string Label, Vector3 Offset)[] Points { get; } public float MaximumOffset { get; } public Vector3 Scale { get; private set; } = Vector3.one; public bool SyncScale { get; private set; } internal static bool PhysicalSpawnerLabel(string label) { return PhysicalSpawnerLabels.Contains(label); } internal static bool PhysicalSpawnerPrefab(string name) { return SourceLabels.ContainsKey(name); } private SharedMapLandmarkPrefab(string name, List<(string Path, string Label, Vector3 Offset)> points) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) Name = name; Points = points.ToArray(); MaximumOffset = ((points.Count == 0) ? 0f : points.Max<(string, string, Vector3)>(((string Path, string Label, Vector3 Offset) p) => Mathf.Sqrt(p.Offset.x * p.Offset.x + p.Offset.z * p.Offset.z))); } internal static Vector3 Offset(Transform root, Transform point) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Unknown result type (might be due to invalid IL or missing references) return Quaternion.Inverse(root.rotation) * (point.position - root.position); } private static string Path(Transform root, Transform point) { List list = new List(); Transform val = point; while ((Object)(object)val != (Object)(object)root) { if ((Object)(object)val == (Object)null) { throw new InvalidOperationException("Source is outside its prefab."); } list.Insert(0, val.GetSiblingIndex().ToString(CultureInfo.InvariantCulture)); val = val.parent; } if (list.Count != 0) { return string.Join("/", list); } return "root"; } private static bool Active(Transform root, Transform point, bool rune) { Transform val = point; while ((Object)(object)val != (Object)null) { if ((Object)(object)val != (Object)(object)root && !((Component)val).gameObject.activeSelf) { return false; } MonoBehaviour[] array = PrefabRegistry.Components((Component)(object)val); foreach (MonoBehaviour val2 in array) { if ((Object)(object)val2 == (Object)null) { return false; } if (((Behaviour)val2).enabled) { if (val2 is RandomSpawn || val2 is RandomObject || val2 is SnapToGround) { return false; } if (rune && !(val2 is RuneStone) && !(val2 is Location) && !(val2 is LodFadeInOut) && !(val2 is StaticPhysics)) { return false; } if (!rune && !(val2 is ZNetView) && !(val2 is SpawnArea) && !(val2 is CreatureSpawner) && !(val2 is Destructible) && !(val2 is StaticPhysics) && !(val2 is LodFadeInOut) && ((object)val2).GetType().Name != "HoverText" && ((object)val2).GetType().Name != "DropOnDestroyed" && ((object)val2).GetType().Name != "TriggerPersistentEventOnDestroy") { return false; } } } if (PrefabRegistry.Components((Component)(object)val).Any((Component c) => (Object)(object)c == (Object)null || ((object)c).GetType().Name == "Animator" || ((object)c).GetType().Name == "Animation")) { return false; } if ((Object)(object)val == (Object)(object)root) { return true; } val = val.parent; } return false; } public static SharedMapLandmarkPrefab? ReadRunestone(GameObject prefab) { //IL_00ce: Unknown result type (might be due to invalid IL or missing references) //IL_00d3: Unknown result type (might be due to invalid IL or missing references) //IL_00d5: Unknown result type (might be due to invalid IL or missing references) //IL_00de: Unknown result type (might be due to invalid IL or missing references) //IL_0113: Unknown result type (might be due to invalid IL or missing references) PrefabRegistry.Current.Observe(prefab); if (!Runestones.TryGetValue(((Object)prefab).name, out string value) || (Object)(object)PrefabRegistry.Component(prefab) == (Object)null) { return null; } List<(string, string, Vector3)> list = new List<(string, string, Vector3)>(); RuneStone[] array = PrefabRegistry.Children(prefab, inactive: true); foreach (RuneStone val in array) { if (((Behaviour)val).enabled && !((Object)(object)PrefabRegistry.Component((Component?)(object)val) != (Object)null) && !((Object)(object)PrefabRegistry.Component((Component?)(object)val) != (Object)null) && !((Object)(object)PrefabRegistry.Component((Component?)(object)val) == (Object)null) && !((Object)(object)PrefabRegistry.Component((Component?)(object)val) == (Object)null) && !((Object)(object)PrefabRegistry.Component((Component?)(object)val) != (Object)null) && Active(prefab.transform, ((Component)val).transform, rune: true)) { Vector3 val2 = Offset(prefab.transform, ((Component)val).transform); if (SharedMapDungeonPrefab.Finite(val2) && !(Math.Abs(val2.y) >= 1000f) && !(((Vector3)(ref val2)).sqrMagnitude > 16384f)) { list.Add((Path(prefab.transform, ((Component)val).transform), value, val2)); } } } if (list.Count != 0 && list.Count <= 16) { return new SharedMapLandmarkPrefab(((Object)prefab).name, list); } return null; } internal static bool Repeating(float interval) { if (SharedMapExploration.Finite(interval)) { return interval > 0f; } return false; } private static bool PhysicalPartActive(Transform root, Transform part) { Transform val = part; while ((Object)(object)val != (Object)null) { if ((Object)(object)val != (Object)(object)root && !((Component)val).gameObject.activeSelf) { return false; } MonoBehaviour[] array = PrefabRegistry.Components((Component)(object)val); foreach (MonoBehaviour val2 in array) { if ((Object)(object)val2 == (Object)null || (((Behaviour)val2).enabled && (val2 is RandomSpawn || val2 is RandomObject || val2 is SnapToGround))) { return false; } } if ((Object)(object)val == (Object)(object)root) { return true; } val = val.parent; } return false; } private static bool OwnedByRoot(Transform root, Transform part, ZNetView view) { Transform val = part; while ((Object)(object)val != (Object)null) { ZNetView val2 = PrefabRegistry.Component((Component?)(object)val); if ((Object)(object)val2 != (Object)null) { return (Object)(object)val2 == (Object)(object)view; } if ((Object)(object)val == (Object)(object)root) { return false; } val = val.parent; } return false; } public static SharedMapLandmarkPrefab? ReadSpawner(GameObject prefab, out string rejection) { //IL_0296: Unknown result type (might be due to invalid IL or missing references) //IL_029b: Unknown result type (might be due to invalid IL or missing references) //IL_02a3: 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_02b8: Unknown result type (might be due to invalid IL or missing references) //IL_02c5: Unknown result type (might be due to invalid IL or missing references) //IL_0317: Unknown result type (might be due to invalid IL or missing references) rejection = "outside_physical_allowlist"; if (!SourceLabels.TryGetValue(((Object)prefab).name, out string label)) { return null; } rejection = "missing_or_invalid_destructible"; Destructible val = PrefabRegistry.Component(prefab); if ((Object)(object)val == (Object)null || !((Behaviour)val).enabled || !SharedMapExploration.Finite(val.m_health) || val.m_health <= 0f) { return null; } ZNetView view = PrefabRegistry.Component(prefab); rejection = "unsupported_root_metadata"; List<(string, string, Vector3)> points; HashSet transforms; if (!((Object)(object)view == (Object)null) && view.m_persistent && !((Object)(object)PrefabRegistry.Component(prefab) != (Object)null) && !((Object)(object)PrefabRegistry.Component(prefab) != (Object)null) && !((Object)(object)PrefabRegistry.Component(prefab) != (Object)null)) { Rigidbody val2 = PrefabRegistry.Component(prefab); if (val2 == null || val2.isKinematic) { bool num = PrefabRegistry.Children(prefab, inactive: true).Any((Collider c) => c.enabled && !c.isTrigger && OwnedByRoot(prefab.transform, ((Component)c).transform, view) && PhysicalPartActive(prefab.transform, ((Component)c).transform)); rejection = "missing_owned_hit_collider"; if (!num) { return null; } points = new List<(string, string, Vector3)>(); transforms = new HashSet(); SpawnArea[] array = PrefabRegistry.Children(prefab, inactive: true); foreach (SpawnArea val3 in array) { if (OwnedByRoot(prefab.transform, ((Component)val3).transform, view) && Repeating(val3.m_spawnIntervalSec) && val3.m_maxNear > 0 && val3.m_maxTotal > 0 && val3.m_prefabs.Count > 0 && val3.m_prefabs.All((SpawnData p) => (Object)(object)p.m_prefab != (Object)null && SharedMapExploration.Finite(p.m_weight) && p.m_weight > 0f)) { Add((Behaviour)(object)val3, val3.m_prefabs.Select((SpawnData p) => p.m_prefab)); } } CreatureSpawner[] array2 = PrefabRegistry.Children(prefab, inactive: true); foreach (CreatureSpawner val4 in array2) { if ((Object)(object)PrefabRegistry.Component((Component?)(object)val4) == (Object)(object)view && Repeating(val4.m_respawnTimeMinuts) && (Object)(object)val4.m_creaturePrefab != (Object)null) { Add((Behaviour)(object)val4, (IEnumerable)(object)new GameObject[1] { val4.m_creaturePrefab }); } } Vector3 localScale = prefab.transform.localScale; rejection = "invalid_scale"; if (!SharedMapDungeonPrefab.Finite(localScale) || localScale.x <= 0f || localScale.y <= 0f || localScale.z <= 0f) { return null; } rejection = "no_supported_recurring_source"; if (points.Count == 0 || points.Count > 64) { return null; } rejection = ""; return new SharedMapLandmarkPrefab(((Object)prefab).name, points) { Scale = localScale, SyncScale = view.m_syncInitialScale }; } } return null; void Add(Behaviour source, IEnumerable creatures) { //IL_009d: Unknown result type (might be due to invalid IL or missing references) //IL_00a2: 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_0105: Unknown result type (might be due to invalid IL or missing references) if (source.enabled && Active(prefab.transform, ((Component)source).transform, rune: false) && transforms.Add(((Component)source).transform)) { GameObject[] array3 = creatures.Where((GameObject c) => (Object)(object)c != (Object)null).ToArray(); if (array3.Length != 0 && !array3.Any((GameObject c) => (Object)(object)PrefabRegistry.Component(c) == (Object)null && (Object)(object)PrefabRegistry.Component(c) == (Object)null)) { Vector3 val5 = Offset(prefab.transform, ((Component)source).transform); if (!label.Contains("$") && Encoding.UTF8.GetByteCount(label) <= 128 && SharedMapDungeonPrefab.Finite(val5) && !(((Vector3)(ref val5)).sqrMagnitude > 16384f)) { points.Add((Path(prefab.transform, ((Component)source).transform), label, val5)); } } } } } } internal sealed class SharedMapLandmarks : IDisposable { private readonly ZDOMan _world; private CandidateSubscription? _index; private readonly SharedMapLandmarkStore? _runestones; private readonly SharedMapLandmarkStore? _spawners; private readonly SharedMapExploration _map; private readonly SharedMapSettings _settings; private readonly SharedMapDiagnostics _diagnostics; private readonly Action _fail; private readonly PrefabCatalog _runes = PrefabRegistry.Current.Catalog("SharedMapRunes"); private readonly PrefabCatalog _sources = PrefabRegistry.Current.Catalog("SharedMapSources"); private readonly List _near = new List(); private readonly List _scan = new List(); private readonly Queue<(ZDOID Id, Vector3? Player)> _pending = new Queue<(ZDOID, Vector3?)>(); private readonly HashSet _queued = new HashSet(); private readonly Dictionary _bindings = new Dictionary(StringComparer.Ordinal); private readonly HashSet _ambiguous = new HashSet(StringComparer.Ordinal); private readonly Dictionary _sampleCursors = new Dictionary(); private readonly List _scanNames = new List(); private readonly HashSet _inspectedLocations = new HashSet(StringComparer.Ordinal); private readonly HashSet _inspectedSources = new HashSet(); private readonly Dictionary _spawnerRejections = new Dictionary(StringComparer.Ordinal); private int _spawnerCandidates; private readonly List _unavailable = new List(); private readonly string _proxyName; private readonly int _proxyHash; private int _locationCursor; private int _prefabCursor; private int _scanName; private int _sector; private int _scanCursor; private int _addedRunes; private int _addedSpawners; private int _retired; private bool _metadataReady; private bool _chunkComplete; private bool _disposed; private float _maximumOffset; private readonly ScheduleToken _nextScan = new ScheduleToken(); private readonly Dictionary _pointCache = new Dictionary(); private readonly List<(MapMarker Marker, bool Spawner)> _pointScratch = new List<(MapMarker, bool)>(); public SharedMapLandmarks(ZDOMan world, SharedMapLandmarkStore? runestones, SharedMapLandmarkStore? spawners, SharedMapExploration map, SharedMapSettings settings, SharedMapDiagnostics diagnostics, Action fail) { _world = world; _runestones = runestones; _spawners = spawners; _map = map; _settings = settings; _diagnostics = diagnostics; _fail = fail; GameObject locationProxyPrefab = ZoneSystem.instance.m_locationProxyPrefab; if (!((Object)(object)locationProxyPrefab == (Object)null) && !((Object)(object)PrefabRegistry.Component(locationProxyPrefab) == (Object)null)) { ZNetView? obj = PrefabRegistry.Component(locationProxyPrefab); if (obj != null && obj.m_persistent) { _proxyName = ((Object)locationProxyPrefab).name; _proxyHash = StringExtensionMethods.GetStableHashCode(_proxyName); return; } } throw new InvalidOperationException("Native persistent location-proxy metadata is unavailable."); } public static void CheckCompatibility() { if (typeof(ZDOMan).GetField("m_onZDODestroyed")?.FieldType != typeof(Action) || typeof(CreatureSpawner).GetField("m_respawnTimeMinuts")?.FieldType != typeof(float) || typeof(SpawnArea).GetField("m_spawnIntervalSec")?.FieldType != typeof(float)) { throw new MissingMemberException("Native landmark source APIs are unavailable."); } } public void Install() { if (_spawners != null) { ZDOMan world = _world; world.m_onZDODestroyed = (Action)Delegate.Combine(world.m_onZDODestroyed, new Action(Destroyed)); } } private void InspectOne() { //IL_0084: Unknown result type (might be due to invalid IL or missing references) //IL_0089: Unknown result type (might be due to invalid IL or missing references) //IL_008c: Unknown result type (might be due to invalid IL or missing references) if (_runestones != null && _locationCursor < ZoneSystem.instance.m_locations.Count) { ZoneLocation val = ZoneSystem.instance.m_locations[_locationCursor++]; if (!val.m_prefab.IsValid || !SharedMapLandmarkPrefab.Runestones.ContainsKey(val.m_prefab.Name) || !_inspectedLocations.Add(val.m_prefab.Name)) { return; } SoftReference prefab = val.m_prefab; try { prefab.Load(); SharedMapLandmarkPrefab sharedMapLandmarkPrefab = (((Object)(object)prefab.Asset == (Object)null) ? null : SharedMapLandmarkPrefab.ReadRunestone(prefab.Asset)); if (sharedMapLandmarkPrefab == null) { _unavailable.Add(prefab.Name); return; } _runes.Add(StringExtensionMethods.GetStableHashCode(sharedMapLandmarkPrefab.Name), sharedMapLandmarkPrefab); _maximumOffset = Math.Max(_maximumOffset, sharedMapLandmarkPrefab.MaximumOffset); return; } finally { prefab.Release(); } } if (_spawners != null && _prefabCursor < ZNetScene.instance.m_prefabs.Count) { GameObject val2 = ZNetScene.instance.m_prefabs[_prefabCursor++]; if ((Object)(object)val2 != (Object)null) { InspectSpawner(val2); } return; } if (_runestones != null) { _unavailable.AddRange(SharedMapLandmarkPrefab.Runestones.Keys.Where((string n) => !_inspectedLocations.Contains(n))); } if (_runes.Count > 0) { _scanNames.Add(_proxyName); } _scanNames.AddRange(_sources.Values.Select((SharedMapLandmarkPrefab p) => p.Name).OrderBy((string n) => n, StringComparer.Ordinal)); _metadataReady = true; _diagnostics.LandmarkCatalog(_runes.Count, _sources.Count, _unavailable, _runestones != null, _spawners != null, _spawnerCandidates, string.Join(",", from p in _spawnerRejections.OrderBy, string>((KeyValuePair p) => p.Key, StringComparer.Ordinal) select p.Key + ":" + p.Value)); _unavailable.Clear(); _spawnerRejections.Clear(); } private void InspectSpawner(GameObject prefab) { int stableHashCode = StringExtensionMethods.GetStableHashCode(((Object)prefab).name); if (_inspectedSources.Add(stableHashCode) && SharedMapLandmarkPrefab.PhysicalSpawnerPrefab(((Object)prefab).name)) { _spawnerCandidates++; string rejection; SharedMapLandmarkPrefab sharedMapLandmarkPrefab = SharedMapLandmarkPrefab.ReadSpawner(prefab, out rejection); if (sharedMapLandmarkPrefab == null) { _spawnerRejections.TryGetValue(rejection, out var value); _spawnerRejections[rejection] = value + 1; } else { _sources.Add(stableHashCode, sharedMapLandmarkPrefab); _maximumOffset = Math.Max(_maximumOffset, sharedMapLandmarkPrefab.MaximumOffset * (float)((!sharedMapLandmarkPrefab.SyncScale) ? 1 : 4)); } } } public void Sample(long peer, Vector3 player) { //IL_008d: Unknown result type (might be due to invalid IL or missing references) //IL_00eb: Unknown result type (might be due to invalid IL or missing references) if (!_metadataReady) { return; } float zoneSize = ZoneSystem.instance.m_zoneSize; if (!SharedMapExploration.Finite(zoneSize) || zoneSize < 16f) { throw new InvalidOperationException("Unsupported landmark sector geometry."); } int num = (int)Math.Ceiling((_map.Radius + _maximumOffset) / zoneSize) + 1; if (num > 16) { throw new InvalidOperationException("Landmark sector extent exceeds supported bounds."); } if (_index == null) { _index = WorldObjectProvider.Current.Subscribe("SharedMap", (ZDO z) => z.GetPrefab() == _proxyHash || _sources.ContainsKey(z.GetPrefab())); } _index.Read(player, num, _near, classic: true); if (_near.Count > 65536) { throw new InvalidOperationException("Landmark nearby candidate limit exceeded."); } _sampleCursors.TryGetValue(peer, out var value); for (int num2 = 0; num2 < Math.Min(256, _near.Count); num2++) { value %= _near.Count; Enqueue(_near[value++], player); } _sampleCursors[peer] = value; } private void Enqueue(ZDO zdo, Vector3? player) { //IL_0052: 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) if (zdo.IsValid() && zdo.Persistent && ((zdo.GetPrefab() == _proxyHash && _runes.ContainsKey(zdo.GetInt(ZDOVars.s_location, 0))) || _sources.ContainsKey(zdo.GetPrefab())) && _queued.Add(zdo.m_uid)) { if (_pending.Count >= 65536) { throw new InvalidOperationException("Landmark encounter queue limit exceeded."); } _pending.Enqueue((zdo.m_uid, player)); } } private (MapMarker Marker, bool Spawner)[] Points(ZDO zdo) { //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_0044: Unknown result type (might be due to invalid IL or missing references) //IL_0051: Unknown result type (might be due to invalid IL or missing references) //IL_005e: Unknown result type (might be due to invalid IL or missing references) //IL_006b: 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_007e: Unknown result type (might be due to invalid IL or missing references) //IL_0086: Unknown result type (might be due to invalid IL or missing references) //IL_008c: Unknown result type (might be due to invalid IL or missing references) //IL_0094: Unknown result type (might be due to invalid IL or missing references) //IL_009a: 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_0108: 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_0223: Unknown result type (might be due to invalid IL or missing references) //IL_0224: Unknown result type (might be due to invalid IL or missing references) //IL_0232: Unknown result type (might be due to invalid IL or missing references) //IL_0121: 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) //IL_012b: Unknown result type (might be due to invalid IL or missing references) //IL_012d: 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_0179: Unknown result type (might be due to invalid IL or missing references) //IL_0181: Unknown result type (might be due to invalid IL or missing references) //IL_018c: Unknown result type (might be due to invalid IL or missing references) //IL_0194: Unknown result type (might be due to invalid IL or missing references) //IL_019f: Unknown result type (might be due to invalid IL or missing references) //IL_01a7: Unknown result type (might be due to invalid IL or missing references) //IL_01b7: Unknown result type (might be due to invalid IL or missing references) //IL_0142: 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_0282: Unknown result type (might be due to invalid IL or missing references) //IL_0283: Unknown result type (might be due to invalid IL or missing references) //IL_0286: Unknown result type (might be due to invalid IL or missing references) //IL_028b: Unknown result type (might be due to invalid IL or missing references) //IL_028d: Unknown result type (might be due to invalid IL or missing references) //IL_0292: Unknown result type (might be due to invalid IL or missing references) //IL_0297: Unknown result type (might be due to invalid IL or missing references) //IL_029c: 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_01c0: Unknown result type (might be due to invalid IL or missing references) //IL_0170: Unknown result type (might be due to invalid IL or missing references) //IL_0168: Unknown result type (might be due to invalid IL or missing references) //IL_02a7: Unknown result type (might be due to invalid IL or missing references) //IL_0366: Unknown result type (might be due to invalid IL or missing references) //IL_0331: Unknown result type (might be due to invalid IL or missing references) //IL_01ce: Unknown result type (might be due to invalid IL or missing references) //IL_0175: Unknown result type (might be due to invalid IL or missing references) //IL_02b6: Unknown result type (might be due to invalid IL or missing references) //IL_02bc: Unknown result type (might be due to invalid IL or missing references) //IL_02c2: Unknown result type (might be due to invalid IL or missing references) //IL_02e0: Unknown result type (might be due to invalid IL or missing references) //IL_02e7: Unknown result type (might be due to invalid IL or missing references) //IL_02ee: Unknown result type (might be due to invalid IL or missing references) //IL_01dc: Unknown result type (might be due to invalid IL or missing references) //IL_01ea: Unknown result type (might be due to invalid IL or missing references) //IL_01f8: Unknown result type (might be due to invalid IL or missing references) //IL_0206: Unknown result type (might be due to invalid IL or missing references) if (!zdo.IsValid() || !zdo.Persistent) { return Array.Empty<(MapMarker, bool)>(); } Vector3 position = zdo.GetPosition(); Quaternion rotation = zdo.GetRotation(); if (!SharedMapDungeonPrefab.Finite(position) || Character.InInterior(position) || !SharedMapExploration.Finite(rotation.x) || !SharedMapExploration.Finite(rotation.y) || !SharedMapExploration.Finite(rotation.z) || !SharedMapExploration.Finite(rotation.w) || Math.Abs(rotation.x * rotation.x + rotation.y * rotation.y + rotation.z * rotation.z + rotation.w * rotation.w - 1f) > 0.01f) { return Array.Empty<(MapMarker, bool)>(); } bool flag = zdo.GetPrefab() != _proxyHash; if (!(flag ? _sources : _runes).TryGetValue(flag ? zdo.GetPrefab() : zdo.GetInt(ZDOVars.s_location, 0), out SharedMapLandmarkPrefab value)) { return Array.Empty<(MapMarker, bool)>(); } Vector3 one = Vector3.one; if (flag && value.SyncScale) { Vector3 val = zdo.GetVec3(ZDOVars.s_scaleHash, Vector3.zero); if (val == Vector3.zero) { float num = zdo.GetFloat(ZDOVars.s_scaleScalarHash, value.Scale.x); val = (Vector3)((num == value.Scale.x) ? value.Scale : new Vector3(num, num, num)); } ((Vector3)(ref one))..ctor(val.x / value.Scale.x, val.y / value.Scale.y, val.z / value.Scale.z); if (!SharedMapDungeonPrefab.Finite(one) || one.x <= 0f || one.y <= 0f || one.z <= 0f || one.x > 4f || one.y > 4f || one.z > 4f) { return Array.Empty<(MapMarker, bool)>(); } } (string, Vector3, Quaternion, Vector3) tuple = (value.Name, position, rotation, one); if (_pointCache.TryGetValue(zdo.m_uid, out ((string, Vector3, Quaternion, Vector3), (MapMarker, bool)[]) value2) && value2.Item1.Equals(tuple)) { return value2.Item2; } List<(MapMarker, bool)> pointScratch = _pointScratch; pointScratch.Clear(); (string, string, Vector3)[] points = value.Points; for (int i = 0; i < points.Length; i++) { (string, string, Vector3) tuple2 = points[i]; Vector3 val2 = position + rotation * Vector3.Scale(tuple2.Item3, one); if (SharedMapDungeonPrefab.Finite(val2) && !Character.InInterior(val2)) { string identity = SharedMapLandmarkStore.SourceIdentity(value.Name, position.x, position.y, position.z, tuple2.Item1, flag); pointScratch.Add((new MapMarker(tuple2.Item2, val2.x, val2.y, val2.z, identity), flag)); } } if (_pointCache.Count >= 65536 && !_pointCache.ContainsKey(zdo.m_uid)) { throw new InvalidOperationException("Landmark placed-source cache limit exceeded."); } (MapMarker, bool)[] array = new(MapMarker, bool)[pointScratch.Count]; pointScratch.CopyTo(array); _pointCache[zdo.m_uid] = (tuple, array); return array; } private bool Bind(string identity, ZDO zdo) { //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_00a7: 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_0051: Unknown result type (might be due to invalid IL or missing references) if (_ambiguous.Contains(identity)) { return false; } if (_bindings.TryGetValue(identity, out var value) && value != zdo.m_uid && _world.GetZDO(value) != null) { _ambiguous.Add(identity); _diagnostics.LandmarkEvidence(identity, zdo.GetPosition(), "ambiguous_persistent_source"); return false; } if (_bindings.Count >= 65536 && !_bindings.ContainsKey(identity)) { throw new InvalidOperationException("Landmark source binding limit exceeded."); } _bindings[identity] = zdo.m_uid; return true; } public void Tick(float now) { //IL_01a4: Unknown result type (might be due to invalid IL or missing references) //IL_01b7: Unknown result type (might be due to invalid IL or missing references) //IL_0247: Unknown result type (might be due to invalid IL or missing references) //IL_0272: Unknown result type (might be due to invalid IL or missing references) //IL_0308: Unknown result type (might be due to invalid IL or missing references) if (!_metadataReady) { InspectOne(); return; } if (_scanNames.Count > 0 && _nextScan.Ready(now) && _pending.Count < 32768) { if (_scanCursor == _scan.Count) { if (_chunkComplete) { _chunkComplete = false; _sector = 0; _scanName++; if (_scanName >= _scanNames.Count) { _scanName = 0; _nextScan.Postpone(now, _settings.TableIntervalSeconds.Value); } } if (_nextScan.Ready(now)) { _scan.Clear(); _scanCursor = 0; _chunkComplete = _world.GetAllZDOsWithPrefabIterative(_scanNames[_scanName], _scan, ref _sector); if (_scan.Count > 65536) { throw new InvalidOperationException("Landmark retrospective candidate limit exceeded."); } } } for (int i = 0; i < 256; i++) { if (_scanCursor >= _scan.Count) { break; } if (_pending.Count >= 32768) { break; } Enqueue(_scan[_scanCursor++], null); } } int num = 256; int num2 = 0; while (num >= 64 && num2++ < 256 && _pending.Count > 0) { (ZDOID, Vector3?) tuple = _pending.Dequeue(); _queued.Remove(tuple.Item1); ZDO zDO = _world.GetZDO(tuple.Item1); if (zDO == null) { continue; } (MapMarker, bool)[] array = Points(zDO); for (int j = 0; j < array.Length; j++) { (MapMarker, bool) tuple2 = array[j]; num--; SharedMapLandmarkStore sharedMapLandmarkStore = (tuple2.Item2 ? _spawners : _runestones); if (sharedMapLandmarkStore != null && Bind(tuple2.Item1.Identity, zDO) && sharedMapLandmarkStore.Discover(tuple2.Item1, tuple.Item2?.x, tuple.Item2?.z, _map.Radius, _map, !tuple.Item2.HasValue)) { if (tuple2.Item2) { _addedSpawners++; } else { _addedRunes++; } _diagnostics.LandmarkEvidence(tuple2.Item1.Identity, new Vector3(tuple2.Item1.X, tuple2.Item1.Y, tuple2.Item1.Z), tuple.Item2.HasValue ? "observed_source_proximity" : "community_explored_source_point", tuple.Item2, _map.Radius); } } } } private void Destroyed(ZDO zdo) { //IL_00f9: Unknown result type (might be due to invalid IL or missing references) if (_disposed || _spawners == null || _spawners.Count == 0) { return; } try { if (!_metadataReady && _spawners.Count > 0 && !_inspectedSources.Contains(zdo.GetPrefab())) { GameObject val = PrefabRegistry.Current.Prefab(zdo.GetPrefab()); if ((Object)(object)val != (Object)null) { InspectSpawner(val); } } bool flag = false; (MapMarker, bool)[] array = Points(zdo); for (int i = 0; i < array.Length; i++) { (MapMarker, bool) tuple = array[i]; if (tuple.Item2 && _spawners.Contains(tuple.Item1.Identity) && Bind(tuple.Item1.Identity, zdo) && _spawners.Retire(tuple.Item1.Identity)) { flag = true; _retired++; _diagnostics.LandmarkEvidence(tuple.Item1.Identity, zdo.GetPosition(), "accepted_terminal_zdo_destruction"); } } if (flag) { _spawners.Save(); } } catch (Exception obj) { _fail(obj); } } public IReadOnlyList Runestones() { return _runestones?.Read(_settings.RunestoneMarkerSync.Value) ?? Array.Empty(); } public IReadOnlyList Spawners() { return _spawners?.Read(_settings.SpawnerMarkerSync.Value) ?? Array.Empty(); } public void Report() { _diagnostics.LandmarkResults(_addedRunes, _addedSpawners, _retired); _addedRunes = (_addedSpawners = (_retired = 0)); } public void Dispose() { _disposed = true; ZDOMan world = _world; world.m_onZDODestroyed = (Action)Delegate.Remove(world.m_onZDODestroyed, new Action(Destroyed)); _index?.Dispose(); _index = null; _pointCache.Clear(); _pointScratch.Clear(); _pending.Clear(); _queued.Clear(); _near.Clear(); _scan.Clear(); _runes.Clear(); _sources.Clear(); _bindings.Clear(); _ambiguous.Clear(); _sampleCursors.Clear(); _scanNames.Clear(); _inspectedLocations.Clear(); _unavailable.Clear(); _inspectedSources.Clear(); _addedRunes = (_addedSpawners = (_retired = 0)); } } public sealed class SharedMapLandmarkStore { public const int MaximumDiscoveries = 65536; public const int MaximumMarkers = 4096; private const uint Magic = 1280133960u; private readonly long _world; private readonly bool _spawners; private Dictionary _records = new Dictionary(StringComparer.Ordinal); private HashSet _retired = new HashSet(StringComparer.Ordinal); private bool _dirty; private readonly ScheduleToken _nextSave = new ScheduleToken(); private IReadOnlyList? _activeMarkers; private IReadOnlyList? _historicalMarkers; public string FilePath { get; } public int Count => _records.Count; public SharedMapLandmarkStore(string directory, long world, bool spawners) { _world = world; _spawners = spawners; FilePath = Path.Combine(directory, "world-" + world.ToString("X16", CultureInfo.InvariantCulture) + (spawners ? ".spawners" : ".runestones")); } public bool Contains(string identity) { return _records.ContainsKey(identity); } public static string SourceIdentity(string prefab, float x, float y, float z, string path, bool spawner) { if (!SharedMapExploration.Finite(y)) { throw new ArgumentException("Invalid source height."); } return SharedMapDungeonIdentity.Create(prefab, x, spawner ? 0f : y, z, path); } public bool Retired(string identity) { return _retired.Contains(identity); } private static bool Valid(MapMarker marker) { if (SharedMapPinRemovals.ValidId(marker.Identity) && marker.Name.Length > 0 && Encoding.UTF8.GetByteCount(marker.Name) <= 128 && !marker.Name.Contains("$") && SharedMapExploration.Finite(marker.X) && SharedMapExploration.Finite(marker.Y) && SharedMapExploration.Finite(marker.Z) && Math.Abs(marker.X) <= 100000f && Math.Abs(marker.Z) <= 100000f) { return Math.Abs(marker.Y) < 4000f; } return false; } public bool Discover(MapMarker marker, float? playerX, float? playerZ, float radius, SharedMapExploration map, bool retrospective) { if (!Valid(marker)) { throw new InvalidDataException("Invalid landmark discovery."); } if ((!playerX.HasValue || !playerZ.HasValue || !SharedMapExploration.Finite(playerX.Value) || !SharedMapExploration.Finite(playerZ.Value) || !SharedMapExploration.Finite(radius) || !(radius > 0f) || !(Math.Pow((double)marker.X - (double)playerX.Value, 2.0) + Math.Pow((double)marker.Z - (double)playerZ.Value, 2.0) <= (double)radius * (double)radius)) && (!retrospective || !map.IsExplored(marker.X, marker.Z))) { return false; } if (_records.TryGetValue(marker.Identity, out MapMarker value)) { if (value.X != marker.X || (!_spawners && value.Y != marker.Y) || value.Z != marker.Z || value.Name != marker.Name) { throw new InvalidDataException("Conflicting landmark source identity."); } return false; } if (Count >= 65536) { throw new InvalidOperationException("Landmark discovery limit exceeded; prior data was retained."); } _records.Add(marker.Identity, marker); _dirty = true; _activeMarkers = (_historicalMarkers = null); return true; } public bool Retire(string identity) { if (!_spawners || !_records.ContainsKey(identity) || !_retired.Add(identity)) { return false; } _dirty = true; _activeMarkers = null; return true; } public IReadOnlyList Read(bool enabled, bool removeDestroyed = true) { if (!enabled) { return Array.Empty(); } IReadOnlyList readOnlyList = (removeDestroyed ? _activeMarkers : _historicalMarkers); if (readOnlyList != null) { return readOnlyList; } MapMarker[] array = (from p in _records.Where>((KeyValuePair p) => (!_spawners || SharedMapLandmarkPrefab.PhysicalSpawnerLabel(p.Value.Name)) && (!removeDestroyed || !_retired.Contains(p.Key))).OrderBy, string>((KeyValuePair p) => p.Key, StringComparer.Ordinal) select p.Value).ToArray(); if (array.Length > 4096) { throw new InvalidOperationException("Landmark publication limit exceeded; prior table data must be retained."); } if (removeDestroyed) { _activeMarkers = array; } else { _historicalMarkers = array; } return array; } public bool Load() { if (!File.Exists(FilePath)) { if (File.Exists(FilePath + ".bak")) { throw new InvalidDataException("Landmark store is missing beside its backup."); } return false; } using FileStream fileStream = new FileStream(FilePath, FileMode.Open, FileAccess.Read, FileShare.Read); if (fileStream.Length < 53 || fileStream.Length > 11468853) { throw new InvalidDataException("Invalid landmark store length."); } using BinaryReader binaryReader = new BinaryReader(fileStream); byte[] buffer = binaryReader.ReadBytes((int)fileStream.Length - 32); using SHA256 sHA = SHA256.Create(); if (!((ReadOnlySpan)sHA.ComputeHash(buffer)).SequenceEqual((ReadOnlySpan)binaryReader.ReadBytes(32))) { throw new InvalidDataException("Landmark checksum mismatch."); } using BinaryReader binaryReader2 = new BinaryReader(new MemoryStream(buffer, writable: false), new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true)); if (binaryReader2.ReadUInt32() != 1280133960 || binaryReader2.ReadInt32() != 1 || binaryReader2.ReadInt64() != _world || (uint)binaryReader2.ReadByte() != (_spawners ? 1u : 0u)) { throw new InvalidDataException("Landmark schema, world or source kind mismatch."); } int num = binaryReader2.ReadInt32(); if (num < 0 || num > 65536) { throw new InvalidDataException("Invalid landmark record count."); } Dictionary dictionary = new Dictionary(StringComparer.Ordinal); HashSet hashSet = new HashSet(StringComparer.Ordinal); for (int i = 0; i < num; i++) { byte[] array = binaryReader2.ReadBytes(32); if (array.Length != 32) { throw new EndOfStreamException(); } int num2 = binaryReader2.ReadUInt16(); if (num2 < 1 || num2 > 128) { throw new InvalidDataException("Invalid landmark label length."); } byte[] array2 = binaryReader2.ReadBytes(num2); if (array2.Length != num2) { throw new EndOfStreamException(); } MapMarker mapMarker = new MapMarker(new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true).GetString(array2), binaryReader2.ReadSingle(), binaryReader2.ReadSingle(), binaryReader2.ReadSingle(), BitConverter.ToString(array).Replace("-", "").ToLowerInvariant()); byte b = binaryReader2.ReadByte(); if (!Valid(mapMarker) || b > 1 || (!_spawners && b != 0) || dictionary.ContainsKey(mapMarker.Identity)) { throw new InvalidDataException("Invalid landmark record."); } dictionary.Add(mapMarker.Identity, mapMarker); if (b == 1) { hashSet.Add(mapMarker.Identity); } } if (binaryReader2.BaseStream.Position != binaryReader2.BaseStream.Length) { throw new InvalidDataException("Trailing landmark data."); } _records = dictionary; _retired = hashSet; _dirty = false; _activeMarkers = (_historicalMarkers = null); return true; } public bool SaveIfDue(float now, float interval) { if (!_nextSave.Ready(now)) { return false; } _nextSave.Postpone(now, interval); return Save(); } public bool Save() { if (!_dirty) { return false; } using MemoryStream memoryStream = new MemoryStream(); using (BinaryWriter binaryWriter = new BinaryWriter(memoryStream, Encoding.UTF8, leaveOpen: true)) { binaryWriter.Write(1280133960u); binaryWriter.Write(1); binaryWriter.Write(_world); binaryWriter.Write(_spawners ? ((byte)1) : ((byte)0)); binaryWriter.Write(Count); foreach (MapMarker item in from p in _records.OrderBy, string>((KeyValuePair p) => p.Key, StringComparer.Ordinal) select p.Value) { for (int num = 0; num < 64; num += 2) { binaryWriter.Write(byte.Parse(item.Identity.Substring(num, 2), NumberStyles.HexNumber, CultureInfo.InvariantCulture)); } byte[] bytes = Encoding.UTF8.GetBytes(item.Name); binaryWriter.Write((ushort)bytes.Length); binaryWriter.Write(bytes); binaryWriter.Write(item.X); binaryWriter.Write(item.Y); binaryWriter.Write(item.Z); binaryWriter.Write(Retired(item.Identity) ? ((byte)1) : ((byte)0)); } } Directory.CreateDirectory(Path.GetDirectoryName(FilePath)); string text = FilePath + "." + Guid.NewGuid().ToString("N") + ".tmp"; try { byte[] array = memoryStream.ToArray(); using SHA256 sHA = SHA256.Create(); using (FileStream fileStream = new FileStream(text, FileMode.CreateNew, FileAccess.Write, FileShare.None)) { fileStream.Write(array, 0, array.Length); byte[] array2 = sHA.ComputeHash(array); fileStream.Write(array2, 0, array2.Length); fileStream.Flush(flushToDisk: true); } if (File.Exists(FilePath)) { File.Replace(text, FilePath, FilePath + ".bak"); } else { File.Move(text, FilePath); } _dirty = false; return true; } finally { if (File.Exists(text)) { File.Delete(text); } } } } public static class SharedMapLogTopics { public static readonly LogTopic Exploration = new LogTopic("exploration"); public static readonly LogTopic Portals = new LogTopic("portals"); public static readonly LogTopic Resources = new LogTopic("resources"); public static readonly LogTopic Dungeons = new LogTopic("dungeons"); public static readonly LogTopic Landmarks = new LogTopic("landmarks"); public static readonly LogTopic Tables = new LogTopic("tables"); public static readonly LogTopic Save = new LogTopic("save"); } public static class SharedMapMarkerClusters { public static IReadOnlyList> Group(IEnumerable ordered, float distance, Func x, Func z, Func sameKind) { if (!SharedMapExploration.Finite(distance) || distance < 0f || distance > 100f) { throw new ArgumentOutOfRangeException("distance"); } List> list = new List>(); Dictionary<(long, long), List> dictionary = new Dictionary<(long, long), List>(); foreach (T item in ordered) { List list2 = null; double num = (double)distance * (double)distance; int num2 = int.MaxValue; long num3 = ((distance > 0f) ? ((long)Math.Max(-1000000000000.0, Math.Min(1000000000000.0, Math.Floor((double)x(item) / (double)Math.Max(distance, 1f))))) : 0); long num4 = ((distance > 0f) ? ((long)Math.Max(-1000000000000.0, Math.Min(1000000000000.0, Math.Floor((double)z(item) / (double)Math.Max(distance, 1f))))) : 0); if (distance > 0f) { for (long num5 = num3 - 1; num5 <= num3 + 1; num5++) { for (long num6 = num4 - 1; num6 <= num4 + 1; num6++) { if (!dictionary.TryGetValue((num5, num6), out var value)) { continue; } foreach (int item2 in value) { List list3 = list[item2]; if (sameKind(item, list3[0])) { double num7 = (double)x(item) - (double)x(list3[0]); double num8 = (double)z(item) - (double)z(list3[0]); double num9 = num7 * num7 + num8 * num8; if (!(num9 > num) && (num9 != num || item2 < num2)) { list2 = list3; num = num9; num2 = item2; } } } } } } if (list2 == null) { if (!dictionary.TryGetValue((num3, num4), out var value2)) { dictionary.Add((num3, num4), value2 = new List()); } value2.Add(list.Count); list.Add(new List { item }); } else { list2.Add(item); } } return list; } } public sealed class SharedMapMarkerRefresh { private readonly uint _magic; private static readonly (float X, float Z)[] Slots = new(float, float)[9] { (0f, 0f), (2f, 0f), (2f, 2f), (0f, 2f), (-2f, 2f), (-2f, 0f), (-2f, -2f), (0f, -2f), (2f, -2f) }; private readonly long _world; private readonly Action? _published; private readonly Action? _removed; private Dictionary _states = new Dictionary(StringComparer.Ordinal); private long _revision; private long _savedRevision; private readonly ScheduleToken _nextSave = new ScheduleToken(); public string FilePath { get; } public int Count => _states.Count; public long Revision => _revision; public SharedMapMarkerRefresh(string directory, long world, Action? published = null, Action? removed = null, bool resourcePins = false) { _world = world; _published = published; _removed = removed; _magic = (resourcePins ? 1381124936u : 1380993864u); FilePath = Path.Combine(directory, "world-" + world.ToString("X16", CultureInfo.InvariantCulture) + (resourcePins ? ".resource-pins" : ".portal-pins")); } public IReadOnlyList Apply(IReadOnlyList markers) { if (markers.Count > 4096) { throw new InvalidDataException("Too many marker publications."); } Dictionary dictionary = new Dictionary(StringComparer.Ordinal); List list = new List(); bool flag = _states.Count != markers.Count; HashSet migrated = new HashSet(StringComparer.Ordinal); foreach (MapMarker marker in markers) { if (string.IsNullOrEmpty(marker.Identity) || Encoding.UTF8.GetByteCount(marker.Identity) > 256 || Encoding.UTF8.GetByteCount(marker.Name) > 4096 || !SharedMapExploration.Finite(marker.X) || !SharedMapExploration.Finite(marker.Y) || !SharedMapExploration.Finite(marker.Z) || dictionary.ContainsKey(marker.Identity)) { throw new InvalidDataException("Invalid marker publication identity, label or position."); } _states.TryGetValue(marker.Identity, out MarkerPublicationState value); if (value == null && _magic == 1380993864 && marker.Identity.StartsWith("portal:", StringComparison.Ordinal)) { KeyValuePair[] array = _states.Where>((KeyValuePair p) => !migrated.Contains(p.Key) && LegacyPortalKey(p.Key) && DistanceSquared(marker.X, marker.Z, p.Value.X - Slots[p.Value.Slot].X, p.Value.Z - Slots[p.Value.Slot].Z) <= 0.25).Take(2).ToArray(); if (array.Length == 1) { value = array[0].Value; migrated.Add(array[0].Key); flag = true; } } int num = value?.Slot ?? 0; if (value != null && value.Name != marker.Name) { for (int num2 = 0; num2 < Slots.Length; num2++) { num = (num + 1) % Slots.Length; double num3 = marker.X + Slots[num].X - value.X; double num4 = marker.Z + Slots[num].Z - value.Z; if (num3 * num3 + num4 * num4 > 1.21) { break; } if (num2 == Slots.Length - 1) { throw new InvalidDataException("No separated marker publication position available."); } } } float num5 = marker.X + Slots[num].X; float num6 = marker.Z + Slots[num].Z; if (!SharedMapExploration.Finite(num5) || !SharedMapExploration.Finite(num6)) { throw new InvalidDataException("Invalid published marker position."); } dictionary.Add(marker.Identity, new MarkerPublicationState(marker.Name, num, num5, num6)); list.Add(new MapMarker(marker.Name, num5, marker.Y, num6, marker.Identity)); flag |= value == null || value.Name != marker.Name || value.Slot != num || value.X != num5 || value.Z != num6; } if (!flag) { return list; } Dictionary states = _states; _states = dictionary; _revision++; if (_removed != null) { foreach (KeyValuePair item in states) { if (!dictionary.ContainsKey(item.Key)) { _removed(item.Key, item.Value.Name); } } } if (_published != null) { for (int num7 = 0; num7 < markers.Count; num7++) { MapMarker mapMarker = markers[num7]; MapMarker mapMarker2 = list[num7]; states.TryGetValue(mapMarker.Identity, out var value2); if (value2 == null || !(value2.Name == mapMarker.Name) || value2.X != mapMarker2.X || value2.Z != mapMarker2.Z) { _published((value2 == null) ? null : new MapMarker(value2.Name, value2.X, mapMarker.Y, value2.Z, mapMarker.Identity), mapMarker, mapMarker2, dictionary[mapMarker.Identity].Slot); } } } return list; } private static double DistanceSquared(float x, float z, float otherX, float otherZ) { double num = (double)x - (double)otherX; double num2 = (double)z - (double)otherZ; return num * num + num2 * num2; } private static bool LegacyPortalKey(string key) { int num = key.IndexOf(':'); uint result2; if (num > 0 && long.TryParse(key.Substring(0, num), NumberStyles.Integer, CultureInfo.InvariantCulture, out var _)) { return uint.TryParse(key.Substring(num + 1), NumberStyles.Integer, CultureInfo.InvariantCulture, out result2); } return false; } public bool AvoidObsoletePin(string name, float x, float z) { bool result = false; string[] array = _states.Keys.ToArray(); foreach (string text in array) { MarkerPublicationState markerPublicationState = _states[text]; double num = (double)markerPublicationState.X - (double)x; double num2 = (double)markerPublicationState.Z - (double)z; if (!string.Equals(markerPublicationState.Name, name, StringComparison.OrdinalIgnoreCase) || num * num + num2 * num2 >= 1.0) { continue; } float num3 = markerPublicationState.X - Slots[markerPublicationState.Slot].X; float num4 = markerPublicationState.Z - Slots[markerPublicationState.Slot].Z; for (int j = 1; j < Slots.Length; j++) { int num5 = (markerPublicationState.Slot + j) % Slots.Length; float num6 = num3 + Slots[num5].X; float num7 = num4 + Slots[num5].Z; num = (double)num6 - (double)x; num2 = (double)num7 - (double)z; if (!(num * num + num2 * num2 <= 1.21) && !(num * num + num2 * num2 > 9.0)) { _states[text] = new MarkerPublicationState(markerPublicationState.Name, num5, num6, num7); _revision++; result = true; _published?.Invoke(new MapMarker(markerPublicationState.Name, markerPublicationState.X, 0f, markerPublicationState.Z, text), new MapMarker(markerPublicationState.Name, num3, 0f, num4, text), new MapMarker(markerPublicationState.Name, num6, 0f, num7, text), num5); break; } } } return result; } public bool Load() { if (!File.Exists(FilePath)) { if (File.Exists(FilePath + ".bak")) { throw new InvalidDataException("Marker refresh state is missing but its backup exists: " + FilePath); } return false; } using FileStream fileStream = new FileStream(FilePath, FileMode.Open, FileAccess.Read, FileShare.Read); if (fileStream.Length < 52 || fileStream.Length > 20971520) { throw new InvalidDataException("Invalid marker refresh state length."); } using BinaryReader binaryReader = new BinaryReader(fileStream); byte[] buffer = binaryReader.ReadBytes((int)fileStream.Length - 32); byte[] array = binaryReader.ReadBytes(32); using SHA256 sHA = SHA256.Create(); if (!((ReadOnlySpan)sHA.ComputeHash(buffer)).SequenceEqual((ReadOnlySpan)array)) { throw new InvalidDataException("Marker refresh state checksum mismatch."); } using BinaryReader binaryReader2 = new BinaryReader(new MemoryStream(buffer, writable: false), new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true)); if (binaryReader2.ReadUInt32() != _magic || binaryReader2.ReadInt32() != 1 || binaryReader2.ReadInt64() != _world) { throw new InvalidDataException("Unsupported marker refresh state format or world."); } int num = binaryReader2.ReadInt32(); if (num < 0 || num > 4096) { throw new InvalidDataException("Invalid marker refresh state count."); } Dictionary dictionary = new Dictionary(StringComparer.Ordinal); for (int i = 0; i < num; i++) { string text = ReadString(binaryReader2, 256); string name = ReadString(binaryReader2, 4096); int num2 = binaryReader2.ReadInt32(); float num3 = binaryReader2.ReadSingle(); float num4 = binaryReader2.ReadSingle(); if (text.Length == 0 || dictionary.ContainsKey(text) || num2 < 0 || num2 >= Slots.Length || !SharedMapExploration.Finite(num3) || !SharedMapExploration.Finite(num4)) { throw new InvalidDataException("Invalid marker refresh record."); } dictionary.Add(text, new MarkerPublicationState(name, num2, num3, num4)); } if (binaryReader2.BaseStream.Position != binaryReader2.BaseStream.Length) { throw new InvalidDataException("Trailing marker refresh data."); } _states = dictionary; _revision = (_savedRevision = 0L); return true; } private static string ReadString(BinaryReader reader, int maximum) { uint num = 0u; for (int i = 0; i <= 28; i += 7) { byte b = reader.ReadByte(); if (i == 28 && b > 7) { throw new InvalidDataException("Invalid marker refresh string length."); } num |= (uint)((b & 0x7F) << i); if ((b & 0x80) == 0) { if (num > maximum || num > reader.BaseStream.Length - reader.BaseStream.Position) { throw new InvalidDataException("Oversized or truncated marker refresh string."); } return new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true).GetString(reader.ReadBytes((int)num)); } } throw new InvalidDataException("Invalid marker refresh string length."); } public bool SaveIfDue(float now, float interval) { if (!_nextSave.Ready(now)) { return false; } _nextSave.Postpone(now, interval); return Save(); } public bool Save() { if (_revision == _savedRevision) { return false; } Directory.CreateDirectory(Path.GetDirectoryName(FilePath)); string text = FilePath + "." + Guid.NewGuid().ToString("N") + ".tmp"; try { using MemoryStream memoryStream = new MemoryStream(); using (BinaryWriter binaryWriter = new BinaryWriter(memoryStream, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true), leaveOpen: true)) { binaryWriter.Write(_magic); binaryWriter.Write(1); binaryWriter.Write(_world); binaryWriter.Write(_states.Count); foreach (KeyValuePair item in _states.OrderBy, string>((KeyValuePair p) => p.Key, StringComparer.Ordinal)) { binaryWriter.Write(item.Key); binaryWriter.Write(item.Value.Name); binaryWriter.Write(item.Value.Slot); binaryWriter.Write(item.Value.X); binaryWriter.Write(item.Value.Z); } } byte[] array = memoryStream.ToArray(); using SHA256 sHA = SHA256.Create(); byte[] array2 = sHA.ComputeHash(array); using (FileStream fileStream = new FileStream(text, FileMode.CreateNew, FileAccess.Write, FileShare.None)) { fileStream.Write(array, 0, array.Length); fileStream.Write(array2, 0, array2.Length); fileStream.Flush(flushToDisk: true); } if (File.Exists(FilePath)) { File.Replace(text, FilePath, FilePath + ".bak"); } else { File.Move(text, FilePath); } _savedRevision = _revision; return true; } finally { if (File.Exists(text)) { File.Delete(text); } } } } internal sealed class SharedMapPatches : IDisposable { private readonly Harmony _harmony = new Harmony("heimkit.sharedmap"); [ThreadStatic] private static SharedMapController? _receiving; [ThreadStatic] private static int _internalWrite; [ThreadStatic] private static ZNetPeer? _receivingPeer; private static MethodInfo Target(Type type, string name, params Type[] parameters) { return NativeAccess.Target(type, name, parameters); } private static HarmonyMethod Hook(string name) { //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Expected O, but got Unknown return new HarmonyMethod(typeof(SharedMapPatches), name, (Type[])null); } public static void CheckCompatibility() { Target(typeof(ZDOMan), "GetAllZDOsWithPrefabIterative", typeof(string), typeof(List), typeof(int).MakeByRefType()); Target(typeof(ZDOMan), "RPC_ZDOData", typeof(ZRpc), typeof(ZPackage)); Target(typeof(ZDOMan), "GetPortalList"); Target(typeof(ZDO), "Deserialize", typeof(ZPackage)); Target(typeof(ZDO), "Set", typeof(int), typeof(byte[])); Target(typeof(ZDO), "SetPrefab", typeof(int)); } public void Install() { CheckCompatibility(); try { _harmony.Patch((MethodBase)Target(typeof(ZDOMan), "RPC_ZDOData", typeof(ZRpc), typeof(ZPackage)), Hook("BeginPacket"), (HarmonyMethod)null, (HarmonyMethod)null, Hook("EndPacket"), (HarmonyMethod)null); _harmony.Patch((MethodBase)Target(typeof(ZDO), "Deserialize", typeof(ZPackage)), Hook("BeforeDeserialize"), Hook("AfterDeserialize"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); _harmony.Patch((MethodBase)Target(typeof(ZDO), "Set", typeof(int), typeof(byte[])), Hook("BeforeSet"), Hook("AfterSet"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); _harmony.Patch((MethodBase)Target(typeof(ZDO), "SetPrefab", typeof(int)), (HarmonyMethod)null, Hook("PrefabAssigned"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } catch { Dispose(); throw; } } private static void BeginPacket(ZRpc rpc, out MapPacketScope? __state) { __state = new MapPacketScope(_receiving, _receivingPeer); _receiving = null; _receivingPeer = null; SharedMapController active = SharedMapController.Active; if (active != null && active.Running) { ZNetPeer val = active.ReadyPeer(rpc); if (val != null) { _receivingPeer = val; _receiving = active; __state.Current = active; active.BeginBatch(); } } } private static Exception? EndPacket(Exception? __exception, MapPacketScope? __state) { if (__state == null) { return __exception; } SharedMapController current = __state.Current; _receiving = __state.Previous; _receivingPeer = __state.PreviousPeer; try { current?.EndBatch(); } catch (Exception error) { current?.Fail(error); } return __exception; } private static void BeforeDeserialize(ZDO __instance, ZPackage pkg, out MapReplicationSnapshot? __state) { __state = null; SharedMapController receiving = _receiving; if (receiving == null || !receiving.Running) { return; } int pos = pkg.GetPos(); try { if (pkg.Size() - pos >= 6) { pkg.ReadUShort(); int num = pkg.ReadInt(); if (num == SharedMapController.TablePrefab) { __state = new MapReplicationSnapshot(receiving) { Table = new TableMapSnapshot(receiving, __instance.GetByteArray(ZDOVars.s_data, (byte[])null)) { SenderPeer = _receivingPeer?.m_uid, SenderName = (_receivingPeer?.m_playerName ?? "") } }; } else if (receiving.ObservesResourceRecord(num)) { __state = new MapReplicationSnapshot(receiving) { PreviousPrefab = __instance.GetPrefab(), Terrain = __instance.GetByteArray(ZDOVars.s_TCData, (byte[])null), MiningString = __instance.GetString(ZDOVars.s_health, ""), MiningHealth = receiving.ResourceHealthBaseline(__instance) }; } } } finally { pkg.SetPos(pos); } } private static void AfterDeserialize(ZDO __instance, MapReplicationSnapshot? __state) { if (__state == null || !__state.Controller.Running) { return; } try { if (__state.Table != null) { __state.Controller.Incoming(__instance, __state.Table); } else { __state.Controller.AcceptedResourceRecord(__instance, __state); } } catch (Exception error) { __state.Controller.Fail(error); } } private static bool BeforeSet(ZDO __instance, int hash, ref byte[] bytes, out TableMapSnapshot? __state) { __state = null; SharedMapController active = SharedMapController.Active; if (_internalWrite != 0 || active == null || !active.Running || hash != ZDOVars.s_data || __instance.GetPrefab() != SharedMapController.TablePrefab) { return true; } try { byte[] byteArray = __instance.GetByteArray(hash, (byte[])null); int removedDeaths; byte[] array = active.Normalize(bytes, byteArray, out removedDeaths); if (array == null) { return false; } if (!SharedMapController.Equal(byteArray, array) || !SharedMapController.Equal(bytes, array)) { __state = new TableMapSnapshot(active, byteArray) { RemovedDeaths = removedDeaths, Received = bytes, Expected = array, SenderPeer = _receivingPeer?.m_uid, SenderName = (_receivingPeer?.m_playerName ?? "") }; } bytes = array; return true; } catch (Exception error) { active.Fail(error); return false; } } private static void AfterSet(ZDO __instance, TableMapSnapshot? __state) { if (__state == null || !__state.Controller.Running) { return; } byte[] byteArray = __instance.GetByteArray(ZDOVars.s_data, (byte[])null); if (!SharedMapController.Equal(__state.Expected, byteArray)) { return; } try { __state.Controller.AcceptedServerWrite(__instance, __state); } catch (Exception error) { __state.Controller.Fail(error); } } private static void PrefabAssigned(ZDO __instance) { SharedMapController active = SharedMapController.Active; if (_receiving != null || active == null || !active.Running || __instance.GetPrefab() != SharedMapController.TablePrefab) { return; } try { active.Reconcile(__instance, "table_prefab_assigned"); } catch (Exception error) { active.Fail(error); } } internal static void Write(ZDO table, byte[]? data) { //IL_004b: Unknown result type (might be due to invalid IL or missing references) _internalWrite++; try { if (data != null) { table.Set(ZDOVars.s_data, data); } else if (table.RemoveByteArray(ZDOVars.s_data)) { uint dataRevision = table.DataRevision; table.DataRevision = dataRevision + 1; ZDOMan.instance.SetDirtySector(table); } ZDOMan.instance.ForceSendZDO(table.m_uid); } finally { _internalWrite--; } } public void Dispose() { _harmony.UnpatchSelf(); } } internal sealed class SharedMapPinAdministration : IDisposable { private readonly ZDOMan _world; private readonly int _size; private readonly ManualLogSource _logger; private readonly Func _budget; private readonly Action _reconcile; private readonly string _request; private readonly List _tables = new List(); private readonly HashSet _reported = new HashSet(StringComparer.Ordinal); private int _sector; private int _cursor; private int _examined; private int _invalid; private bool _lastChunk; private bool _sweep; private bool _warned; private string? _find; private readonly ScheduleToken _nextPoll = new ScheduleToken(); public SharedMapPinRemovals Removals { get; } public SharedMapPinAdministration(ZDOMan world, int size, string directory, long worldId, ManualLogSource logger, Func budget, Action reconcile) { _world = world; _size = size; _logger = logger; _budget = budget; _reconcile = reconcile; Removals = new SharedMapPinRemovals(directory, worldId); Removals.Load(); _request = Path.Combine(directory, "world-" + worldId.ToString("X16", CultureInfo.InvariantCulture) + ".pin-admin.request"); } public void Tick(float now) { if (_find == null && !_sweep && _nextPoll.Ready(now)) { _nextPoll.Postpone(now, 1f); try { ReadRequest(); _warned = false; } catch (Exception ex) { if (!_warned) { Write("Could not process pin-administration request: " + ex.Message, (LogLevel)4); } _warned = true; } } if (_find == null && !_sweep) { return; } try { if (_cursor >= _tables.Count) { if (_lastChunk) { Complete(); return; } _tables.Clear(); _cursor = 0; _lastChunk = _world.GetAllZDOsWithPrefabIterative("piece_cartographytable", _tables, ref _sector); if (_tables.Count > 65536) { throw new InvalidDataException("Cartography scan candidate limit exceeded."); } } for (int i = 0; i < _budget(); i++) { if (_cursor >= _tables.Count) { break; } ZDO val = _tables[_cursor++]; if (!val.IsValid() || val.GetPrefab() != SharedMapController.TablePrefab) { continue; } _examined++; try { IReadOnlyList readOnlyList = SharedMapTableData.ReadPins(_size, val.GetByteArray(ZDOVars.s_data, (byte[])null)); if (_sweep) { _reconcile(val); continue; } foreach (MapPin item in readOnlyList) { if (!string.Equals(item.Name, _find, StringComparison.Ordinal)) { continue; } string text = SharedMapPinRemovals.Identity(item); if (_reported.Add(text)) { if (_reported.Count > 64) { Write("Pin lookup stopped after 64 distinct results; additional matches exist.", (LogLevel)16); Complete(); return; } Write("Table pin " + text + ": " + Display(item.Name) + "; icon " + item.Icon + "; XYZ " + item.X.ToString("R", CultureInfo.InvariantCulture) + ", " + item.Y.ToString("R", CultureInfo.InvariantCulture) + ", " + item.Z.ToString("R", CultureInfo.InvariantCulture) + "; owner " + item.Owner.ToString(CultureInfo.InvariantCulture) + ".", (LogLevel)16); } } } catch (Exception ex2) when (ex2 is IOException || ex2 is InvalidDataException || ex2 is ArgumentException) { _invalid++; } } if (_lastChunk && _cursor >= _tables.Count) { Complete(); } } catch (Exception ex3) { ManualLogSource logger = _logger; LogTopic tables = SharedMapLogTopics.Tables; Exception error = ex3; DiagnosticLog.Write(logger, "SharedMap", tables, "Pin administration stopped; saved removal rules are retained.", default(LogFields), (LogLevel)2, verbose: false, error); Reset(); } } private void ReadRequest() { if (!File.Exists(_request)) { return; } string text; using (FileStream fileStream = new FileStream(_request, FileMode.Open, FileAccess.Read, FileShare.Read)) { if (fileStream.Length < 1 || fileStream.Length > 4096) { throw new InvalidDataException("Request must contain one command of at most 4096 bytes."); } using StreamReader streamReader = new StreamReader(fileStream, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true)); text = streamReader.ReadToEnd().Trim(); } int num = text.IndexOf(' '); if (num < 1 || text.IndexOfAny(new char[2] { '\r', '\n' }) >= 0) { throw new InvalidDataException("Use find , remove , or allow ."); } string text2 = text.Substring(0, num); string text3 = text.Substring(num + 1).Trim(); bool flag = text2 == "find"; bool flag2 = text2 == "remove"; bool flag3 = text2 == "allow"; if (text3.Length == 0 || (!flag && ((!flag2 && !flag3) || !SharedMapPinRemovals.ValidId(text3)))) { throw new InvalidDataException("Use find , remove , or allow ."); } File.Delete(_request); Reset(); if (flag) { _find = text3; Write("Looking up table pins named " + Display(text3) + ".", (LogLevel)16); return; } bool flag4 = Removals.Set(text3, flag2); Write((flag2 ? "Removal rule enabled for pin " : "Future uploads allowed for pin ") + text3 + (flag4 ? "." : " (already configured)."), (LogLevel)16); if (flag2) { _sweep = true; } } private static string Display(string value) { return "\"" + new string((from c in value.Take(128) select (!char.IsControl(c)) ? c : ' ').ToArray()).Replace("\"", "\\\"") + "\""; } private void Complete() { Write((_sweep ? "Selected-pin cleanup sweep completed" : ("Pin lookup completed with " + Math.Min(64, _reported.Count) + " distinct matches")) + "; examined " + _examined + " table records" + ((_invalid == 0) ? "." : ("; skipped " + _invalid + " malformed tables.")), (LogLevel)16); Reset(); } private void Write(string message, LogLevel level = (LogLevel)16) { //IL_000c: Unknown result type (might be due to invalid IL or missing references) DiagnosticLog.Write(_logger, "SharedMap", message, level); } private void Reset() { _tables.Clear(); _reported.Clear(); _find = null; _sweep = (_lastChunk = false); _sector = (_cursor = (_examined = (_invalid = 0))); } public void Dispose() { Reset(); } } public static class SharedMapPinChanges { public static MapPinChanges Compare(IReadOnlyList before, IReadOnlyList after) { Dictionary<(string, bool, string), Queue> dictionary = new Dictionary<(string, bool, string), Queue>(); foreach (MapPin item2 in before) { (string, bool, string) key = (SharedMapPinRemovals.Identity(item2), item2.Checked, item2.Author); if (!dictionary.TryGetValue(key, out var value)) { dictionary.Add(key, value = new Queue()); } value.Enqueue(item2); } List<(string, MapPin)> list = new List<(string, MapPin)>(); foreach (MapPin item3 in after) { string item = SharedMapPinRemovals.Identity(item3); if (dictionary.TryGetValue((item, item3.Checked, item3.Author), out var value2) && value2.Count > 0) { value2.Dequeue(); } else { list.Add((item, item3)); } } Dictionary> dictionary2 = new Dictionary>(); foreach (KeyValuePair<(string, bool, string), Queue> item4 in dictionary) { if (item4.Value.Count == 0) { continue; } if (!dictionary2.TryGetValue(item4.Key.Item1, out var value3)) { dictionary2.Add(item4.Key.Item1, value3 = new Queue()); } foreach (MapPin item5 in item4.Value) { value3.Enqueue(item5); } } MapPinChanges mapPinChanges = new MapPinChanges(); foreach (var item6 in list) { if (dictionary2.TryGetValue(item6.Item1, out var value4) && value4.Count > 0) { mapPinChanges.Updated.Add((value4.Dequeue(), item6.Item2)); } else { mapPinChanges.Added.Add(item6.Item2); } } foreach (Queue value5 in dictionary2.Values) { mapPinChanges.Removed.AddRange(value5); } return mapPinChanges; } } public sealed class SharedMapPinRemovals { private const uint Magic = 1297238856u; private const int Maximum = 8192; private readonly long _world; private HashSet _ids = new HashSet(StringComparer.Ordinal); public string FilePath { get; } public long Revision { get; private set; } public SharedMapPinRemovals(string directory, long world) { _world = world; FilePath = Path.Combine(directory, "world-" + world.ToString("X16", CultureInfo.InvariantCulture) + ".pin-removals"); } public static string Identity(MapPin pin) { if (Encoding.UTF8.GetByteCount(pin.Name) > 4096 || !SharedMapExploration.Finite(pin.X) || !SharedMapExploration.Finite(pin.Y) || !SharedMapExploration.Finite(pin.Z) || pin.Icon < 0 || pin.Icon > 16) { throw new InvalidDataException("Invalid selected table pin."); } using MemoryStream memoryStream = new MemoryStream(); using (BinaryWriter binaryWriter = new BinaryWriter(memoryStream, Encoding.UTF8, leaveOpen: true)) { binaryWriter.Write(pin.Owner); binaryWriter.Write(pin.Name); binaryWriter.Write((pin.X == 0f) ? 0f : pin.X); binaryWriter.Write((pin.Y == 0f) ? 0f : pin.Y); binaryWriter.Write((pin.Z == 0f) ? 0f : pin.Z); binaryWriter.Write(pin.Icon); } using SHA256 sHA = SHA256.Create(); return BitConverter.ToString(sHA.ComputeHash(memoryStream.ToArray())).Replace("-", "").ToLowerInvariant(); } public static bool ValidId(string id) { if (id.Length == 64) { return id.All((char c) => (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f')); } return false; } public bool Contains(MapPin pin) { if (_ids.Count > 0) { return _ids.Contains(Identity(pin)); } return false; } public bool Contains(string id) { return _ids.Contains(id); } public void Load() { if (!File.Exists(FilePath)) { if (File.Exists(FilePath + ".bak")) { throw new InvalidDataException("Pin-removal rules are missing but a backup exists."); } return; } using FileStream fileStream = new FileStream(FilePath, FileMode.Open, FileAccess.Read, FileShare.Read); if (fileStream.Length < 52 || fileStream.Length > 262196) { throw new InvalidDataException("Invalid pin-removal file length."); } using BinaryReader binaryReader = new BinaryReader(fileStream); byte[] buffer = binaryReader.ReadBytes((int)fileStream.Length - 32); byte[] array = binaryReader.ReadBytes(32); using SHA256 sHA = SHA256.Create(); if (!((ReadOnlySpan)sHA.ComputeHash(buffer)).SequenceEqual((ReadOnlySpan)array)) { throw new InvalidDataException("Pin-removal checksum mismatch."); } using BinaryReader binaryReader2 = new BinaryReader(new MemoryStream(buffer, writable: false)); if (binaryReader2.ReadUInt32() != 1297238856 || binaryReader2.ReadInt32() != 1 || binaryReader2.ReadInt64() != _world) { throw new InvalidDataException("Unsupported pin-removal format or world."); } int num = binaryReader2.ReadInt32(); if (num < 0 || num > 8192 || binaryReader2.BaseStream.Length != 20 + (long)num * 32L) { throw new InvalidDataException("Invalid pin-removal count."); } HashSet hashSet = new HashSet(StringComparer.Ordinal); for (int i = 0; i < num; i++) { if (!hashSet.Add(BitConverter.ToString(binaryReader2.ReadBytes(32)).Replace("-", "").ToLowerInvariant())) { throw new InvalidDataException("Duplicate pin-removal identity."); } } _ids = hashSet; } public bool Set(string id, bool removed) { if (!ValidId(id)) { throw new ArgumentException("Use the full lowercase pin ID reported by find.", "id"); } if (_ids.Contains(id) == removed) { return false; } HashSet hashSet = new HashSet(_ids, StringComparer.Ordinal); if (removed) { hashSet.Add(id); } else { hashSet.Remove(id); } if (hashSet.Count > 8192) { throw new InvalidOperationException("Pin-removal rule limit exceeded."); } Directory.CreateDirectory(Path.GetDirectoryName(FilePath)); string text = FilePath + "." + Guid.NewGuid().ToString("N") + ".tmp"; try { using MemoryStream memoryStream = new MemoryStream(); using (BinaryWriter binaryWriter = new BinaryWriter(memoryStream, Encoding.UTF8, leaveOpen: true)) { binaryWriter.Write(1297238856u); binaryWriter.Write(1); binaryWriter.Write(_world); binaryWriter.Write(hashSet.Count); foreach (string item in hashSet.OrderBy((string v) => v, StringComparer.Ordinal)) { for (int num = 0; num < 64; num += 2) { binaryWriter.Write(byte.Parse(item.Substring(num, 2), NumberStyles.HexNumber, CultureInfo.InvariantCulture)); } } } byte[] array = memoryStream.ToArray(); using SHA256 sHA = SHA256.Create(); using (FileStream fileStream = new FileStream(text, FileMode.CreateNew, FileAccess.Write, FileShare.None)) { fileStream.Write(array, 0, array.Length); byte[] array2 = sHA.ComputeHash(array); fileStream.Write(array2, 0, array2.Length); fileStream.Flush(flushToDisk: true); } if (File.Exists(FilePath)) { File.Replace(text, FilePath, FilePath + ".bak"); } else { File.Move(text, FilePath); } _ids = hashSet; Revision++; return true; } finally { if (File.Exists(text)) { File.Delete(text); } } } } public sealed class SharedMapPinState { private sealed class State { public MapPin Source; public bool Target; public int Slot; public MapPin Published => Copy(Source, Source.X + Slots[Slot].X, Source.Z + Slots[Slot].Z, Source.Checked); public State(MapPin source, bool target, int slot = 0) { Source = source; Target = target; Slot = slot; } } private const int Maximum = 32768; private const uint Magic = 1397771080u; private static readonly (float X, float Z)[] Slots = new(float, float)[9] { (0f, 0f), (2f, 0f), (2f, 2f), (0f, 2f), (-2f, 2f), (-2f, 0f), (-2f, -2f), (0f, -2f), (2f, -2f) }; private readonly Dictionary _states = new Dictionary(StringComparer.Ordinal); private readonly Dictionary> _issued = new Dictionary>(StringComparer.Ordinal); private readonly Dictionary _adopted = new Dictionary(StringComparer.Ordinal); private readonly long _world; private readonly Action? _changed; private bool _dirty; private readonly ScheduleToken _nextSave = new ScheduleToken(); public long Revision { get; private set; } public string FilePath { get; } public SharedMapPinState(string directory, long world, Action? changed = null) { _world = world; _changed = changed; FilePath = Path.Combine(directory, "world-" + world.ToString("X16", CultureInfo.InvariantCulture) + ".pin-state"); } private static bool Managed(long owner) { return SharedMapTableData.ManagedOwner(owner); } private static MapPin Copy(MapPin p, float x, float z, bool check) { return new MapPin(p.Owner, p.Name, x, p.Y, z, p.Icon, check, p.Author); } public static string MarkerKey(long owner, string identity) { return SharedMapPinRemovals.Identity(new MapPin(owner, identity, 0f, 0f, 0f, 0)); } private void Index(string key, State state, bool add) { foreach (string item in new string[2] { SharedMapPinRemovals.Identity(state.Source), SharedMapPinRemovals.Identity(state.Published) }.Distinct()) { HashSet value2; if (add) { if (!_issued.TryGetValue(item, out HashSet value)) { value = (_issued[item] = new HashSet()); } value.Add(key); } else if (_issued.TryGetValue(item, out value2)) { value2.Remove(key); if (value2.Count == 0) { _issued.Remove(item); } } } } private string? Resolve(MapPin pin) { string text = SharedMapPinRemovals.Identity(pin); if (_adopted.TryGetValue(text, out string value)) { return value; } if (_issued.TryGetValue(text, out HashSet value2)) { if (value2.Count != 1) { return null; } return value2.First(); } if (!Managed(pin.Owner)) { return text; } return null; } public int Accept(IReadOnlyList incoming, IReadOnlyList previous, bool enabled) { HashSet incomingIds = new HashSet(incoming.Select(SharedMapPinRemovals.Identity), StringComparer.Ordinal); HashSet hashSet = new HashSet(previous.Select(SharedMapPinRemovals.Identity), StringComparer.Ordinal); Dictionary dictionary = previous.Where((MapPin p) => Managed(p.Owner) && !incomingIds.Contains(SharedMapPinRemovals.Identity(p))).GroupBy(Shape).ToDictionary((IGrouping g) => g.Key, (IGrouping g) => (from k in g.Select(Resolve) where k != null select k).Distinct().ToArray()); foreach (MapPin item2 in incoming.Where((MapPin p) => !Managed(p.Owner))) { string text = SharedMapPinRemovals.Identity(item2); if (!_adopted.ContainsKey(text) && !hashSet.Contains(text) && dictionary.TryGetValue(Shape(item2), out var value) && value.Length == 1) { if (_adopted.Count >= 32768) { throw new InvalidDataException("Shared adopted-pin limit exceeded."); } _adopted.Add(text, value[0]); _dirty = true; Revision++; _changed?.Invoke(value[0], item2, "accepted_pin_adoption"); } } if (!enabled) { return 0; } Dictionary dictionary2 = (from p in previous select (Key: Resolve(p), Pin: p) into p where p.Key != null group p by p.Key).ToDictionary((IGrouping g) => g.Key, (IGrouping g) => g.Select(((string Key, MapPin Pin) p) => p.Pin.Checked).Distinct().ToArray()); int num = 0; foreach (IGrouping item3 in from p in incoming select (Key: Resolve(p), Pin: p) into p where p.Key != null group p by p.Key) { if (item3.Select<(string, MapPin), bool>(((string Key, MapPin Pin) p) => p.Pin.Checked).Distinct().Count() != 1) { continue; } MapPin item = item3.First().Item2; if ((dictionary2.TryGetValue(item3.Key, out var value2) && (value2.Length != 1 || value2[0] == item.Checked)) || (!dictionary2.ContainsKey(item3.Key) && !item.Checked)) { continue; } if (!_states.TryGetValue(item3.Key, out State value3)) { if (Managed(item.Owner)) { continue; } if (_states.Count >= 32768) { throw new InvalidDataException("Shared pin-state limit exceeded."); } value3 = new State(Copy(item, item.X, item.Z, check: false), target: false); _states.Add(item3.Key, value3); Index(item3.Key, value3, add: true); } if (value3.Target != item.Checked) { value3.Target = item.Checked; _dirty = true; Revision++; num++; _changed?.Invoke(item3.Key, item, "accepted_checkmark"); } } return num; static string Shape(MapPin p) { return SharedMapPinRemovals.Identity(new MapPin(0L, p.Name, p.X, p.Y, p.Z, p.Icon)); } } public bool Adopted(MapPin pin) { return _adopted.ContainsKey(SharedMapPinRemovals.Identity(pin)); } public MapPin Publish(MapPin pin, string? markerIdentity, bool shareChecks) { string text = ((markerIdentity == null) ? Resolve(pin) : MarkerKey(pin.Owner, markerIdentity)); if (text == null) { return Copy(pin, pin.X, pin.Z, check: false); } if (!_states.TryGetValue(text, out State value)) { if (markerIdentity == null && !shareChecks) { return Copy(pin, pin.X, pin.Z, check: false); } if (_states.Count >= 32768) { throw new InvalidDataException("Shared pin-state limit exceeded."); } value = new State(Copy(pin, pin.X, pin.Z, check: false), target: false); _states.Add(text, value); Index(text, value, add: true); _dirty = true; Revision++; } MapPin mapPin = ((markerIdentity == null) ? new MapPin(pin.Owner, value.Source.Name, value.Source.X, value.Source.Y, value.Source.Z, pin.Icon, isChecked: false, pin.Author) : pin); bool flag = shareChecks && value.Target; if (mapPin.Name != value.Source.Name || mapPin.X != value.Source.X || mapPin.Y != value.Source.Y || mapPin.Z != value.Source.Z || flag != value.Source.Checked) { MapPin published = value.Published; Index(text, value, add: false); for (int i = 0; i < Slots.Length; i++) { if (flag == value.Source.Checked && mapPin.Owner != -9223372036854775806L) { break; } value.Slot = (value.Slot + 1) % Slots.Length; double num = mapPin.X + Slots[value.Slot].X - published.X; double num2 = mapPin.Z + Slots[value.Slot].Z - published.Z; if (num * num + num2 * num2 > 1.21) { break; } } value.Source = Copy(mapPin, mapPin.X, mapPin.Z, flag); Index(text, value, add: true); _dirty = true; Revision++; _changed?.Invoke(text, value.Published, "pin_publication"); } MapPin published2 = value.Published; return new MapPin(pin.Owner, pin.Name, published2.X, pin.Y, published2.Z, pin.Icon, flag, pin.Author); } public void Load() { if (!File.Exists(FilePath)) { if (File.Exists(FilePath + ".bak")) { throw new InvalidDataException("Shared pin state missing beside backup."); } return; } using FileStream fileStream = new FileStream(FilePath, FileMode.Open, FileAccess.Read, FileShare.Read); if (fileStream.Length < 52 || fileStream.Length > 157286400) { throw new InvalidDataException("Invalid shared pin-state length."); } using BinaryReader binaryReader = new BinaryReader(fileStream); byte[] buffer = binaryReader.ReadBytes((int)fileStream.Length - 32); using SHA256 sHA = SHA256.Create(); if (!((ReadOnlySpan)sHA.ComputeHash(buffer)).SequenceEqual((ReadOnlySpan)binaryReader.ReadBytes(32))) { throw new InvalidDataException("Shared pin-state checksum mismatch."); } using BinaryReader binaryReader2 = new BinaryReader(new MemoryStream(buffer, writable: false), new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true)); uint num = binaryReader2.ReadUInt32(); int num2 = binaryReader2.ReadInt32(); if (num != 1397771080 || (num2 != 1 && num2 != 2) || binaryReader2.ReadInt64() != _world) { throw new InvalidDataException("Shared pin-state format/world mismatch."); } int num3 = binaryReader2.ReadInt32(); if (num3 < 0 || num3 > 32768) { throw new InvalidDataException("Shared pin-state count invalid."); } Dictionary dictionary = new Dictionary(); for (int i = 0; i < num3; i++) { byte[] array = binaryReader2.ReadBytes(32); if (array.Length != 32) { throw new EndOfStreamException(); } string key = BitConverter.ToString(array).Replace("-", "").ToLowerInvariant(); long owner = binaryReader2.ReadInt64(); int num4 = binaryReader2.ReadUInt16(); if (num4 > 4096) { throw new InvalidDataException("Shared pin-state label too long."); } byte[] array2 = binaryReader2.ReadBytes(num4); if (array2.Length != num4) { throw new EndOfStreamException(); } MapPin mapPin = new MapPin(owner, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true).GetString(array2), binaryReader2.ReadSingle(), binaryReader2.ReadSingle(), binaryReader2.ReadSingle(), binaryReader2.ReadInt32(), binaryReader2.ReadBoolean()); bool target = binaryReader2.ReadBoolean(); int num5 = binaryReader2.ReadByte(); SharedMapPinRemovals.Identity(mapPin); if (num5 >= Slots.Length || dictionary.ContainsKey(key)) { throw new InvalidDataException("Invalid shared pin-state record."); } dictionary.Add(key, new State(mapPin, target, num5)); } Dictionary dictionary2 = new Dictionary(); if (num2 >= 2) { int num6 = binaryReader2.ReadInt32(); if (num6 < 0 || num6 > 32768) { throw new InvalidDataException("Invalid adopted pin count."); } for (int j = 0; j < num6; j++) { byte[] array3 = binaryReader2.ReadBytes(32); byte[] array4 = binaryReader2.ReadBytes(32); if (array3.Length != 32 || array4.Length != 32) { throw new EndOfStreamException(); } string key2 = BitConverter.ToString(array3).Replace("-", "").ToLowerInvariant(); string text = BitConverter.ToString(array4).Replace("-", "").ToLowerInvariant(); if (!dictionary.ContainsKey(text) || dictionary2.ContainsKey(key2)) { throw new InvalidDataException("Invalid adopted pin mapping."); } dictionary2.Add(key2, text); } } if (binaryReader2.BaseStream.Position != binaryReader2.BaseStream.Length) { throw new InvalidDataException("Trailing shared pin-state bytes."); } _states.Clear(); _issued.Clear(); foreach (KeyValuePair item in dictionary) { _states.Add(item.Key, item.Value); Index(item.Key, item.Value, add: true); } _dirty = false; _adopted.Clear(); foreach (KeyValuePair item2 in dictionary2) { _adopted.Add(item2.Key, item2.Value); } } public bool SaveIfDue(float now, float interval) { if (!_nextSave.Ready(now)) { return false; } _nextSave.Postpone(now, interval); return Save(); } public bool Save() { if (!_dirty) { return false; } using MemoryStream memoryStream = new MemoryStream(); using (BinaryWriter binaryWriter = new BinaryWriter(memoryStream, Encoding.UTF8, leaveOpen: true)) { binaryWriter.Write(1397771080u); binaryWriter.Write(2); binaryWriter.Write(_world); binaryWriter.Write(_states.Count); foreach (KeyValuePair item in _states.OrderBy, string>((KeyValuePair p) => p.Key, StringComparer.Ordinal)) { for (int num = 0; num < 64; num += 2) { binaryWriter.Write(byte.Parse(item.Key.Substring(num, 2), NumberStyles.HexNumber, CultureInfo.InvariantCulture)); } MapPin source = item.Value.Source; binaryWriter.Write(source.Owner); byte[] bytes = Encoding.UTF8.GetBytes(source.Name); binaryWriter.Write((ushort)bytes.Length); binaryWriter.Write(bytes); binaryWriter.Write(source.X); binaryWriter.Write(source.Y); binaryWriter.Write(source.Z); binaryWriter.Write(source.Icon); binaryWriter.Write(source.Checked); binaryWriter.Write(item.Value.Target); binaryWriter.Write((byte)item.Value.Slot); } binaryWriter.Write(_adopted.Count); foreach (KeyValuePair item2 in _adopted.OrderBy, string>((KeyValuePair p) => p.Key, StringComparer.Ordinal)) { string[] array = new string[2] { item2.Key, item2.Value }; foreach (string text in array) { for (int num3 = 0; num3 < 64; num3 += 2) { binaryWriter.Write(byte.Parse(text.Substring(num3, 2), NumberStyles.HexNumber, CultureInfo.InvariantCulture)); } } } } Directory.CreateDirectory(Path.GetDirectoryName(FilePath)); string text2 = FilePath + "." + Guid.NewGuid().ToString("N") + ".tmp"; try { byte[] array2 = memoryStream.ToArray(); using SHA256 sHA = SHA256.Create(); using (FileStream fileStream = new FileStream(text2, FileMode.CreateNew, FileAccess.Write, FileShare.None)) { fileStream.Write(array2, 0, array2.Length); byte[] array3 = sHA.ComputeHash(array2); fileStream.Write(array3, 0, array3.Length); fileStream.Flush(flushToDisk: true); } if (File.Exists(FilePath)) { File.Replace(text2, FilePath, FilePath + ".bak"); } else { File.Move(text2, FilePath); } _dirty = false; return true; } finally { if (File.Exists(text2)) { File.Delete(text2); } } } } public static class SharedMapPortalClusters { public static IReadOnlyList Group(IReadOnlyList portals, float distance) { if (!SharedMapExploration.Finite(distance) || distance < 0f || distance > 100f) { throw new ArgumentOutOfRangeException("distance"); } if (portals.Count > 4096) { throw new ArgumentOutOfRangeException("portals"); } if (distance == 0f) { return portals; } return (from @group in SharedMapMarkerClusters.Group(portals, distance, (MapMarker p) => p.X, (MapMarker p) => p.Z, (MapMarker a, MapMarker b) => true) select (@group.Count != 1) ? new MapMarker("Multi Portals (" + @group.Count + ")", (float)((IEnumerable)@group).Average((Func)((MapMarker p) => p.X)), (float)((IEnumerable)@group).Average((Func)((MapMarker p) => p.Y)), (float)((IEnumerable)@group).Average((Func)((MapMarker p) => p.Z)), @group[0].Identity) : @group[0]).ToArray(); } } public static class SharedMapPortalIdentity { public static string Create(int prefab, float x, float y, float z) { if (!SharedMapExploration.Finite(x) || !SharedMapExploration.Finite(y) || !SharedMapExploration.Finite(z)) { throw new ArgumentException("A portal identity requires finite coordinates."); } return "portal:" + prefab.ToString("X8", CultureInfo.InvariantCulture) + ":" + Coordinate(x) + ":" + Coordinate(y) + ":" + Coordinate(z); } private static string Coordinate(float value) { return BitConverter.SingleToInt32Bits((value == 0f) ? 0f : value).ToString("X8", CultureInfo.InvariantCulture); } } internal sealed class SharedMapPortals { private readonly ZDOMan _world; private readonly SharedMapExploration _map; private readonly List _portals = new List(); private readonly HashSet _seen = new HashSet(); private readonly Dictionary _observed = new Dictionary(); private readonly List _expired = new List(); private readonly List _markers = new List(); private readonly List _unique = new List(); private readonly Dictionary _identities = new Dictionary(StringComparer.Ordinal); private static readonly Comparison IdOrder = NativeIdentity.CompareOrdinal; private static readonly Comparison MarkerOrder = (MapMarker a, MapMarker b) => StringComparer.Ordinal.Compare(a.Identity, b.Identity); private IReadOnlyList? _grouped; private List? _previous; private float _cluster; public int RegisteredCount => _portals.Count; public int EligibleCount { get; private set; } public SharedMapPortals(ZDOMan world, SharedMapExploration map) { _world = world; _map = map; } public void Refresh() { //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) //IL_00a6: Unknown result type (might be due to invalid IL or missing references) //IL_00ab: Unknown result type (might be due to invalid IL or missing references) //IL_00b2: Unknown result type (might be due to invalid IL or missing references) //IL_00c0: Unknown result type (might be due to invalid IL or missing references) //IL_00f0: Unknown result type (might be due to invalid IL or missing references) //IL_00f5: Unknown result type (might be due to invalid IL or missing references) //IL_00fd: Unknown result type (might be due to invalid IL or missing references) _portals.Clear(); _seen.Clear(); foreach (ZDO portal in _world.GetPortalList()) { if (portal.IsValid() && _seen.Add(portal.m_uid)) { _portals.Add(portal.m_uid); } } _portals.Sort(IdOrder); _expired.Clear(); foreach (ZDOID key in _observed.Keys) { if (!_seen.Contains(key)) { _expired.Add(key); } } foreach (ZDOID item in _expired) { _observed.Remove(item); } } public IReadOnlyList Read(float clusterDistance) { //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_002c: 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_007c: Unknown result type (might be due to invalid IL or missing references) //IL_007e: Unknown result type (might be due to invalid IL or missing references) //IL_008f: Unknown result type (might be due to invalid IL or missing references) //IL_00a0: Unknown result type (might be due to invalid IL or missing references) //IL_00b1: Unknown result type (might be due to invalid IL or missing references) //IL_00c3: Unknown result type (might be due to invalid IL or missing references) //IL_00ca: Unknown result type (might be due to invalid IL or missing references) //IL_00f4: Unknown result type (might be due to invalid IL or missing references) //IL_017b: Unknown result type (might be due to invalid IL or missing references) //IL_0182: Unknown result type (might be due to invalid IL or missing references) //IL_0189: Unknown result type (might be due to invalid IL or missing references) //IL_0197: Unknown result type (might be due to invalid IL or missing references) //IL_019e: Unknown result type (might be due to invalid IL or missing references) //IL_01a5: Unknown result type (might be due to invalid IL or missing references) //IL_012a: 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_01d5: 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_0154: Unknown result type (might be due to invalid IL or missing references) List markers = _markers; markers.Clear(); foreach (ZDOID portal in _portals) { ZDO zDO = _world.GetZDO(portal); if (zDO == null || !zDO.IsValid() || !Game.instance.PortalPrefabHash.Contains(zDO.GetPrefab()) || zDO.GetLong(ZDOVars.s_creator, 0L) == 0L) { continue; } Vector3 position = zDO.GetPosition(); if (!SharedMapExploration.Finite(position.x) || !SharedMapExploration.Finite(position.y) || !SharedMapExploration.Finite(position.z) || Character.InInterior(position) || !_map.IsExplored(position.x, position.z)) { continue; } string text = zDO.GetString(ZDOVars.s_tag, ""); if (!_observed.TryGetValue(portal, out (int, string, MapMarker) value) || value.Item1 != zDO.GetPrefab() || value.Item2 != text || value.Item3.X != position.x || value.Item3.Y != position.y || value.Item3.Z != position.z) { value = (zDO.GetPrefab(), text, new MapMarker(string.IsNullOrWhiteSpace(text) ? "NoName" : text, position.x, position.y, position.z, SharedMapPortalIdentity.Create(zDO.GetPrefab(), position.x, position.y, position.z))); if (_observed.Count >= 4096 && !_observed.ContainsKey(portal)) { throw new InvalidOperationException("Community portal marker limit exceeded; table data was not replaced."); } _observed[portal] = value; } markers.Add(value.Item3); if (markers.Count > 4096) { throw new InvalidOperationException("Community portal marker limit exceeded; table data was not replaced."); } } if (_grouped != null && _cluster == clusterDistance && _previous != null && SharedMapReconciliationState.SameMarkers(markers, _previous)) { return _grouped; } if (_previous == null) { _previous = new List(); } _previous.Clear(); _previous.AddRange(markers); _cluster = clusterDistance; _identities.Clear(); foreach (MapMarker item in markers) { _identities.TryGetValue(item.Identity, out var value2); _identities[item.Identity] = value2 + 1; } _unique.Clear(); foreach (MapMarker item2 in markers) { if (_identities[item2.Identity] == 1) { _unique.Add(item2); } } _unique.Sort(MarkerOrder); MapMarker[] array = new MapMarker[_unique.Count]; _unique.CopyTo(array); EligibleCount = array.Length; return _grouped = SharedMapPortalClusters.Group(array, clusterDistance); } } internal sealed class SharedMapReconciliationState { internal readonly int Pixels; internal readonly long Pins; internal readonly long Removals; internal readonly long PortalPublications; internal readonly float HideDistance; internal readonly IReadOnlyList Portals; internal readonly IReadOnlyList Resources; internal readonly IReadOnlyList Dungeons; internal readonly IReadOnlyList Runestones; internal readonly IReadOnlyList Spawners; internal SharedMapReconciliationState(int pixels, long pins, long removals, long portalPublications, float hideDistance, IReadOnlyList portals, IReadOnlyList resources, IReadOnlyList dungeons, IReadOnlyList runestones, IReadOnlyList spawners) { Pixels = pixels; Pins = pins; Removals = removals; PortalPublications = portalPublications; HideDistance = hideDistance; Portals = Copy(portals); Resources = Copy(resources); Dungeons = Copy(dungeons); Runestones = Copy(runestones); Spawners = Copy(spawners); } private static MapMarker[] Copy(IReadOnlyList source) { MapMarker[] array = new MapMarker[source.Count]; for (int i = 0; i < array.Length; i++) { array[i] = source[i]; } return array; } internal bool Same(SharedMapReconciliationState other) { if (Pixels == other.Pixels && Pins == other.Pins && Removals == other.Removals && PortalPublications == other.PortalPublications && HideDistance == other.HideDistance && SameMarkers(Portals, other.Portals) && SameMarkers(Resources, other.Resources) && SameMarkers(Dungeons, other.Dungeons) && SameMarkers(Runestones, other.Runestones)) { return SameMarkers(Spawners, other.Spawners); } return false; } internal static bool SameMarkers(IReadOnlyList left, IReadOnlyList right) { if (left.Count != right.Count) { return false; } for (int i = 0; i < left.Count; i++) { MapMarker mapMarker = left[i]; MapMarker mapMarker2 = right[i]; if (mapMarker.Name != mapMarker2.Name || mapMarker.Identity != mapMarker2.Identity || mapMarker.X != mapMarker2.X || mapMarker.Y != mapMarker2.Y || mapMarker.Z != mapMarker2.Z) { return false; } } return true; } } public static class SharedMapResourceClusters { public static IReadOnlyList Group(IEnumerable discoveries, float distance, bool removeDepleted) { IReadOnlyList> readOnlyList = SharedMapMarkerClusters.Group(from d in discoveries where d.Kind != ResourceKind.Silver || d.SilverDiscovered orderby d.Identity select d, distance, (ResourceDeposit d) => d.X, (ResourceDeposit d) => d.Z, (ResourceDeposit a, ResourceDeposit b) => a.Kind == b.Kind); List list = new List(); foreach (List item in readOnlyList) { ResourceDeposit[] array = item.Where((ResourceDeposit d) => !removeDepleted || !d.Depleted).ToArray(); if (array.Length != 0) { string text = item[0].Kind.ToString(); if (item[0].Kind == ResourceKind.Copper || item[0].Kind == ResourceKind.Silver) { text = PercentageLabel(item); } if (item[0].Kind == ResourceKind.Tin && array.Length > 1) { text = text + " (" + array.Length.ToString(CultureInfo.InvariantCulture) + ")"; } list.Add(new MapMarker(text, (float)((IEnumerable)array).Average((Func)((ResourceDeposit d) => d.X)), (float)((IEnumerable)array).Average((Func)((ResourceDeposit d) => d.Y)), (float)((IEnumerable)array).Average((Func)((ResourceDeposit d) => d.Z)), item[0].Identity.ToString(CultureInfo.InvariantCulture))); if (list.Count > 4096) { throw new InvalidOperationException("Community resource marker limit exceeded; table data was not replaced."); } } } return list; } private static string PercentageLabel(IReadOnlyList group) { string text = group[0].Kind.ToString(); if (group.All((ResourceDeposit d) => d.Depleted)) { return text + " 0%"; } if (group.Any((ResourceDeposit d) => !d.Progress.HasValue)) { return text + " ?%"; } long num = ((IEnumerable)group).Sum((Func)((ResourceDeposit d) => d.Progress.Value.TotalSections)); return text + " " + ((((IEnumerable)group).Sum((Func)((ResourceDeposit d) => (!d.Depleted) ? d.Progress.Value.RemainingSections : 0)) * 100 + num - 1) / num).ToString(CultureInfo.InvariantCulture) + "%"; } } public static class SharedMapResourceHealth { public static bool? Sections(string encoded, int expected) { MiningProgress? miningProgress = Progress(encoded, expected); if (!miningProgress.HasValue) { return null; } return miningProgress.Value.RemainingSections == 0; } public static MiningProgress? Progress(string encoded, int expected) { if (expected < 1 || expected > 8192) { return null; } if (encoded.Length == 0) { return new MiningProgress(expected, expected); } if (encoded.Length > 4 * ((4 + expected * 4 + 2) / 3)) { return null; } try { byte[] array = Convert.FromBase64String(encoded); if (array.Length != 4 + expected * 4) { return null; } using BinaryReader binaryReader = new BinaryReader(new MemoryStream(array, writable: false)); if (binaryReader.ReadInt32() != expected) { return null; } int num = 0; for (int i = 0; i < expected; i++) { float num2 = binaryReader.ReadSingle(); if (!SharedMapExploration.Finite(num2)) { return null; } if (num2 > 0f) { num++; } } return new MiningProgress(num, expected); } catch (FormatException) { return null; } } } public static class SharedMapResourcePinSpacing { public static int Apply(List publications, float distance) { if (!SharedMapExploration.Finite(distance) || distance < 0f || distance > 100f) { throw new ArgumentOutOfRangeException("distance"); } if (distance == 0f) { return 0; } double cellSize = Math.Max(1f, distance); double squared = (double)distance * (double)distance; Dictionary<(double X, double Z), List> cells = new Dictionary<(double, double), List>(); foreach (MapPin publication in publications) { if (publication.Owner != -9223372036854775807L && SharedMapTableData.ManagedOwner(publication.Owner)) { (double, double) key = Cell(publication); if (!cells.TryGetValue(key, out List value)) { cells.Add(key, value = new List()); } value.Add(publication); } } if (cells.Count == 0) { return 0; } return publications.RemoveAll(Hidden); (double X, double Z) Cell(MapPin pin) { return (X: Math.Floor((double)pin.X / cellSize), Z: Math.Floor((double)pin.Z / cellSize)); } bool Hidden(MapPin pin) { if (pin.Owner != -9223372036854775807L) { return false; } (double, double) tuple = Cell(pin); for (int i = -1; i <= 1; i++) { for (int j = -1; j <= 1; j++) { if (cells.TryGetValue((tuple.Item1 + (double)i, tuple.Item2 + (double)j), out List value2)) { foreach (MapPin item in value2) { double num = (double)pin.X - (double)item.X; double num2 = (double)pin.Z - (double)item.Z; if (num * num + num2 * num2 <= squared) { return true; } } } } } return false; } } } internal sealed class SharedMapResourcePrefab { private readonly int _sections; private readonly int[] _healthKeys; private readonly bool _mineRock; private readonly bool _mineRock5; private readonly float _health; public string Name { get; } public ResourceKind Kind { get; } public int Hash { get; } public bool ReplacesWithMining { get; } public MiningProgress InitialProgress => new MiningProgress(_sections, _sections); private SharedMapResourcePrefab(string name, ResourceKind kind, bool replacement, int sections, bool mineRock, bool mineRock5, float health) { Name = name; Kind = kind; Hash = StringExtensionMethods.GetStableHashCode(name); ReplacesWithMining = replacement; _healthKeys = new int[mineRock ? sections : 0]; for (int i = 0; i < _healthKeys.Length; i++) { _healthKeys[i] = StringExtensionMethods.GetStableHashCode("Health" + i); } _sections = sections; _mineRock = mineRock; _mineRock5 = mineRock5; _health = health; } public static SharedMapResourcePrefab? Read(string name, ResourceKind kind, string drop, string? successor) { GameObject val = PrefabRegistry.Current.Prefab(name); if (!((Object)(object)val == (Object)null) && !((Object)(object)PrefabRegistry.Component(val) != (Object)null) && !((Object)(object)PrefabRegistry.Component(val) != (Object)null) && !((Object)(object)PrefabRegistry.Component(val) != (Object)null) && !((Object)(object)PrefabRegistry.Component(val) != (Object)null)) { ZNetView? obj = PrefabRegistry.Component(val); if (obj != null && obj.m_persistent) { MineRock val2 = PrefabRegistry.Component(val); MineRock5 val3 = PrefabRegistry.Component(val); Destructible val4 = PrefabRegistry.Component(val); bool flag = successor != null; SharedMapResourcePrefab sharedMapResourcePrefab = null; if (flag) { if ((Object)(object)val4 == (Object)null || (Object)(object)val4.m_spawnWhenDestroyed == (Object)null || ((Object)val4.m_spawnWhenDestroyed).name != successor) { return null; } sharedMapResourcePrefab = Read(successor, kind, drop, null); if (sharedMapResourcePrefab == null) { return null; } } else { DropTable val5 = (((Object)(object)val2 != (Object)null) ? val2.m_dropItems : (((Object)(object)val3 != (Object)null) ? val3.m_dropItems : PrefabRegistry.Component(val)?.m_dropWhenDestroyed)); if (val5 == null || !val5.m_drops.Any((DropData d) => (Object)(object)d.m_item != (Object)null && ((Object)d.m_item).name == drop)) { return null; } } int num = (((Object)(object)val2 != (Object)null) ? PrefabRegistry.Children(((Object)(object)val2.m_areaRoot != (Object)null) ? val2.m_areaRoot : val, inactive: false).Length : (((Object)(object)val3 != (Object)null) ? PrefabRegistry.Children(val, inactive: false).Length : (sharedMapResourcePrefab?._sections ?? 1))); float num2 = (((Object)(object)val2 != (Object)null) ? val2.m_health : (((Object)(object)val3 != (Object)null) ? val3.m_health : (((Object)(object)val4 != (Object)null) ? val4.m_health : float.NaN))); if (num < 1 || num > 8192 || !SharedMapExploration.Finite(num2) || num2 <= 0f || ((Object)(object)val2 == (Object)null && (Object)(object)val3 == (Object)null && (Object)(object)val4 == (Object)null)) { return null; } return new SharedMapResourcePrefab(name, kind, flag, num, (Object)(object)val2 != (Object)null, (Object)(object)val3 != (Object)null, num2); } } return null; } public float HealthBaseline(ZDO zdo) { return zdo.GetFloat(ZDOVars.s_health, _health); } public bool? Depleted(ZDO zdo) { MiningProgress? miningProgress = Progress(zdo); if (!miningProgress.HasValue) { return null; } return miningProgress.Value.RemainingSections == 0; } public MiningProgress? Progress(ZDO zdo) { if (_mineRock5) { return SharedMapResourceHealth.Progress(zdo.GetString(ZDOVars.s_health, ""), _sections); } if (_mineRock) { int num = 0; for (int i = 0; i < _sections; i++) { float num2 = zdo.GetFloat(_healthKeys[i], _health); if (!SharedMapExploration.Finite(num2)) { return null; } if (num2 > 0f) { num++; } } return new MiningProgress(num, _sections); } float num3 = zdo.GetFloat(ZDOVars.s_health, _health); if (!SharedMapExploration.Finite(num3)) { return null; } if (!(num3 <= 0f) || !ReplacesWithMining) { return new MiningProgress((num3 > 0f) ? _sections : 0, _sections); } return null; } } internal sealed class SharedMapResources : IDisposable { private const int CandidatesPerPlayer = 256; private readonly ZDOMan _world; private readonly SharedMapSilverDiscovery _silverDiscovery; private readonly List _miningNear = new List(); private readonly SharedMapResourceStore _store; private readonly SharedMapMarkerRefresh _refresh; private readonly SharedMapExploration _map; private readonly SharedMapSettings _settings; private readonly SharedMapDiagnostics _diagnostics; private readonly Action _failed; private readonly PrefabCatalog _prefabs = PrefabRegistry.Current.Catalog("SharedMapResources._prefabs"); private readonly List _scanPrefabs = new List(); private readonly List _near = new List(); private readonly List _scan = new List(); private readonly List _candidates = new List(); private readonly HashSet _seen = new HashSet(); private readonly Dictionary _playerCursors = new Dictionary(); private readonly Queue _retrospective = new Queue(); private long _markerRevision = -1L; private float _distance = -1f; private readonly ScheduleToken _nextRetro = new ScheduleToken(); private bool _removeDepleted; private bool _disposed; private int _prefabCursor; private int _sectorCursor; private int _added; private int _retired; private IReadOnlyList _markers = Array.Empty(); private static readonly (string Name, ResourceKind Kind, string Drop, string? Successor)[] Catalog = new(string, ResourceKind, string, string)[10] { ("rock4_copper", ResourceKind.Copper, "CopperOre", "rock4_copper_frac"), ("rock4_copper_frac", ResourceKind.Copper, "CopperOre", null), ("MineRock_Copper", ResourceKind.Copper, "CopperOre", null), ("MineRock_Tin", ResourceKind.Tin, "TinOre", null), ("silvervein", ResourceKind.Silver, "SilverOre", "silvervein_frac"), ("silvervein_frac", ResourceKind.Silver, "SilverOre", null), ("rock3_silver", ResourceKind.Silver, "SilverOre", "rock3_silver_frac"), ("rock3_silver_frac", ResourceKind.Silver, "SilverOre", null), ("MineRock_Obsidian", ResourceKind.Obsidian, "Obsidian", null), ("MineRock_Meteorite", ResourceKind.Flametal, "FlametalOreNew", null) }; private readonly Dictionary _progressCache = new Dictionary(); public SharedMapResources(ZDOMan world, SharedMapResourceStore store, SharedMapMarkerRefresh refresh, SharedMapExploration map, SharedMapSettings settings, SharedMapDiagnostics diagnostics, Action failed, IPlayerPresence presence, PlayerRoutedMessages messages) { _world = world; _store = store; _refresh = refresh; _map = map; _settings = settings; _diagnostics = diagnostics; _failed = failed; _silverDiscovery = new SharedMapSilverDiscovery(world, presence, messages, MiningImpact, failed); } public void Install() { List list = new List(); (string, ResourceKind, string, string)[] catalog = Catalog; for (int i = 0; i < catalog.Length; i++) { (string, ResourceKind, string, string) tuple = catalog[i]; SharedMapResourcePrefab sharedMapResourcePrefab = SharedMapResourcePrefab.Read(tuple.Item1, tuple.Item2, tuple.Item3, tuple.Item4); if (sharedMapResourcePrefab == null) { list.Add(tuple.Item1); continue; } _prefabs.Add(sharedMapResourcePrefab.Hash, sharedMapResourcePrefab); _scanPrefabs.Add(sharedMapResourcePrefab); } _diagnostics.UnsupportedResources(list); _silverDiscovery.Install(); ZDOMan world = _world; world.m_onZDODestroyed = (Action)Delegate.Combine(world.m_onZDODestroyed, new Action(Destroyed)); } public static void CheckCompatibility() { if (typeof(ZDOMan).GetField("m_onZDODestroyed")?.FieldType != typeof(Action) || typeof(ZDOMan).GetMethod("FindSectorObjects", new Type[4] { typeof(Vector2s), typeof(SimulationDistance), typeof(List), typeof(List) }) == null) { throw new MissingMemberException("Native resource record discovery/destruction APIs are unavailable."); } } private bool Eligible(ZDO zdo, out SharedMapResourcePrefab prefab, out Vector3 position) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0041: Unknown result type (might be due to invalid IL or missing references) //IL_0046: Unknown result type (might be due to invalid IL or missing references) //IL_0073: Unknown result type (might be due to invalid IL or missing references) position = default(Vector3); prefab = null; if (!zdo.IsValid() || !zdo.Persistent || !_prefabs.TryGetValue(zdo.GetPrefab(), out prefab) || zdo.GetLong(ZDOVars.s_creator, 0L) != 0L) { return false; } position = zdo.GetPosition(); if (SharedMapExploration.Finite(position.x) && SharedMapExploration.Finite(position.y) && SharedMapExploration.Finite(position.z)) { return !Character.InInterior(position); } return false; } private MiningProgress? Progress(ZDO zdo, SharedMapResourcePrefab prefab) { //IL_0007: 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_005d: Unknown result type (might be due to invalid IL or missing references) if (_progressCache.TryGetValue(zdo.m_uid, out (ZDO, SharedMapResourcePrefab, uint, MiningProgress?) value) && value.Item1 == zdo && value.Item2 == prefab && value.Item3 == zdo.DataRevision) { return value.Item4; } MiningProgress? miningProgress = prefab.Progress(zdo); if (_progressCache.Count < 65536 || _progressCache.ContainsKey(zdo.m_uid)) { _progressCache[zdo.m_uid] = (zdo, prefab, zdo.DataRevision, miningProgress); } return miningProgress; } private bool? Depleted(ZDO zdo, SharedMapResourcePrefab prefab) { MiningProgress? miningProgress = Progress(zdo, prefab); if (!miningProgress.HasValue) { return null; } return miningProgress.Value.RemainingSections == 0; } private void Observe(ZDO zdo, SharedMapResourcePrefab prefab, Vector3 position, bool discoverSilver = false, MiningProgress? handoff = null) { //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_00ce: Unknown result type (might be due to invalid IL or missing references) //IL_00d4: 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) int count = _store.Deposits.Count; bool ambiguous; ResourceDeposit resourceDeposit = _store.Find(prefab.Kind, position.x, position.y, position.z, out ambiguous); bool flag = resourceDeposit?.Depleted ?? false; bool flag2 = resourceDeposit != null && prefab.Kind == ResourceKind.Silver && !resourceDeposit.SilverDiscovered; MiningProgress? progress = ((prefab.Kind != ResourceKind.Copper && prefab.Kind != ResourceKind.Silver) ? ((MiningProgress?)null) : (handoff ?? Progress(zdo, prefab))); bool? depleted = (progress.HasValue ? new bool?(progress.Value.RemainingSections == 0) : Depleted(zdo, prefab)); ResourceDeposit resourceDeposit2 = _store.Observe(prefab.Kind, position.x, position.y, position.z, depleted, allowNew: true, progress, discoverSilver); _added += _store.Deposits.Count - count; if (resourceDeposit2 != null && flag2 && resourceDeposit2.SilverDiscovered) { _added++; } if (resourceDeposit2 != null && !flag && resourceDeposit2.Depleted) { _retired++; } } internal bool Observes(int prefab) { if (prefab != SharedMapSilverDiscovery.TerrainPrefab) { if (_prefabs.TryGetValue(prefab, out SharedMapResourcePrefab value)) { return value.Kind == ResourceKind.Silver; } return false; } return true; } internal float HealthBaseline(ZDO zdo) { if (!_prefabs.TryGetValue(zdo.GetPrefab(), out SharedMapResourcePrefab value)) { return float.NaN; } return value.HealthBaseline(zdo); } internal void Accepted(ZDO zdo, MapReplicationSnapshot before) { SharedMapResourcePrefab prefab; Vector3 position; if (zdo.GetPrefab() == SharedMapSilverDiscovery.TerrainPrefab) { _silverDiscovery.AcceptedTerrain(zdo, before.Terrain); } else if (Eligible(zdo, out prefab, out position) && prefab.Kind == ResourceKind.Silver) { _silverDiscovery.AcceptedSilver(zdo, before); } } private void MiningImpact(Vector3 point, ZDOID directTarget) { //IL_0178: Unknown result type (might be due to invalid IL or missing references) //IL_0179: Unknown result type (might be due to invalid IL or missing references) //IL_0181: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0062: Unknown result type (might be due to invalid IL or missing references) //IL_0201: Unknown result type (might be due to invalid IL or missing references) //IL_0208: Unknown result type (might be due to invalid IL or missing references) //IL_020f: Unknown result type (might be due to invalid IL or missing references) //IL_02c5: Unknown result type (might be due to invalid IL or missing references) //IL_0093: Unknown result type (might be due to invalid IL or missing references) //IL_022b: Unknown result type (might be due to invalid IL or missing references) //IL_0233: Unknown result type (might be due to invalid IL or missing references) //IL_023b: Unknown result type (might be due to invalid IL or missing references) //IL_0243: Unknown result type (might be due to invalid IL or missing references) if (!((ZDOID)(ref directTarget)).IsNone()) { ZDO zDO = _world.GetZDO(directTarget); if (zDO != null && Eligible(zDO, out SharedMapResourcePrefab prefab, out Vector3 position) && prefab.Kind == ResourceKind.Silver) { if (Depleted(zDO, prefab) == false) { Observe(zDO, prefab, position, discoverSilver: true); } else if (prefab.ReplacesWithMining && prefab.HealthBaseline(zDO) <= 0f) { Observe(zDO, prefab, position, discoverSilver: true, prefab.InitialProgress); } return; } GameObject val = ((zDO == null) ? null : PrefabRegistry.Current.Prefab(zDO.GetPrefab())); if ((Object)(object)val == (Object)null || zDO.GetLong(ZDOVars.s_creator, 0L) != 0L || (Object)(object)PrefabRegistry.Component(val) != (Object)null || (Object)(object)PrefabRegistry.Component(val) != (Object)null || (Object)(object)PrefabRegistry.Component(val) != (Object)null || ((Object)(object)PrefabRegistry.Component(val) == (Object)null && (Object)(object)PrefabRegistry.Component(val) == (Object)null && (Object)(object)PrefabRegistry.Component(val) == (Object)null)) { return; } } float value = _settings.SilverDiscoveryRadiusMeters.Value; _miningNear.Clear(); int num = (int)Math.Ceiling(value / ZoneSystem.instance.m_zoneSize) + 1; WorldObjectProvider.Current.For("SharedMap").Query(ZoneSystem.GetZone(point), new SimulationDistance(num, 0, true), _miningNear); ZDO val2 = null; double num2 = (double)value * (double)value; foreach (ZDO item in _miningNear) { if (!Eligible(item, out SharedMapResourcePrefab prefab2, out Vector3 position2) || prefab2.Kind != ResourceKind.Silver) { continue; } bool? flag = Depleted(item, prefab2); bool ambiguous = false; if (flag != ambiguous) { continue; } ResourceDeposit? resourceDeposit = _store.Find(ResourceKind.Silver, position2.x, position2.y, position2.z, out ambiguous); if (resourceDeposit == null || !resourceDeposit.SilverDiscovered) { double num3 = (double)position2.x - (double)point.x; double num4 = (double)position2.z - (double)point.z; double num5 = num3 * num3 + num4 * num4; if (!(num5 > num2) && (num5 != num2 || val2 == null || string.CompareOrdinal(((object)Unsafe.As(ref item.m_uid)/*cast due to .constrained prefix*/).ToString(), ((object)Unsafe.As(ref val2.m_uid)/*cast due to .constrained prefix*/).ToString()) < 0)) { val2 = item; num2 = num5; } } } if (val2 != null && Eligible(val2, out SharedMapResourcePrefab prefab3, out Vector3 position3)) { Observe(val2, prefab3, position3, discoverSilver: true); } } public void Sample(long player, Vector3 position) { //IL_007d: Unknown result type (might be due to invalid IL or missing references) //IL_007e: Unknown result type (might be due to invalid IL or missing references) //IL_0086: 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_00df: Unknown result type (might be due to invalid IL or missing references) //IL_00e7: Unknown result type (might be due to invalid IL or missing references) //IL_00ef: Unknown result type (might be due to invalid IL or missing references) //IL_010c: Unknown result type (might be due to invalid IL or missing references) //IL_0120: Unknown result type (might be due to invalid IL or missing references) //IL_01a5: Unknown result type (might be due to invalid IL or missing references) //IL_01c8: Unknown result type (might be due to invalid IL or missing references) _near.Clear(); _candidates.Clear(); _seen.Clear(); if (!SharedMapExploration.Finite(ZoneSystem.instance.m_zoneSize) || ZoneSystem.instance.m_zoneSize < 16f) { throw new InvalidOperationException("Unsupported native resource-sector geometry."); } int num = (int)Math.Ceiling(_map.Radius / ZoneSystem.instance.m_zoneSize) + 1; WorldObjectProvider.Current.For("SharedMap").Query(ZoneSystem.GetZone(position), new SimulationDistance(num, 0, true), _near); double num2 = (double)_map.Radius * (double)_map.Radius; foreach (ZDO item in _near) { if (Eligible(item, out SharedMapResourcePrefab _, out Vector3 position2)) { double num3 = (double)position2.x - (double)position.x; double num4 = (double)position2.z - (double)position.z; if (num3 * num3 + num4 * num4 <= num2 && _seen.Add(item.m_uid)) { _candidates.Add(item.m_uid); } } } if (_candidates.Count == 0) { return; } _playerCursors.TryGetValue(player, out var value); value %= _candidates.Count; int num5 = Math.Min(256, _candidates.Count); for (int i = 0; i < num5; i++) { ZDO zDO = _world.GetZDO(_candidates[(value + i) % _candidates.Count]); if (zDO != null && Eligible(zDO, out SharedMapResourcePrefab prefab2, out Vector3 position3)) { Observe(zDO, prefab2, position3); } } _playerCursors[player] = (value + num5) % _candidates.Count; } public void Tick(float now) { //IL_0142: Unknown result type (might be due to invalid IL or missing references) //IL_00c3: Unknown result type (might be due to invalid IL or missing references) //IL_0166: 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_0180: Unknown result type (might be due to invalid IL or missing references) if (_disposed || !_settings.ResourceDiscoverPreviouslyExplored.Value || _scanPrefabs.Count <= 0 || !_nextRetro.Ready(now)) { return; } if (_retrospective.Count == 0) { _scan.Clear(); bool allZDOsWithPrefabIterative = _world.GetAllZDOsWithPrefabIterative(_scanPrefabs[_prefabCursor].Name, _scan, ref _sectorCursor); if (_scan.Count > 65536) { throw new InvalidOperationException("Resource scan candidate limit exceeded; discoveries were retained."); } foreach (ZDO item in _scan) { _retrospective.Enqueue(item.m_uid); } if (allZDOsWithPrefabIterative) { _sectorCursor = 0; if (++_prefabCursor == _scanPrefabs.Count) { _prefabCursor = 0; _nextRetro.Postpone(now, _settings.TableIntervalSeconds.Value); } } } for (int i = 0; i < 256; i++) { if (_retrospective.Count <= 0) { break; } ZDO zDO = _world.GetZDO(_retrospective.Dequeue()); if (zDO != null && Eligible(zDO, out SharedMapResourcePrefab prefab, out Vector3 position) && _map.IsExplored(position.x, position.z)) { Observe(zDO, prefab, position); } } } public IReadOnlyList Read() { if (_markerRevision != _store.Revision || _distance != _settings.ResourceClusterDistanceMeters.Value || _removeDepleted != _settings.ResourceRemoveDepleted.Value) { _markers = _refresh.Apply(SharedMapResourceClusters.Group(_store.Deposits, _settings.ResourceClusterDistanceMeters.Value, _settings.ResourceRemoveDepleted.Value)); _markerRevision = _store.Revision; _distance = _settings.ResourceClusterDistanceMeters.Value; _removeDepleted = _settings.ResourceRemoveDepleted.Value; } return _markers; } public void Report(float now) { _diagnostics.ResourceResults(_added, _retired); _added = (_retired = 0); _diagnostics.ResourceCatalog(now, _store.Deposits.Count, _markers.Count, _settings.ResourceDiscoverPreviouslyExplored.Value); } private void Destroyed(ZDO zdo) { //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Unknown result type (might be due to invalid IL or missing references) //IL_0039: Unknown result type (might be due to invalid IL or missing references) if (_disposed) { return; } try { if (Eligible(zdo, out SharedMapResourcePrefab prefab, out Vector3 position) && !prefab.ReplacesWithMining && _store.Retire(prefab.Kind, position.x, position.y, position.z)) { _retired++; } } catch (Exception obj) { _failed(obj); } } public void Dispose() { _progressCache.Clear(); if (!_disposed) { _disposed = true; ZDOMan world = _world; world.m_onZDODestroyed = (Action)Delegate.Remove(world.m_onZDODestroyed, new Action(Destroyed)); _silverDiscovery.Dispose(); _miningNear.Clear(); _near.Clear(); _scan.Clear(); _candidates.Clear(); _seen.Clear(); _retrospective.Clear(); _playerCursors.Clear(); _added = (_retired = 0); } } } public sealed class SharedMapResourceStore { private const uint Magic = 1146243912u; public const int MaximumDeposits = 65536; private readonly long _world; private readonly List _deposits = new List(); private readonly Dictionary<(int, int), List> _cells = new Dictionary<(int, int), List>(); private long _revision; private long _savedRevision; private readonly ScheduleToken _nextSave = new ScheduleToken(); public string FilePath { get; } public long Revision => _revision; public IReadOnlyList Deposits => _deposits; public SharedMapResourceStore(string directory, long world) { _world = world; FilePath = Path.Combine(directory, "world-" + world.ToString("X16", CultureInfo.InvariantCulture) + ".resources"); } private void Add(ResourceDeposit deposit) { _deposits.Add(deposit); (int, int) key = ((int)Math.Floor(deposit.X), (int)Math.Floor(deposit.Z)); if (!_cells.TryGetValue(key, out List value)) { _cells.Add(key, value = new List()); } value.Add(deposit); } public ResourceDeposit? Find(ResourceKind kind, float x, float y, float z, out bool ambiguous) { ambiguous = false; ResourceDeposit resourceDeposit = null; if (!ValidPosition(x, y, z)) { return null; } int num = (int)Math.Floor(x); int num2 = (int)Math.Floor(z); for (int i = num - 1; i <= num + 1; i++) { for (int j = num2 - 1; j <= num2 + 1; j++) { if (!_cells.TryGetValue((i, j), out List value)) { continue; } foreach (ResourceDeposit item in value) { double num3 = (double)item.X - (double)x; double num4 = (double)item.Y - (double)y; double num5 = (double)item.Z - (double)z; if (item.Kind == kind && !(num3 * num3 + num4 * num4 + num5 * num5 > 0.25)) { if (resourceDeposit != null) { ambiguous = true; return null; } resourceDeposit = item; } } } } return resourceDeposit; } public ResourceDeposit? Observe(ResourceKind kind, float x, float y, float z, bool? depleted, bool allowNew, MiningProgress? progress = null, bool silverDiscovered = false) { if (!Enum.IsDefined(typeof(ResourceKind), kind) || !ValidPosition(x, y, z)) { return null; } if (progress.HasValue && ((kind != ResourceKind.Copper && kind != ResourceKind.Silver) || progress.Value.TotalSections < 1 || progress.Value.TotalSections > 8192 || progress.Value.RemainingSections < 0 || progress.Value.RemainingSections > progress.Value.TotalSections || (depleted.HasValue && depleted.Value != (progress.Value.RemainingSections == 0)))) { throw new ArgumentException("Invalid observed resource progress.", "progress"); } bool ambiguous; ResourceDeposit resourceDeposit = Find(kind, x, y, z, out ambiguous); if (ambiguous || (kind == ResourceKind.Silver && !silverDiscovered && (resourceDeposit == null || !resourceDeposit.SilverDiscovered))) { return null; } if (resourceDeposit == null) { if (!allowNew || depleted != false) { return null; } if (_deposits.Count >= 65536) { throw new InvalidOperationException("Resource discovery storage limit exceeded; existing discoveries were retained."); } resourceDeposit = new ResourceDeposit(_deposits.Count + 1, kind, x, y, z); Add(resourceDeposit); _revision++; } else if (depleted.HasValue && resourceDeposit.Depleted != depleted.Value) { resourceDeposit.Depleted = depleted.Value; _revision++; } if (kind == ResourceKind.Silver && silverDiscovered && !resourceDeposit.SilverDiscovered) { resourceDeposit.SilverDiscovered = true; _revision++; } if (progress.HasValue && (!resourceDeposit.Progress.HasValue || resourceDeposit.Progress.Value.TotalSections != progress.Value.TotalSections || resourceDeposit.Progress.Value.RemainingSections != progress.Value.RemainingSections)) { resourceDeposit.Progress = progress; _revision++; } if (resourceDeposit.Depleted && resourceDeposit.Progress.HasValue && resourceDeposit.Progress.Value.RemainingSections != 0) { resourceDeposit.Progress = new MiningProgress(0, resourceDeposit.Progress.Value.TotalSections); _revision++; } return resourceDeposit; } public bool Retire(ResourceKind kind, float x, float y, float z) { bool ambiguous; ResourceDeposit resourceDeposit = Find(kind, x, y, z, out ambiguous); if (resourceDeposit == null || resourceDeposit.Depleted) { return false; } resourceDeposit.Depleted = true; if (resourceDeposit.Progress.HasValue) { resourceDeposit.Progress = new MiningProgress(0, resourceDeposit.Progress.Value.TotalSections); } _revision++; return true; } private static bool ValidPosition(float x, float y, float z) { if (SharedMapExploration.Finite(x) && SharedMapExploration.Finite(y) && SharedMapExploration.Finite(z) && Math.Abs(x) <= 100000f && Math.Abs(y) <= 100000f) { return Math.Abs(z) <= 100000f; } return false; } public bool Load() { if (!File.Exists(FilePath)) { if (File.Exists(FilePath + ".bak")) { throw new InvalidDataException("Resource discoveries are missing but their backup exists: " + FilePath); } return false; } using FileStream fileStream = new FileStream(FilePath, FileMode.Open, FileAccess.Read, FileShare.Read); if (fileStream.Length < 52 || fileStream.Length > 1966132) { throw new InvalidDataException("Invalid resource discovery file length."); } using BinaryReader binaryReader = new BinaryReader(fileStream); byte[] buffer = binaryReader.ReadBytes((int)fileStream.Length - 32); byte[] array = binaryReader.ReadBytes(32); using SHA256 sHA = SHA256.Create(); if (!((ReadOnlySpan)sHA.ComputeHash(buffer)).SequenceEqual((ReadOnlySpan)array)) { throw new InvalidDataException("Resource discovery checksum mismatch."); } using BinaryReader binaryReader2 = new BinaryReader(new MemoryStream(buffer, writable: false)); uint num = binaryReader2.ReadUInt32(); int num2 = binaryReader2.ReadInt32(); long num3 = binaryReader2.ReadInt64(); if (num != 1146243912 || num2 < 1 || num2 > 3 || num3 != _world) { throw new InvalidDataException("Unsupported resource discovery format or world."); } int num4 = binaryReader2.ReadInt32(); if (num4 < 0 || num4 > 65536 || binaryReader2.BaseStream.Length != 20 + num4 * num2 switch { 2 => 29L, 1 => 21L, _ => 30L, }) { throw new InvalidDataException("Invalid resource discovery count or length."); } List list = new List(); for (int i = 0; i < num4; i++) { int num5 = binaryReader2.ReadInt32(); int num6 = binaryReader2.ReadInt32(); float x = binaryReader2.ReadSingle(); float y = binaryReader2.ReadSingle(); float z = binaryReader2.ReadSingle(); byte b = binaryReader2.ReadByte(); int num7 = ((num2 >= 2) ? binaryReader2.ReadInt32() : (-1)); int num8 = ((num2 >= 2) ? binaryReader2.ReadInt32() : 0); byte b2 = (byte)((num2 >= 3) ? binaryReader2.ReadByte() : 0); if (b2 > 1 || (num6 != 2 && b2 != 0)) { throw new InvalidDataException("Invalid Silver discovery evidence."); } if (num5 != i + 1 || !Enum.IsDefined(typeof(ResourceKind), num6) || !ValidPosition(x, y, z) || b > 1) { throw new InvalidDataException("Invalid resource discovery record."); } if ((num7 != -1 || num8 != 0) && ((num6 != 0 && num6 != 2) || num8 < 1 || num8 > 8192 || num7 < 0 || num7 > num8 || b != 0 != (num7 == 0))) { throw new InvalidDataException("Invalid resource discovery progress."); } MiningProgress? progress = ((num8 > 0) ? new MiningProgress?(new MiningProgress(num7, num8)) : ((MiningProgress?)null)); list.Add(new ResourceDeposit(num5, (ResourceKind)num6, x, y, z, b != 0, progress, b2 != 0)); } _deposits.Clear(); _cells.Clear(); foreach (ResourceDeposit item in list) { Add(item); } _revision = (_savedRevision = 0L); return true; } public bool SaveIfDue(float now, float interval) { if (!_nextSave.Ready(now)) { return false; } _nextSave.Postpone(now, interval); return Save(); } public bool Save() { if (_revision == _savedRevision) { return false; } Directory.CreateDirectory(Path.GetDirectoryName(FilePath)); string text = FilePath + "." + Guid.NewGuid().ToString("N") + ".tmp"; try { using MemoryStream memoryStream = new MemoryStream(); using (BinaryWriter binaryWriter = new BinaryWriter(memoryStream, Encoding.UTF8, leaveOpen: true)) { binaryWriter.Write(1146243912u); binaryWriter.Write(3); binaryWriter.Write(_world); binaryWriter.Write(_deposits.Count); foreach (ResourceDeposit deposit in _deposits) { binaryWriter.Write(deposit.Identity); binaryWriter.Write((int)deposit.Kind); binaryWriter.Write(deposit.X); binaryWriter.Write(deposit.Y); binaryWriter.Write(deposit.Z); binaryWriter.Write(deposit.Depleted); binaryWriter.Write(deposit.Progress?.RemainingSections ?? (-1)); binaryWriter.Write(deposit.Progress?.TotalSections ?? 0); binaryWriter.Write(deposit.SilverDiscovered); } } byte[] array = memoryStream.ToArray(); using SHA256 sHA = SHA256.Create(); using (FileStream fileStream = new FileStream(text, FileMode.CreateNew, FileAccess.Write, FileShare.None)) { fileStream.Write(array, 0, array.Length); byte[] array2 = sHA.ComputeHash(array); fileStream.Write(array2, 0, array2.Length); fileStream.Flush(flushToDisk: true); } if (File.Exists(FilePath)) { File.Replace(text, FilePath, FilePath + ".bak"); } else { File.Move(text, FilePath); } _savedRevision = _revision; return true; } finally { if (File.Exists(text)) { File.Delete(text); } } } } public sealed class SharedMapSettings { public ConfigEntry Enabled { get; } public ConfigEntry DebugMode { get; } public ConfigEntry PinDebugNameFilter { get; } public ConfigEntry PortalMarkerSync { get; } public ConfigEntry PortalClusterDistanceMeters { get; } public ConfigEntry ResourceMarkerSync { get; } public ConfigEntry ResourceDiscoverPreviouslyExplored { get; } public ConfigEntry ResourceClusterDistanceMeters { get; } public ConfigEntry ResourceMarkerHideDistanceMeters { get; } public ConfigEntry SilverDiscoveryRadiusMeters { get; } public ConfigEntry ResourceRemoveDepleted { get; } public ConfigEntry DungeonMarkerSync { get; } public ConfigEntry DungeonDiscoverPreviouslyExplored { get; } public ConfigEntry AllowPlayerMapWrites { get; } public ConfigEntry SharePinCheckmarks { get; } public ConfigEntry DungeonLootProgress { get; } public ConfigEntry RunestoneMarkerSync { get; } public ConfigEntry SpawnerMarkerSync { get; } public ConfigEntry TableIntervalSeconds { get; } public ConfigEntry MaxTablesPerPass { get; } public ConfigEntry SaveIntervalSeconds { get; } public ConfigEntry GlobalDebugMode { get; } public DebugLoggingPolicy DebugLogging { get; } public SharedMapSettings(ConfigFile config, ManualLogSource? logger = null) { //IL_0068: Unknown result type (might be due to invalid IL or missing references) //IL_0072: Expected O, but got Unknown //IL_00d9: Unknown result type (might be due to invalid IL or missing references) //IL_00e3: Expected O, but got Unknown //IL_0112: Unknown result type (might be due to invalid IL or missing references) //IL_011c: Expected O, but got Unknown //IL_014b: Unknown result type (might be due to invalid IL or missing references) //IL_0155: Expected O, but got Unknown //IL_0264: Unknown result type (might be due to invalid IL or missing references) //IL_026e: Expected O, but got Unknown //IL_0291: Unknown result type (might be due to invalid IL or missing references) //IL_029b: Expected O, but got Unknown //IL_02ca: Unknown result type (might be due to invalid IL or missing references) //IL_02d4: Expected O, but got Unknown Enabled = config.Bind("SharedMap", "Enabled", true, "Persist community exploration and normalize vanilla table map data, excluding shared death pins. Optionally add player-built portals, outdoor resource deposits and supported dungeon entrances. Restart after edits."); PortalMarkerSync = config.Bind("SharedMap", "PortalMarkerSync", true, "Automatically maintain named player-built portal markers in explored terrain. Replace all portal-icon pins from server portal records, blocking stale names and positions. Renamed markers use small persistent offsets to encourage replacement on Read Map; client replacement is not guaranteed. Player hammer pins are preserved. Other icons are preserved except matching portal labels within three metres of a generated marker. Disabling removes generated portal pins while preserving player-owned pins. Restart after edits."); PortalClusterDistanceMeters = config.Bind("SharedMap", "PortalClusterDistanceMeters", 60f, new ConfigDescription("Group portals within this horizontal distance of a group's first portal into one Multi Portals marker at their centre. Zero shows separate portal markers. Restart after edits.", (AcceptableValueBase)(object)new AcceptableValueRange(0f, 100f), Array.Empty())); ResourceMarkerSync = config.Bind("SharedMap", "ResourceMarkerSync", true, "Record outdoor Copper, Tin, Silver, Obsidian and static Flametal deposits and share dot markers through Read Map. Excludes scraps, dungeons, creatures and ordinary stone. Independent of PortalMarkerSync. Restart after edits."); ResourceDiscoverPreviouslyExplored = config.Bind("SharedMap", "ResourceDiscoverPreviouslyExplored", false, "Also discover remaining eligible deposits in previously community-explored terrain without a player revisit. False collects only within current player exploration range. Silver always requires mining discovery evidence. Previously recorded discoveries persist either way. Restart after edits."); ResourceClusterDistanceMeters = config.Bind("SharedMap", "ResourceClusterDistanceMeters", 30f, new ConfigDescription("Group same-type discoveries within this horizontal distance of a fixed first discovery. Tin groups show remaining discovered node counts; zero disables grouping. Restart after edits.", (AcceptableValueBase)(object)new AcceptableValueRange(0f, 100f), Array.Empty())); ResourceMarkerHideDistanceMeters = config.Bind("SharedMap", "ResourceMarkerHideDistanceMeters", 10f, new ConfigDescription("Hide generated resource markers at or within this horizontal distance of published portal, dungeon, runestone or physical-spawner markers. Compare final publication positions; discoveries and depletion tracking are retained. Personal pins and resource-to-resource grouping are unchanged. Zero disables hiding. Restart after edits.", (AcceptableValueBase)(object)new AcceptableValueRange(0f, 100f), Array.Empty())); SilverDiscoveryRadiusMeters = config.Bind("SharedMap", "SilverDiscoveryRadiusMeters", 10f, new ConfigDescription("Reveal only the nearest undiscovered Silver vein within this horizontal distance of an observed player pickaxe impact. A direct pickaxe hit always selects the struck eligible Silver vein. Old explored terrain cannot bypass mining discovery. Restart after edits.", (AcceptableValueBase)(object)new AcceptableValueRange(1f, 30f), Array.Empty())); ResourceRemoveDepleted = config.Bind("SharedMap", "ResourceRemoveDepleted", true, "Remove resource nodes only after confirmed terminal destruction or complete depleted health. Missing/unloaded records never establish depletion. False retains historical nodes in markers. Restart after edits."); DungeonMarkerSync = config.Bind("SharedMap", "DungeonMarkerSync", true, "Record supported dungeon exterior entrances within native player exploration range and share labeled hammer markers through Read Map. Publish one dungeon anchor within ten horizontal metres and clean nearby uploaded dungeon-labeled hammer copies. Retain independent saved discoveries. Independent of portal and resource markers. Disabling retains discoveries and removes generated dungeon pins during normalization. Restart after edits."); DungeonLootProgress = config.Bind("SharedMap", "DungeonLootProgress", true, "Show remaining permanent-pickup percentages after observed entry or verified already-picked items. Supported empty inventories show 0%. Visits persist across restarts. Restart after edits."); SharePinCheckmarks = config.Bind("SharedMap", "SharePinCheckmarks", false, "Share player X checkmarks through accepted Write Map uploads and Read Map. Requires AllowPlayerMapWrites. False leaves player checkmarks personal. Manual checkmarks do not change dungeon pickup percentages. Restart after edits."); DungeonDiscoverPreviouslyExplored = config.Bind("SharedMap", "DungeonDiscoverPreviouslyExplored", false, "Also discover supported placed dungeon entrances in previously community-explored terrain without a revisit. Never reveals entrances in unexplored terrain or generates locations. Existing discoveries persist either way. Restart after edits."); AllowPlayerMapWrites = config.Bind("SharedMap", "AllowPlayerMapWrites", true, "Accept player cartography uploads, including exploration and ordinary pins. False rejects incoming map-field changes before importing terrain, retaining server data and Read Map. Vanilla clients still show Write Map and may report success locally. Existing table data and first-run import are retained. Restart after edits."); RunestoneMarkerSync = config.Bind("SharedMap", "RunestoneMarkerSync", true, "Record validated placed lore runestones within native exploration range or saved community exploration and share dot markers. Disabling removes generated table pins and retains discovery history. Independent of other marker switches. Restart after edits."); SpawnerMarkerSync = config.Bind("SharedMap", "SpawnerMarkerSync", true, "Record visible, player-destructible persistent recurring spawner objects within native exploration range or saved community exploration and share dot markers. Hide confirmed destroyed sources. Excludes invisible spawn points, one-shot sources and unassociated interiors. Independent of other marker switches. Restart after edits."); TableIntervalSeconds = config.Bind("SharedMap", "TableIntervalSeconds", 10f, new ConfigDescription("Seconds between nearby table reconciliation passes.", (AcceptableValueBase)(object)new AcceptableValueRange(2f, 120f), Array.Empty())); MaxTablesPerPass = config.Bind("SharedMap", "MaxTablesPerPass", 1, new ConfigDescription("Maximum table payloads per first-run import tick, periodic reconciliation pass or requested pin-administration tick; incoming writes and new tables are handled at their native event.", (AcceptableValueBase)(object)new AcceptableValueRange(1, 8), Array.Empty())); SaveIntervalSeconds = config.Bind("SharedMap", "SaveIntervalSeconds", 60f, new ConfigDescription("Seconds between dirty community-map saves; lifecycle transitions flush without waiting.", (AcceptableValueBase)(object)new AcceptableValueRange(10f, 600f), Array.Empty())); PinDebugNameFilter = config.Bind("SharedMap", "PinDebugNameFilter", "", "Limit per-pin Debug detail to this exact case-sensitive label, or leave empty to sample all labels. Summary counts cover all labels. Requires effective Debug logging; does not affect pins or normal output. Restart after edits."); GlobalDebugMode = DiagnosticsSettings.Bind(config); DebugMode = config.Bind("SharedMap", "DebugMode", false, "Enable this module's diagnostics even when global DebugMode is off. The hidden suppression override still applies. Restart after edits."); DebugLogging = DebugLoggingResolver.Resolve(config, "SharedMap", GlobalDebugMode, logger, DebugMode); } } internal sealed class SharedMapSilverDiscovery : IDisposable { internal static readonly int TerrainPrefab = StringExtensionMethods.GetStableHashCode("_TerrainCompiler"); private readonly ZDOMan _world; private readonly IPlayerPresence _presence; private readonly PlayerRoutedMessages _messages; private readonly Action _impact; private readonly Action _failed; private readonly Dictionary _recent = new Dictionary(); private IDisposable? _subscription; private int _terrainBudget; private float _terrainWindow; public SharedMapSilverDiscovery(ZDOMan world, IPlayerPresence presence, PlayerRoutedMessages messages, Action impact, Action failed) { _world = world; _presence = presence; _messages = messages; _impact = impact; _failed = failed; } public void Install() { if ((Object)(object)PrefabRegistry.Component(PrefabRegistry.Current.Prefab(TerrainPrefab)) == (Object)null) { throw new InvalidOperationException("Native terrain compiler is unavailable for Silver discovery."); } _subscription = _messages.Subscribe(Observe, _failed); } private bool Actor(ZNetPeer peer, out ZDO actor, out Vector3 position, out string animation) { //IL_0004: 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_007e: 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_0099: Unknown result type (might be due to invalid IL or missing references) //IL_00a6: Unknown result type (might be due to invalid IL or missing references) //IL_00e5: Unknown result type (might be due to invalid IL or missing references) //IL_00ec: Invalid comparison between Unknown and I4 actor = null; position = default(Vector3); animation = ""; if (!peer.IsReady() || ((ZDOID)(ref peer.m_characterID)).IsNone()) { return false; } actor = _world.GetZDO(peer.m_characterID); if (actor == null || !actor.IsValid() || actor.GetOwner() != peer.m_uid || actor.GetBool(ZDOVars.s_dead, false)) { return false; } float num = actor.GetFloat(ZDOVars.s_health, float.NaN); position = actor.GetPosition(); if (!SharedMapExploration.Finite(num) || num <= 0f || !Finite(position) || Character.InInterior(position)) { return false; } ItemDrop val = PrefabRegistry.Component(PrefabRegistry.Current.Prefab(actor.GetInt(ZDOVars.s_rightItem, 0))); if ((Object)(object)val == (Object)null || (int)val.m_itemData.m_shared.m_skillType != 12) { return false; } animation = val.m_itemData.m_shared.m_attack?.m_attackAnimation ?? ""; return animation.Length > 0; } private static bool Finite(Vector3 point) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_001a: Unknown result type (might be due to invalid IL or missing references) if (SharedMapExploration.Finite(point.x) && SharedMapExploration.Finite(point.y)) { return SharedMapExploration.Finite(point.z); } return false; } private static bool Near(Vector3 actor, Vector3 point) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_0009: Unknown result type (might be due to invalid IL or missing references) //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Unknown result type (might be due to invalid IL or missing references) if (Finite(point)) { Vector3 val = actor - point; return ((Vector3)(ref val)).sqrMagnitude <= 64f; } return false; } private static bool AttackTrigger(string trigger, string animation) { if (trigger == animation) { return true; } if (!trigger.StartsWith(animation, StringComparison.Ordinal) || trigger.Length > animation.Length + 2) { return false; } string text = trigger.Substring(animation.Length); if (text.Length > 0) { return text.All((char c) => c >= '0' && c <= '9'); } return false; } private void Observe(ZRpc rpc, ZPackage packet) { //IL_01ec: Unknown result type (might be due to invalid IL or missing references) //IL_00cf: Unknown result type (might be due to invalid IL or missing references) //IL_00d2: Unknown result type (might be due to invalid IL or missing references) //IL_02f2: Unknown result type (might be due to invalid IL or missing references) //IL_02f9: Expected O, but got Unknown //IL_0332: Unknown result type (might be due to invalid IL or missing references) //IL_0338: Unknown result type (might be due to invalid IL or missing references) //IL_0346: Unknown result type (might be due to invalid IL or missing references) //IL_034d: Invalid comparison between Unknown and I4 //IL_01cd: Unknown result type (might be due to invalid IL or missing references) //IL_0274: 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_0375: Unknown result type (might be due to invalid IL or missing references) //IL_0378: Unknown result type (might be due to invalid IL or missing references) //IL_0294: Unknown result type (might be due to invalid IL or missing references) //IL_038e: Unknown result type (might be due to invalid IL or missing references) //IL_0393: 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_02cd: Unknown result type (might be due to invalid IL or missing references) //IL_02e1: 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) if (_presence.HasJoinedPlayers != true) { return; } ZNetPeer val = ((IEnumerable)_presence.Peers).FirstOrDefault((Func)((ZNetPeer p) => p.IsReady() && p.m_rpc == rpc)); if (val == null || !RoutedActivityReader.TryRead(packet, val.m_uid, out var _, out var method) || (method != StringExtensionMethods.GetStableHashCode("SetTrigger") && method != StringExtensionMethods.GetStableHashCode("RPC_ApplyOperation") && method != StringExtensionMethods.GetStableHashCode("RPC_Damage") && method != StringExtensionMethods.GetStableHashCode("Hit")) || !Actor(val, out ZDO _, out Vector3 position, out string animation) || !RoutedActivityReader.TryReadParameters(packet, val.m_uid, out ZDOID target2, out int _, out ZPackage parameters) || parameters == null) { return; } try { if (method == StringExtensionMethods.GetStableHashCode("SetTrigger")) { string text = parameters.ReadString(); if (target2 != val.m_characterID || text.Length > 128 || parameters.GetPos() != parameters.Size() || !AttackTrigger(text, animation)) { return; } if (_recent.Count >= 4096) { long[] array = (from p in _recent where Time.unscaledTime < p.Value.At || Time.unscaledTime - p.Value.At > 3f select p.Key).ToArray(); foreach (long key in array) { _recent.Remove(key); } } if (_recent.Count < 4096 || _recent.ContainsKey(val.m_uid)) { _recent[val.m_uid] = (val.m_characterID, Time.unscaledTime); } return; } ZDO zDO = _world.GetZDO(target2); if (zDO == null || !zDO.IsValid()) { return; } if (method == StringExtensionMethods.GetStableHashCode("RPC_ApplyOperation")) { if (zDO.GetPrefab() != TerrainPrefab) { return; } int pos = parameters.GetPos(); int num = parameters.ReadInt(); if (num < 17 || num > 64 || parameters.Size() - parameters.GetPos() != num) { return; } parameters.SetPos(pos); ZPackage val2 = parameters.ReadPackage(); Vector3 val3 = val2.ReadVector3(); byte b = val2.ReadByte(); if (b <= 1 && (b == 0 || Finite(val2.ReadVector3()))) { int num2 = val2.ReadInt(); if (val2.GetPos() == val2.Size() && num2 == StringExtensionMethods.GetStableHashCode("digg_v3") && Near(position, val3)) { _impact(val3, ZDOID.None); } } return; } HitData val4 = new HitData(); val4.Deserialize(ref parameters); switch (parameters.Size() - parameters.GetPos()) { case 4: if (parameters.ReadInt() < 0) { return; } break; default: return; case 0: break; } if (!(val4.m_attacker != val.m_characterID) && (int)val4.m_skill == 12 && SharedMapExploration.Finite(val4.m_damage.m_pickaxe) && !(val4.m_damage.m_pickaxe <= 0f) && Near(position, val4.m_point)) { _impact(val4.m_point, target2); } } catch (Exception ex) when (ex is IOException || ex is InvalidDataException || ex is ArgumentException || ex is FormatException) { } } private bool RecentNear(Vector3 point) { //IL_0049: Unknown result type (might be due to invalid IL or missing references) //IL_004f: 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_0086: Unknown result type (might be due to invalid IL or missing references) float unscaledTime = Time.unscaledTime; int num = 0; for (int i = 0; i < _presence.Peers.Count; i++) { ZNetPeer val = _presence.Peers[i]; if (_recent.TryGetValue(val.m_uid, out (ZDOID, float) value) && !(value.Item1 != val.m_characterID) && !(unscaledTime < value.Item2) && !(unscaledTime - value.Item2 > 3f) && Actor(val, out ZDO _, out Vector3 position, out string _) && Near(position, point) && ++num > 1) { return false; } } return num == 1; } public void AcceptedTerrain(ZDO zdo, byte[]? previous) { //IL_0090: Unknown result type (might be due to invalid IL or missing references) //IL_00ad: Unknown result type (might be due to invalid IL or missing references) //IL_00ae: Unknown result type (might be due to invalid IL or missing references) if (_recent.Count == 0 || zdo.GetPrefab() != TerrainPrefab || previous == null) { return; } float unscaledTime = Time.unscaledTime; if (unscaledTime < _terrainWindow || unscaledTime - _terrainWindow >= 1f) { _terrainWindow = unscaledTime; _terrainBudget = 0; } if (_terrainBudget++ >= 32) { return; } TerrainSnapshot terrainSnapshot = SharedMapTerrainData.Read(zdo.GetByteArray(ZDOVars.s_TCData, (byte[])null)); if (terrainSnapshot != null) { Vector3 val = default(Vector3); ((Vector3)(ref val))..ctor(terrainSnapshot.X, terrainSnapshot.Y, terrainSnapshot.Z); if (RecentNear(val) && SharedMapTerrainData.Lowered(SharedMapTerrainData.Read(previous), terrainSnapshot)) { _impact(val, ZDOID.None); } } } public void AcceptedSilver(ZDO zdo, MapReplicationSnapshot before) { //IL_0065: Unknown result type (might be due to invalid IL or missing references) //IL_0078: Unknown result type (might be due to invalid IL or missing references) //IL_007e: Unknown result type (might be due to invalid IL or missing references) if (before.PreviousPrefab == zdo.GetPrefab()) { string text = zdo.GetString(ZDOVars.s_health, ""); float num = zdo.GetFloat(ZDOVars.s_health, float.NaN); if ((text != before.MiningString || (SharedMapExploration.Finite(num) && SharedMapExploration.Finite(before.MiningHealth) && num < before.MiningHealth)) && RecentNear(zdo.GetPosition())) { _impact(zdo.GetPosition(), zdo.m_uid); } } } public void Dispose() { IDisposable subscription = _subscription; _subscription = null; try { subscription?.Dispose(); } finally { _recent.Clear(); } } } public sealed class SharedMapStore { private const uint Magic = 1297304392u; private readonly long _world; private readonly SharedMapExploration _map; private int _savedPixels; private readonly ScheduleToken _nextSave = new ScheduleToken(); private Task? _write; private int _writingPixels; public string FilePath { get; } public SharedMapStore(string directory, long world, SharedMapExploration map) { _world = world; _map = map; FilePath = Path.Combine(directory, "world-" + world.ToString("X16", CultureInfo.InvariantCulture) + ".map"); } public bool Load() { if (!File.Exists(FilePath)) { if (File.Exists(FilePath + ".bak")) { throw new InvalidDataException("Community map is missing but its backup exists: " + FilePath); } return false; } using FileStream fileStream = new FileStream(FilePath, FileMode.Open, FileAccess.Read, FileShare.Read); int num = (_map.Size * _map.Size + 7) / 8; if (fileStream.Length != 28L + (long)num + 32) { throw new InvalidDataException("Invalid community-map length: " + FilePath); } using BinaryReader binaryReader = new BinaryReader(fileStream, Encoding.UTF8, leaveOpen: true); byte[] buffer = binaryReader.ReadBytes(28 + num); byte[] array = binaryReader.ReadBytes(32); using SHA256 sHA = SHA256.Create(); if (!((ReadOnlySpan)sHA.ComputeHash(buffer)).SequenceEqual((ReadOnlySpan)array)) { throw new InvalidDataException("Community-map checksum mismatch: " + FilePath); } using BinaryReader binaryReader2 = new BinaryReader(new MemoryStream(buffer, writable: false)); if (binaryReader2.ReadUInt32() != 1297304392 || binaryReader2.ReadInt32() != 1 || binaryReader2.ReadInt64() != _world || binaryReader2.ReadInt32() != _map.Size || binaryReader2.ReadSingle() != _map.PixelSize || binaryReader2.ReadInt32() != num) { throw new InvalidDataException("Unsupported community-map format, world or grid: " + FilePath); } _map.ImportPacked(binaryReader2.ReadBytes(num)); _savedPixels = _map.ExploredPixels; return true; } public bool SaveIfDue(float now, float interval) { bool result = Poll(); if (_write != null) { return result; } if (!_nextSave.Ready(now)) { return result; } _nextSave.Postpone(now, interval); if (_savedPixels != _map.ExploredPixels) { _writingPixels = _map.ExploredPixels; byte[] snapshot = Snapshot(); _write = Task.Run(delegate { Write(snapshot); }); } return result; } private bool Poll(bool wait = false) { if (_write == null || (!wait && !_write.IsCompleted)) { return false; } Task? write = _write; _write = null; write.GetAwaiter().GetResult(); _savedPixels = _writingPixels; return true; } public bool Save(bool initialize = false) { bool result = Poll(wait: true); if (!initialize && _savedPixels == _map.ExploredPixels) { return result; } int exploredPixels = _map.ExploredPixels; Write(Snapshot()); _savedPixels = exploredPixels; return true; } private byte[] Snapshot() { byte[] array = _map.ExportPacked(); using MemoryStream memoryStream = new MemoryStream(); using (BinaryWriter binaryWriter = new BinaryWriter(memoryStream, Encoding.UTF8, leaveOpen: true)) { binaryWriter.Write(1297304392u); binaryWriter.Write(1); binaryWriter.Write(_world); binaryWriter.Write(_map.Size); binaryWriter.Write(_map.PixelSize); binaryWriter.Write(array.Length); binaryWriter.Write(array); } return memoryStream.ToArray(); } private void Write(byte[] bytes) { Directory.CreateDirectory(Path.GetDirectoryName(FilePath)); string text = FilePath + "." + Guid.NewGuid().ToString("N") + ".tmp"; try { using SHA256 sHA = SHA256.Create(); byte[] array = sHA.ComputeHash(bytes); using (FileStream fileStream = new FileStream(text, FileMode.CreateNew, FileAccess.Write, FileShare.None)) { fileStream.Write(bytes, 0, bytes.Length); fileStream.Write(array, 0, array.Length); fileStream.Flush(flushToDisk: true); } if (File.Exists(FilePath)) { File.Replace(text, FilePath, FilePath + ".bak"); } else { File.Move(text, FilePath); } } finally { if (File.Exists(text)) { File.Delete(text); } } } } public static class SharedMapTableData { internal sealed class ValidatedTable { internal readonly byte[] Raw; internal readonly int RemovedDeaths; internal ValidatedTable(byte[] raw, int removedDeaths) { Raw = raw; RemovedDeaths = removedDeaths; } } public const int MaximumCompressedBytes = 2097152; private const int MaximumPinBytes = 2097152; public const long PortalOwner = long.MinValue; public const long ResourceOwner = -9223372036854775807L; public const long DungeonOwner = -9223372036854775806L; public const long RunestoneOwner = -9223372036854775805L; public const long SpawnerOwner = -9223372036854775804L; public static bool ManagedOwner(long owner) { if (owner != long.MinValue && owner != -9223372036854775807L && owner != -9223372036854775806L && owner != -9223372036854775805L) { return owner == -9223372036854775804L; } return true; } public static void Import(SharedMapExploration exploration, byte[] compressed) { int num = exploration.Size * exploration.Size; byte[] raw = Decompress(compressed, num + 2097152 + 12); raw = ValidateAndClean(raw, num, out var _); exploration.Import(raw, 8); } public static byte[]? Merge(SharedMapExploration exploration, byte[]? compressed) { int removedDeaths; return Merge(exploration, compressed, out removedDeaths); } public static byte[]? Merge(SharedMapExploration exploration, byte[]? compressed, out int removedDeaths, IReadOnlyList? portals = null, bool managePortalIcons = false, Action? matchingPreservedPin = null, IReadOnlyList? resources = null, Func? removePin = null, IReadOnlyList? dungeons = null, Func? publication = null, IReadOnlyList? runestones = null, IReadOnlyList? spawners = null, Action? dungeonCleanup = null, float resourceMarkerHideDistanceMeters = 10f) { return MergeValidated(exploration, Decode(exploration.Size, compressed), out removedDeaths, portals, managePortalIcons, matchingPreservedPin, resources, removePin, dungeons, publication, runestones, spawners, dungeonCleanup, resourceMarkerHideDistanceMeters); } internal static ValidatedTable? Decode(int size, byte[]? compressed) { if (compressed == null || compressed.Length == 0) { return null; } int num = checked(size * size); int removedDeaths; return new ValidatedTable(ValidateAndClean(Decompress(compressed, num + 2097152 + 12), num, out removedDeaths), removedDeaths); } internal static void ImportValidated(SharedMapExploration exploration, ValidatedTable? table) { if (table != null) { exploration.Import(table.Raw, 8); } } internal static byte[]? MergeValidated(SharedMapExploration exploration, ValidatedTable? table, out int removedDeaths, IReadOnlyList? portals = null, bool managePortalIcons = false, Action? matchingPreservedPin = null, IReadOnlyList? resources = null, Func? removePin = null, IReadOnlyList? dungeons = null, Func? publication = null, IReadOnlyList? runestones = null, IReadOnlyList? spawners = null, Action? dungeonCleanup = null, float resourceMarkerHideDistanceMeters = 10f) { removedDeaths = 0; int num = exploration.Size * exploration.Size; bool flag = false; byte[] array; if (table == null) { if (exploration.ExploredPixels == 0 && (portals == null || portals.Count == 0) && (resources == null || resources.Count == 0) && (dungeons == null || dungeons.Count == 0) && (runestones == null || runestones.Count == 0) && (spawners == null || spawners.Count == 0)) { return null; } using MemoryStream memoryStream = new MemoryStream(); using BinaryWriter binaryWriter = new BinaryWriter(memoryStream); binaryWriter.Write(1); binaryWriter.Write(num); binaryWriter.Write(exploration.Pixels); array = memoryStream.ToArray(); flag = true; } else { removedDeaths = table.RemovedDeaths; flag = removedDeaths != 0; array = table.Raw; for (int i = 0; i < num; i++) { if (exploration.Pixels[i] != 0 && array[8 + i] == 0) { if (array == table.Raw) { array = (byte[])array.Clone(); } array[8 + i] = 1; flag = true; } } } if (portals != null || resources != null || removePin != null || dungeons != null || publication != null || runestones != null || spawners != null) { byte[] array2 = ReconcilePins(array, num, portals ?? Array.Empty(), resources ?? Array.Empty(), dungeons ?? Array.Empty(), managePortalIcons, matchingPreservedPin, removePin, publication, runestones ?? Array.Empty(), spawners ?? Array.Empty(), dungeonCleanup, resourceMarkerHideDistanceMeters); flag |= !((ReadOnlySpan)array).SequenceEqual((ReadOnlySpan)array2); array = array2; } if (!flag) { exploration.Import(array, 8); return null; } using MemoryStream memoryStream2 = new MemoryStream(); using (GZipStream gZipStream = new GZipStream(memoryStream2, CompressionLevel.Fastest, leaveOpen: true)) { gZipStream.Write(array, 0, array.Length); } if (memoryStream2.Length > 2097152) { throw new InvalidDataException("Merged table exceeds the compressed-data limit."); } exploration.Import(array, 8); return memoryStream2.ToArray(); } private static byte[] ReconcilePins(byte[] raw, int count, IReadOnlyList portals, IReadOnlyList resources, IReadOnlyList dungeons, bool managePortalIcons, Action? matchingPreservedPin, Func? removePin, Func? publication, IReadOnlyList runestones, IReadOnlyList spawners, Action? dungeonCleanup, float resourceMarkerHideDistanceMeters) { if (portals.Count > 4096 || resources.Count > 4096 || dungeons.Count > 4096 || runestones.Count > 4096 || spawners.Count > 4096) { throw new InvalidDataException("Too many community markers."); } SharedMapDungeonPins sharedMapDungeonPins = new SharedMapDungeonPins(dungeons); dungeons = sharedMapDungeonPins.Markers; int num = 0; portals = portals.Where(delegate(MapMarker p) { Func? func3 = removePin; return func3 == null || !func3(new MapPin(long.MinValue, p.Name, p.X, p.Y, p.Z, 6)); }).ToArray(); resources = resources.Where(delegate(MapMarker p) { Func? func3 = removePin; return func3 == null || !func3(new MapPin(-9223372036854775807L, p.Name, p.X, p.Y, p.Z, 3)); }).ToArray(); dungeons = dungeons.Where(delegate(MapMarker p) { Func? func3 = removePin; return func3 == null || !func3(new MapPin(-9223372036854775806L, p.Name, p.X, p.Y, p.Z, 2)); }).ToArray(); List generated; using (BinaryReader binaryReader = new BinaryReader(new MemoryStream(raw, writable: false), new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true))) { int num2 = binaryReader.ReadInt32(); binaryReader.BaseStream.Position = 8 + count; int num3 = ((num2 >= 2) ? binaryReader.ReadInt32() : 0); using MemoryStream memoryStream = new MemoryStream(); using BinaryWriter writer = new BinaryWriter(memoryStream, Encoding.UTF8, leaveOpen: true); int num4 = 0; Dictionary dictionary = portals.GroupBy((MapMarker p) => p.Name, StringComparer.OrdinalIgnoreCase).ToDictionary, string, MapMarker[]>((IGrouping g) => g.Key, (IGrouping g) => g.ToArray(), StringComparer.OrdinalIgnoreCase); for (int num5 = 0; num5 < num3; num5++) { int num6 = (int)binaryReader.BaseStream.Position; long num7 = binaryReader.ReadInt64(); string text = binaryReader.ReadString(); float x = binaryReader.ReadSingle(); float num8 = binaryReader.ReadSingle(); float z = binaryReader.ReadSingle(); int num9 = binaryReader.ReadInt32(); bool flag = binaryReader.ReadBoolean(); string text2 = ((num2 >= 3) ? binaryReader.ReadString() : ""); Func? func = removePin; if ((func != null && func(new MapPin(num7, text, x, num8, z, num9))) || ManagedOwner(num7) || (managePortalIcons && num9 == 6)) { continue; } if (sharedMapDungeonPins.Obsolete(new MapPin(num7, text, x, num8, z, num9, flag, text2))) { num++; continue; } if (dictionary.TryGetValue(text, out var value)) { bool flag2 = managePortalIcons && num9 != 2 && value.Any((MapMarker p) => ((double)p.X - (double)x) * (double)(p.X - x) + ((double)p.Z - (double)z) * (double)(p.Z - z) <= 9.0); matchingPreservedPin?.Invoke(text, num9, num7, x, z, flag2); if (flag2) { continue; } } if (publication == null) { memoryStream.Write(raw, num6, (int)binaryReader.BaseStream.Position - num6); } else { MapPin mapPin = publication(new MapPin(num7, text, x, num8, z, num9, flag, text2), null); if (mapPin == null) { continue; } Func? func2 = removePin; if (func2 != null && func2(mapPin)) { continue; } if (mapPin.Owner == num7 && mapPin.Name == text && mapPin.X == x && mapPin.Y == num8 && mapPin.Z == z && mapPin.Icon == num9 && mapPin.Checked == flag && mapPin.Author == text2) { memoryStream.Write(raw, num6, (int)binaryReader.BaseStream.Position - num6); } else { WritePin(writer, num2, mapPin); } } num4++; } if (num2 == 1 && portals.Count == 0 && resources.Count == 0 && dungeons.Count == 0 && runestones.Count == 0 && spawners.Count == 0) { return raw; } generated = new List(); Add(portals, long.MinValue, 6); Add(resources, -9223372036854775807L, 3); Add(dungeons, -9223372036854775806L, 2); Add(runestones, -9223372036854775805L, 3); Add(spawners, -9223372036854775804L, 3); SharedMapResourcePinSpacing.Apply(generated, resourceMarkerHideDistanceMeters); if (num4 + generated.Count > 8192) { throw new InvalidDataException("Merged table exceeds the pin limit."); } int num10 = ((num2 == 1) ? 3 : num2); using MemoryStream memoryStream2 = new MemoryStream(); using BinaryWriter binaryWriter = new BinaryWriter(memoryStream2, Encoding.UTF8, leaveOpen: true); binaryWriter.Write(num10); binaryWriter.Write(count); binaryWriter.Write(raw, 8, count); binaryWriter.Write(num4 + generated.Count); binaryWriter.Write(memoryStream.ToArray()); foreach (MapPin item in generated) { WritePin(binaryWriter, num10, item); } if (memoryStream2.Length > count + 2097152 + 12) { throw new InvalidDataException("Merged marker data exceeds the payload limit."); } dungeonCleanup?.Invoke(sharedMapDungeonPins.Suppressed, num); return memoryStream2.ToArray(); } void Add(IReadOnlyList markers, long owner, int icon) { foreach (MapMarker marker in markers) { MapPin mapPin2 = new MapPin(owner, marker.Name, marker.X, marker.Y, marker.Z, icon); Func? func3 = removePin; if (func3 == null || !func3(mapPin2)) { MapPin mapPin3 = ((publication == null) ? mapPin2 : publication(mapPin2, (marker.Identity.Length > 0) ? marker.Identity : SharedMapPinRemovals.Identity(mapPin2))); if (mapPin3 != null) { Func? func4 = removePin; if (func4 == null || !func4(mapPin3)) { generated.Add(mapPin3); } } } } } } public static IReadOnlyList ReadPins(int size, byte[]? compressed, bool includeDeaths = false) { if (compressed == null || compressed.Length == 0) { return Array.Empty(); } int num = checked(size * size); byte[] raw = Decompress(compressed, num + 2097152 + 12); int removedDeaths; byte[] array = ValidateAndClean(raw, num, out removedDeaths); if (!includeDeaths) { raw = array; } return ReadValidatedPins(num, raw); } internal static IReadOnlyList ReadValidatedPins(int size, ValidatedTable? table) { if (table != null) { return ReadValidatedPins(checked(size * size), table.Raw); } return Array.Empty(); } private static IReadOnlyList ReadValidatedPins(int count, byte[] raw) { using BinaryReader binaryReader = new BinaryReader(new MemoryStream(raw, writable: false), new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true)); int num = binaryReader.ReadInt32(); binaryReader.BaseStream.Position = 8 + count; int num2 = ((num >= 2) ? binaryReader.ReadInt32() : 0); List list = new List(); for (int i = 0; i < num2; i++) { long owner = binaryReader.ReadInt64(); string name = binaryReader.ReadString(); float x = binaryReader.ReadSingle(); float y = binaryReader.ReadSingle(); float z = binaryReader.ReadSingle(); int icon = binaryReader.ReadInt32(); bool isChecked = binaryReader.ReadBoolean(); string author = ((num >= 3) ? binaryReader.ReadString() : ""); list.Add(new MapPin(owner, name, x, y, z, icon, isChecked, author)); } return list; } private static void WritePin(BinaryWriter writer, int version, MapPin pin) { SharedMapPinRemovals.Identity(pin); writer.Write(pin.Owner); writer.Write(pin.Name); writer.Write(pin.X); writer.Write(pin.Y); writer.Write(pin.Z); writer.Write(pin.Icon); writer.Write(pin.Checked); if (version >= 3) { writer.Write(pin.Author); } } private static byte[] Decompress(byte[] compressed, int limit) { if (compressed.Length > 2097152) { throw new InvalidDataException("Oversized compressed table."); } using MemoryStream stream = new MemoryStream(compressed, writable: false); using GZipStream gZipStream = new GZipStream(stream, CompressionMode.Decompress); using MemoryStream memoryStream = new MemoryStream(); byte[] array = new byte[8192]; int num; while ((num = gZipStream.Read(array, 0, Math.Min(array.Length, limit + 1 - (int)memoryStream.Length))) > 0) { if (memoryStream.Length + num > limit) { throw new InvalidDataException("Oversized decompressed table."); } memoryStream.Write(array, 0, num); } return memoryStream.ToArray(); } private static byte[] ValidateAndClean(byte[] raw, int count, out int removedDeaths) { removedDeaths = 0; using MemoryStream memoryStream = new MemoryStream(raw, writable: false); using BinaryReader binaryReader = new BinaryReader(memoryStream, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true)); int num = binaryReader.ReadInt32(); if (num < 1 || num > 3 || binaryReader.ReadInt32() != count) { throw new InvalidDataException("Unsupported table format or exploration dimensions."); } if (memoryStream.Length - memoryStream.Position < count) { throw new InvalidDataException("Truncated exploration."); } for (int i = 0; i < count; i++) { ReadBoolean(binaryReader); } using MemoryStream memoryStream2 = new MemoryStream(); int num2 = 0; if (num >= 2) { num2 = binaryReader.ReadInt32(); if (num2 < 0 || num2 > 8192) { throw new InvalidDataException("Invalid pin count."); } for (int j = 0; j < num2; j++) { int num3 = (int)memoryStream.Position; binaryReader.ReadInt64(); SkipString(binaryReader, 4096); for (int k = 0; k < 3; k++) { if (!SharedMapExploration.Finite(binaryReader.ReadSingle())) { throw new InvalidDataException("Invalid pin position."); } } int num4 = binaryReader.ReadInt32(); if (num4 < 0 || num4 > 16) { throw new InvalidDataException("Unsupported native pin type."); } ReadBoolean(binaryReader); if (num >= 3) { SkipString(binaryReader, 512); } if (num4 == 4) { removedDeaths++; } else { memoryStream2.Write(raw, num3, (int)memoryStream.Position - num3); } } } if (memoryStream.Position != memoryStream.Length) { throw new InvalidDataException("Trailing table data."); } if (removedDeaths == 0) { return raw; } using MemoryStream memoryStream3 = new MemoryStream(); using BinaryWriter binaryWriter = new BinaryWriter(memoryStream3); binaryWriter.Write(raw, 0, 8 + count); binaryWriter.Write(num2 - removedDeaths); binaryWriter.Write(memoryStream2.ToArray()); return memoryStream3.ToArray(); } private static void ReadBoolean(BinaryReader reader) { if (reader.ReadByte() > 1) { throw new InvalidDataException("Invalid boolean byte."); } } private static void SkipString(BinaryReader reader, int limit) { uint num = 0u; for (int i = 0; i <= 28; i += 7) { byte b = reader.ReadByte(); if (i == 28 && b > 7) { throw new InvalidDataException("Invalid string length."); } num |= (uint)((b & 0x7F) << i); if ((b & 0x80) == 0) { if (num > limit || num > reader.BaseStream.Length - reader.BaseStream.Position) { throw new InvalidDataException("Oversized or truncated pin string."); } new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true).GetString(reader.ReadBytes((int)num)); return; } } throw new InvalidDataException("Invalid string length."); } } public static class SharedMapTerrainData { public static TerrainSnapshot? Read(byte[]? compressed) { if (compressed == null || compressed.Length == 0 || compressed.Length > 2097152) { return null; } try { using MemoryStream stream = new MemoryStream(compressed, writable: false); using GZipStream gZipStream = new GZipStream(stream, CompressionMode.Decompress); using MemoryStream memoryStream = new MemoryStream(); byte[] array = new byte[8192]; int num; while ((num = gZipStream.Read(array, 0, array.Length)) > 0) { if (memoryStream.Length + num > 4194304) { return null; } memoryStream.Write(array, 0, num); } memoryStream.Position = 0L; using BinaryReader binaryReader = new BinaryReader(memoryStream); if (binaryReader.ReadInt32() != 1) { return null; } int num2 = binaryReader.ReadInt32(); float num3 = binaryReader.ReadSingle(); float num4 = binaryReader.ReadSingle(); float num5 = binaryReader.ReadSingle(); float num6 = binaryReader.ReadSingle(); if (num2 < 0 || !Finite(num3) || !Finite(num4) || !Finite(num5) || !Finite(num6) || num6 < 0f || num6 > 1000f) { return null; } int num7 = binaryReader.ReadInt32(); if (num7 < 1 || num7 > 66049) { return null; } float[] array2 = new float[num7]; for (int i = 0; i < num7; i++) { byte b = binaryReader.ReadByte(); if (b > 1) { return null; } if (b != 0) { float num8 = binaryReader.ReadSingle(); float num9 = binaryReader.ReadSingle(); if (!Finite(num8) || !Finite(num9) || !Finite(num8 + num9)) { return null; } array2[i] = num8 + num9; } } int num10 = binaryReader.ReadInt32(); if (num10 < 0 || num10 > 65536) { return null; } for (int j = 0; j < num10; j++) { byte b2 = binaryReader.ReadByte(); if (b2 > 1) { return null; } if (b2 == 0) { continue; } for (int k = 0; k < 4; k++) { if (!Finite(binaryReader.ReadSingle())) { return null; } } } if (binaryReader.BaseStream.Position != binaryReader.BaseStream.Length) { return null; } return new TerrainSnapshot(num2, num3, num4, num5, array2); } catch (Exception ex) when (ex is IOException || ex is InvalidDataException || ex is ArgumentException) { return null; } } private static bool Finite(float value) { return SharedMapExploration.Finite(value); } public static bool Lowered(TerrainSnapshot? before, TerrainSnapshot? after) { if (before == null || after == null || after.Operations <= before.Operations || (long)after.Operations - (long)before.Operations > 64 || before.Heights.Length != after.Heights.Length) { return false; } for (int i = 0; i < before.Heights.Length; i++) { if (after.Heights[i] < before.Heights[i] - 0.01f) { return true; } } return false; } } } namespace HeimKit.Features.SharedMap.Models { internal sealed class DungeonGateway { public string Path { get; } public Vector3 Offset { get; } public Vector3 InteriorOffset { get; } public DungeonGateway(string path, Vector3 offset, Vector3 interiorOffset = default(Vector3)) { //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) Path = path; Offset = offset; InteriorOffset = interiorOffset; } } public sealed class DungeonRoomPlacement { public int Hash { get; } public Vector3 Position { get; } public Vector3 RotationEuler { get; } public DungeonRoomPlacement(int hash, Vector3 position, Vector3 rotationEuler) { //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) Hash = hash; Position = position; RotationEuler = rotationEuler; } } public sealed class MapMarker { public string Name { get; } public float X { get; } public float Y { get; } public float Z { get; } public string Identity { get; } public MapMarker(string name, float x, float y, float z, string identity = "") { Name = name; X = x; Y = y; Z = z; Identity = identity; } } internal sealed class MapPacketScope { public SharedMapController? Previous { get; } public ZNetPeer? PreviousPeer { get; } public SharedMapController? Current { get; set; } public MapPacketScope(SharedMapController? previous, ZNetPeer? previousPeer) { Previous = previous; PreviousPeer = previousPeer; } } public sealed class MapPin { public long Owner { get; } public string Name { get; } public float X { get; } public float Y { get; } public float Z { get; } public int Icon { get; } public bool Checked { get; } public string Author { get; } public MapPin(long owner, string name, float x, float y, float z, int icon, bool isChecked = false, string author = "") { Owner = owner; Name = name; X = x; Y = y; Z = z; Icon = icon; Checked = isChecked; Author = author; } } public sealed class MapPinChanges { public List Added { get; } = new List(); public List Removed { get; } = new List(); public List<(MapPin Before, MapPin After)> Updated { get; } = new List<(MapPin, MapPin)>(); public bool Any { get { if (Added.Count == 0 && Removed.Count == 0) { return Updated.Count != 0; } return true; } } } internal sealed class MapReplicationSnapshot { public SharedMapController Controller { get; } public TableMapSnapshot? Table { get; set; } public byte[]? Terrain { get; set; } public int PreviousPrefab { get; set; } public string MiningString { get; set; } = ""; public float MiningHealth { get; set; } = float.NaN; public MapReplicationSnapshot(SharedMapController controller) { Controller = controller; } } internal sealed class MarkerPublicationState { public string Name { get; } public int Slot { get; } public float X { get; } public float Z { get; } public MarkerPublicationState(string name, int slot, float x, float z) { Name = name; Slot = slot; X = x; Z = z; } } public readonly struct MiningProgress { public int RemainingSections { get; } public int TotalSections { get; } public MiningProgress(int remainingSections, int totalSections) { if (totalSections < 1 || totalSections > 8192 || remainingSections < 0 || remainingSections > totalSections) { throw new ArgumentOutOfRangeException("remainingSections"); } RemainingSections = remainingSections; TotalSections = totalSections; } } public sealed class ResourceDeposit { public int Identity { get; } public ResourceKind Kind { get; } public float X { get; } public float Y { get; } public float Z { get; } public bool Depleted { get; internal set; } public bool SilverDiscovered { get; internal set; } public MiningProgress? Progress { get; internal set; } public ResourceDeposit(int identity, ResourceKind kind, float x, float y, float z, bool depleted = false, MiningProgress? progress = null, bool silverDiscovered = false) { Identity = identity; Kind = kind; X = x; Y = y; Z = z; Depleted = depleted; Progress = progress; SilverDiscovered = silverDiscovered; } } public enum ResourceKind { Copper, Tin, Silver, Obsidian, Flametal } internal sealed class TableMapSnapshot { public SharedMapController Controller { get; } public byte[]? Previous { get; } public byte[]? Received { get; set; } public long? SenderPeer { get; set; } public string SenderName { get; set; } = ""; public int RemovedDeaths { get; set; } public byte[]? Expected { get; set; } public TableMapSnapshot(SharedMapController controller, byte[]? previous) { Controller = controller; Previous = previous; } } public sealed class TerrainSnapshot { public int Operations { get; } public float X { get; } public float Y { get; } public float Z { get; } internal float[] Heights { get; } internal TerrainSnapshot(int operations, float x, float y, float z, float[] heights) { Operations = operations; X = x; Y = y; Z = z; Heights = heights; } } } namespace HeimKit.Features.SeaSalvage { public sealed class SeaSalvage : IServerModule { private readonly SeaSalvageSettings _settings; private readonly ManualLogSource _logger; private readonly GameVersionCompatibility _compatibility; private readonly PlayerServices _players; private SeaSalvageController? _controller; private IDisposable? _presenceRegistration; private bool _occupied; private ZDOMan? _world; private long _worldUid; private readonly string _directory; private readonly PlayerProcessingNotices _processing; public string Name => "SeaSalvage"; public bool IsActive { get; private set; } public SeaSalvage(ConfigFile config, ManualLogSource logger, PlayerServices players) { _directory = Path.Combine(Path.GetDirectoryName(config.ConfigFilePath), "HeimKit", "SeaSalvage"); _logger = logger; _compatibility = GameVersionCompatibility.Resolve(config, logger); _settings = new SeaSalvageSettings(config, logger); _players = players; _processing = new PlayerProcessingNotices(logger, Name, () => _settings.DebugLogging.Enabled); } public void Initialize(string gameVersion) { Shutdown(); Log(_settings.Enabled.Value ? "Enabled." : "Disabled.", (LogLevel)16); _settings.DebugLogging.ReportStartup(_logger, Name, _settings.Enabled.Value); if (!_settings.Enabled.Value) { return; } if (!_compatibility.Supports(gameVersion)) { Log("DISABLED: unsupported game version " + gameVersion + "; required version " + _compatibility.RequiredVersion, (LogLevel)4); return; } IsActive = true; if (_settings.DebugLogging.Enabled) { Log("Waiting for joined players and dedicated-server world", (LogLevel)32); } try { _presenceRegistration = _players.Events.Subscribe(PresenceChanged, Fail, () => _processing.IsEmptyPaused, () => _processing.IsRunning, () => _processing.IsServerReady); } catch (Exception error) { Fail(error); } if (!IsActive) { IDisposable? presenceRegistration = _presenceRegistration; _presenceRegistration = null; presenceRegistration?.Dispose(); } } public void Tick(float now) { if (!IsActive) { return; } if (!_settings.Enabled.Value) { Shutdown(); return; } try { bool flag = WorldServices.Activity && WorldServices.Terrain; if (flag) { _processing.ServerReady(); } if (!_occupied) { StopController(); return; } if (!flag) { StopController(); _processing.Paused("world services unavailable"); return; } long worldUID = ZNet.instance.GetWorldUID(); if (_world != ZDOMan.instance || _worldUid != worldUID) { StopController(); _world = ZDOMan.instance; _worldUid = worldUID; } StartController(); _controller?.Tick(now); } catch (Exception error) { Fail(error); } } private void PresenceChanged(bool? occupied) { _occupied = occupied == true; if (IsActive && !_occupied) { StopController(); if (occupied.HasValue) { _processing.EmptyPaused(); } else { _processing.Unavailable("player presence unavailable"); } } } private void StartController() { if (_settings.Enabled.Value && _controller == null) { _controller = new SeaSalvageController(this, _settings, _logger, _players, _directory); _processing.Ready(); } } private void StopController() { SeaSalvageController controller = _controller; _controller = null; if (controller != null) { ModuleScheduler.Current.Forget(controller); } try { controller?.Dispose(); } finally { WorldObjectProvider.Current?.ReleaseOwner(Name); } } internal void Fail(Exception error) { if (IsActive) { DiagnosticLog.Write(_logger, Name, CoreLogTopics.Lifecycle, "Disabled after a runtime failure.", default(LogFields), (LogLevel)2, verbose: false, error); Shutdown(); } } private void Log(string message, LogLevel level = (LogLevel)16) { //IL_000d: Unknown result type (might be due to invalid IL or missing references) DiagnosticLog.Write(_logger, Name, message, level); } public void Shutdown() { IsActive = false; _occupied = false; _processing.Reset(); IDisposable registration = _presenceRegistration; _presenceRegistration = null; ModuleCleanup.Run(_logger, Name, delegate { registration?.Dispose(); }, StopController); } } internal sealed class SeaSalvageController : IDisposable { private static readonly int Consumed = StringExtensionMethods.GetStableHashCode("heimkit_seasalvage_consumed"); private readonly SeaSalvageSettings _settings; private readonly ManualLogSource _log; private readonly SeaSalvageDiagnostics _diagnostics; private readonly PlayerWorldScope _scope; private readonly ObjectAuthority _authority; private readonly TerrainContext _terrain; private readonly Dictionary _settling = new Dictionary(); private readonly PrefabCatalog _definitions = PrefabRegistry.Current.Catalog("SeaSalvageController._definitions"); private readonly GameObject _crate; private readonly Container _container; private readonly ZDOMan _world = ZDOMan.instance; private int _scanCursor; private long _transferred; private readonly List _remove = new List(); private readonly List _ready = new List(); private readonly List _group = new List(); private readonly HashSet _held = new HashSet(); public SeaSalvageController(SeaSalvage module, SeaSalvageSettings settings, ManualLogSource log, PlayerServices players, string directory) { _settings = settings; _log = log; _scope = WorldObjectProvider.Current.CreateScope("SeaSalvage"); _diagnostics = new SeaSalvageDiagnostics(log, settings.DebugLogging); if (settings.MinimumDepthMeters.Value >= settings.MaximumDepthMeters.Value) { throw new InvalidOperationException("SeaSalvage depth bounds must be ordered."); } _crate = PrefabRegistry.Current.Prefab("CargoCrate"); _container = PrefabRegistry.Component(_crate); if (!((Object)(object)_crate == (Object)null) && !((Object)(object)_container == (Object)null) && _container.m_width == 2 && _container.m_height == 2 && !((Object)(object)PrefabRegistry.Component(_crate) == (Object)null)) { ZNetView? obj = PrefabRegistry.Component(_crate); if (obj != null && obj.m_persistent && _container.m_defaultItems.m_drops.Count == 0) { _terrain = new TerrainContext(); try { _authority = new ObjectAuthority(module.Fail, log, players.Presence, false); } catch { _terrain.Dispose(); throw; } try { _scope.Index((ZDO z) => (Object)(object)Definition(z.GetPrefab()) != (Object)null); return; } catch { Dispose(); throw; } } } throw new InvalidOperationException("Native floating four-slot CargoCrate is unavailable."); } private ItemDrop? Definition(int hash) { if (_definitions.TryGetValue(hash, out ItemDrop value)) { return value; } GameObject val = PrefabRegistry.Current.Prefab(hash); value = PrefabRegistry.Component(val); if (!((Object)(object)val == (Object)null)) { ZNetView? obj = PrefabRegistry.Component(val); if (obj != null && obj.m_persistent && !((Object)(object)PrefabRegistry.Component(val) != (Object)null) && !((Object)(object)PrefabRegistry.Component(val) != (Object)null) && !((Object)(object)PrefabRegistry.Component(val) != (Object)null) && !((Object)(object)PrefabRegistry.Component(val) != (Object)null) && !((Object)(object)PrefabRegistry.Component(val) != (Object)null) && !((Object)(object)PrefabRegistry.Component(val) != (Object)null)) { goto IL_009b; } } value = null; goto IL_009b; IL_009b: if (_definitions.Count < 4096) { _definitions[hash] = value; } return value; } public void Tick(float now) { //IL_0069: 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_0076: 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_02f6: Unknown result type (might be due to invalid IL or missing references) //IL_0784: Unknown result type (might be due to invalid IL or missing references) //IL_0791: Unknown result type (might be due to invalid IL or missing references) //IL_0337: Unknown result type (might be due to invalid IL or missing references) //IL_033c: 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_00bb: Unknown result type (might be due to invalid IL or missing references) //IL_00c3: Unknown result type (might be due to invalid IL or missing references) //IL_00d0: Unknown result type (might be due to invalid IL or missing references) //IL_0372: Unknown result type (might be due to invalid IL or missing references) //IL_039d: Unknown result type (might be due to invalid IL or missing references) //IL_0381: Unknown result type (might be due to invalid IL or missing references) //IL_0362: Unknown result type (might be due to invalid IL or missing references) //IL_03ad: Unknown result type (might be due to invalid IL or missing references) //IL_018c: Unknown result type (might be due to invalid IL or missing references) //IL_0178: Unknown result type (might be due to invalid IL or missing references) //IL_0418: Unknown result type (might be due to invalid IL or missing references) //IL_01c0: Unknown result type (might be due to invalid IL or missing references) //IL_01c5: Unknown result type (might be due to invalid IL or missing references) //IL_01cd: Unknown result type (might be due to invalid IL or missing references) //IL_0490: Unknown result type (might be due to invalid IL or missing references) //IL_04b0: Unknown result type (might be due to invalid IL or missing references) //IL_04b2: Unknown result type (might be due to invalid IL or missing references) //IL_0479: Unknown result type (might be due to invalid IL or missing references) //IL_0443: Unknown result type (might be due to invalid IL or missing references) //IL_0448: Unknown result type (might be due to invalid IL or missing references) //IL_044a: Unknown result type (might be due to invalid IL or missing references) //IL_044f: Unknown result type (might be due to invalid IL or missing references) //IL_0525: Unknown result type (might be due to invalid IL or missing references) //IL_054a: Unknown result type (might be due to invalid IL or missing references) //IL_0562: Unknown result type (might be due to invalid IL or missing references) //IL_0573: Unknown result type (might be due to invalid IL or missing references) //IL_0584: Unknown result type (might be due to invalid IL or missing references) //IL_05e3: Unknown result type (might be due to invalid IL or missing references) //IL_05ea: Expected O, but got Unknown //IL_05f1: Unknown result type (might be due to invalid IL or missing references) //IL_05f7: Unknown result type (might be due to invalid IL or missing references) //IL_06a6: Unknown result type (might be due to invalid IL or missing references) //IL_06ad: Expected O, but got Unknown //IL_06ce: Unknown result type (might be due to invalid IL or missing references) //IL_06d3: Unknown result type (might be due to invalid IL or missing references) //IL_06d9: Unknown result type (might be due to invalid IL or missing references) //IL_06db: Unknown result type (might be due to invalid IL or missing references) if (!ModuleScheduler.Current.Due(this, "processing", now, _settings.IntervalSeconds.Value)) { return; } using (_diagnostics.OptionalEnabled ? _diagnostics.Measure(now, () => _scope.Records.Count) : null) { _remove.Clear(); foreach (ZDOID item in _held) { if (_world.GetZDO(item) == null) { _remove.Add(item); } } foreach (ZDOID item2 in _remove) { _authority.Release(item2); _held.Remove(item2); } if (!_scope.Refresh(_settings.ScanRangeMeters.Value)) { _settling.Clear(); _terrain.Clear(); return; } _remove.Clear(); foreach (KeyValuePair item3 in _settling) { if (now - item3.Value.Seen > 120f || now < item3.Value.Since || _world.GetZDO(item3.Key) == null) { _remove.Add(item3.Key); } } foreach (ZDOID item4 in _remove) { _settling.Remove(item4); } List ready = _ready; ready.Clear(); int num = 0; int num2 = 0; int num3 = 0; int num4 = 0; int num5 = 0; int num6 = 0; int num7 = 0; int num8 = 0; int num9 = ((_scope.Records.Count != 0) ? (_scanCursor % _scope.Records.Count) : 0); for (int num10 = 0; num10 < _scope.Records.Count; num10++) { int num11 = (num9 + num10) % _scope.Records.Count; ZDO val = _scope.Records[num11]; _scanCursor = (num11 + 1) % _scope.Records.Count; if (ready.Count >= _settings.MaxItemsPerPass.Value || _held.Count >= 256) { break; } if (!val.IsValid() || val.GetBool(Consumed, false) || val.GetBool(ZDOVars.s_piece, false) || !_scope.InRange(val.GetPosition(), _settings.ScanRangeMeters.Value)) { continue; } ItemDrop val2 = Definition(val.GetPrefab()); if ((Object)(object)val2 == (Object)null) { continue; } num2++; Vector3 position = val.GetPosition(); long owner = val.GetOwner(); if (owner != 0L && owner != ZDOMan.GetSessionID()) { num3++; _settling.Remove(val.m_uid); continue; } if (Character.InInterior(position) || _scope.PlayerNear(position, 10f)) { num4++; _settling.Remove(val.m_uid); continue; } if (position.y > 30f - _settings.MinimumDepthMeters.Value) { num7++; continue; } byte[] byteArray = val.GetByteArray(ZDOVars.s_itemData, (byte[])null); if (byteArray == null || byteArray.Length < 10 || byteArray.Length > 262144 || byteArray[0] != 110) { num8++; continue; } if (_settling.TryGetValue(val.m_uid, out SettlingObservation value) && value.Owner == owner && value.Revision == val.DataRevision) { Vector3 val3 = value.Position - position; if (!(((Vector3)(ref val3)).sqrMagnitude > 0.01f)) { value.Seen = now; if (now - value.Since < _settings.DelaySeconds.Value) { num5++; continue; } if (++num > 4) { _scanCursor = num11; break; } if (!_scope.ContextReady() || !_terrain.Prepare(position, _scope.Context, now)) { num6++; continue; } Heightmap val4 = Heightmap.FindHeightmap(position); if ((Object)(object)val4 == (Object)null || val4.IsLava(position, 0.6f)) { continue; } float liquidLevel = Floating.GetLiquidLevel(position, 0f, (LiquidType)0); float num12 = liquidLevel - position.y; if (!PlayerWorldScope.Finite(liquidLevel) || liquidLevel <= -9999f || num12 < _settings.MinimumDepthMeters.Value || num12 > _settings.MaximumDepthMeters.Value) { num7++; continue; } ItemData val5 = val2.m_itemData.Clone(); ZPackage val6 = new ZPackage(byteArray); Item val7 = (Item)val6.ReadByte(); int num13; try { num13 = ItemData.Load(val6, val5, val7); } catch (IOException) { num8++; continue; } catch (ArgumentException) { num8++; continue; } if (num13 == val.GetPrefab() && val6.GetPos() == val6.Size() && (byteArray[8] & 0x40) != 0) { val5.m_dropPrefab = ((Component)val2).gameObject; if (val5.m_stack > 0 && val5.m_stack <= val5.m_shared.m_maxStackSize && val5.m_quality >= 1 && PlayerWorldScope.Finite(val5.m_durability)) { ItemData obj = val5.Clone(); obj.m_stack = 0; ZPackage val8 = new ZPackage(); val8.Write((byte)110); obj.Save(val8); ready.Add(new SalvageSource { Record = val, Identity = val.m_uid, Position = position, Revision = val.DataRevision, Owner = owner, Original = (byte[])byteArray.Clone(), Empty = val8.GetArray() }); } } continue; } } if (_settling.Count < 4096 || _settling.ContainsKey(val.m_uid)) { _settling[val.m_uid] = new SettlingObservation { Owner = owner, Revision = val.DataRevision, Position = position, Since = now, Seen = now }; } } int num14 = 0; while (ready.Count > 0) { SalvageSource salvageSource = ready[0]; ready.RemoveAt(0); List list = _group; list.Clear(); list.Add(salvageSource); if (_settings.GroupRadiusMeters.Value > 0f) { int num15 = 0; while (num15 < ready.Count && list.Count < _settings.SlotsPerCrate.Value) { if (Utils.DistanceXZ(salvageSource.Position, ready[num15].Position) <= _settings.GroupRadiusMeters.Value) { list.Add(ready[num15]); ready.RemoveAt(num15); } else { num15++; } } } num14 += Transfer(list); } _transferred += num14; _diagnostics.Scan(now, _scope.Records.Count, num2, num3, num4, num5, num6, num7, num8); if (num14 > 0) { DiagnosticLog.Write(_log, "SeaSalvage", (num14 == 1) ? "Transferred one item drop into floating cargo." : $"Transferred {num14} item drops into floating cargo.", (LogLevel)16); } _diagnostics.Result(now, num14, _transferred, _settling.Count); } } private int Transfer(List group) { //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_00f9: Unknown result type (might be due to invalid IL or missing references) //IL_00fe: Unknown result type (might be due to invalid IL or missing references) //IL_00ff: Unknown result type (might be due to invalid IL or missing references) //IL_011d: Unknown result type (might be due to invalid IL or missing references) //IL_03ea: Unknown result type (might be due to invalid IL or missing references) //IL_03fc: Unknown result type (might be due to invalid IL or missing references) //IL_03a5: Unknown result type (might be due to invalid IL or missing references) //IL_03ac: Unknown result type (might be due to invalid IL or missing references) //IL_0165: Unknown result type (might be due to invalid IL or missing references) //IL_016a: Unknown result type (might be due to invalid IL or missing references) //IL_0170: Expected O, but got Unknown //IL_00bd: Unknown result type (might be due to invalid IL or missing references) //IL_01a9: 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_01d4: Unknown result type (might be due to invalid IL or missing references) //IL_0273: Unknown result type (might be due to invalid IL or missing references) //IL_027a: Unknown result type (might be due to invalid IL or missing references) //IL_02ae: Unknown result type (might be due to invalid IL or missing references) //IL_0315: Unknown result type (might be due to invalid IL or missing references) foreach (SalvageSource item in group) { if (!item.Record.IsValid() || item.Record.m_uid != item.Identity || item.Record.DataRevision != item.Revision || item.Record.GetOwner() != item.Owner || item.Record.GetBool(Consumed, false) || !((ReadOnlySpan)item.Original).SequenceEqual((ReadOnlySpan)(item.Record.GetByteArray(ZDOVars.s_itemData, (byte[])null) ?? Array.Empty())) || _scope.PlayerNear(item.Position, 10f)) { return 0; } } Vector3 position = group[0].Position; float liquidLevel = Floating.GetLiquidLevel(position, 0f, (LiquidType)0); if (!PlayerWorldScope.Finite(liquidLevel) || liquidLevel <= -9999f || liquidLevel < position.y + _settings.MinimumDepthMeters.Value) { return 0; } position.y = liquidLevel + 0.5f; byte[] array = SeaSalvageInventory.Pack(group); Inventory val = new Inventory(_container.m_name, _container.m_bkg, 2, 2); ZPackage val2 = new ZPackage(); val.Save(val2); ZDO val3 = null; bool flag = false; try { foreach (SalvageSource item2 in group) { _authority.Retain(item2.Record); _held.Add(item2.Identity); } val3 = NativeWorldObject.Create(_crate, position, Quaternion.identity); val3.Set(ZDOVars.s_addedDefaultItems, true); val3.Set(ZDOVars.s_items, array); foreach (SalvageSource item3 in group) { item3.Record.Set(ZDOVars.s_itemData, item3.Empty); item3.Record.Set(Consumed, true); } flag = true; foreach (SalvageSource item4 in group) { _diagnostics.Transfer(Time.unscaledTime, item4.Identity, val3.m_uid); } ObjectAuthority.Assign(val3, 0L); _world.ForceSendZDO(val3.m_uid); foreach (SalvageSource item5 in group) { ZNetView val4 = ZNetScene.instance.FindInstance(item5.Record); if ((Object)(object)val4 != (Object)null) { ZNetScene.instance.Destroy(((Component)val4).gameObject); } else { _world.DestroyZDO(item5.Record); } _settling.Remove(item5.Identity); } return group.Count; } catch { if (!flag) { if (val3 != null && val3.IsValid()) { val3.Set(ZDOVars.s_items, val2.GetArray()); _world.DestroyZDO(val3); } foreach (SalvageSource item6 in group) { if (item6.Record.IsValid() && item6.Record.m_uid == item6.Identity) { item6.Record.Set(ZDOVars.s_itemData, item6.Original); item6.Record.Set(Consumed, false); } _authority.Release(item6.Identity); _held.Remove(item6.Identity); } } throw; } } public void Dispose() { try { _authority.Dispose(); } finally { try { _scope.Dispose(); } finally { _terrain.Dispose(); _settling.Clear(); _held.Clear(); } } } } internal sealed class SeaSalvageDiagnostics : FeatureDiagnostics { private readonly ManualLogSource _log; private readonly ProcessingTiming _timing; private readonly DebugLoggingPolicy _policy; private readonly ScheduleToken _next = new ScheduleToken(); private long _last; private int _scope = -1; private readonly ScheduleToken _nextScan = new ScheduleToken(); public IDisposable Measure(float now, Func scope) { return _timing.Measure(now, scope); } public SeaSalvageDiagnostics(ManualLogSource log, DebugLoggingPolicy policy) { _log = log; _policy = policy; ConfigureDiagnostics(() => policy.Enabled, log, "SeaSalvage"); _timing = new ProcessingTiming(log, "SeaSalvage", policy); } public void Scan(float now, int records, int candidates, int owners, int players, int settling, int terrain, int depth, int invalid) { if (base.DiagnosticsEnabled && candidates != 0 && _nextScan.Ready(now)) { _nextScan.Postpone(now, 60f); if (DiagnosticLog.DebugAvailable(_log, "SeaSalvage")) { DiagnosticLog.Write(_log, "SeaSalvage", CoreLogTopics.Scope, $"Evaluated {candidates} sunken-item candidates this pass.", new(string, object)[8] { ("records", records), ("candidates", candidates), ("client_owned", owners), ("player_near", players), ("settling", settling), ("terrain_wait", terrain), ("depth_excluded", depth), ("invalid_items", invalid) }, (LogLevel)32); } } } public void Transfer(float now, ZDOID source, ZDOID cargo) { //IL_0055: Unknown result type (might be due to invalid IL or missing references) //IL_006c: Unknown result type (might be due to invalid IL or missing references) if (base.DiagnosticsEnabled && _budget.Reserve(now, "transfers", 16) && DiagnosticLog.DebugAvailable(_log, "SeaSalvage")) { DiagnosticLog.Write(_log, "SeaSalvage", SeaSalvageLogTopics.Salvage, "Recorded source inventory in cargo before source destruction.", new(string, object)[2] { ("source", source), ("cargo", cargo) }, (LogLevel)32); } } public void Result(float now, int count, long total, int scope) { if (base.DiagnosticsEnabled && (scope != 0 || total != _last) && (scope != _scope || total != _last) && _next.Ready(now)) { _next.Postpone(now, 60f); _last = total; _scope = scope; if (DiagnosticLog.DebugAvailable(_log, "SeaSalvage")) { DiagnosticLog.Write(_log, "SeaSalvage", CoreLogTopics.Scope, "Processing scope or results changed this pass.", new(string, object)[3] { ("scope", scope), ("results", count), ("lifetime_results", total) }, (LogLevel)32); } } } } internal static class SeaSalvageInventory { public static byte[] Pack(IReadOnlyList sources) { if (sources.Count < 1 || sources.Count > 4) { throw new ArgumentOutOfRangeException("sources"); } using MemoryStream memoryStream = new MemoryStream(); using BinaryWriter binaryWriter = new BinaryWriter(memoryStream); binaryWriter.Write(110); binaryWriter.Write((ushort)sources.Count); for (int i = 0; i < sources.Count; i++) { byte[] array = (byte[])sources[i].Original.Clone(); if (array.Length < 10 || array[0] != 110 || (array[8] & 0x40) == 0) { throw new InvalidDataException("Unsupported native item payload."); } array[5] = (byte)(i % 2); array[6] = (byte)(i / 2); binaryWriter.Write(array, 1, array.Length - 1); } binaryWriter.Flush(); return memoryStream.ToArray(); } } public static class SeaSalvageLogTopics { public static readonly LogTopic Salvage = new LogTopic("salvage"); } public sealed class SeaSalvageSettings { public ConfigEntry Enabled { get; } public ConfigEntry DebugMode { get; } public DebugLoggingPolicy DebugLogging { get; } public ConfigEntry MinimumDepthMeters { get; } public ConfigEntry MaximumDepthMeters { get; } public ConfigEntry DelaySeconds { get; } public ConfigEntry ScanRangeMeters { get; } public ConfigEntry GroupRadiusMeters { get; } public ConfigEntry SlotsPerCrate { get; } public ConfigEntry MaxItemsPerPass { get; } public ConfigEntry IntervalSeconds { get; } public SeaSalvageSettings(ConfigFile config, ManualLogSource logger) { //IL_0068: Unknown result type (might be due to invalid IL or missing references) //IL_0072: Expected O, but got Unknown //IL_00a1: Unknown result type (might be due to invalid IL or missing references) //IL_00ab: Expected O, but got Unknown //IL_00da: Unknown result type (might be due to invalid IL or missing references) //IL_00e4: Expected O, but got Unknown //IL_0113: Unknown result type (might be due to invalid IL or missing references) //IL_011d: Expected O, but got Unknown //IL_014c: Unknown result type (might be due to invalid IL or missing references) //IL_0156: Expected O, but got Unknown //IL_0179: Unknown result type (might be due to invalid IL or missing references) //IL_0183: Expected O, but got Unknown //IL_01a8: Unknown result type (might be due to invalid IL or missing references) //IL_01b2: Expected O, but got Unknown //IL_01e1: Unknown result type (might be due to invalid IL or missing references) //IL_01eb: Expected O, but got Unknown Enabled = config.Bind("SeaSalvage", "Enabled", true, "Enable SeaSalvage. Restart after edits."); DebugMode = config.Bind("SeaSalvage", "DebugMode", false, "Enable feature diagnostics through the shared debug policy."); MinimumDepthMeters = config.Bind("SeaSalvage", "MinimumDepthMeters", 4f, new ConfigDescription("Minimum item depth beneath native water. Restart after edits.", (AcceptableValueBase)(object)new AcceptableValueRange(3f, 100f), Array.Empty())); MaximumDepthMeters = config.Bind("SeaSalvage", "MaximumDepthMeters", 50f, new ConfigDescription("Maximum salvage depth. Restart after edits.", (AcceptableValueBase)(object)new AcceptableValueRange(4f, 500f), Array.Empty())); DelaySeconds = config.Bind("SeaSalvage", "DelaySeconds", 30f, new ConfigDescription("Continuous unchanged source settling interval. Restart after edits.", (AcceptableValueBase)(object)new AcceptableValueRange(10f, 3600f), Array.Empty())); ScanRangeMeters = config.Bind("SeaSalvage", "ScanRangeMeters", 128f, new ConfigDescription("Range around a rotating ready player. Restart after edits.", (AcceptableValueBase)(object)new AcceptableValueRange(32f, 512f), Array.Empty())); GroupRadiusMeters = config.Bind("SeaSalvage", "GroupRadiusMeters", 4f, new ConfigDescription("Maximum horizontal distance from first grouped drop; zero means one per crate. Restart after edits.", (AcceptableValueBase)(object)new AcceptableValueRange(0f, 10f), Array.Empty())); SlotsPerCrate = config.Bind("SeaSalvage", "SlotsPerCrate", 4, new ConfigDescription("Whole drops per native four-slot crate. Restart after edits.", (AcceptableValueBase)(object)new AcceptableValueRange(1, 4), Array.Empty())); MaxItemsPerPass = config.Bind("SeaSalvage", "MaxItemsPerPass", 16, new ConfigDescription("Maximum whole item drops transferred per pass. Restart after edits.", (AcceptableValueBase)(object)new AcceptableValueRange(1, 32), Array.Empty())); IntervalSeconds = config.Bind("SeaSalvage", "IntervalSeconds", 2f, new ConfigDescription("Processing interval. Restart after edits.", (AcceptableValueBase)(object)new AcceptableValueRange(1f, 30f), Array.Empty())); float[] array = new float[6] { MinimumDepthMeters.Value, MaximumDepthMeters.Value, DelaySeconds.Value, ScanRangeMeters.Value, GroupRadiusMeters.Value, IntervalSeconds.Value }; foreach (float f in array) { if (float.IsNaN(f) || float.IsInfinity(f)) { throw new ArgumentException("SeaSalvage settings must be finite."); } } DebugLogging = DebugLoggingResolver.Resolve(config, "SeaSalvage", DiagnosticsSettings.Bind(config), logger, DebugMode); } } } namespace HeimKit.Features.SeaSalvage.Models { internal sealed class SalvageSource { public ZDO Record; public ZDOID Identity; public Vector3 Position; public uint Revision; public long Owner; public byte[] Original; public byte[] Empty; } internal sealed class SettlingObservation { public long Owner; public uint Revision; public Vector3 Position; public float Since; public float Seen; } } namespace HeimKit.Features.InfiniteTorches { public sealed class InfiniteTorches : IServerModule { private readonly InfiniteTorchesSettings _settings; private readonly ManualLogSource _logger; private readonly GameVersionCompatibility _compatibility; private InfiniteTorchesController? _controller; private readonly PlayerServices _players; private IDisposable? _presenceRegistration; private bool _occupied; private ZDOMan? _world; private readonly PlayerProcessingNotices _processing; public string Name => "InfiniteTorches"; public bool IsActive { get; private set; } private static bool ServerReady => WorldServices.World; public InfiniteTorches(ConfigFile config, ManualLogSource logger, PlayerServices players) { _logger = logger; _compatibility = GameVersionCompatibility.Resolve(config, logger); _players = players; _settings = new InfiniteTorchesSettings(config, logger); _processing = new PlayerProcessingNotices(logger, Name, () => _settings.DebugLogging.Enabled); } public void Initialize(string gameVersion) { Shutdown(); DiagnosticLog.Write(_logger, Name, _settings.Enabled.Value ? "Enabled." : "Disabled.", (LogLevel)16); _settings.DebugLogging.ReportStartup(_logger, Name, _settings.Enabled.Value); if (!_settings.Enabled.Value) { return; } if (!_compatibility.Supports(gameVersion)) { DiagnosticLog.Write(_logger, "InfiniteTorches", "DISABLED (unsupported Valheim version " + gameVersion + "; required version " + _compatibility.RequiredVersion + "; built-in audited version 1.0.20). Configuration requests Enabled = true.", (LogLevel)4); return; } IsActive = true; if (_settings.DebugLogging.Enabled && DiagnosticLog.DebugAvailable(_logger, Name)) { DiagnosticLog.Write(_logger, Name, CoreLogTopics.Lifecycle, "Waiting for joined players and dedicated-server world", new(string, object)[4] { ("interval_s", _settings.IntervalSeconds.Value), ("maximum_requests_per", _settings.MaxMessagesPerPass.Value), ("debug_mode", true), ("log_schema", 1) }, (LogLevel)32); } _presenceRegistration = _players.Events.Subscribe(PresenceChanged, delegate(Exception error) { Fail(error, "responding to player presence"); }, () => _processing.IsEmptyPaused, () => _processing.IsRunning, () => _processing.IsServerReady); } public void Tick(float now) { if (!IsActive) { return; } if (!_settings.Enabled.Value) { Shutdown(); return; } if (ServerReady) { _processing.ServerReady(); } if (!_occupied) { return; } _ = ZNet.instance; ZDOMan instance = ZDOMan.instance; if (!WorldObjectProvider.Current.Ready) { StopController(); _processing.Paused("world services unavailable"); return; } if (_world != null && _world != instance) { StopController(); _processing.Paused("world changed"); } _world = instance; if (_controller == null) { _controller = new InfiniteTorchesController(this, _settings, _logger, _players.Presence); } _controller.Tick(now); } private void PresenceChanged(bool? occupied) { _occupied = occupied == true; if (!IsActive) { return; } if (!_occupied) { StopController(); if (occupied.HasValue) { _processing.EmptyPaused(); } else { _processing.Unavailable("player presence unavailable"); } } else if (_settings.Enabled.Value && _controller == null) { _controller = new InfiniteTorchesController(this, _settings, _logger, _players.Presence); } } internal void ProcessingReady() { _processing.Ready(); } private void StopController() { InfiniteTorchesController controller = _controller; _controller = null; if (controller != null) { ModuleScheduler.Current.Forget(controller); } _world = null; try { controller?.Dispose(); } finally { WorldObjectProvider.Current?.ReleaseOwner(Name); } } internal void Fail(Exception error, string operation) { DiagnosticLog.Write(_logger, "InfiniteTorches", CoreLogTopics.Lifecycle, "Disabled after runtime error while " + operation + ".", default(LogFields), (LogLevel)2, verbose: false, error); Shutdown(); } public void Shutdown() { IsActive = false; _occupied = false; _processing.Reset(); IDisposable registration = _presenceRegistration; _presenceRegistration = null; ModuleCleanup.Run(_logger, Name, delegate { registration?.Dispose(); }, StopController); } } internal sealed class InfiniteTorchesController : IDisposable { private readonly ManualLogSource _logger; private readonly IPlayerPresence _presence; private readonly InfiniteTorches _module; private readonly InfiniteTorchesSettings _settings; private readonly InfiniteTorchesDiagnostics _diagnostics; private readonly InfiniteTorchesPendingRefills _pending = new InfiniteTorchesPendingRefills(); private readonly PrefabCatalog _torches = PrefabRegistry.Current.Catalog("InfiniteTorchesController._torches"); private readonly List _sector = new List(); private CandidateSubscription? _index; private readonly List _distant = new List(); private readonly List _candidates = new List(); private readonly HashSet _seen = new HashSet(); private readonly Dictionary _owners = new Dictionary(); private ZNetScene? _scene; private string _configuredNames = ""; private int _configuredFireplaces; private int _cursor; private float _reconcileNow; private readonly Func _observeRefill; private readonly Action _reportRefill; private bool _announced; private readonly Dictionary _outcomes = new Dictionary(); internal string SettingsDescription => _diagnostics.SettingsDescription; public InfiniteTorchesController(InfiniteTorches module, InfiniteTorchesSettings settings, ManualLogSource logger, IPlayerPresence presence) { _logger = logger; _observeRefill = ObserveRefill; _presence = presence; _module = module; _settings = settings; _diagnostics = new InfiniteTorchesDiagnostics((Func)(() => _settings.DebugLogging.Enabled), logger, (Func>?)(() => new Dictionary(_outcomes))); _reportRefill = delegate(RefillResult result) { Count(result.Outcome); _diagnostics.Result(_reconcileNow, result); }; } public void Tick(float now) { //IL_0521: Unknown result type (might be due to invalid IL or missing references) //IL_05f0: Unknown result type (might be due to invalid IL or missing references) //IL_0231: Unknown result type (might be due to invalid IL or missing references) //IL_02b7: Unknown result type (might be due to invalid IL or missing references) //IL_0445: Unknown result type (might be due to invalid IL or missing references) //IL_045e: Unknown result type (might be due to invalid IL or missing references) //IL_0463: Unknown result type (might be due to invalid IL or missing references) //IL_0474: Unknown result type (might be due to invalid IL or missing references) //IL_049a: Unknown result type (might be due to invalid IL or missing references) //IL_04c9: Unknown result type (might be due to invalid IL or missing references) //IL_04f2: Unknown result type (might be due to invalid IL or missing references) //IL_0570: Unknown result type (might be due to invalid IL or missing references) if (!ModuleScheduler.Current.Due(this, "processing", now, _settings.IntervalSeconds.Value)) { return; } _ = ZNet.instance; ZNetScene instance = ZNetScene.instance; _ = ZDOMan.instance; ZRoutedRpc instance2 = ZRoutedRpc.instance; if (!WorldServices.World) { ReportUnavailableWorld(now); return; } string text = "resolving configured light-source prefabs"; ZNetPeer val = null; try { text = "checking pending refill results"; _reconcileNow = now; int fuelUpdates = _pending.Reconcile(now, _observeRefill, _reportRefill); _diagnostics.RefillSummary(fuelUpdates); text = "resolving configured light-source prefabs"; if ((Object)(object)_scene != (Object)(object)instance || _configuredNames != _settings.Prefabs.Value || _configuredFireplaces != _settings.FireplaceSelection) { LoadPrefabs(instance); } if (_torches.Count == 0) { if (_diagnostics.SummaryReady(now)) { _diagnostics.Report(now, () => "No supported light-source prefabs configured. Check Torches.Prefabs and startup warnings."); } return; } _owners.Clear(); for (int num = 0; num < _presence.Peers.Count; num++) { ZNetPeer val2 = _presence.Peers[num]; if (val2.IsReady() && !((ZDOID)(ref val2.m_characterID)).IsNone()) { _owners[val2.m_uid] = val2; } } _candidates.Clear(); _seen.Clear(); if (_owners.Count == 0) { if (_diagnostics.SummaryReady(now)) { _diagnostics.Report(now, () => "No ready connected players with character IDs."); } return; } int num2 = 0; foreach (ZNetPeer value in _owners.Values) { text = "scanning sectors"; val = value; _sector.Clear(); _distant.Clear(); _index.Read(value.m_refPos, ((SimulationDistance)(ref value.m_simulationDistance)).NearSimulationDistance, _sector, ((SimulationDistance)(ref value.m_simulationDistance)).IsClassic, includeDistant: false); num2 += _sector.Count; foreach (ZDO item in _sector) { if (item.IsValid() && item.GetOwner() == value.m_uid && _torches.ContainsKey(item.GetPrefab()) && _seen.Add(item.m_uid)) { _candidates.Add(item); } } } if (_candidates.Count == 0) { _cursor = 0; if (_diagnostics.SummaryReady(now)) { ReportEmptyScope(now, num2); } return; } int num3 = 0; int num4 = 0; int num5 = 0; int num6 = 0; int num7 = 0; int num8 = 0; int num9 = 0; int num10 = 0; _cursor %= _candidates.Count; while (num4 < _candidates.Count && num3 < _settings.MaxMessagesPerPass.Value) { ZDO val3 = _candidates[_cursor]; _cursor = (_cursor + 1) % _candidates.Count; num4++; Fireplace val4 = _torches[val3.GetPrefab()]; long owner = val3.GetOwner(); if (!_owners.ContainsKey(owner)) { num8++; continue; } if (val3.GetInt(ZDOVars.s_state, 1) != 1) { num6++; continue; } float num11 = val3.GetFloat(ZDOVars.s_fuel, val4.m_startFuel); if (float.IsNaN(num11) || float.IsInfinity(num11)) { num7++; continue; } if (num11 >= val4.m_maxFuel * 0.75f) { num5++; continue; } if (_pending.Contains(val3.m_uid)) { num9++; continue; } Vector3 position = val3.GetPosition(); text = $"requesting refill: object={val3.m_uid}; prefab={((Object)((Component)val4).gameObject).name}; owner={owner}; position={position}; fuel={num11}; target={val4.m_maxFuel}"; if (!_pending.TryTrack(val3.m_uid, owner, num11, val4.m_maxFuel, now)) { num10++; continue; } try { instance2.InvokeRoutedRPC(owner, val3.m_uid, "RPC_SetFuelAmount", new object[1] { val4.m_maxFuel }); } catch { _pending.Remove(val3.m_uid); throw; } num3++; Count("requests_sent"); if (_diagnostics.IsDebugEnabled) { _diagnostics.Request(now, ((object)Unsafe.As(ref val3.m_uid)/*cast due to .constrained prefix*/).ToString(), ((Object)((Component)val4).gameObject).name, position, num11, val4.m_maxFuel); } } if (_diagnostics.SummaryReady(now)) { ReportScan(now, num3, num4, num5, num6, num7, num8, num9, num10); } } catch (Exception error) { if (text == "scanning sectors" && val != null) { text = $"scanning sectors for owner {val.m_uid} at {val.m_refPos}"; } _module.Fail(error, text); } } private void ReportUnavailableWorld(float now) { if (!_diagnostics.SummaryReady(now)) { return; } ZNet net = ZNet.instance; ZNetScene scene = ZNetScene.instance; ZDOMan manager = ZDOMan.instance; ZRoutedRpc routed = ZRoutedRpc.instance; if ((Object)(object)net == (Object)null || (Object)(object)scene == (Object)null || manager == null || routed == null) { _diagnostics.Report(now, () => "Waiting for world services. Unavailable: " + (((Object)(object)net == (Object)null) ? "network " : "") + (((Object)(object)scene == (Object)null) ? "scene " : "") + (((manager == null) ? "world-object data " : "") + ((routed == null) ? "RPC routing" : "")).TrimEnd() + "."); } else { _diagnostics.Report(now, () => "Not running in a dedicated-server network session."); } } private void ReportEmptyScope(float now, int sectorRecords) { _diagnostics.Report(now, () => $"No eligible client-owned light sources in players' nearby areas; ready_players_now={_owners.Count}; prefab_types_now={_torches.Count}; sector_records_pass={sectorRecords}."); } private void ReportScan(float now, int sent, int examined, int sufficientFuel, int stateOff, int invalidFuel, int changedOwner, int pendingSkipped, int trackingFull) { if (_diagnostics.SummaryReady(now)) { _diagnostics.Report(now, delegate { string text = ((sent > 0) ? "Refill requests sent this pass; client application is unconfirmed." : ((sufficientFuel == examined) ? "All examined light sources have enough fuel (at least 75%)." : ((pendingSkipped > 0) ? "Waiting for previously requested refills; duplicate requests suppressed." : "No examined light source could be refilled this pass; see skip counts."))); return $"{text}; ready_players_now={_owners.Count}; candidates_now={_candidates.Count}; examined_pass={examined}; requests_sent_pass={sent}; " + $"sufficient_fuel_pass={sufficientFuel}; off_pass={stateOff}; invalid_fuel_pass={invalidFuel}; owner_unavailable_pass={changedOwner}; " + $"pending_now={_pending.Count}; duplicates_suppressed_pass={pendingSkipped}; tracking_capacity_skips_pass={trackingFull}; " + $"deferred_pass={_candidates.Count - examined}."; }); } } private RefillObservation? ObserveRefill(ZDOID id) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) ZDO zDO = ZDOMan.instance.GetZDO(id); if (zDO == null || !zDO.IsValid()) { return null; } return new RefillObservation(zDO.GetOwner(), zDO.GetFloat(ZDOVars.s_fuel, -1f)); } private void Count(string kind) { _outcomes.TryGetValue(kind, out var value); _outcomes[kind] = value + 1; } private void LoadPrefabs(ZNetScene scene) { _index?.Dispose(); _index = null; _torches.Clear(); Dictionary dictionary = new Dictionary(); int num = 0; HashSet hashSet = new HashSet(StringComparer.Ordinal); string[] array = _settings.Prefabs.Value.Split(','); foreach (string text in array) { if (text.Trim().Length > 0) { hashSet.Add(text.Trim()); } } array = new string[3] { "fire_pit", "hearth", "bonfire" }; foreach (string text2 in array) { if (_settings.FireplaceEnabled(text2)) { hashSet.Add(text2); } } foreach (string item in hashSet) { string text3 = item.Trim(); if (text3.Length != 0) { GameObject val = PrefabRegistry.Current.Prefab(text3); Fireplace val2 = (((Object)(object)val != (Object)null) ? PrefabRegistry.Component(val) : null); string text4 = (((Object)(object)val == (Object)null) ? "prefab not found" : (((Object)(object)val2 == (Object)null) ? "no Fireplace component" : InfiniteTorchesRefillRules.RejectionReason(text3, val2.m_canRefill, val2.m_infiniteFuel, val2.m_canTurnOff, (Object)(object)val2.m_enabledObjectLow != (Object)null || (Object)(object)val2.m_enabledObjectHigh != (Object)null, val2.m_maxFuel, _settings.FireplaceEnabled(text3)))); if (text4 != null) { dictionary.TryGetValue(text4, out var value); dictionary[text4] = value + 1; num++; } else { _torches[scene.GetPrefabHash(val)] = val2; } } } _diagnostics.UnsupportedPrefabs(num, dictionary); _index = WorldObjectProvider.Current.Subscribe("InfiniteTorches", (ZDO z) => _torches.ContainsKey(z.GetPrefab())); _scene = scene; _configuredNames = _settings.Prefabs.Value; _configuredFireplaces = _settings.FireplaceSelection; if (!_announced) { if (_torches.Count > 0) { _module.ProcessingReady(); } else { DiagnosticLog.Write(_logger, "InfiniteTorches", "No supported light-source prefabs are available; refilling is unavailable.", (LogLevel)4); } if (_diagnostics.IsDebugEnabled && DiagnosticLog.DebugAvailable(_logger, "InfiniteTorches")) { DiagnosticLog.Write(_logger, "InfiniteTorches", InfiniteTorchesLogTopics.Refill, "Resolved light-source prefab definitions.", new(string, object)[1] { ("prefab_types", _torches.Count) }, (LogLevel)32); } _announced = true; } } public void Dispose() { _index?.Dispose(); _index = null; _torches.Clear(); _sector.Clear(); _distant.Clear(); _candidates.Clear(); _seen.Clear(); _owners.Clear(); _scene = null; _configuredNames = ""; _cursor = 0; _announced = false; _diagnostics.Reset(); _pending.Clear(); } } public sealed class InfiniteTorchesDiagnostics : FeatureDiagnostics { private readonly ManualLogSource _logger; private readonly Func _debugEnabled; private readonly Func>? _totals; private Dictionary _previous = new Dictionary(); private float _lastSummary; private bool _reported; public const int RefillDetailLimit = 4; public bool IsDebugEnabled => base.DiagnosticsEnabled; public string SettingsDescription => $"debug mode {IsDebugEnabled}; automatic diagnostic interval 60s"; public InfiniteTorchesDiagnostics(ConfigFile config, ManualLogSource logger) : this(new InfiniteTorchesSettings(config, logger).DebugLogging, logger) { } public InfiniteTorchesDiagnostics(ConfigEntry debugMode, ManualLogSource logger, Func>? totals = null) : this((Func)(() => debugMode.Value), logger, totals) { } public InfiniteTorchesDiagnostics(DebugLoggingPolicy policy, ManualLogSource logger) : this((Func)(() => policy.Enabled), logger, (Func>?)null) { } public InfiniteTorchesDiagnostics(Func debugEnabled, ManualLogSource logger, Func>? totals = null) { _logger = logger; _debugEnabled = debugEnabled; ConfigureDiagnostics(debugEnabled, logger, "InfiniteTorches"); _totals = totals; } private void Write(LogTopic topic, string message, Dictionary fields) { if (IsDebugEnabled) { LogFields logFields = fields; DiagnosticLog.Write(_logger, "InfiniteTorches", topic, message, logFields.Take(8), (LogLevel)32); if (base.VerboseEnabled && fields.Count > 8) { DiagnosticLog.Write(_logger, "InfiniteTorches", topic, (fields.TryGetValue("object", out object value) && value != null) ? $"Refill evidence for object {value}." : "Refill evidence for the last minute.", logFields.Skip(8), (LogLevel)32, verbose: true); } } } private static (string Message, Dictionary Fields) Payload(string text, int maximum = 8) { string[] array = text.Split(new string[1] { "; " }, StringSplitOptions.None); Dictionary dictionary = new Dictionary(); string[] array2 = array; foreach (string text2 in array2) { if (dictionary.Count >= maximum) { break; } int num = text2.IndexOf('='); if (num < 0) { continue; } string text3 = new string((from c in text2.Substring(0, num) select (!char.IsLetterOrDigit(c)) ? '_' : char.ToLowerInvariant(c)).ToArray()); string text4 = text2.Substring(num + 1).TrimEnd('.'); string[] array3 = new string[3] { "_now", "_pass", "_interval" }; foreach (string text5 in array3) { if (text3.EndsWith(text5, StringComparison.Ordinal)) { text3 = text3.Substring(0, text3.Length - text5.Length); break; } } dictionary[text3] = (long.TryParse(text4, out var result) ? ((object)result) : (bool.TryParse(text4, out var result2) ? ((object)result2) : text4)); } return (Message: array[0].Contains("=") ? "Refill request sent; client application unconfirmed" : array[0], Fields: dictionary); } public void LogRefillRequest(float now, Func describe) { if (IsDebugEnabled && _budget.Reserve(now, "refill_requests", 4)) { (string, Dictionary) tuple = Payload(describe()); Write(InfiniteTorchesLogTopics.Refill, tuple.Item1, tuple.Item2); } } public void Request(float now, string id, string prefab, Vector3 position, float before, float target) { //IL_004c: Unknown result type (might be due to invalid IL or missing references) if (IsDebugEnabled && _budget.Reserve(now, "refill_requests", 4)) { Write(InfiniteTorchesLogTopics.Refill, "Refill request sent; client application unconfirmed", new Dictionary { ["object"] = id, ["prefab"] = prefab, ["pos"] = position, ["fuel_before"] = DiagnosticLog.Kept(before), ["fuel_target"] = target }); } } public void UnsupportedPrefabs(int count, IReadOnlyDictionary reasons) { if (count > 0) { string arg = string.Join(", ", from pair in reasons orderby pair.Key select pair.Key + " (" + pair.Value + ")"); DiagnosticLog.Write(_logger, "InfiniteTorches", $"Skipped {count} unsupported prefab entries: {arg}. Review Torches.Prefabs.", (LogLevel)4); } } public void RefillSummary(int fuelUpdates) { if (fuelUpdates > 0) { DiagnosticLog.Write(_logger, "InfiniteTorches", string.Format("Fuel increase observed for {0} {1}.", fuelUpdates, (fuelUpdates == 1) ? "light source" : "light sources"), (LogLevel)16); } } public void Result(float now, RefillResult result) { if (IsDebugEnabled && _budget.Reserve(now, "refill_results", 6)) { string message = ((result.Outcome == "fuel_increase") ? "Fuel increase observed after request; delivery acknowledgement unavailable" : ((result.Outcome == "timeout") ? "Sufficient fuel increase not observed; retry permitted if eligible" : ((result.Outcome == "owner_changed") ? "Owner changed; prior request tracking cleared" : "Object unavailable; request tracking cleared"))); Dictionary dictionary = new Dictionary { ["object"] = result.Object, ["outcome"] = result.Outcome, ["wait_s"] = result.WaitSeconds, ["fuel_before"] = DiagnosticLog.Kept(result.Before), ["fuel_target"] = result.Target, ["fuel_observed"] = DiagnosticLog.Kept(result.Fuel) }; if (result.Outcome == "owner_changed") { dictionary["requested_owner"] = result.RequestedOwner; dictionary["observed_owner"] = result.ObservedOwner; } Write(InfiniteTorchesLogTopics.Refill, message, dictionary); } } public void Report(float now, Func describe) { if (!IsDebugEnabled || !_budget.Reserve(now, "summary", 1, countOmitted: false)) { return; } bool verboseAfterNormalEnabled = base.VerboseAfterNormalEnabled; (string, Dictionary) tuple = Payload(describe(), verboseAfterNormalEnabled ? int.MaxValue : 5); tuple.Item2["interval_s"] = (_reported ? Math.Max(0f, now - _lastSummary) : 0f); tuple.Item2["omitted_messages"] = _budget.TakeOmitted(); Dictionary dictionary = _totals?.Invoke() ?? new Dictionary(); foreach (KeyValuePair item in dictionary) { if (!verboseAfterNormalEnabled && tuple.Item2.Count >= 8) { break; } _previous.TryGetValue(item.Key, out var value); tuple.Item2[item.Key] = Math.Max(0L, item.Value - value); } Write(CoreLogTopics.Scope, tuple.Item1, tuple.Item2); _previous = new Dictionary(dictionary); _lastSummary = now; _reported = true; } public void Reset() { _budget.Reset(); _previous.Clear(); _lastSummary = 0f; _reported = false; } } public static class InfiniteTorchesLogTopics { public static readonly LogTopic Refill = new LogTopic("refill"); } public sealed class InfiniteTorchesPendingRefills { public const float TimeoutSeconds = 30f; public const int Capacity = 2048; private readonly Dictionary _requests = new Dictionary(); private readonly List _completed = new List(); public int Count => _requests.Count; public bool Contains(ZDOID id) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) return _requests.ContainsKey(id); } public bool TryTrack(ZDOID id, long owner, float before, float target, float now) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0028: Unknown result type (might be due to invalid IL or missing references) if (_requests.ContainsKey(id) || _requests.Count >= 2048) { return false; } _requests.Add(id, new RefillRequest(owner, before, target, now)); return true; } public void Remove(ZDOID id) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) _requests.Remove(id); } public int Reconcile(float now, Func observe, Action? report) { //IL_0031: 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_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_020f: Unknown result type (might be due to invalid IL or missing references) //IL_0125: Unknown result type (might be due to invalid IL or missing references) //IL_012a: Unknown result type (might be due to invalid IL or missing references) _completed.Clear(); int num = 0; foreach (KeyValuePair request in _requests) { RefillRequest value = request.Value; RefillObservation? refillObservation = observe(request.Key); string text = null; if (!refillObservation.HasValue) { text = "object_missing"; } else if (refillObservation.Value.Owner != value.Owner) { text = "owner_changed"; } else if (!float.IsNaN(refillObservation.Value.Fuel) && !float.IsInfinity(refillObservation.Value.Fuel) && refillObservation.Value.Fuel > value.Before + 0.001f && refillObservation.Value.Fuel >= value.Target * 0.75f) { text = "fuel_increase"; } else if (now - value.SentAt >= 30f) { text = "timeout"; } if (text != null) { _completed.Add(request.Key); if (text == "fuel_increase") { num++; } report?.Invoke(new RefillResult { Object = ((object)request.Key/*cast due to .constrained prefix*/).ToString(), Outcome = text, RequestedOwner = value.Owner, ObservedOwner = refillObservation?.Owner, Fuel = refillObservation?.Fuel, Before = value.Before, Target = value.Target, WaitSeconds = now - value.SentAt }); } } foreach (ZDOID item in _completed) { _requests.Remove(item); } _completed.Clear(); return num; } public void Clear() { _requests.Clear(); _completed.Clear(); } } internal static class InfiniteTorchesRefillRules { internal static bool IsFireplace(string name) { if (!(name == "fire_pit") && !(name == "hearth")) { return name == "bonfire"; } return true; } internal static string? RejectionReason(string name, bool canRefill, bool infiniteFuel, bool canTurnOff, bool hasWetFlames, float maximumFuel, bool includeFireplaces = false) { bool flag = name == "piece_brazierceiling01" || name == "piece_brazierfloor01" || name == "piece_brazierfloor02"; bool flag2 = IsFireplace(name); if (!flag2 || includeFireplaces) { if (canRefill) { if (!infiniteFuel) { if (!canTurnOff) { if (!hasWetFlames || flag || flag2) { if (!(maximumFuel <= 0f) && !float.IsNaN(maximumFuel) && !float.IsInfinity(maximumFuel)) { return null; } return "invalid maximum fuel"; } return "wet-flame behavior is outside the supported light-source scope"; } return "toggle-off behavior is outside the supported light-source scope"; } return "already has infinite fuel"; } return "refilling not supported"; } return "fire type disabled by fireplace settings"; } } public sealed class InfiniteTorchesSettings { public ConfigEntry Enabled { get; } public ConfigEntry IntervalSeconds { get; } public ConfigEntry MaxMessagesPerPass { get; } public ConfigEntry Prefabs { get; } public ConfigEntry IncludeFireplaces { get; } public ConfigEntry Campfires { get; } public ConfigEntry Hearths { get; } public ConfigEntry Bonfires { get; } internal int FireplaceSelection { get { if (IncludeFireplaces.Value) { return (int)((Campfires.Value ? 1u : 0u) | (uint)(Hearths.Value ? 2 : 0)) | (Bonfires.Value ? 4 : 0); } return 0; } } public ConfigEntry DebugMode { get; } public ConfigEntry GlobalDebugMode { get; } public DebugLoggingPolicy DebugLogging { get; } internal bool FireplaceEnabled(string name) { bool flag = IncludeFireplaces.Value; if (flag) { flag = name switch { "fire_pit" => Campfires.Value, "hearth" => Hearths.Value, "bonfire" => Bonfires.Value, _ => false, }; } return flag; } public InfiniteTorchesSettings(ConfigFile config, ManualLogSource? logger = null) { //IL_004c: Unknown result type (might be due to invalid IL or missing references) //IL_0056: Expected O, but got Unknown //IL_007e: Unknown result type (might be due to invalid IL or missing references) //IL_0088: Expected O, but got Unknown Enabled = config.Bind("Torches", "Enabled", true, "Automatically refill eligible torches, braziers and configured fires for free. Restart after config edits."); IntervalSeconds = config.Bind("Torches", "IntervalSeconds", 5f, new ConfigDescription("Seconds between refills. Large bases may take several passes.", (AcceptableValueBase)(object)new AcceptableValueRange(2f, 60f), Array.Empty())); MaxMessagesPerPass = config.Bind("Torches", "MaxMessagesPerPass", 32, new ConfigDescription("Limits network traffic; processing rotates across candidates.", (AcceptableValueBase)(object)new AcceptableValueRange(1, 256), Array.Empty())); IncludeFireplaces = config.Bind("Torches", "IncludeFireplaces", false, "Enable fireplace refilling, controlled individually by Campfires, Hearths and Bonfires. False excludes these fires even if listed in Prefabs. Native smoke, shelter and water behavior remains active. Restart after edits."); Campfires = config.Bind("Torches", "Campfires", true, "Refill campfires when IncludeFireplaces is true. False excludes them even if listed in Prefabs. Restart after edits."); Hearths = config.Bind("Torches", "Hearths", true, "Refill hearths when IncludeFireplaces is true. False excludes them even if listed in Prefabs. Restart after edits."); Bonfires = config.Bind("Torches", "Bonfires", true, "Refill bonfires when IncludeFireplaces is true. False excludes them even if listed in Prefabs. Restart after edits."); Prefabs = config.Bind("Torches", "Prefabs", "piece_groundtorch_wood,piece_groundtorch,piece_groundtorch_green,piece_groundtorch_blue,piece_walltorch,piece_brazierceiling01,piece_brazierfloor01,piece_brazierfloor02", "Exact prefab allowlist. Only refillable non-toggle lights qualify. Wet-flame objects qualify only for the three default braziers and, with IncludeFireplaces and the corresponding type enabled, campfires, hearths and bonfires."); GlobalDebugMode = DiagnosticsSettings.Bind(config); DebugMode = config.Bind("Torches", "DebugMode", false, "Enable diagnostics for this feature even when global DebugMode is off. The hidden suppression override still takes precedence. Restart after edits."); DebugLogging = DebugLoggingResolver.Resolve(config, "Torches", GlobalDebugMode, logger, DebugMode); } } } namespace HeimKit.Features.InfiniteTorches.Models { public readonly struct RefillObservation { public readonly long Owner; public readonly float Fuel; public RefillObservation(long owner, float fuel) { Owner = owner; Fuel = fuel; } } internal readonly struct RefillRequest { public readonly long Owner; public readonly float Before; public readonly float Target; public readonly float SentAt; public RefillRequest(long owner, float before, float target, float now) { Owner = owner; Before = before; Target = target; SentAt = now; } } public sealed class RefillResult { public string Object { get; set; } = ""; public string Outcome { get; set; } = ""; public long RequestedOwner { get; set; } public long? ObservedOwner { get; set; } public float Before { get; set; } public float Target { get; set; } public float? Fuel { get; set; } public float WaitSeconds { get; set; } } } namespace HeimKit.Features.HeimMender { public sealed class HeimMender : IServerModule { private readonly ConfigFile _config; private readonly HeimMenderSettings _settings; private readonly ManualLogSource _logger; private readonly GameVersionCompatibility _compatibility; private readonly PlayerServices _players; private readonly PlayerProcessingNotices _processing; private HeimMenderController? _controller; private HeimMenderConfiguration? _configuration; private HeimMenderAdministration? _administration; private IDisposable? _presenceRegistration; private bool _occupied; private bool _compatible; private bool _failed; private int _requestId; private ZDOMan? _world; private long _worldUid; public string Name => "HeimMender"; public bool IsActive { get; private set; } public HeimMender(ConfigFile config, ManualLogSource logger, PlayerServices players) { _config = config; _logger = logger; _players = players; _compatibility = GameVersionCompatibility.Resolve(config, logger); _settings = new HeimMenderSettings(config, logger); _processing = new PlayerProcessingNotices(logger, Name, () => _settings.DebugLogging.Enabled); } public void Initialize(string gameVersion) { Shutdown(); _failed = false; _compatible = _compatibility.Supports(gameVersion); _requestId = _settings.RepairRequestId.Value; Log(_settings.Enabled.Value ? "Enabled." : "Disabled.", (LogLevel)16); _settings.DebugLogging.ReportStartup(_logger, Name, _settings.Enabled.Value); if (!_compatible) { if (_settings.Enabled.Value) { Log("DISABLED: unsupported game version " + gameVersion + "; required version " + _compatibility.RequiredVersion, (LogLevel)4); } } else { _configuration = new HeimMenderConfiguration(_config, _settings, _logger); ApplyEnabled(); } } private void ApplyEnabled() { bool flag = _settings.Enabled.Value && _compatible && !_failed; if (flag == IsActive) { return; } if (!flag) { IsActive = false; _occupied = false; StopController(); IDisposable? presenceRegistration = _presenceRegistration; _presenceRegistration = null; presenceRegistration?.Dispose(); _processing.Paused("disabled by configuration"); Log("Disabled.", (LogLevel)16); return; } IsActive = true; try { _presenceRegistration = _players.Events.Subscribe(PresenceChanged, Fail, () => _processing.IsEmptyPaused, () => _processing.IsRunning, () => _processing.IsServerReady); } catch (Exception error) { Fail(error); } if (!IsActive) { IDisposable? presenceRegistration2 = _presenceRegistration; _presenceRegistration = null; presenceRegistration2?.Dispose(); } } public void Tick(float now) { _configuration?.Tick(now); ApplyEnabled(); try { bool flag = WorldServices.Activity && WorldServices.Terrain; if (_compatible && !_failed && flag && _administration == null) { _administration = new HeimMenderAdministration(Request, () => _controller?.Status ?? "HeimMender: no active repair scope."); } if (IsActive && flag) { _processing.ServerReady(); } if (!IsActive || !_occupied || !flag) { StopController(); if (IsActive && _occupied && !flag) { _processing.Paused("world services unavailable"); } } else { long worldUID = ZNet.instance.GetWorldUID(); if (_world != ZDOMan.instance || _worldUid != worldUID) { StopController(); _world = ZDOMan.instance; _worldUid = worldUID; } if (_controller == null) { _controller = new HeimMenderController(_settings, _logger, _players, Fail); _processing.Ready(); } _controller.Tick(now); } int value = _settings.RepairRequestId.Value; if (value > _requestId) { _requestId = value; Request(_settings.RepairTarget.Value, null); } } catch (Exception error) { Fail(error); } } private void Request(string target, float? radius) { try { if (!IsActive || _controller == null) { Log("Repair request rejected: enabled gameplay and a ready joined player are required.", (LogLevel)4); } else { _controller.Request(target.Trim(), radius, Time.unscaledTime); } } catch (Exception error) { Fail(error); } } private void PresenceChanged(bool? occupied) { _occupied = occupied == true; if (IsActive && !_occupied) { StopController(); if (occupied.HasValue) { _processing.EmptyPaused(); } else { _processing.Unavailable("player presence unavailable"); } } } private void StopController() { HeimMenderController controller = _controller; _controller = null; if (controller != null) { ModuleScheduler.Current.Forget(controller); } try { controller?.Dispose(); } finally { WorldObjectProvider.Current?.ReleaseOwner(Name); } } internal void Fail(Exception error) { if (!_failed) { _failed = true; DiagnosticLog.Write(_logger, Name, CoreLogTopics.Lifecycle, "Disabled after a runtime failure.", default(LogFields), (LogLevel)2, verbose: false, error); IsActive = false; _occupied = false; IDisposable registration = _presenceRegistration; _presenceRegistration = null; ModuleCleanup.Run(_logger, Name, delegate { registration?.Dispose(); }, StopController, delegate { _administration?.Dispose(); }); _administration = null; } } private void Log(string message, LogLevel level = (LogLevel)16) { //IL_000d: Unknown result type (might be due to invalid IL or missing references) DiagnosticLog.Write(_logger, Name, message, level); } public void Shutdown() { IsActive = false; _compatible = false; _occupied = false; _processing.Reset(); IDisposable registration = _presenceRegistration; _presenceRegistration = null; ModuleCleanup.Run(_logger, Name, delegate { registration?.Dispose(); }, StopController, delegate { _configuration?.Dispose(); }, delegate { _administration?.Dispose(); }); _configuration = null; _administration = null; _world = null; } } internal sealed class HeimMenderAdministration : IDisposable { private readonly Dictionary _commands; private readonly ConsoleCommand _command; public HeimMenderAdministration(Action request, Func status) { //IL_0086: Unknown result type (might be due to invalid IL or missing references) //IL_009a: Expected O, but got Unknown //IL_0095: Unknown result type (might be due to invalid IL or missing references) //IL_009f: Expected O, but got Unknown NativeAccess.Method(typeof(Terminal), "InitTerminal", Array.Empty())(); _commands = NativeAccess.StaticField>(typeof(Terminal), "commands")(); if (_commands.ContainsKey("heimmender")) { throw new InvalidOperationException("Another provider registered heimmender."); } _command = new ConsoleCommand("heimmender", "status | repair [radius] (dedicated-server terminal)", (ConsoleEvent)delegate(ConsoleEventArgs args) { if (args.Length == 2 && args[1] == "status") { Terminal context = args.Context; if (context != null) { context.AddString(status()); } } else if (args.Length < 3 || args.Length > 4 || args[1] != "repair") { Terminal context2 = args.Context; if (context2 != null) { context2.AddString("Usage: heimmender repair [radius]"); } } else { float? arg = null; if (args.Length == 4) { if (!float.TryParse(args[3], NumberStyles.Float, CultureInfo.InvariantCulture, out var result)) { Terminal context3 = args.Context; if (context3 != null) { context3.AddString("Invalid radius."); } return; } arg = result; } request(args[2], arg); } }, false, false, true, false, false, false, (ConsoleOptionsFetcher)null, false, false, false); } public void Dispose() { if (_commands.TryGetValue("heimmender", out ConsoleCommand value) && value == _command) { _commands.Remove("heimmender"); } } } internal sealed class HeimMenderConfiguration : IDisposable { private readonly ConfigFile _config; private readonly HeimMenderSettings _settings; private readonly ManualLogSource _log; private FileSystemWatcher? _watcher; private long _changed; private DateTime _stamp; private readonly ScheduleToken _nextPoll = new ScheduleToken(); private string _lastError = ""; public HeimMenderConfiguration(ConfigFile config, HeimMenderSettings settings, ManualLogSource log) { _config = config; _settings = settings; _log = log; _stamp = File.GetLastWriteTimeUtc(config.ConfigFilePath); try { _watcher = new FileSystemWatcher(Path.GetDirectoryName(config.ConfigFilePath), Path.GetFileName(config.ConfigFilePath)); _watcher.NotifyFilter = NotifyFilters.FileName | NotifyFilters.Size | NotifyFilters.LastWrite; _watcher.Changed += Changed; _watcher.Created += Changed; _watcher.Renamed += Renamed; _watcher.Error += delegate { Interlocked.Exchange(ref _changed, DateTime.UtcNow.Ticks); }; _watcher.EnableRaisingEvents = true; } catch (Exception ex) { _watcher?.Dispose(); _watcher = null; Report("File watcher unavailable; timestamp polling remains active: " + ex.Message); } } private void Changed(object sender, FileSystemEventArgs args) { Interlocked.Exchange(ref _changed, DateTime.UtcNow.Ticks); } private void Renamed(object sender, RenamedEventArgs args) { Changed(sender, args); } public void Tick(float now) { if (!_nextPoll.Ready(now)) { return; } _nextPoll.Postpone(now, 1f); try { DateTime lastWriteTimeUtc = File.GetLastWriteTimeUtc(_config.ConfigFilePath); if (lastWriteTimeUtc != _stamp) { _stamp = lastWriteTimeUtc; Interlocked.Exchange(ref _changed, DateTime.UtcNow.Ticks); return; } long num = Interlocked.Read(in _changed); if (num == 0L || DateTime.UtcNow.Ticks - num < 10000000 || Interlocked.CompareExchange(ref _changed, 0L, num) != num) { return; } FileInfo fileInfo = new FileInfo(_config.ConfigFilePath); if (!fileInfo.Exists || fileInfo.Length > 1048576) { throw new InvalidDataException("Config missing or exceeds 1 MiB."); } Dictionary dictionary = new Dictionary(StringComparer.Ordinal); bool flag = false; string[] array = File.ReadAllLines(fileInfo.FullName); for (int i = 0; i < array.Length; i++) { string text = array[i].Trim(); if (text.StartsWith("[")) { flag = text == "[HeimMender]"; } else if (flag && text.Length != 0 && !text.StartsWith("#")) { int num2 = text.IndexOf('='); if (num2 <= 0) { throw new InvalidDataException("Malformed HeimMender setting."); } string text2 = text.Substring(0, num2).Trim(); if (dictionary.ContainsKey(text2)) { throw new InvalidDataException("Duplicate setting: " + text2); } dictionary.Add(text2, text.Substring(num2 + 1).Trim()); } } List<(ConfigEntryBase, object)> list = new List<(ConfigEntryBase, object)>(); foreach (ConfigEntryBase entry in _settings.Entries) { if (!dictionary.TryGetValue(entry.Definition.Key, out var value)) { continue; } object obj; if (entry.SettingType == typeof(bool)) { obj = bool.Parse(value); } else if (entry.SettingType == typeof(int)) { obj = int.Parse(value, CultureInfo.InvariantCulture); } else if (entry.SettingType == typeof(float)) { float num3 = float.Parse(value, CultureInfo.InvariantCulture); if (!PlayerWorldScope.Finite(num3)) { throw new FormatException("Nonfinite " + entry.Definition.Key); } obj = num3; } else { obj = value; } if (entry.Description.AcceptableValues != null && !entry.Description.AcceptableValues.IsValid(obj)) { throw new FormatException("Out of range: " + entry.Definition.Key); } if (!object.Equals(obj, entry.BoxedValue)) { list.Add((entry, obj)); } } bool saveOnConfigSet = _config.SaveOnConfigSet; try { _config.SaveOnConfigSet = false; foreach (var item in list) { item.Item1.BoxedValue = item.Item2; } } finally { _config.SaveOnConfigSet = saveOnConfigSet; } if (list.Count > 0) { DiagnosticLog.Write(_log, "HeimMender", "Reloaded " + list.Count + " settings.", (LogLevel)16); } _lastError = ""; } catch (Exception ex) { Report("Configuration reload rejected; keeping current settings: " + ex.Message); } } private void Report(string message) { if (!(message == _lastError)) { _lastError = message; DiagnosticLog.Write(_log, "HeimMender", message, (LogLevel)4); } } public void Dispose() { _watcher?.Dispose(); _watcher = null; } } internal sealed class HeimMenderController : IDisposable { private static readonly int SayMethod = StringExtensionMethods.GetStableHashCode("Say"); private static readonly int ChatMethod = StringExtensionMethods.GetStableHashCode("ChatMessage"); private readonly HeimMenderSettings _settings; private readonly ManualLogSource _log; private readonly PlayerServices _players; private readonly PlayerWorldScope _scope; private readonly HeimMenderRules _rules = new HeimMenderRules(); private readonly HeimMenderDiagnostics _diagnostics; private readonly Dictionary _observations = new Dictionary(); private readonly Dictionary _threats = new Dictionary(); private readonly Queue _queue = new Queue(); private readonly Dictionary _pending = new Dictionary(); private readonly Dictionary _adminRate = new Dictionary(); private readonly Random _random = new Random(); private readonly IDisposable _messages; private readonly List _expiredAdmins = new List(); private readonly List _expiredRecords = new List(); private readonly List _playerPositions = new List(); private readonly List _threatPositions = new List(); private readonly List _candidates = new List(); private readonly ScheduleToken _cycle = new ScheduleToken(); private float _interval; private float _threatUnknownUntil; private bool _observationCapacity; private int _sent; private int _confirmed; private int _unconfirmed; private string _kind = ""; public string Status => "HeimMender: queued=" + _queue.Count + ", pending=" + _pending.Count + ", batch=" + ((_kind.Length == 0) ? "none" : _kind) + "."; public HeimMenderController(HeimMenderSettings settings, ManualLogSource log, PlayerServices players, Action fail) { _settings = settings; _log = log; _players = players; _scope = WorldObjectProvider.Current.CreateScope("HeimMender"); _diagnostics = new HeimMenderDiagnostics(log, settings.DebugLogging); _interval = settings.IntervalSeconds.Value; _cycle.Postpone(Time.unscaledTime, _interval); _messages = players.RoutedMessages.Subscribe(Observe, fail); try { _scope.Index((ZDO z) => _rules.Monster(z.GetPrefab()) || _rules.Eligible(z, out var _, out var _)); } catch { _messages.Dispose(); throw; } } public void Tick(float now) { //IL_01ac: 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_01e5: Unknown result type (might be due to invalid IL or missing references) //IL_01ed: Unknown result type (might be due to invalid IL or missing references) //IL_024e: Unknown result type (might be due to invalid IL or missing references) //IL_0282: 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_028f: Unknown result type (might be due to invalid IL or missing references) //IL_0385: Unknown result type (might be due to invalid IL or missing references) //IL_03e0: Unknown result type (might be due to invalid IL or missing references) //IL_03c8: Unknown result type (might be due to invalid IL or missing references) //IL_035c: Unknown result type (might be due to invalid IL or missing references) //IL_0348: Unknown result type (might be due to invalid IL or missing references) //IL_0459: Unknown result type (might be due to invalid IL or missing references) //IL_0410: Unknown result type (might be due to invalid IL or missing references) //IL_0425: Unknown result type (might be due to invalid IL or missing references) //IL_042a: Unknown result type (might be due to invalid IL or missing references) //IL_048f: Unknown result type (might be due to invalid IL or missing references) //IL_0494: Unknown result type (might be due to invalid IL or missing references) if (!ModuleScheduler.Current.Due(this, "processing", now, 2f)) { return; } using (_diagnostics.OptionalEnabled ? _diagnostics.Measure(now, () => _observations.Count) : null) { if (_interval != _settings.IntervalSeconds.Value) { _interval = _settings.IntervalSeconds.Value; _cycle.Postpone(now, _interval); } _expiredAdmins.Clear(); foreach (long key in _adminRate.Keys) { bool flag = false; for (int num = 0; num < _players.Presence.Peers.Count; num++) { ZNetPeer val = _players.Presence.Peers[num]; if (val.m_uid == key && val.IsReady()) { flag = true; break; } } if (!flag) { _expiredAdmins.Add(key); } } foreach (long expiredAdmin in _expiredAdmins) { _adminRate.Remove(expiredAdmin); } Reconcile(now); _expiredRecords.Clear(); foreach (KeyValuePair observation in _observations) { if (now - observation.Value.Seen > 180f) { _expiredRecords.Add(observation.Key); } } foreach (ZDOID expiredRecord in _expiredRecords) { _observations.Remove(expiredRecord); } _expiredRecords.Clear(); foreach (KeyValuePair threat in _threats) { if (now - threat.Value.Item2 > 180f) { _expiredRecords.Add(threat.Key); } } foreach (ZDOID expiredRecord2 in _expiredRecords) { _threats.Remove(expiredRecord2); } if (_scope.Refresh(_settings.ScanRangeMeters.Value)) { bool flag2 = false; foreach (ZDO record in _scope.Records) { if (_rules.Monster(record.GetPrefab()) && !record.GetBool(ZDOVars.s_tamed, false) && record.GetFloat(ZDOVars.s_health, 0f) > 0f) { if (_threats.Count < 256 || _threats.ContainsKey(record.m_uid)) { _threats[record.m_uid] = (record, now); } else { _threatUnknownUntil = now + 180f; } } if (!_scope.InRange(record.GetPosition(), _settings.ScanRangeMeters.Value) || !_rules.Eligible(record, out var health, out var maximum)) { continue; } if (health >= maximum) { _observations.Remove(record.m_uid); continue; } if (!_observations.TryGetValue(record.m_uid, out RepairObservation value)) { if (_observations.Count >= 4096) { flag2 = true; continue; } value = (_observations[record.m_uid] = new RepairObservation { Record = record, Identity = record.m_uid, Health = health, Damaged = now }); } if (value.Record != record) { _observations.Remove(record.m_uid); continue; } if (health < value.Health) { value.Damaged = now; } value.Health = health; value.Maximum = maximum; value.Position = record.GetPosition(); value.Seen = now; } if (flag2 != _observationCapacity) { _observationCapacity = flag2; DiagnosticLog.Write(_log, "HeimMender", flag2 ? "Damaged-piece observation capacity reached; additional damaged pieces are deferred." : "Damaged-piece observation capacity is available again.", (LogLevel)(flag2 ? 4 : 16)); } } if (!_settings.AutomaticEnabled.Value) { _cycle.Postpone(now, _settings.IntervalSeconds.Value); } else if (_cycle.Ready(now) && _kind.Length == 0) { _cycle.Postpone(now, _settings.IntervalSeconds.Value); SelectAutomatic(now); } if (_kind == "automatic" && !_settings.AutomaticEnabled.Value) { _queue.Clear(); } Issue(now); Finish(now); } } private bool Nearby(Vector3 point) { //IL_004f: 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_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) for (int i = 0; i < _players.Presence.Peers.Count; i++) { ZNetPeer val = _players.Presence.Peers[i]; if (!val.IsReady() || ((ZDOID)(ref val.m_characterID)).IsNone()) { continue; } ZDO zDO = ZDOMan.instance.GetZDO(val.m_characterID); if (zDO != null && zDO.GetOwner() == val.m_uid && zDO.GetFloat(ZDOVars.s_health, 0f) > 0f) { Vector3 val2 = zDO.GetPosition() - point; if (((Vector3)(ref val2)).sqrMagnitude <= _settings.ScanRangeMeters.Value * _settings.ScanRangeMeters.Value) { return true; } } } return false; } private bool Threat(Vector3 point, float now) { //IL_0041: Unknown result type (might be due to invalid IL or missing references) //IL_0052: Unknown result type (might be due to invalid IL or missing references) //IL_0068: Unknown result type (might be due to invalid IL or missing references) //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_00cd: Unknown result type (might be due to invalid IL or missing references) //IL_00d2: Unknown result type (might be due to invalid IL or missing references) float value = _settings.HostileClearanceMeters.Value; if (value <= 0f) { return false; } if (now < _threatUnknownUntil) { return true; } foreach (KeyValuePair threat in _threats) { if (threat.Key == threat.Value.Item1.m_uid && ZDOMan.instance.GetZDO(threat.Key) == threat.Value.Item1 && threat.Value.Item1.GetFloat(ZDOVars.s_health, 0f) > 0f && !threat.Value.Item1.GetBool(ZDOVars.s_tamed, false)) { Vector3 val = threat.Value.Item1.GetPosition() - point; if (((Vector3)(ref val)).sqrMagnitude <= value * value) { return true; } } } return false; } private void SelectAutomatic(float now) { //IL_0074: Unknown result type (might be due to invalid IL or missing references) //IL_00e6: Unknown result type (might be due to invalid IL or missing references) //IL_00f7: Unknown result type (might be due to invalid IL or missing references) //IL_010a: 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_016f: Unknown result type (might be due to invalid IL or missing references) //IL_0252: 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_026f: Unknown result type (might be due to invalid IL or missing references) //IL_02b0: Unknown result type (might be due to invalid IL or missing references) //IL_031f: Unknown result type (might be due to invalid IL or missing references) //IL_039d: Unknown result type (might be due to invalid IL or missing references) int num = 0; int num2 = 0; int num3 = 0; int num4 = 0; _playerPositions.Clear(); _threatPositions.Clear(); for (int i = 0; i < _players.Presence.Peers.Count; i++) { ZNetPeer val = _players.Presence.Peers[i]; if (val.IsReady() && !((ZDOID)(ref val.m_characterID)).IsNone()) { ZDO zDO = ZDOMan.instance.GetZDO(val.m_characterID); if (zDO != null && zDO.GetOwner() == val.m_uid && zDO.GetFloat(ZDOVars.s_health, 0f) > 0f) { _playerPositions.Add(zDO.GetPosition()); } } } foreach (KeyValuePair threat in _threats) { if (threat.Key == threat.Value.Item1.m_uid && ZDOMan.instance.GetZDO(threat.Key) == threat.Value.Item1 && threat.Value.Item1.GetFloat(ZDOVars.s_health, 0f) > 0f && !threat.Value.Item1.GetBool(ZDOVars.s_tamed, false)) { _threatPositions.Add(threat.Value.Item1.GetPosition()); } } List candidates = _candidates; candidates.Clear(); foreach (RepairObservation value2 in _observations.Values) { candidates.Add(value2); } for (int num5 = candidates.Count - 1; num5 > 0; num5--) { int index = _random.Next(num5 + 1); RepairObservation value = candidates[num5]; candidates[num5] = candidates[index]; candidates[index] = value; } foreach (RepairObservation item in candidates) { if (item.Record.m_uid != item.Identity) { continue; } ZDO zDO2 = ZDOMan.instance.GetZDO(item.Identity); if (zDO2 == item.Record && _rules.Eligible(zDO2, out var health, out var maximum) && !(health >= maximum) && NearAny(_playerPositions, zDO2.GetPosition(), _settings.ScanRangeMeters.Value)) { num++; if (now - item.Damaged < _settings.DamageQuietSeconds.Value) { num2++; } else if (_settings.HostileClearanceMeters.Value > 0f && (now < _threatUnknownUntil || NearAny(_threatPositions, zDO2.GetPosition(), _settings.HostileClearanceMeters.Value))) { num3++; } else if (!HeimMenderRules.OwnerReady(zDO2)) { num4++; } else if (!(_random.NextDouble() * 100.0 >= (double)_settings.RepairChancePercent.Value) && _queue.Count < _settings.MaxRepairsPerCycle.Value) { _queue.Enqueue(zDO2.m_uid); } } } _diagnostics.Cycle(now, "automatic", candidates.Count, num, num2, num3, num4, _queue.Count); if (_queue.Count > 0) { _kind = "automatic"; } } private static bool NearAny(List positions, Vector3 point, float radius) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) foreach (Vector3 position in positions) { Vector3 val = position - point; if (((Vector3)(ref val)).sqrMagnitude <= radius * radius) { return true; } } return false; } public bool Request(string target, float? radius, float now) { //IL_00ba: 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_0114: 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_012a: Unknown result type (might be due to invalid IL or missing references) //IL_012c: Unknown result type (might be due to invalid IL or missing references) //IL_0143: Unknown result type (might be due to invalid IL or missing references) //IL_0180: Unknown result type (might be due to invalid IL or missing references) //IL_0185: Unknown result type (might be due to invalid IL or missing references) //IL_0187: Unknown result type (might be due to invalid IL or missing references) //IL_018c: Unknown result type (might be due to invalid IL or missing references) //IL_01c4: Unknown result type (might be due to invalid IL or missing references) if (_kind.Length > 0) { return Reject("A repair batch is already running."); } float num = radius ?? _settings.AdminRadiusMeters.Value; if (!PlayerWorldScope.Finite(num) || num < 1f || num > 128f) { return Reject("Repair radius must be between 1 and 128 metres."); } ZNetPeer[] array = _players.Presence.Peers.Where((ZNetPeer p) => p.IsReady() && !((ZDOID)(ref p.m_characterID)).IsNone() && (target.Length == 0 || p.m_playerName == target || p.m_uid.ToString(CultureInfo.InvariantCulture) == target)).Take(2).ToArray(); if (array.Length != 1) { return Reject("Repair target must identify exactly one ready joined player."); } ZNetPeer val = array[0]; ZDO zDO = ZDOMan.instance.GetZDO(val.m_characterID); if (zDO == null || zDO.GetOwner() != val.m_uid || zDO.GetFloat(ZDOVars.s_health, 0f) <= 0f || !PlayerWorldScope.Finite(zDO.GetPosition())) { return Reject("Repair target position is unavailable."); } List list = new List(); Vector3 position = zDO.GetPosition(); WorldObjectProvider.Current.For("HeimMender").Query(ZoneSystem.GetZone(position), new SimulationDistance((int)Math.Ceiling(num / 64f) + 1, 0, false), list); if (list.Count > 8192) { return Reject("Repair scope exceeds the object budget; reduce radius."); } foreach (ZDO item in list) { Vector3 val2 = item.GetPosition() - position; if (!(((Vector3)(ref val2)).sqrMagnitude > num * num) && _rules.Eligible(item, out var health, out var maximum) && !(health >= maximum) && HeimMenderRules.OwnerReady(item)) { _queue.Enqueue(item.m_uid); if (_queue.Count >= _settings.AdminMaxPieces.Value) { break; } } } DiagnosticLog.Write(_log, "HeimMender", "Accepted nearby repair request for " + val.m_playerName + ": " + _queue.Count + " candidates.", (LogLevel)16); _diagnostics.Cycle(now, "administrative", list.Count, _queue.Count, 0, 0, 0, _queue.Count); if (_queue.Count > 0) { _kind = "administrative"; } return true; } private bool Reject(string message) { DiagnosticLog.Write(_log, "HeimMender", message, (LogLevel)4); return false; } private void Issue(float now) { //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Unknown result type (might be due to invalid IL or missing references) //IL_00c1: Unknown result type (might be due to invalid IL or missing references) //IL_010b: Unknown result type (might be due to invalid IL or missing references) //IL_0076: Unknown result type (might be due to invalid IL or missing references) //IL_00a0: Unknown result type (might be due to invalid IL or missing references) //IL_00af: Unknown result type (might be due to invalid IL or missing references) for (int i = 0; i < 4; i++) { if (_queue.Count <= 0) { break; } ZDOID val = _queue.Dequeue(); ZDO zDO = ZDOMan.instance.GetZDO(val); if (zDO != null && !_pending.ContainsKey(val) && _rules.Eligible(zDO, out var health, out var maximum) && !(health >= maximum) && HeimMenderRules.OwnerReady(zDO) && (!(_kind == "automatic") || (_observations.TryGetValue(val, out RepairObservation value) && !(now - value.Damaged < _settings.DamageQuietSeconds.Value) && !Threat(zDO.GetPosition(), now) && Nearby(zDO.GetPosition())))) { _pending.Add(val, new RepairRequest { Record = zDO, Sent = now, Maximum = maximum }); _sent++; _diagnostics.Request(now, zDO, health, maximum); ZRoutedRpc.instance.InvokeRoutedRPC(zDO.GetOwner(), val, "RPC_Repair", Array.Empty()); } } } private void Reconcile(float now) { //IL_0033: Unknown result type (might be due to invalid IL or missing references) //IL_00a0: 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_00ff: Unknown result type (might be due to invalid IL or missing references) //IL_0107: Unknown result type (might be due to invalid IL or missing references) //IL_00c3: Unknown result type (might be due to invalid IL or missing references) _expiredRecords.Clear(); foreach (KeyValuePair item in _pending) { RepairRequest value = item.Value; ZDO zDO = ZDOMan.instance.GetZDO(item.Key); bool flag = zDO == value.Record; bool flag2 = flag && zDO.GetFloat(ZDOVars.s_health, 0f) >= value.Maximum; if (!(!flag2 && flag) || !(now - value.Sent < 10f)) { if (flag2) { _confirmed++; _observations.Remove(item.Key); } else { _unconfirmed++; } _expiredRecords.Add(item.Key); } } foreach (ZDOID expiredRecord in _expiredRecords) { _pending.Remove(expiredRecord); } } private void Finish(float now) { if (_kind.Length != 0 && _queue.Count == 0 && _pending.Count == 0) { _diagnostics.Finished(now, _kind, _sent, _confirmed, _unconfirmed); _kind = ""; _sent = (_confirmed = (_unconfirmed = 0)); } } private void Observe(ZRpc rpc, ZPackage packet) { try { ObserveCommand(rpc, packet); } catch (IOException) { } catch (ArgumentException) { } } private void ObserveCommand(ZRpc rpc, ZPackage packet) { //IL_00ab: Unknown result type (might be due to invalid IL or missing references) //IL_00b1: Unknown result type (might be due to invalid IL or missing references) //IL_00d5: Unknown result type (might be due to invalid IL or missing references) if (packet.Size() > 4096) { return; } ZNetPeer val = PlayerPeerLookup.Ready(_players.Presence.Peers, rpc); if (val == null || !RoutedActivityReader.TryRead(packet, val.m_uid, out var _, out var method) || (method != SayMethod && method != ChatMethod)) { return; } RoutedRPCData val2 = ZdoPackets.ReadRouted(packet); if (val2.m_senderPeerID != val.m_uid || (val2.m_targetPeerID != 0L && val2.m_targetPeerID != ZDOMan.GetSessionID())) { return; } bool flag = val2.m_methodHash == StringExtensionMethods.GetStableHashCode("ChatMessage") && ((ZDOID)(ref val2.m_targetZDO)).IsNone(); bool flag2 = val2.m_methodHash == StringExtensionMethods.GetStableHashCode("Say") && val2.m_targetZDO == val.m_characterID; if (!flag && !flag2) { return; } ZPackage parameters = val2.m_parameters; if (flag) { parameters.ReadVector3(); } int num = parameters.ReadInt(); parameters.ReadString(); parameters.ReadString(); string text = parameters.ReadString().Trim(); if (num < 0 || num > 2 || parameters.GetPos() != parameters.Size() || text != "!heimmender repair") { return; } float unscaledTime = Time.unscaledTime; if ((!_adminRate.TryGetValue(val.m_uid, out var value) || !(unscaledTime - value < 5f)) && (_adminRate.Count < 64 || _adminRate.ContainsKey(val.m_uid))) { _adminRate[val.m_uid] = unscaledTime; if (!ZNet.instance.IsAdmin(val.m_socket.GetHostName())) { Reject("Rejected repair request from non-admin " + val.m_playerName + "."); } else { Request(val.m_uid.ToString(CultureInfo.InvariantCulture), null, unscaledTime); } } } public void Dispose() { _scope.Dispose(); _messages.Dispose(); _queue.Clear(); _pending.Clear(); _observations.Clear(); _threats.Clear(); _adminRate.Clear(); } } internal sealed class HeimMenderDiagnostics : FeatureDiagnostics { private readonly ManualLogSource _log; private readonly ProcessingTiming _timing; private readonly DebugLoggingPolicy _policy; public IDisposable Measure(float now, Func scope) { return _timing.Measure(now, scope); } public HeimMenderDiagnostics(ManualLogSource log, DebugLoggingPolicy policy) { _log = log; _policy = policy; ConfigureDiagnostics(() => policy.Enabled, log, "HeimMender"); _timing = new ProcessingTiming(log, "HeimMender", policy); } public void Cycle(float now, string kind, int observed, int damaged, int quiet, int threats, int owners, int selected) { if (base.DiagnosticsEnabled && _budget.Reserve(now, "cycles", 12) && DiagnosticLog.DebugAvailable(_log, "HeimMender")) { DiagnosticLog.Write(_log, "HeimMender", CoreLogTopics.Scope, $"Selected {selected} repair requests for the {kind} batch this pass.", new(string, object)[8] { ("kind", kind), ("observations", observed), ("damaged", damaged), ("quiet", quiet), ("threat", threats), ("owner_unavailable", owners), ("selected", selected), ("omitted", _budget.TakeOmitted()) }, (LogLevel)32); } } public void Request(float now, ZDO record, float health, float maximum) { //IL_0059: Unknown result type (might be due to invalid IL or missing references) if (base.DiagnosticsEnabled && _budget.Reserve(now, "objects", 16) && DiagnosticLog.DebugAvailable(_log, "HeimMender")) { DiagnosticLog.Write(_log, "HeimMender", HeimMenderLogTopics.Repair, "Sent native owner repair request.", new(string, object)[5] { ("zdo", record.m_uid), ("prefab", record.GetPrefab()), ("owner", record.GetOwner()), ("health", health), ("maximum", maximum) }, (LogLevel)32); } } public void Finished(float now, string kind, int sent, int confirmed, int unconfirmed) { if (confirmed > 0) { DiagnosticLog.Write(_log, "HeimMender", "Confirmed " + confirmed + " repairs in the " + kind + " batch.", (LogLevel)16); } if (base.DiagnosticsEnabled && _budget.Reserve(now, "completed", 12) && DiagnosticLog.DebugAvailable(_log, "HeimMender")) { DiagnosticLog.Write(_log, "HeimMender", HeimMenderLogTopics.Repair, $"Repair batch {kind} finished with {confirmed} confirmations and {unconfirmed} unconfirmed requests.", new(string, object)[4] { ("kind", kind), ("requests", sent), ("confirmed", confirmed), ("unconfirmed", unconfirmed) }, (LogLevel)32); } } } public static class HeimMenderLogTopics { public static readonly LogTopic Repair = new LogTopic("repair"); } internal sealed class HeimMenderRules { private readonly PrefabCatalog _prefabs = PrefabRegistry.Current.Catalog("HeimMenderRules._prefabs"); private readonly PrefabCatalog _monsters = PrefabRegistry.Current.Catalog("HeimMenderRules._monsters"); public bool Monster(int hash) { if (_monsters.TryGetValue(hash, out var value)) { return value; } GameObject val = PrefabRegistry.Current.Prefab(hash); value = Object.op_Implicit((Object)(object)val) && Object.op_Implicit((Object)(object)PrefabRegistry.Component(val)); if (_monsters.Count < 4096) { _monsters[hash] = value; } return value; } public bool Eligible(ZDO zdo, out float health, out float maximum) { //IL_01a8: 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_00bf: Invalid comparison between Unknown and I4 //IL_00c3: Unknown result type (might be due to invalid IL or missing references) //IL_00c9: Invalid comparison between Unknown and I4 //IL_00cd: Unknown result type (might be due to invalid IL or missing references) //IL_00d3: Invalid comparison between Unknown and I4 health = (maximum = 0f); if (!zdo.IsValid() || zdo.GetLong(ZDOVars.s_creator, 0L) == 0L) { return false; } int prefab = zdo.GetPrefab(); if (!_prefabs.TryGetValue(prefab, out var value)) { GameObject val = PrefabRegistry.Current.Prefab(prefab); Piece val2 = (Object.op_Implicit((Object)(object)val) ? PrefabRegistry.Component(val) : null); WearNTear val3 = (Object.op_Implicit((Object)(object)val) ? PrefabRegistry.Component(val) : null); ZNetView val4 = (Object.op_Implicit((Object)(object)val) ? PrefabRegistry.Component(val) : null); value = 0f; if (Object.op_Implicit((Object)(object)val2) && Object.op_Implicit((Object)(object)val3) && Object.op_Implicit((Object)(object)val4) && val4.m_persistent && val3.m_staticPosition && ((int)val2.m_category == 2 || (int)val2.m_category == 3 || (int)val2.m_category == 5) && !Object.op_Implicit((Object)(object)PrefabRegistry.Component(val)) && !Object.op_Implicit((Object)(object)PrefabRegistry.Component(val)) && !Object.op_Implicit((Object)(object)PrefabRegistry.Component(val)) && !Object.op_Implicit((Object)(object)PrefabRegistry.Component(val))) { value = val3.m_health; } if (_prefabs.Count < 4096) { _prefabs[prefab] = value; } } if (!PlayerWorldScope.Finite(value) || value <= 0f) { return false; } maximum = value; if (Game.m_worldLevel > 0) { if (!Object.op_Implicit((Object)(object)Game.instance)) { return false; } maximum += (float)Game.m_worldLevel * Game.instance.m_worldLevelPieceHPMultiplier * maximum; } health = zdo.GetFloat(ZDOVars.s_health, maximum); if (PlayerWorldScope.Finite(maximum) && maximum > 0f && PlayerWorldScope.Finite(health) && health > 0f) { return PlayerWorldScope.Finite(zdo.GetPosition()); } return false; } public static bool OwnerReady(ZDO zdo) { //IL_001a: Unknown result type (might be due to invalid IL or missing references) long owner = zdo.GetOwner(); if (owner == 0L) { return false; } if (owner == ZDOMan.GetSessionID()) { GameObject val = ZNetScene.instance.FindInstance(zdo.m_uid); ZNetView val2 = (Object.op_Implicit((Object)(object)val) ? val.GetComponent() : null); if ((Object)(object)val2 != (Object)null && val2.IsValid() && val2.GetZDO() == zdo && val2.IsOwner()) { return Object.op_Implicit((Object)(object)val.GetComponent()); } return false; } ZNetPeer peer = ZNet.instance.GetPeer(owner); if (peer != null && peer.IsReady()) { return !((ZDOID)(ref peer.m_characterID)).IsNone(); } return false; } } public sealed class HeimMenderSettings { public readonly List Entries = new List(); public ConfigEntry Enabled { get; } public ConfigEntry DebugMode { get; } public DebugLoggingPolicy DebugLogging { get; } public ConfigEntry AutomaticEnabled { get; } public ConfigEntry IntervalSeconds { get; } public ConfigEntry RepairChancePercent { get; } public ConfigEntry MaxRepairsPerCycle { get; } public ConfigEntry ScanRangeMeters { get; } public ConfigEntry DamageQuietSeconds { get; } public ConfigEntry HostileClearanceMeters { get; } public ConfigEntry AdminRadiusMeters { get; } public ConfigEntry AdminMaxPieces { get; } public ConfigEntry RepairRequestId { get; } public ConfigEntry RepairTarget { get; } public HeimMenderSettings(ConfigFile config, ManualLogSource logger) { ConfigFile config2 = config; base..ctor(); HeimMenderSettings heimMenderSettings = this; Enabled = Bind("Enabled", value: true, "Enable HeimMender."); DebugMode = Bind("DebugMode", value: false, "Enable shared-policy feature diagnostics."); AutomaticEnabled = Bind("AutomaticEnabled", value: true, "Enable gradual automatic repairs."); IntervalSeconds = Bind("IntervalSeconds", 300f, "Seconds between automatic repair cycles.", (AcceptableValueBase?)(object)new AcceptableValueRange(10f, 86400f)); RepairChancePercent = Bind("RepairChancePercent", 50f, "Independent chance per damaged candidate per cycle.", (AcceptableValueBase?)(object)new AcceptableValueRange(0f, 100f)); MaxRepairsPerCycle = Bind("MaxRepairsPerCycle", 10, "Maximum automatic requests per cycle.", (AcceptableValueBase?)(object)new AcceptableValueRange(1, 200)); ScanRangeMeters = Bind("ScanRangeMeters", 64f, "Nearby rotating-player scan radius.", (AcceptableValueBase?)(object)new AcceptableValueRange(16f, 128f)); DamageQuietSeconds = Bind("DamageQuietSeconds", 60f, "Automatic deferral after observed health loss.", (AcceptableValueBase?)(object)new AcceptableValueRange(0f, 3600f)); HostileClearanceMeters = Bind("HostileClearanceMeters", 30f, "Automatic deferral around untamed MonsterAI; zero disables.", (AcceptableValueBase?)(object)new AcceptableValueRange(0f, 64f)); AdminRadiusMeters = Bind("AdminRadiusMeters", 64f, "Default administrative repair radius.", (AcceptableValueBase?)(object)new AcceptableValueRange(1f, 128f)); AdminMaxPieces = Bind("AdminMaxPieces", 200, "Maximum native requests per administrative batch.", (AcceptableValueBase?)(object)new AcceptableValueRange(1, 2000)); RepairRequestId = Bind("RepairRequestId", 0, "Increase while running to request a batch. Startup never replays it.", (AcceptableValueBase?)(object)new AcceptableValueRange(0, int.MaxValue)); RepairTarget = Bind("RepairTarget", "", "Exact ready player name or peer UID; empty requires one ready player."); foreach (ConfigEntryBase entry in Entries) { if (entry.BoxedValue is float f && (float.IsNaN(f) || float.IsInfinity(f))) { throw new ArgumentException("HeimMender settings must be finite."); } } DebugLogging = DebugLoggingResolver.Resolve(config2, "HeimMender", DiagnosticsSettings.Bind(config2), logger, DebugMode); ConfigEntry Bind(string key, T value, string description, AcceptableValueBase? range = null) where T : notnull { //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Expected O, but got Unknown ConfigEntry val = config2.Bind("HeimMender", key, value, new ConfigDescription(description + " Reloads during play.", range, Array.Empty())); Entries.Add((ConfigEntryBase)(object)val); return val; } } } } namespace HeimKit.Features.HeimMender.Models { internal sealed class RepairObservation { public ZDO Record; public ZDOID Identity; public Vector3 Position; public float Health; public float Maximum; public float Seen; public float Damaged; } internal sealed class RepairRequest { public ZDO Record; public float Sent; public float Maximum; } } namespace HeimKit.Features.ForestRenewal { public sealed class ForestRenewal : IServerModule { private readonly ForestRenewalSettings _settings; private readonly ManualLogSource _logger; private readonly GameVersionCompatibility _compatibility; private readonly PlayerServices _players; private ForestRenewalController? _controller; private IDisposable? _presenceRegistration; private bool _occupied; private ZDOMan? _world; private long _worldUid; private readonly string _directory; private readonly PlayerProcessingNotices _processing; public string Name => "ForestRenewal"; public bool IsActive { get; private set; } public ForestRenewal(ConfigFile config, ManualLogSource logger, PlayerServices players) { _directory = Path.Combine(Path.GetDirectoryName(config.ConfigFilePath), "HeimKit", "ForestRenewal"); _logger = logger; _compatibility = GameVersionCompatibility.Resolve(config, logger); _settings = new ForestRenewalSettings(config, logger); _players = players; _processing = new PlayerProcessingNotices(logger, Name, () => _settings.DebugLogging.Enabled); } public void Initialize(string gameVersion) { Shutdown(); Log(_settings.Enabled.Value ? "Enabled." : "Disabled.", (LogLevel)16); _settings.DebugLogging.ReportStartup(_logger, Name, _settings.Enabled.Value); if (!_settings.Enabled.Value) { return; } if (!_compatibility.Supports(gameVersion)) { Log("DISABLED: unsupported game version " + gameVersion + "; required version " + _compatibility.RequiredVersion, (LogLevel)4); return; } IsActive = true; if (_settings.DebugLogging.Enabled) { Log("Waiting for joined players and dedicated-server world", (LogLevel)32); } try { _presenceRegistration = _players.Events.Subscribe(PresenceChanged, Fail, () => _processing.IsEmptyPaused, () => _processing.IsRunning, () => _processing.IsServerReady); } catch (Exception error) { Fail(error); } if (!IsActive) { IDisposable? presenceRegistration = _presenceRegistration; _presenceRegistration = null; presenceRegistration?.Dispose(); } } public void Tick(float now) { if (!IsActive) { return; } if (!_settings.Enabled.Value) { Shutdown(); return; } try { bool flag = WorldServices.Activity && WorldServices.Terrain; if (flag) { _processing.ServerReady(); } if (!_occupied) { StopController(); return; } if (!flag) { StopController(); _processing.Paused("world services unavailable"); return; } long worldUID = ZNet.instance.GetWorldUID(); if (_world != ZDOMan.instance || _worldUid != worldUID) { StopController(); _world = ZDOMan.instance; _worldUid = worldUID; } StartController(); _controller?.Tick(now); } catch (Exception error) { Fail(error); } } private void PresenceChanged(bool? occupied) { _occupied = occupied == true; if (IsActive && !_occupied) { StopController(); if (occupied.HasValue) { _processing.EmptyPaused(); } else { _processing.Unavailable("player presence unavailable"); } } } private void StartController() { if (_settings.Enabled.Value && _controller == null) { _controller = new ForestRenewalController(this, _settings, _logger, _players, _directory); _processing.Ready(); } } private void StopController() { ForestRenewalController controller = _controller; _controller = null; if (controller != null) { ModuleScheduler.Current.Forget(controller); } try { controller?.Dispose(); } finally { WorldObjectProvider.Current?.ReleaseOwner(Name); } } internal void Fail(Exception error) { if (IsActive) { DiagnosticLog.Write(_logger, Name, CoreLogTopics.Lifecycle, "Disabled after a runtime failure.", default(LogFields), (LogLevel)2, verbose: false, error); Shutdown(); } } private void Log(string message, LogLevel level = (LogLevel)16) { //IL_000d: Unknown result type (might be due to invalid IL or missing references) DiagnosticLog.Write(_logger, Name, message, level); } public void Shutdown() { IsActive = false; _occupied = false; _processing.Reset(); IDisposable registration = _presenceRegistration; _presenceRegistration = null; ModuleCleanup.Run(_logger, Name, delegate { registration?.Dispose(); }, StopController); } } internal static class ForestRenewalCommitRules { public static bool Ready(RenewalPlacement placement, long durableRevision) { if (placement.RequiredRevision > 0 && durableRevision >= placement.RequiredRevision && placement.Decision.State == 2) { return !placement.MutationStarted; } return false; } public static void RestorePending(RenewalPlacement placement) { if (placement.MutationStarted || placement.Decision.State != 2 || (placement.PendingState != 0 && placement.PendingState != 3)) { throw new InvalidOperationException("An attempted or invalid renewal cannot return to pending."); } placement.Decision.State = placement.PendingState; placement.Decision.DecisionTicks = placement.PreviousDecisionTicks; } } internal sealed class ForestRenewalController : IDisposable { private readonly ForestRenewal _module; private readonly ForestRenewalSettings _settings; private readonly ManualLogSource _log; private readonly ForestRenewalDiagnostics _diagnostics; private readonly PlayerWorldScope _scope; private readonly ZDOMan _world = ZDOMan.instance; private readonly ForestRenewalStore _store; private readonly TerrainContext _terrain; private readonly ForestRenewalStructures _structures = new ForestRenewalStructures(); private readonly ForestRenewalReplacement _replacement; private readonly PrefabCatalog _saplings = PrefabRegistry.Current.Catalog("ForestRenewalController._saplings"); private readonly PrefabCatalog _mappings = PrefabRegistry.Current.Catalog("ForestRenewalController._mappings"); private readonly HashSet _pending = new HashSet(); private readonly List _due = new List(); private readonly Dictionary<(int X, int Z), HashSet> _cooldowns = new Dictionary<(int, int), HashSet>(); private readonly PrefabCatalog<(GameObject Prefab, Plant? Plant, bool Tree)> _vegetation = PrefabRegistry.Current.Catalog<(GameObject, Plant, bool)>("ForestRenewalController._vegetation"); private float _scopeAt = -1000f; private long _placed; private int _pendingCursor; private int _pendingCount; private int _destroyedIntake; private bool _disposed; private bool _capacityWarning; private bool _dirty; private long _revision; private long _writingRevision; private long _durableRevision; private Task? _write; private RenewalPlacement? _placement; private int PendingWork => _pendingCount + ((_placement != null) ? 1 : 0); public ForestRenewalController(ForestRenewal module, ForestRenewalSettings settings, ManualLogSource log, PlayerServices players, string directory) { _module = module; _settings = settings; _log = log; _diagnostics = new ForestRenewalDiagnostics(log, settings.DebugLogging); _scope = WorldObjectProvider.Current.CreateScope("ForestRenewal"); string[] array = new string[6] { "Beech_Sapling", "Birch_Sapling", "Oak_Sapling", "FirTree_Sapling", "PineTree_Sapling", "FirTree_big_Sapling" }; foreach (string text in array) { GameObject val = PrefabRegistry.Current.Prefab(text); Plant val2 = PrefabRegistry.Component(val); if ((Object)(object)val2 == (Object)null) { continue; } ZNetView? obj = PrefabRegistry.Component(val); if (obj == null || !obj.m_persistent) { continue; } GameObject[] array2 = val2.m_grownPrefabs.Select((GameObject p) => PrefabRegistry.Component(p)?.m_stubPrefab).ToArray(); if (array2.Length == 0 || array2.Any((GameObject s) => (Object)(object)s == (Object)null || (Object)(object)PrefabRegistry.Component(s) == (Object)null)) { continue; } int stableHashCode = StringExtensionMethods.GetStableHashCode(text); _saplings.Add(stableHashCode, val); foreach (GameObject item in array2.Distinct()) { int stableHashCode2 = StringExtensionMethods.GetStableHashCode(((Object)item).name); if (_mappings.TryGetValue(stableHashCode2, out var value) && value != stableHashCode) { throw new InvalidOperationException("Ambiguous native tree-to-sapling mapping."); } _mappings[stableHashCode2] = stableHashCode; } } if (_mappings.Count == 0) { throw new InvalidOperationException("No supported native saplings are available."); } _store = new ForestRenewalStore(directory, ZNet.instance.GetWorldUID()); _pendingCount = _store.Records.Values.Count(Pending); foreach (RenewalRecord value2 in _store.Records.Values) { if (Pending(value2)) { _pending.Add(value2); } if (value2.State == 2) { IndexCooldown(value2, add: true); } } _terrain = new TerrainContext(); try { _replacement = new ForestRenewalReplacement(module.Fail, log, players.Presence); } catch { _terrain.Dispose(); throw; } ZDOMan world = _world; world.m_onZDODestroyed = (Action)Delegate.Combine(world.m_onZDODestroyed, new Action(Destroyed)); try { _scope.Index((ZDO z) => _mappings.ContainsKey(z.GetPrefab())); } catch { Dispose(); throw; } } private void Destroyed(ZDO source) { //IL_004a: Unknown result type (might be due to invalid IL or missing references) //IL_00d6: Unknown result type (might be due to invalid IL or missing references) //IL_00db: Unknown result type (might be due to invalid IL or missing references) //IL_00dc: Unknown result type (might be due to invalid IL or missing references) //IL_00e4: 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) if (_disposed || !_module.IsActive || _world != ZDOMan.instance) { return; } try { if (!_mappings.TryGetValue(source.GetPrefab(), out var value)) { return; } if (_store.Records.TryGetValue(source.m_uid, out RenewalRecord value2)) { if (_placement != null && _placement.Decision == value2 && _placement.Stump == source) { _placement.Stump = null; _placement.PendingState = 0; } if (value2.State == 3) { value2.State = 0; MarkDirty(); } } else if (!(Time.unscaledTime - _scopeAt > 2f * _settings.IntervalSeconds.Value)) { Vector3 position = source.GetPosition(); if (PlayerWorldScope.Finite(position) && !Character.InInterior(position) && NearObservedPlayer(position) && _destroyedIntake < 32 && Register(source, value, standing: false)) { _destroyedIntake++; MarkDirty(); } } } catch (Exception error) { _module.Fail(error); } } private bool NearObservedPlayer(Vector3 position) { //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_003c: Unknown result type (might be due to invalid IL or missing references) //IL_003d: 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) float num = _settings.ScanRangeMeters.Value * _settings.ScanRangeMeters.Value; foreach (Vector3 position2 in _scope.Positions) { Vector3 val = position2 - position; if (((Vector3)(ref val)).sqrMagnitude <= num) { return true; } } return false; } public void Tick(float now) { //IL_012c: Unknown result type (might be due to invalid IL or missing references) //IL_0140: Unknown result type (might be due to invalid IL or missing references) //IL_015e: Unknown result type (might be due to invalid IL or missing references) //IL_0278: Unknown result type (might be due to invalid IL or missing references) //IL_029f: Unknown result type (might be due to invalid IL or missing references) //IL_02f5: Unknown result type (might be due to invalid IL or missing references) //IL_02fc: Unknown result type (might be due to invalid IL or missing references) //IL_0301: Unknown result type (might be due to invalid IL or missing references) //IL_0306: Unknown result type (might be due to invalid IL or missing references) //IL_0395: Unknown result type (might be due to invalid IL or missing references) //IL_0372: Unknown result type (might be due to invalid IL or missing references) //IL_03ec: Unknown result type (might be due to invalid IL or missing references) //IL_03f1: Unknown result type (might be due to invalid IL or missing references) //IL_03f8: Unknown result type (might be due to invalid IL or missing references) //IL_03ca: Unknown result type (might be due to invalid IL or missing references) //IL_041b: Unknown result type (might be due to invalid IL or missing references) //IL_0429: Unknown result type (might be due to invalid IL or missing references) //IL_0479: Unknown result type (might be due to invalid IL or missing references) //IL_047b: Unknown result type (might be due to invalid IL or missing references) if (!ModuleScheduler.Current.Due(this, "processing", now, _settings.IntervalSeconds.Value)) { return; } using (_diagnostics.OptionalEnabled ? _diagnostics.Measure(now, () => _scope.Records.Count) : null) { PollSave(now); _destroyedIntake = 0; long started = _diagnostics.BeginStage(); bool flag; try { flag = _scope.Refresh(_settings.ScanRangeMeters.Value); } finally { _diagnostics.EndStage(now, "scope_refresh", started); } if (!flag) { _scopeAt = -1000f; _terrain.Clear(); Flush(); return; } _scopeAt = now; long ticks = ZNet.instance.GetTime().Ticks; int num = 0; int num2 = 0; int num3 = 0; foreach (ZDO record in _scope.Records) { if (record.IsValid() && _mappings.TryGetValue(record.GetPrefab(), out var value) && !_store.Records.ContainsKey(record.m_uid) && _scope.InRange(record.GetPosition(), _settings.ScanRangeMeters.Value) && !Character.InInterior(record.GetPosition()) && (!Register(record, value, standing: true) || ++num3 >= 32)) { break; } } if (num3 > 0) { MarkDirty(); } bool flag2 = _placement != null; if (flag2) { num2 += CompletePlacement(now, ticks); } List due = _due; due.Clear(); if (!flag2) { foreach (RenewalRecord item in _pending) { if (item.DueTicks <= ticks) { due.Add(item); } } } int num4 = ((due.Count != 0) ? (_pendingCursor % due.Count) : 0); float num7 = default(float); for (int num5 = 0; !flag2 && num5 < due.Count; num5++) { int num6 = (num4 + num5) % due.Count; RenewalRecord renewalRecord = due[num6]; _pendingCursor = (num6 + 1) % due.Count; if (!_scope.InRange(renewalRecord.Position, _settings.ScanRangeMeters.Value)) { continue; } ZDO zDO = _world.GetZDO(renewalRecord.Source); if (renewalRecord.State == 3 && zDO == null) { continue; } if (zDO != null) { if (!zDO.IsValid() || !_mappings.TryGetValue(zDO.GetPrefab(), out var value2) || value2 != renewalRecord.Sapling) { continue; } Vector3 val = zDO.GetPosition() - renewalRecord.Position; if (((Vector3)(ref val)).sqrMagnitude > 0.01f) { continue; } } if (++num > 1) { _pendingCursor = num6; break; } if (!_saplings.TryGetValue(renewalRecord.Sapling, out GameObject value3)) { Consume(renewalRecord, ticks, 1); } else { if (!StructureKnown(renewalRecord, now, out var blocked)) { continue; } if (blocked) { _diagnostics.Decision(now, renewalRecord.Source, "structure_buffer"); Consume(renewalRecord, ticks, 1); } else { if (!PrepareTerrain(renewalRecord.Position, now) || !ContextKnown(renewalRecord, value3)) { continue; } if (Excluded(renewalRecord, ticks, value3)) { _diagnostics.Decision(now, renewalRecord.Source, "plant_tree_terrain_or_cooldown"); Consume(renewalRecord, ticks, 1); continue; } Vector3 position = renewalRecord.Position; if (ZoneSystem.instance.GetGroundHeight(position, ref num7) && PlayerWorldScope.Finite(num7)) { position.y = num7; if (!(Floating.GetLiquidLevel(position, 0f, (LiquidType)10) > position.y)) { byte state = renewalRecord.State; long decisionTicks = renewalRecord.DecisionTicks; Consume(renewalRecord, ticks, 2); _placement = new RenewalPlacement { Decision = renewalRecord, Stump = zDO, Prefab = value3, Position = position, RequiredRevision = _revision, Created = now, PendingState = state, PreviousDecisionTicks = decisionTicks }; break; } Consume(renewalRecord, ticks, 1); } } } } Flush(); if (num2 > 0) { DiagnosticLog.Write(_log, "ForestRenewal", (num2 == 1) ? "Placed one tree sapling." : $"Placed {num2} tree saplings.", (LogLevel)16); } if (_capacityWarning && _store.Records.Count < 16384 && PendingWork < _settings.MaxPending.Value) { _capacityWarning = false; DiagnosticLog.Write(_log, "ForestRenewal", "Pending renewal capacity is available again.", (LogLevel)16); } _diagnostics.Result(now, num2, _placed, PendingWork); } } private static bool Pending(RenewalRecord record) { if (record.State != 0) { return record.State == 3; } return true; } private bool Register(ZDO source, int sapling, bool standing) { //IL_0070: Unknown result type (might be due to invalid IL or missing references) //IL_0075: Unknown result type (might be due to invalid IL or missing references) //IL_007c: Unknown result type (might be due to invalid IL or missing references) //IL_0081: Unknown result type (might be due to invalid IL or missing references) //IL_00f2: Unknown result type (might be due to invalid IL or missing references) if (_store.Records.Count >= 16384 || PendingWork >= _settings.MaxPending.Value) { if (!_capacityWarning) { _capacityWarning = true; DiagnosticLog.Write(_log, "ForestRenewal", "Renewal ledger capacity reached; new stumps will be skipped.", (LogLevel)4); } return false; } long ticks = ZNet.instance.GetTime().Ticks; RenewalRecord renewalRecord = new RenewalRecord { Source = source.m_uid, Position = source.GetPosition(), Sapling = sapling, DueTicks = ticks + TimeSpan.FromSeconds(_settings.DelaySeconds.Value).Ticks, DecisionTicks = ticks, State = (byte)((Random.Range(0, 100) >= _settings.ChancePercent.Value) ? 1u : (standing ? 3u : 0u)) }; _store.Records.Add(renewalRecord.Source, renewalRecord); if (Pending(renewalRecord)) { _pendingCount++; _pending.Add(renewalRecord); } return true; } private void MarkDirty() { _dirty = true; _revision++; } private void Flush() { if (!_dirty || _write != null) { return; } _writingRevision = _revision; long started = _diagnostics.BeginStage(); try { _write = _store.SaveAsync(); _dirty = false; } finally { _diagnostics.EndStage(Time.unscaledTime, "ledger_snapshot", started); } } private void PollSave(float now) { if (_write != null && _write.IsCompleted) { double result = _write.GetAwaiter().GetResult(); _write = null; _durableRevision = _writingRevision; _diagnostics.LedgerWrite(now, result); } } private void Consume(RenewalRecord record, long ticks, byte state) { bool flag = Pending(record); if (record.State == 2) { IndexCooldown(record, add: false); } record.State = state; if (record.State == 2) { IndexCooldown(record, add: true); } if (Pending(record)) { _pending.Add(record); } else { _pending.Remove(record); } if (flag && !Pending(record)) { _pendingCount--; } else if (!flag && Pending(record)) { _pendingCount++; } record.DecisionTicks = ticks; MarkDirty(); } private int CompletePlacement(float now, long ticks) { //IL_0040: Unknown result type (might be due to invalid IL or missing references) //IL_0065: Unknown result type (might be due to invalid IL or missing references) //IL_0085: Unknown result type (might be due to invalid IL or missing references) //IL_008b: Unknown result type (might be due to invalid IL or missing references) //IL_0123: Unknown result type (might be due to invalid IL or missing references) //IL_00fe: 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_00bc: Unknown result type (might be due to invalid IL or missing references) //IL_00c1: Unknown result type (might be due to invalid IL or missing references) //IL_00c6: Unknown result type (might be due to invalid IL or missing references) //IL_017d: Unknown result type (might be due to invalid IL or missing references) //IL_0182: Unknown result type (might be due to invalid IL or missing references) //IL_0189: Unknown result type (might be due to invalid IL or missing references) //IL_0159: Unknown result type (might be due to invalid IL or missing references) //IL_01a8: Unknown result type (might be due to invalid IL or missing references) //IL_01b6: 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_020b: Unknown result type (might be due to invalid IL or missing references) //IL_0247: Unknown result type (might be due to invalid IL or missing references) RenewalPlacement placement = _placement; RenewalRecord decision = placement.Decision; if (now - placement.Created > 60f) { RetryPlacement(now, "placement_context_retry"); return 0; } if (!ForestRenewalCommitRules.Ready(placement, _durableRevision) || !_scope.InRange(decision.Position, _settings.ScanRangeMeters.Value)) { return 0; } ZDO zDO = _world.GetZDO(decision.Source); if (zDO == placement.Stump) { if (zDO == null) { goto IL_00e4; } if (zDO.IsValid() && !(zDO.m_uid != decision.Source) && _mappings.TryGetValue(zDO.GetPrefab(), out var value) && value == decision.Sapling) { Vector3 val = zDO.GetPosition() - decision.Position; if (!(((Vector3)(ref val)).sqrMagnitude > 0.01f)) { goto IL_00e4; } } } RetryPlacement(now, "placement_source_retry"); return 0; IL_00e4: if (!StructureKnown(decision, now, out var blocked)) { return 0; } if (blocked) { _diagnostics.Decision(now, decision.Source, "placement_structure_buffer"); Consume(decision, ticks, 1); _placement = null; return 0; } if (!PrepareTerrain(decision.Position, now) || !ContextKnown(decision, placement.Prefab)) { return 0; } if (Excluded(decision, ticks, placement.Prefab)) { _diagnostics.Decision(now, decision.Source, "placement_exclusion_changed"); Consume(decision, ticks, 1); _placement = null; return 0; } Vector3 position = placement.Position; float num = default(float); if (!ZoneSystem.instance.GetGroundHeight(position, ref num) || !PlayerWorldScope.Finite(num)) { return 0; } position.y = num; if (Floating.GetLiquidLevel(position, 0f, (LiquidType)10) > position.y) { _diagnostics.Decision(now, decision.Source, "placement_submerged"); Consume(decision, ticks, 1); _placement = null; return 0; } long started = _diagnostics.BeginStage(); placement.MutationStarted = true; try { _replacement.Place(zDO, placement.Prefab, position, ticks); } finally { _diagnostics.EndStage(now, "world_mutation", started); } _placement = null; _placed++; _diagnostics.Decision(now, decision.Source, (zDO == null) ? "cleared_position_planted" : "standing_stump_replaced"); return 1; } private void RetryPlacement(float now, string reason) { //IL_0054: Unknown result type (might be due to invalid IL or missing references) RenewalPlacement placement = _placement; IndexCooldown(placement.Decision, add: false); ForestRenewalCommitRules.RestorePending(placement); _pending.Add(placement.Decision); _pendingCount++; MarkDirty(); _placement = null; _diagnostics.Decision(now, placement.Decision.Source, reason); } private bool PrepareTerrain(Vector3 position, float now) { //IL_001f: Unknown result type (might be due to invalid IL or missing references) long started = _diagnostics.BeginStage(); try { return _scope.ContextReady() && _terrain.Prepare(position, _scope.Context, now, _settings.ExclusionRadiusMeters.Value + 2f); } finally { _diagnostics.EndStage(now, "terrain_context", started); } } private bool StructureKnown(RenewalRecord record, float now, out bool blocked) { //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_005c: Unknown result type (might be due to invalid IL or missing references) long started = _diagnostics.BeginStage(); try { if (!_scope.ContextReady()) { blocked = false; return false; } ZDO blocker; string reason; bool num = _structures.TryExcluded(_scope.Context, record.Position, _settings.StructureExclusionMeters.Value, out blocked, out blocker, out reason); if (!num) { _diagnostics.Decision(now, record.Source, "structure_context_unknown", blocker, reason); } return num; } finally { _diagnostics.EndStage(now, "structure_exclusion", started); } } private bool ContextKnown(RenewalRecord record, GameObject sapling) { //IL_0028: Unknown result type (might be due to invalid IL or missing references) //IL_0034: Unknown result type (might be due to invalid IL or missing references) //IL_0039: Unknown result type (might be due to invalid IL or missing references) //IL_00af: 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) float growRadius = PrefabRegistry.Component(sapling).m_growRadius; float value = _settings.ExclusionRadiusMeters.Value; for (float num = 0f - value; num <= value; num += 1f) { for (float num2 = 0f - value; num2 <= value; num2 += 1f) { Heightmap val = Heightmap.FindHeightmap(record.Position + new Vector3(num, 0f, num2)); if ((Object)(object)val == (Object)null || val.HaveQueuedRebuild()) { return false; } } } foreach (ZDO item2 in _scope.Context) { if (item2.IsValid()) { (GameObject, Plant, bool) tuple = Vegetation(item2.GetPrefab()); if (Utils.DistanceXZ(item2.GetPosition(), record.Position) <= Math.Max(growRadius, Math.Max(_settings.PlantExclusionMeters.Value, _settings.StructureExclusionMeters.Value)) && (Object)(object)tuple.Item1 == (Object)null) { return false; } Plant item = tuple.Item2; if ((Object)(object)item != (Object)null && (!PlayerWorldScope.Finite(item.m_growRadius) || !PlantScale(item2, ((Component)item).gameObject, out var _))) { return false; } } } return true; } private bool Excluded(RenewalRecord record, long ticks, GameObject sapling) { //IL_0063: Unknown result type (might be due to invalid IL or missing references) //IL_0069: Unknown result type (might be due to invalid IL or missing references) //IL_009f: Unknown result type (might be due to invalid IL or missing references) //IL_00a5: 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_0198: 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_01a2: Unknown result type (might be due to invalid IL or missing references) //IL_01a4: Unknown result type (might be due to invalid IL or missing references) //IL_01c4: 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) if (CoolingDown(record, ticks, TimeSpan.FromHours(_settings.LocationCooldownHours.Value).Ticks)) { return true; } float growRadius = PrefabRegistry.Component(sapling).m_growRadius; foreach (ZDO item2 in _scope.Context) { if (!item2.IsValid() || item2.m_uid == record.Source) { continue; } (GameObject, Plant, bool) tuple = Vegetation(item2.GetPrefab()); var (val, _, _) = tuple; if ((Object)(object)val == (Object)null) { continue; } float num = Utils.DistanceXZ(item2.GetPosition(), record.Position); Plant item = tuple.Item2; if ((Object)(object)item != (Object)null) { if (!PlantScale(item2, val, out var maximum)) { return true; } float num2 = Math.Max(_settings.PlantExclusionMeters.Value, Math.Max(growRadius, item.m_growRadius * maximum)); if (num <= num2) { return true; } } if (num <= 2f && (tuple.Item3 || _mappings.ContainsKey(item2.GetPrefab()))) { return true; } } if (!_settings.ExcludeClearedGround.Value) { return false; } float value = _settings.ExclusionRadiusMeters.Value; for (float num3 = 0f - value; num3 <= value; num3 += 1f) { for (float num4 = 0f - value; num4 <= value; num4 += 1f) { Vector3 val2 = record.Position + new Vector3(num3, 0f, num4); Heightmap val3 = Heightmap.FindHeightmap(val2); if ((Object)(object)val3 == (Object)null || val3.HaveQueuedRebuild()) { return true; } if (val3.IsCleared(val2) || val3.IsCultivated(val2)) { return true; } } } return false; } private bool CoolingDown(RenewalRecord record, long ticks, long cooldown) { //IL_0001: 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_005c: 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: Unknown result type (might be due to invalid IL or missing references) //IL_0081: Unknown result type (might be due to invalid IL or missing references) //IL_0086: 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_008f: Unknown result type (might be due to invalid IL or missing references) //IL_0097: 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) (int, int) tuple = CooldownCell(record.Position); for (int i = -1; i <= 1; i++) { for (int j = -1; j <= 1; j++) { if (!_cooldowns.TryGetValue((tuple.Item1 + i, tuple.Item2 + j), out HashSet value)) { continue; } foreach (RenewalRecord item in value) { if (item.Source != record.Source && ticks - item.DecisionTicks < cooldown) { Vector3 val = item.Position - record.Position; if (val.x * val.x + val.z * val.z < 25f) { return true; } } } } } return false; } private (GameObject? Prefab, Plant? Plant, bool Tree) Vegetation(int hash) { if (_vegetation.TryGetValue(hash, out (GameObject, Plant, bool) value)) { return value; } GameObject val = PrefabRegistry.Current.Prefab(hash); if ((Object)(object)val == (Object)null) { return (Prefab: null, Plant: null, Tree: false); } value = (val, PrefabRegistry.Component(val), (Object)(object)PrefabRegistry.Component(val) != (Object)null); if (_vegetation.Count < 4096) { _vegetation[hash] = value; } return value; } private static (int X, int Z) CooldownCell(Vector3 point) { //IL_0000: 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) return (X: (int)Math.Floor(point.x / 5f), Z: (int)Math.Floor(point.z / 5f)); } private void IndexCooldown(RenewalRecord record, bool add) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) (int, int) key = CooldownCell(record.Position); HashSet value2; if (add) { if (!_cooldowns.TryGetValue(key, out HashSet value)) { value = (_cooldowns[key] = new HashSet()); } value.Add(record); } else if (_cooldowns.TryGetValue(key, out value2)) { value2.Remove(record); if (value2.Count == 0) { _cooldowns.Remove(key); } } } private static bool PlantScale(ZDO record, GameObject prefab, out float maximum) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0051: Unknown result type (might be due to invalid IL or missing references) //IL_0057: Unknown result type (might be due to invalid IL or missing references) //IL_005d: Unknown result type (might be due to invalid IL or missing references) //IL_006e: 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_004a: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_003d: 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_004f: Unknown result type (might be due to invalid IL or missing references) //IL_0090: Unknown result type (might be due to invalid IL or missing references) Vector3 val = record.GetVec3(ZDOVars.s_scaleHash, Vector3.zero); if (val == Vector3.zero) { float num = record.GetFloat(ZDOVars.s_scaleScalarHash, float.NaN); val = (float.IsNaN(num) ? prefab.transform.localScale : (Vector3.one * num)); } maximum = Math.Max(val.x, Math.Max(val.y, val.z)); if (PlayerWorldScope.Finite(val) && val.x > 0f && val.y > 0f && val.z > 0f) { return maximum <= 16f; } return false; } public void Dispose() { if (_disposed) { return; } _disposed = true; ZDOMan world = _world; world.m_onZDODestroyed = (Action)Delegate.Remove(world.m_onZDODestroyed, new Action(Destroyed)); try { if (_placement != null && !_placement.MutationStarted) { RetryPlacement(Time.unscaledTime, "placement_paused_before_mutation"); } if (_write != null) { _write.GetAwaiter().GetResult(); _write = null; } if (_dirty) { _store.Save(); _dirty = false; } _placement = null; } finally { try { _replacement.Dispose(); } finally { try { _scope.Dispose(); } finally { _terrain.Dispose(); } } } } } internal sealed class ForestRenewalDiagnostics : FeatureDiagnostics { private readonly ManualLogSource _log; private readonly ProcessingTiming _timing; private readonly DebugLoggingPolicy _policy; private readonly ScheduleToken _next = new ScheduleToken(); private readonly ScheduleToken _nextWrite = new ScheduleToken(); private readonly Dictionary _stages = new Dictionary(); private long _last; private int _scope = -1; private readonly Dictionary<(ZDOID Object, string Reason, string? Detail), float> _decisions = new Dictionary<(ZDOID, string, string), float>(); public IDisposable Measure(float now, Func scope) { return _timing.Measure(now, scope); } public ForestRenewalDiagnostics(ManualLogSource log, DebugLoggingPolicy policy) { _log = log; _policy = policy; ConfigureDiagnostics(() => policy.Enabled, log, "ForestRenewal"); _timing = new ProcessingTiming(log, "ForestRenewal", policy); } public void Decision(float now, ZDOID source, string reason, ZDO? blocker = null, string? detail = null) { //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_00bb: 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_0117: Unknown result type (might be due to invalid IL or missing references) if (!base.DiagnosticsEnabled) { return; } (ZDOID, string, string) key = (blocker?.m_uid ?? source, reason, detail); if ((!_decisions.TryGetValue(key, out var value) || !(now >= value) || !(now - value < 300f)) && _budget.Reserve(now, "decisions", 16)) { if (_decisions.Count >= 4096 && !_decisions.ContainsKey(key)) { _decisions.Clear(); } _decisions[key] = now; if (DiagnosticLog.DebugAvailable(_log, "ForestRenewal")) { DiagnosticLog.Write(_log, "ForestRenewal", ForestRenewalLogTopics.Renewal, $"Sapling renewal for {source}: {reason.Replace('_', ' ')}.", new(string, object)[5] { ("source", source), ("reason", reason), ("blocking_object", blocker?.m_uid), ("blocking_prefab", (blocker != null) ? new int?(blocker.GetPrefab()) : ((int?)null)), ("blocking_reason", detail) }, (LogLevel)32); } } } public void LedgerWrite(float now, double duration) { if (base.DiagnosticsEnabled && _nextWrite.Ready(now)) { _nextWrite.Postpone(now, 60f); if (DiagnosticLog.DebugAvailable(_log, "ForestRenewal")) { DiagnosticLog.Write(_log, "ForestRenewal", ForestRenewalLogTopics.Renewal, "Durable renewal ledger write completed on background worker.", new(string, object)[1] { ("background_io_ms", duration) }, (LogLevel)32); } } } public long BeginStage() { if (!base.DiagnosticsEnabled) { return 0L; } return Stopwatch.GetTimestamp(); } public void EndStage(float now, string stage, long started) { if (started == 0L || !base.DiagnosticsEnabled) { return; } if (stage != "ledger_snapshot" && stage != "terrain_context" && stage != "world_mutation" && stage != "scope_refresh" && stage != "structure_exclusion") { throw new ArgumentException("Unknown renewal timing stage.", "stage"); } double num = (double)(Stopwatch.GetTimestamp() - started) * 1000.0 / (double)Stopwatch.Frequency; _stages.TryGetValue(stage, out (float, int, double, double) value); value.Item2++; value.Item3 += num; value.Item4 = Math.Max(value.Item4, num); if (now < value.Item1) { _stages[stage] = value; return; } _stages[stage] = (now + 60f, 0, 0.0, 0.0); if (DiagnosticLog.DebugAvailable(_log, "ForestRenewal")) { DiagnosticLog.Write(_log, "ForestRenewal", CoreLogTopics.Timing, "Measured renewal stage processing in the last minute.", new(string, object)[4] { ("stage", stage), ("calls", value.Item2), ("duration_avg_ms", value.Item3 / (double)value.Item2), ("duration_max_ms", value.Item4) }, (LogLevel)32); } } public void Result(float now, int count, long total, int scope) { if (base.DiagnosticsEnabled && (scope != 0 || total != _last) && (scope != _scope || total != _last) && _next.Ready(now)) { _next.Postpone(now, 60f); _last = total; _scope = scope; if (DiagnosticLog.DebugAvailable(_log, "ForestRenewal")) { DiagnosticLog.Write(_log, "ForestRenewal", CoreLogTopics.Scope, "Processing scope or results changed this pass.", new(string, object)[3] { ("scope", scope), ("results", count), ("lifetime_results", total) }, (LogLevel)32); } } } } public static class ForestRenewalLogTopics { public static readonly LogTopic Renewal = new LogTopic("renewal"); } internal sealed class ForestRenewalReplacement : IDisposable { private readonly ObjectAuthority _authority; public ForestRenewalReplacement(Action failed, ManualLogSource log, IPlayerPresence presence) { _authority = new ObjectAuthority(failed, log, presence, false); } public void Place(ZDO? stump, GameObject prefab, Vector3 point, long ticks) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0003: Unknown result type (might be due to invalid IL or missing references) //IL_00cf: Unknown result type (might be due to invalid IL or missing references) //IL_0010: 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_008e: 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_0029: 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: Expected O, but got Unknown //IL_0053: Unknown result type (might be due to invalid IL or missing references) //IL_0079: Unknown result type (might be due to invalid IL or missing references) ZDOID val = stump?.m_uid ?? ZDOID.None; if (stump != null) { _authority.Retain(stump); } try { if (stump != null) { if (ZDOMan.instance.GetZDO(val) != stump || !stump.IsValid()) { throw new InvalidOperationException("Renewal stump changed during replacement."); } ZPackage val2 = new ZPackage(); val2.Write(1); val2.Write(val); ZRoutedRpc.instance.InvokeRoutedRPC(0L, "DestroyZDO", new object[1] { val2 }); if (ZDOMan.instance.GetZDO(val) != null) { throw new InvalidOperationException("Renewal stump removal was not confirmed."); } } ZDO val3 = NativeWorldObject.Create(prefab, point, Quaternion.identity); val3.Set(ZDOVars.s_plantTime, ticks); val3.SetOwner(0L); ZDOMan.instance.ForceSendZDO(val3.m_uid); } finally { if (!((ZDOID)(ref val)).IsNone()) { _authority.Release(val); } } } public void Dispose() { _authority.Dispose(); } } public sealed class ForestRenewalSettings { public ConfigEntry Enabled { get; } public ConfigEntry DebugMode { get; } public DebugLoggingPolicy DebugLogging { get; } public ConfigEntry DelaySeconds { get; } public ConfigEntry ChancePercent { get; } public ConfigEntry StructureExclusionMeters { get; } public ConfigEntry PlantExclusionMeters { get; } public ConfigEntry ExcludeClearedGround { get; } public ConfigEntry ExclusionRadiusMeters { get; } public ConfigEntry LocationCooldownHours { get; } public ConfigEntry MaxPending { get; } public ConfigEntry ScanRangeMeters { get; } public ConfigEntry IntervalSeconds { get; } public ForestRenewalSettings(ConfigFile config, ManualLogSource logger) { //IL_0068: Unknown result type (might be due to invalid IL or missing references) //IL_0072: 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_00d0: Unknown result type (might be due to invalid IL or missing references) //IL_00da: Expected O, but got Unknown //IL_0109: Unknown result type (might be due to invalid IL or missing references) //IL_0113: Expected O, but got Unknown //IL_015e: Unknown result type (might be due to invalid IL or missing references) //IL_0168: Expected O, but got Unknown //IL_0197: Unknown result type (might be due to invalid IL or missing references) //IL_01a1: Expected O, but got Unknown //IL_01cc: Unknown result type (might be due to invalid IL or missing references) //IL_01d6: Expected O, but got Unknown //IL_0205: Unknown result type (might be due to invalid IL or missing references) //IL_020f: Expected O, but got Unknown //IL_023e: Unknown result type (might be due to invalid IL or missing references) //IL_0248: Expected O, but got Unknown Enabled = config.Bind("ForestRenewal", "Enabled", true, "Enable ForestRenewal. Restart after edits."); DebugMode = config.Bind("ForestRenewal", "DebugMode", false, "Enable feature diagnostics through the shared debug policy."); DelaySeconds = config.Bind("ForestRenewal", "DelaySeconds", 300f, new ConfigDescription("Delay from first stump observation or confirmed removal. Restart after edits.", (AcceptableValueBase)(object)new AcceptableValueRange(10f, 86400f), Array.Empty())); ChancePercent = config.Bind("ForestRenewal", "ChancePercent", 50, new ConfigDescription("One renewal chance per original stump. Restart after edits.", (AcceptableValueBase)(object)new AcceptableValueRange(0, 100), Array.Empty())); StructureExclusionMeters = config.Bind("ForestRenewal", "StructureExclusionMeters", 10f, new ConfigDescription("Horizontal clearance from player-built collision footprints; zero disables this exclusion. Restart after edits.", (AcceptableValueBase)(object)new AcceptableValueRange(0f, 50f), Array.Empty())); PlantExclusionMeters = config.Bind("ForestRenewal", "PlantExclusionMeters", 10f, new ConfigDescription("Horizontal clearance from existing saplings and crops. Native growth spacing remains a minimum. Restart after edits.", (AcceptableValueBase)(object)new AcceptableValueRange(10f, 50f), Array.Empty())); ExcludeClearedGround = config.Bind("ForestRenewal", "ExcludeClearedGround", true, "Exclude dirt, cultivated and paved ground. Restart after edits."); ExclusionRadiusMeters = config.Bind("ForestRenewal", "ExclusionRadiusMeters", 3f, new ConfigDescription("Terrain paint exclusion radius. Restart after edits.", (AcceptableValueBase)(object)new AcceptableValueRange(0f, 10f), Array.Empty())); LocationCooldownHours = config.Bind("ForestRenewal", "LocationCooldownHours", 24f, new ConfigDescription("Native world hours between renewals within five metres. Restart after edits.", (AcceptableValueBase)(object)new AcceptableValueRange(1f, 720f), Array.Empty())); MaxPending = config.Bind("ForestRenewal", "MaxPending", 1024, new ConfigDescription("Maximum pending renewals. Restart after edits.", (AcceptableValueBase)(object)new AcceptableValueRange(1, 4096), Array.Empty())); ScanRangeMeters = config.Bind("ForestRenewal", "ScanRangeMeters", 64f, new ConfigDescription("Processing range around a rotating ready player. Restart after edits.", (AcceptableValueBase)(object)new AcceptableValueRange(16f, 128f), Array.Empty())); IntervalSeconds = config.Bind("ForestRenewal", "IntervalSeconds", 2f, new ConfigDescription("Processing interval. Restart after edits.", (AcceptableValueBase)(object)new AcceptableValueRange(1f, 30f), Array.Empty())); float[] array = new float[7] { DelaySeconds.Value, StructureExclusionMeters.Value, PlantExclusionMeters.Value, ExclusionRadiusMeters.Value, LocationCooldownHours.Value, ScanRangeMeters.Value, IntervalSeconds.Value }; foreach (float f in array) { if (float.IsNaN(f) || float.IsInfinity(f)) { throw new ArgumentException("ForestRenewal settings must be finite."); } } DebugLogging = DebugLoggingResolver.Resolve(config, "ForestRenewal", DiagnosticsSettings.Bind(config), logger, DebugMode); } } internal sealed class ForestRenewalStore { public const int Capacity = 16384; public readonly Dictionary Records = new Dictionary(); private readonly string _path; private readonly long _world; private readonly object _writeGate = new object(); public ForestRenewalStore(string directory, long world) { //IL_0193: Unknown result type (might be due to invalid IL or missing references) //IL_0198: 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_01b8: Unknown result type (might be due to invalid IL or missing references) //IL_0203: Unknown result type (might be due to invalid IL or missing references) //IL_023f: Unknown result type (might be due to invalid IL or missing references) //IL_025e: Unknown result type (might be due to invalid IL or missing references) _world = world; _path = Path.Combine(directory, "world-" + world.ToString("X16") + ".renewals"); if (!File.Exists(_path)) { if (File.Exists(_path + ".bak")) { throw new InvalidDataException("Renewal ledger is missing while its backup exists."); } return; } long length = new FileInfo(_path).Length; if (length < 52 || length > 1048576) { throw new InvalidDataException("Invalid renewal ledger length."); } byte[] array = File.ReadAllBytes(_path); if (array.Length < 52 || array.Length > 1048576) { throw new InvalidDataException("Invalid renewal ledger length."); } using SHA256 sHA = SHA256.Create(); byte[] array2 = array.Take(array.Length - 32).ToArray(); if (!sHA.ComputeHash(array2).SequenceEqual(array.Skip(array2.Length))) { throw new InvalidDataException("Renewal ledger checksum mismatch."); } using BinaryReader binaryReader = new BinaryReader(new MemoryStream(array2)); if (binaryReader.ReadUInt32() != 1380338504) { throw new InvalidDataException("Renewal ledger signature mismatch."); } int num = binaryReader.ReadInt32(); if ((num != 1 && num != 2) || binaryReader.ReadInt64() != world) { throw new InvalidDataException("Renewal ledger world/format mismatch."); } int num2 = binaryReader.ReadInt32(); if (num2 < 0 || num2 > 16384) { throw new InvalidDataException("Renewal ledger capacity exceeded."); } for (int i = 0; i < num2; i++) { RenewalRecord renewalRecord = new RenewalRecord { Source = new ZDOID(binaryReader.ReadInt64(), binaryReader.ReadUInt32()), Position = new Vector3(binaryReader.ReadSingle(), binaryReader.ReadSingle(), binaryReader.ReadSingle()), Sapling = binaryReader.ReadInt32(), DueTicks = binaryReader.ReadInt64(), DecisionTicks = binaryReader.ReadInt64(), State = binaryReader.ReadByte() }; if (((ZDOID)(ref renewalRecord.Source)).IsNone() || !PlayerWorldScope.Finite(renewalRecord.Position) || renewalRecord.State > ((num == 1) ? 2 : 3) || renewalRecord.DueTicks < 0 || renewalRecord.DecisionTicks < 0 || Records.ContainsKey(renewalRecord.Source)) { throw new InvalidDataException("Invalid renewal record."); } Records.Add(renewalRecord.Source, renewalRecord); } if (binaryReader.BaseStream.Position != array2.Length) { throw new InvalidDataException("Trailing renewal ledger data."); } } public void Save() { WriteSnapshot(Snapshot()); } public Task SaveAsync() { byte[] snapshot = Snapshot(); return Task.Run(delegate { Stopwatch stopwatch = Stopwatch.StartNew(); WriteSnapshot(snapshot); return stopwatch.Elapsed.TotalMilliseconds; }); } private byte[] Snapshot() { using MemoryStream memoryStream = new MemoryStream(); using (BinaryWriter binaryWriter = new BinaryWriter(memoryStream, Encoding.UTF8, leaveOpen: true)) { binaryWriter.Write(1380338504u); binaryWriter.Write(2); binaryWriter.Write(_world); binaryWriter.Write(Records.Count); foreach (RenewalRecord value in Records.Values) { binaryWriter.Write(((ZDOID)(ref value.Source)).UserID); binaryWriter.Write(((ZDOID)(ref value.Source)).ID); binaryWriter.Write(value.Position.x); binaryWriter.Write(value.Position.y); binaryWriter.Write(value.Position.z); binaryWriter.Write(value.Sapling); binaryWriter.Write(value.DueTicks); binaryWriter.Write(value.DecisionTicks); binaryWriter.Write(value.State); } } return memoryStream.ToArray(); } private void WriteSnapshot(byte[] body) { lock (_writeGate) { Directory.CreateDirectory(Path.GetDirectoryName(_path)); using SHA256 sHA = SHA256.Create(); byte[] array = sHA.ComputeHash(body); string text = _path + "." + Guid.NewGuid().ToString("N") + ".tmp"; try { using (FileStream fileStream = new FileStream(text, FileMode.CreateNew, FileAccess.Write, FileShare.None)) { fileStream.Write(body, 0, body.Length); fileStream.Write(array, 0, array.Length); fileStream.Flush(flushToDisk: true); } if (File.Exists(_path)) { File.Replace(text, _path, _path + ".bak"); } else { File.Move(text, _path); } } finally { if (File.Exists(text)) { File.Delete(text); } } } } } internal sealed class ForestRenewalStructures { private readonly PrefabCatalog<(bool Piece, Bounds? Bounds, Vector3 Scale)> _definitions = PrefabRegistry.Current.Catalog<(bool, Bounds?, Vector3)>("ForestRenewalStructures._definitions"); public bool TryExcluded(IReadOnlyList records, Vector3 point, float clearance, out bool excluded, out ZDO? blocker, out string? reason) { //IL_00ff: Unknown result type (might be due to invalid IL or missing references) //IL_0104: Unknown result type (might be due to invalid IL or missing references) //IL_0108: Unknown result type (might be due to invalid IL or missing references) //IL_0116: Unknown result type (might be due to invalid IL or missing references) //IL_011b: 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_00b3: 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_0144: Unknown result type (might be due to invalid IL or missing references) //IL_0149: 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_014d: 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_0193: Unknown result type (might be due to invalid IL or missing references) //IL_0183: Unknown result type (might be due to invalid IL or missing references) //IL_0174: Unknown result type (might be due to invalid IL or missing references) //IL_017b: 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_0188: Unknown result type (might be due to invalid IL or missing references) //IL_01af: 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_01cb: Unknown result type (might be due to invalid IL or missing references) //IL_01d9: Unknown result type (might be due to invalid IL or missing references) //IL_01f6: 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_01fe: Unknown result type (might be due to invalid IL or missing references) //IL_0203: Unknown result type (might be due to invalid IL or missing references) //IL_0205: 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_021c: Unknown result type (might be due to invalid IL or missing references) //IL_022a: Unknown result type (might be due to invalid IL or missing references) //IL_0238: Unknown result type (might be due to invalid IL or missing references) //IL_0256: Unknown result type (might be due to invalid IL or missing references) //IL_025b: Unknown result type (might be due to invalid IL or missing references) //IL_025d: Unknown result type (might be due to invalid IL or missing references) //IL_025f: Unknown result type (might be due to invalid IL or missing references) //IL_0261: Unknown result type (might be due to invalid IL or missing references) //IL_026f: Unknown result type (might be due to invalid IL or missing references) //IL_0271: Unknown result type (might be due to invalid IL or missing references) //IL_0275: Unknown result type (might be due to invalid IL or missing references) //IL_027a: Unknown result type (might be due to invalid IL or missing references) //IL_027e: Unknown result type (might be due to invalid IL or missing references) //IL_0283: Unknown result type (might be due to invalid IL or missing references) //IL_0285: Unknown result type (might be due to invalid IL or missing references) //IL_028a: 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_0294: 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_02a7: 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_02b2: Unknown result type (might be due to invalid IL or missing references) //IL_02b7: Unknown result type (might be due to invalid IL or missing references) //IL_02b9: Unknown result type (might be due to invalid IL or missing references) //IL_02be: Unknown result type (might be due to invalid IL or missing references) //IL_02c3: Unknown result type (might be due to invalid IL or missing references) //IL_02da: Unknown result type (might be due to invalid IL or missing references) //IL_02e4: Unknown result type (might be due to invalid IL or missing references) //IL_02f0: Unknown result type (might be due to invalid IL or missing references) //IL_02f8: Unknown result type (might be due to invalid IL or missing references) //IL_030f: Unknown result type (might be due to invalid IL or missing references) //IL_0319: Unknown result type (might be due to invalid IL or missing references) //IL_0325: Unknown result type (might be due to invalid IL or missing references) //IL_032d: Unknown result type (might be due to invalid IL or missing references) excluded = false; blocker = null; reason = null; if (clearance <= 0f) { return true; } Bounds val4 = default(Bounds); for (int i = 0; i < records.Count; i++) { ZDO val = records[i]; if (!val.IsValid() || val.GetLong(ZDOVars.s_creator, 0L) == 0L) { continue; } if (!_definitions.TryGetValue(val.GetPrefab(), out (bool, Bounds?, Vector3) value)) { GameObject val2 = PrefabRegistry.Current.Prefab(val.GetPrefab()); if ((Object)(object)val2 == (Object)null) { blocker = val; reason = "prefab_unavailable"; return false; } bool num = (Object)(object)PrefabRegistry.Component(val2) != (Object)null; value = (num, num ? PrefabRegistry.Current.Bounds(val2) : ((Bounds?)null), val2.transform.localScale); if (_definitions.Count < 4096) { _definitions.Add(val.GetPrefab(), value); } } if (!value.Item1) { continue; } Bounds? item = value.Item2; if (item.HasValue) { Bounds value2 = item.Value; if (PlayerWorldScope.Finite(((Bounds)(ref value2)).center)) { value2 = item.Value; if (PlayerWorldScope.Finite(((Bounds)(ref value2)).extents)) { Vector3 val3 = val.GetVec3(ZDOVars.s_scaleHash, Vector3.zero); if (val3 == Vector3.zero) { float num2 = val.GetFloat(ZDOVars.s_scaleScalarHash, float.NaN); val3 = (float.IsNaN(num2) ? value.Item3 : (Vector3.one * num2)); } if (!PlayerWorldScope.Finite(val3) || val3.x <= 0f || val3.y <= 0f || val3.z <= 0f || val3.x > 16f || val3.y > 16f || val3.z > 16f) { blocker = val; reason = "structure_scale_unsupported"; return false; } Vector3 position = val.GetPosition(); Quaternion rotation = val.GetRotation(); if (!PlayerWorldScope.Finite(position) || !PlayerWorldScope.Finite(rotation.x) || !PlayerWorldScope.Finite(rotation.y) || !PlayerWorldScope.Finite(rotation.z) || !PlayerWorldScope.Finite(rotation.w)) { blocker = val; reason = "structure_transform_invalid"; return false; } if (CanReach(item.Value, val3, rotation, position, point, clearance)) { value2 = item.Value; ((Bounds)(ref val4))..ctor(position + rotation * Vector3.Scale(((Bounds)(ref value2)).center, val3), Vector3.zero); for (int j = 0; j < 8; j++) { ((Bounds)(ref val4)).Encapsulate(position + rotation * Vector3.Scale(PrefabCollisionBounds.Corner(item.Value, j), val3)); } float num3 = Math.Max(((Bounds)(ref val4)).min.x - point.x, Math.Max(0f, point.x - ((Bounds)(ref val4)).max.x)); float num4 = Math.Max(((Bounds)(ref val4)).min.z - point.z, Math.Max(0f, point.z - ((Bounds)(ref val4)).max.z)); if (num3 * num3 + num4 * num4 <= clearance * clearance) { excluded = true; return true; } } continue; } } } blocker = val; reason = "collision_geometry_unsupported"; return false; } return true; } internal static bool CanReach(Bounds local, Vector3 scale, Quaternion rotation, Vector3 position, Vector3 point, float clearance) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000d: 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_001b: 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_0029: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_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_0049: Unknown result type (might be due to invalid IL or missing references) //IL_004e: Unknown result type (might be due to invalid IL or missing references) //IL_0057: Unknown result type (might be due to invalid IL or missing references) //IL_005d: Unknown result type (might be due to invalid IL or missing references) //IL_0063: Unknown result type (might be due to invalid IL or missing references) //IL_0093: Unknown result type (might be due to invalid IL or missing references) //IL_0099: 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) //IL_00a7: Unknown result type (might be due to invalid IL or missing references) float num = rotation.x * rotation.x + rotation.y * rotation.y + rotation.z * rotation.z + rotation.w * rotation.w; Vector3 val = ((Bounds)(ref local)).center; float magnitude = ((Vector3)(ref val)).magnitude; val = ((Bounds)(ref local)).extents; float num2 = (magnitude + ((Vector3)(ref val)).magnitude) * Math.Max(scale.x, Math.Max(scale.y, scale.z)) * Math.Max(1f, 2f * num - 1f) * 1.4142137f; float num3 = position.x - point.x; float num4 = position.z - point.z; return num3 * num3 + num4 * num4 <= (clearance + num2) * (clearance + num2); } } } namespace HeimKit.Features.ForestRenewal.Models { internal sealed class RenewalPlacement { public RenewalRecord Decision; public ZDO? Stump; public GameObject Prefab; public Vector3 Position; public long RequiredRevision; public float Created; public byte PendingState; public long PreviousDecisionTicks; public bool MutationStarted; } internal sealed class RenewalRecord { public ZDOID Source; public Vector3 Position; public int Sapling; public long DueTicks; public long DecisionTicks; public byte State; } } namespace HeimKit.Features.DoorKeeper { public sealed class DoorKeeper : IServerModule { private readonly DoorKeeperSettings _settings; private readonly ManualLogSource _logger; private readonly GameVersionCompatibility _compatibility; private readonly PlayerServices _players; private DoorKeeperController? _controller; private IDisposable? _presenceRegistration; private bool _occupied; private ZDOMan? _world; private long _worldUid; private readonly string _directory; private readonly PlayerProcessingNotices _processing; public string Name => "DoorKeeper"; public bool IsActive { get; private set; } public DoorKeeper(ConfigFile config, ManualLogSource logger, PlayerServices players) { _directory = Path.Combine(Path.GetDirectoryName(config.ConfigFilePath), "HeimKit", "DoorKeeper"); _logger = logger; _compatibility = GameVersionCompatibility.Resolve(config, logger); _settings = new DoorKeeperSettings(config, logger); _players = players; _processing = new PlayerProcessingNotices(logger, Name, () => _settings.DebugLogging.Enabled); } public void Initialize(string gameVersion) { Shutdown(); Log(_settings.Enabled.Value ? "Enabled." : "Disabled.", (LogLevel)16); _settings.DebugLogging.ReportStartup(_logger, Name, _settings.Enabled.Value); if (!_settings.Enabled.Value) { return; } if (!_compatibility.Supports(gameVersion)) { Log("DISABLED: unsupported game version " + gameVersion + "; required version " + _compatibility.RequiredVersion, (LogLevel)4); return; } IsActive = true; if (_settings.DebugLogging.Enabled) { Log("Waiting for joined players and dedicated-server world", (LogLevel)32); } try { _presenceRegistration = _players.Events.Subscribe(PresenceChanged, Fail, () => _processing.IsEmptyPaused, () => _processing.IsRunning, () => _processing.IsServerReady); } catch (Exception error) { Fail(error); } if (!IsActive) { IDisposable? presenceRegistration = _presenceRegistration; _presenceRegistration = null; presenceRegistration?.Dispose(); } } public void Tick(float now) { if (!IsActive) { return; } if (!_settings.Enabled.Value) { Shutdown(); return; } try { bool flag = WorldServices.Activity && WorldServices.Terrain; if (flag) { _processing.ServerReady(); } if (!_occupied) { StopController(); return; } if (!flag) { StopController(); _processing.Paused("world services unavailable"); return; } long worldUID = ZNet.instance.GetWorldUID(); if (_world != ZDOMan.instance || _worldUid != worldUID) { StopController(); _world = ZDOMan.instance; _worldUid = worldUID; } StartController(); _controller?.Tick(now); } catch (Exception error) { Fail(error); } } private void PresenceChanged(bool? occupied) { _occupied = occupied == true; if (IsActive && !_occupied) { StopController(); if (occupied.HasValue) { _processing.EmptyPaused(); } else { _processing.Unavailable("player presence unavailable"); } } } private void StartController() { if (_settings.Enabled.Value && _controller == null) { _controller = new DoorKeeperController(this, _settings, _logger, _players, _directory); _processing.Ready(); } } private void StopController() { DoorKeeperController controller = _controller; _controller = null; if (controller != null) { ModuleScheduler.Current.Forget(controller); } try { controller?.Dispose(); } finally { WorldObjectProvider.Current?.ReleaseOwner(Name); } } internal void Fail(Exception error) { if (IsActive) { DiagnosticLog.Write(_logger, Name, CoreLogTopics.Lifecycle, "Disabled after a runtime failure.", default(LogFields), (LogLevel)2, verbose: false, error); Shutdown(); } } private void Log(string message, LogLevel level = (LogLevel)16) { //IL_000d: Unknown result type (might be due to invalid IL or missing references) DiagnosticLog.Write(_logger, Name, message, level); } public void Shutdown() { IsActive = false; _occupied = false; _processing.Reset(); IDisposable registration = _presenceRegistration; _presenceRegistration = null; ModuleCleanup.Run(_logger, Name, delegate { registration?.Dispose(); }, StopController); } } internal sealed class DoorKeeperClearance { private readonly PrefabCatalog _bounds = PrefabRegistry.Current.Catalog("DoorKeeperClearance._bounds"); public bool Occupied(PlayerWorldScope scope, ZDO door, float configuredMinimum) { //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_007b: Unknown result type (might be due to invalid IL or missing references) //IL_007c: Unknown result type (might be due to invalid IL or missing references) //IL_007d: Unknown result type (might be due to invalid IL or missing references) //IL_00be: Unknown result type (might be due to invalid IL or missing references) //IL_00c6: Unknown result type (might be due to invalid IL or missing references) //IL_00b8: Unknown result type (might be due to invalid IL or missing references) //IL_00a4: Unknown result type (might be due to invalid IL or missing references) //IL_00ab: Unknown result type (might be due to invalid IL or missing references) //IL_00d3: Unknown result type (might be due to invalid IL or missing references) //IL_00bd: Unknown result type (might be due to invalid IL or missing references) //IL_00e0: 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_00f9: Unknown result type (might be due to invalid IL or missing references) //IL_0113: 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_0120: Unknown result type (might be due to invalid IL or missing references) //IL_0125: Unknown result type (might be due to invalid IL or missing references) //IL_0129: Unknown result type (might be due to invalid IL or missing references) //IL_012e: 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_0134: Unknown result type (might be due to invalid IL or missing references) //IL_0139: Unknown result type (might be due to invalid IL or missing references) //IL_013e: Unknown result type (might be due to invalid IL or missing references) //IL_0142: Unknown result type (might be due to invalid IL or missing references) //IL_0147: 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_0150: Unknown result type (might be due to invalid IL or missing references) //IL_0151: 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_016c: Unknown result type (might be due to invalid IL or missing references) //IL_0180: Unknown result type (might be due to invalid IL or missing references) GameObject val = PrefabRegistry.Current.Prefab(door.GetPrefab()); if (!Object.op_Implicit((Object)(object)val)) { return true; } if (!_bounds.TryGetValue(door.GetPrefab(), out var value)) { value = PrefabRegistry.Current.Bounds(val); if (_bounds.Count < 4096) { _bounds[door.GetPrefab()] = value; } } if (!value.HasValue) { return true; } Vector3 val2 = door.GetVec3(ZDOVars.s_scaleHash, Vector3.zero); if (val2 == Vector3.zero) { float num = door.GetFloat(ZDOVars.s_scaleScalarHash, float.NaN); val2 = (float.IsNaN(num) ? val.transform.localScale : (Vector3.one * num)); } if (!PlayerWorldScope.Finite(val2) || val2.x <= 0f || val2.y <= 0f || val2.z <= 0f || Math.Max(val2.x, Math.Max(val2.y, val2.z)) > 16f) { return true; } Vector3 position = door.GetPosition(); Quaternion rotation = door.GetRotation(); Bounds value2 = value.Value; Vector3 val3 = position + rotation * Vector3.Scale(((Bounds)(ref value2)).center, val2); value2 = value.Value; Vector3 val4 = Vector3.Scale(((Bounds)(ref value2)).extents, val2); float num2 = Math.Max(configuredMinimum, ((Vector3)(ref val4)).magnitude + 1f); if (!PlayerWorldScope.Finite(val3) || !PlayerWorldScope.Finite(num2)) { return true; } return scope.PlayerNear(val3, num2); } } internal sealed class DoorKeeperContext : IDisposable { private readonly TerrainContext _terrain = new TerrainContext(); private readonly PrefabCatalog<(bool Required, Bounds? Bounds)> _definitions = PrefabRegistry.Current.Catalog<(bool, Bounds?)>("DoorKeeperContext._definitions"); private readonly PrefabCatalog _doorBounds = PrefabRegistry.Current.Catalog("DoorKeeperContext._doorBounds"); public string? WaitReason => _terrain.WaitReason; public ZDOID WaitObject => _terrain.WaitObject; public bool Prepare(PlayerWorldScope scope, ZDO door, float now) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_005f: Unknown result type (might be due to invalid IL or missing references) //IL_0064: Unknown result type (might be due to invalid IL or missing references) //IL_0069: Unknown result type (might be due to invalid IL or missing references) //IL_006b: Unknown result type (might be due to invalid IL or missing references) //IL_006d: 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_00bb: Unknown result type (might be due to invalid IL or missing references) //IL_00bf: Unknown result type (might be due to invalid IL or missing references) //IL_00c4: Unknown result type (might be due to invalid IL or missing references) //IL_00c6: Unknown result type (might be due to invalid IL or missing references) //IL_00cb: Unknown result type (might be due to invalid IL or missing references) //IL_00d7: Unknown result type (might be due to invalid IL or missing references) //IL_00dc: Unknown result type (might be due to invalid IL or missing references) //IL_00e0: Unknown result type (might be due to invalid IL or missing references) //IL_00e5: Unknown result type (might be due to invalid IL or missing references) //IL_00e7: Unknown result type (might be due to invalid IL or missing references) //IL_00ec: Unknown result type (might be due to invalid IL or missing references) //IL_00a8: Unknown result type (might be due to invalid IL or missing references) //IL_0094: Unknown result type (might be due to invalid IL or missing references) //IL_009b: 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_00ad: Unknown result type (might be due to invalid IL or missing references) //IL_0153: Unknown result type (might be due to invalid IL or missing references) //IL_0266: Unknown result type (might be due to invalid IL or missing references) //IL_026b: 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_0272: Unknown result type (might be due to invalid IL or missing references) //IL_0274: Unknown result type (might be due to invalid IL or missing references) //IL_02b8: Unknown result type (might be due to invalid IL or missing references) //IL_02d0: Unknown result type (might be due to invalid IL or missing references) //IL_02d5: Unknown result type (might be due to invalid IL or missing references) //IL_02d9: Unknown result type (might be due to invalid IL or missing references) //IL_02de: Unknown result type (might be due to invalid IL or missing references) //IL_02e0: Unknown result type (might be due to invalid IL or missing references) //IL_02e5: Unknown result type (might be due to invalid IL or missing references) //IL_02f0: Unknown result type (might be due to invalid IL or missing references) //IL_02f5: Unknown result type (might be due to invalid IL or missing references) //IL_02f7: Unknown result type (might be due to invalid IL or missing references) //IL_02fc: Unknown result type (might be due to invalid IL or missing references) //IL_030a: Unknown result type (might be due to invalid IL or missing references) //IL_030f: Unknown result type (might be due to invalid IL or missing references) //IL_0310: Unknown result type (might be due to invalid IL or missing references) //IL_0315: Unknown result type (might be due to invalid IL or missing references) //IL_0317: Unknown result type (might be due to invalid IL or missing references) //IL_031e: Unknown result type (might be due to invalid IL or missing references) //IL_0326: Unknown result type (might be due to invalid IL or missing references) //IL_032d: Unknown result type (might be due to invalid IL or missing references) //IL_02b1: Unknown result type (might be due to invalid IL or missing references) //IL_029c: Unknown result type (might be due to invalid IL or missing references) //IL_02a3: Unknown result type (might be due to invalid IL or missing references) //IL_02b6: Unknown result type (might be due to invalid IL or missing references) Vector3 position = door.GetPosition(); int prefab = door.GetPrefab(); GameObject val = PrefabRegistry.Current.Prefab(prefab); if ((Object)(object)val == (Object)null) { return false; } if (!_doorBounds.TryGetValue(prefab, out var value)) { value = (_doorBounds[prefab] = PrefabRegistry.Current.Bounds(val)); } if (!value.HasValue) { return false; } Vector3 val3 = door.GetVec3(ZDOVars.s_scaleHash, Vector3.zero); if (val3 == Vector3.zero) { float num = door.GetFloat(ZDOVars.s_scaleScalarHash, float.NaN); val3 = (float.IsNaN(num) ? val.transform.localScale : (Vector3.one * num)); } Bounds value2 = value.Value; Vector3 val4 = Vector3.Scale(((Bounds)(ref value2)).center, val3); float num2 = 16f + ((Vector3)(ref val4)).magnitude; value2 = value.Value; val4 = Vector3.Scale(((Bounds)(ref value2)).extents, val3); float num3 = num2 + ((Vector3)(ref val4)).magnitude; if (!PlayerWorldScope.Finite(num3)) { return false; } if (!scope.ContextReady() || !_terrain.Prepare(position, scope.Context, now)) { return false; } bool result = true; foreach (ZDO item2 in scope.Context) { if (!item2.IsValid() || Character.InInterior(item2.GetPosition())) { continue; } GameObject val5 = PrefabRegistry.Current.Prefab(item2.GetPrefab()); if ((Object)(object)val5 == (Object)null) { result = false; continue; } int num4; Bounds? item; if (!_definitions.TryGetValue(item2.GetPrefab(), out (bool, Bounds?) value3)) { if ((Object)(object)PrefabRegistry.Component(val5) == (Object)null && (Object)(object)PrefabRegistry.Component(val5) == (Object)null) { if (!((Object)(object)PrefabRegistry.Component(val5) != (Object)null) && PrefabRegistry.Children(val5, inactive: true).Length == 0 && !((Object)(object)PrefabRegistry.Component(val5) != (Object)null)) { num4 = (((Object)(object)PrefabRegistry.Component(val5) != (Object)null) ? 1 : 0); if (num4 == 0) { goto IL_01fd; } } else { num4 = 1; } item = PrefabRegistry.Current.Bounds(val5); goto IL_0215; } num4 = 0; goto IL_01fd; } goto IL_0242; IL_0242: if (!value3.Item1) { continue; } if (value3.Item2.HasValue) { Vector3 val6 = item2.GetVec3(ZDOVars.s_scaleHash, Vector3.zero); if (val6 == Vector3.zero) { float num5 = item2.GetFloat(ZDOVars.s_scaleScalarHash, float.NaN); val6 = (float.IsNaN(num5) ? val5.transform.localScale : (Vector3.one * num5)); } if (!PlayerWorldScope.Finite(val6)) { return false; } Bounds value4 = value3.Item2.Value; val4 = Vector3.Scale(((Bounds)(ref value4)).center, val6); float magnitude = ((Vector3)(ref val4)).magnitude; val4 = Vector3.Scale(((Bounds)(ref value4)).extents, val6); float num6 = magnitude + ((Vector3)(ref val4)).magnitude; Vector3 val7 = item2.GetPosition() - position; if (val7.x * val7.x + val7.z * val7.z > (num3 + num6) * (num3 + num6)) { continue; } } if (!_terrain.Include(item2, now)) { return false; } if ((Object)(object)ZNetScene.instance.FindInstance(item2) == (Object)null) { result = false; } continue; IL_0215: value3 = ((byte)num4 != 0, item); if (_definitions.Count < 4096) { _definitions[item2.GetPrefab()] = value3; } goto IL_0242; IL_01fd: item = null; goto IL_0215; } return result; } public void Clear() { _terrain.Clear(); } public void Dispose() { _terrain.Dispose(); } } internal sealed class DoorKeeperController : IDisposable { private readonly DoorKeeperSettings _settings; private readonly ManualLogSource _log; private readonly DoorKeeperDiagnostics _diagnostics; private readonly PlayerWorldScope _scope; private readonly ObjectAuthority _authority; private readonly DoorKeeperContext _context; private readonly DoorKeeperClearance _clearance = new DoorKeeperClearance(); private readonly HashSet _prefabs = new HashSet(); private readonly Dictionary _doors = new Dictionary(); private readonly Func _canInteract; private readonly Action _use; private readonly List _expired = new List(); private int _contextCursor; private long _closed; public DoorKeeperController(DoorKeeper module, DoorKeeperSettings settings, ManualLogSource log, PlayerServices players, string directory) { _settings = settings; _log = log; _scope = WorldObjectProvider.Current.CreateScope("DoorKeeper"); _diagnostics = new DoorKeeperDiagnostics(log, settings.DebugLogging); _canInteract = NativeAccess.Method>(typeof(Door), "CanInteract", Array.Empty()); _use = NativeAccess.Method>(typeof(Door), "RPC_UseDoor", new Type[2] { typeof(long), typeof(bool) }); string[] array = new string[10] { "wood_door", "wood_gate", "wood_fence_gate", "darkwood_gate", "iron_grate", "stave_gate", "piece_dvergr_wood_door", "piece_hexagonal_door", "flametal_gate", "ashwood_door" }; foreach (string text in array) { GameObject obj = PrefabRegistry.Current.Prefab(text); Door val = PrefabRegistry.Component(obj); ZNetView val2 = PrefabRegistry.Component(obj); if ((Object)(object)val != (Object)null && (Object)(object)val2 != (Object)null && val2.m_persistent && (Object)(object)PrefabRegistry.Component(obj) != (Object)null && (Object)(object)val.m_keyItem == (Object)null && !val.m_canNotBeClosed && !val.m_invertedOpenClosedText) { _prefabs.Add(StringExtensionMethods.GetStableHashCode(text)); } } if (_prefabs.Count == 0) { throw new InvalidOperationException("No supported native doors are available."); } _context = new DoorKeeperContext(); try { _authority = new ObjectAuthority(module.Fail, log, players.Presence, true, "UseDoor", "RPC_Damage", "RPC_Repair", "RPC_Remove"); } catch { _context.Dispose(); throw; } try { _scope.Index((ZDO z) => _prefabs.Contains(z.GetPrefab())); } catch { Dispose(); throw; } } public void Tick(float now) { //IL_03f3: 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_00bf: Unknown result type (might be due to invalid IL or missing references) //IL_0107: Unknown result type (might be due to invalid IL or missing references) //IL_010c: 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_04a1: Unknown result type (might be due to invalid IL or missing references) //IL_01e1: Unknown result type (might be due to invalid IL or missing references) //IL_021b: Unknown result type (might be due to invalid IL or missing references) //IL_0240: Unknown result type (might be due to invalid IL or missing references) //IL_029a: Unknown result type (might be due to invalid IL or missing references) //IL_03de: Unknown result type (might be due to invalid IL or missing references) if (!ModuleScheduler.Current.Due(this, "processing", now, _settings.IntervalSeconds.Value)) { return; } using (_diagnostics.OptionalEnabled ? _diagnostics.Measure(now, () => _scope.Records.Count) : null) { if (!_scope.Refresh(_settings.ScanRangeMeters.Value)) { ReleaseAll(); _context.Clear(); return; } _expired.Clear(); foreach (KeyValuePair door in _doors) { if (now - door.Value.Item2 > 10f || ZDOMan.instance.GetZDO(door.Key) == null) { _expired.Add(door.Key); } } foreach (ZDOID item in _expired) { _doors.Remove(item); } int num = 0; int num2 = 0; int num3 = 0; bool flag = false; bool ready = true; int num4 = ((_scope.Records.Count != 0) ? (_contextCursor % _scope.Records.Count) : 0); for (int num5 = 0; num5 < _scope.Records.Count; num5++) { int num6 = (num4 + num5) % _scope.Records.Count; ZDO val = _scope.Records[num6]; if (!val.IsValid() || !_prefabs.Contains(val.GetPrefab()) || val.GetLong(ZDOVars.s_creator, 0L) == 0L || !_scope.InRange(val.GetPosition(), _settings.ScanRangeMeters.Value)) { continue; } int num7 = val.GetInt(ZDOVars.s_state, 0); switch (num7) { case 0: _doors.Remove(val.m_uid); break; case -1: case 1: { if (!_doors.TryGetValue(val.m_uid, out (float, float, int) value)) { if (_doors.Count >= 1024) { break; } value = (now, now, num7); } if (num7 != value.Item3) { value.Item1 = now; } value.Item2 = now; value.Item3 = num7; _doors[val.m_uid] = value; if (now - value.Item1 < _settings.CloseDelaySeconds.Value) { num3++; } else if (_clearance.Occupied(_scope, val, _settings.ClearanceMeters.Value)) { num2++; } else { if (flag) { break; } flag = true; _contextCursor = num6 + 1; if (!_context.Prepare(_scope, val, now)) { ready = false; break; } ZNetView val2 = ZNetScene.instance.FindInstance(val); Door val3 = (((Object)(object)val2 == (Object)null) ? null : ((Component)val2).GetComponent()); if ((Object)(object)val3 == (Object)null || !val2.IsValid() || val2.GetZDO() != val || !_canInteract(val3) || val.GetInt(ZDOVars.s_state, 0) == 0) { break; } try { _authority.Retain(val); _use(val3, ZDOMan.GetSessionID(), arg3: false); if (val.GetInt(ZDOVars.s_state, 0) == 0) { num++; _closed++; _doors.Remove(val.m_uid); } } finally { _authority.Release(val.m_uid); } } break; } } } if (num > 0) { DiagnosticLog.Write(_log, "DoorKeeper", (num == 1) ? "Closed one door." : $"Closed {num} doors.", (LogLevel)16); } _diagnostics.Result(now, num, _closed, _doors.Count); _diagnostics.Scan(now, _scope.Records.Count, _doors.Count, num3, num2, ready, _context.WaitReason, _context.WaitObject); } } private void ReleaseAll() { //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_001a: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Unknown result type (might be due to invalid IL or missing references) foreach (ZDOID key in _doors.Keys) { _authority.Release(key); } _doors.Clear(); } public void Dispose() { try { ReleaseAll(); } finally { try { _authority.Dispose(); } finally { try { _scope.Dispose(); } finally { _context.Dispose(); } } } } } internal sealed class DoorKeeperDiagnostics : FeatureDiagnostics { private readonly ManualLogSource _log; private readonly ProcessingTiming _timing; private readonly DebugLoggingPolicy _policy; private readonly ScheduleToken _next = new ScheduleToken(); private long _last; private int _scope = -1; private readonly ScheduleToken _nextScan = new ScheduleToken(); private (int Doors, int Delayed, int Occupied, bool Ready, string? Reason)? _lastScan; public IDisposable Measure(float now, Func scope) { return _timing.Measure(now, scope); } public DoorKeeperDiagnostics(ManualLogSource log, DebugLoggingPolicy policy) { _log = log; _policy = policy; ConfigureDiagnostics(() => policy.Enabled, log, "DoorKeeper"); _timing = new ProcessingTiming(log, "DoorKeeper", policy); } public void Scan(float now, int records, int doors, int delayed, int occupied, bool ready, string? reason = null, ZDOID? blocking = null) { (int, int, int, bool, string) tuple = (doors, delayed, occupied, ready, reason); if (!base.DiagnosticsEnabled || records == 0 || !_nextScan.Ready(now)) { return; } (int, int, int, bool, string)? lastScan = _lastScan; (int, int, int, bool, string) tuple2 = tuple; bool hasValue = lastScan.HasValue; if (hasValue) { if (!hasValue) { return; } (int, int, int, bool, string) valueOrDefault = lastScan.GetValueOrDefault(); if (valueOrDefault.Item1 == tuple2.Item1 && valueOrDefault.Item2 == tuple2.Item2 && valueOrDefault.Item3 == tuple2.Item3 && valueOrDefault.Item4 == tuple2.Item4 && valueOrDefault.Item5 == tuple2.Item5) { return; } } _nextScan.Postpone(now, 60f); _lastScan = tuple; if (DiagnosticLog.DebugAvailable(_log, "DoorKeeper")) { DiagnosticLog.Write(_log, "DoorKeeper", CoreLogTopics.Scope, "Evaluated door eligibility this pass.", new(string, object)[7] { ("records", records), ("doors", doors), ("delay_wait", delayed), ("occupied", occupied), ("context_ready", ready), ("context_reason", reason), ("blocking_object", blocking) }, (LogLevel)32); } } public void Result(float now, int count, long total, int scope) { if (base.DiagnosticsEnabled && (scope != 0 || total != _last) && (scope != _scope || total != _last) && _next.Ready(now)) { _next.Postpone(now, 60f); _last = total; _scope = scope; if (DiagnosticLog.DebugAvailable(_log, "DoorKeeper")) { DiagnosticLog.Write(_log, "DoorKeeper", CoreLogTopics.Scope, "Processing scope or results changed this pass.", new(string, object)[3] { ("scope", scope), ("results", count), ("lifetime_results", total) }, (LogLevel)32); } } } } public static class DoorKeeperLogTopics { public static readonly LogTopic Doors = new LogTopic("doors"); } public sealed class DoorKeeperSettings { public ConfigEntry Enabled { get; } public ConfigEntry DebugMode { get; } public DebugLoggingPolicy DebugLogging { get; } public ConfigEntry CloseDelaySeconds { get; } public ConfigEntry ClearanceMeters { get; } public ConfigEntry ScanRangeMeters { get; } public ConfigEntry IntervalSeconds { get; } public DoorKeeperSettings(ConfigFile config, ManualLogSource logger) { //IL_0068: Unknown result type (might be due to invalid IL or missing references) //IL_0072: Expected O, but got Unknown //IL_00a1: Unknown result type (might be due to invalid IL or missing references) //IL_00ab: Expected O, but got Unknown //IL_00da: Unknown result type (might be due to invalid IL or missing references) //IL_00e4: Expected O, but got Unknown //IL_0113: Unknown result type (might be due to invalid IL or missing references) //IL_011d: Expected O, but got Unknown Enabled = config.Bind("DoorKeeper", "Enabled", true, "Enable DoorKeeper. Restart after edits."); DebugMode = config.Bind("DoorKeeper", "DebugMode", false, "Enable feature diagnostics through the shared debug policy."); CloseDelaySeconds = config.Bind("DoorKeeper", "CloseDelaySeconds", 5f, new ConfigDescription("Continuous observed open time before closing. Restart after edits.", (AcceptableValueBase)(object)new AcceptableValueRange(1f, 300f), Array.Empty())); ClearanceMeters = config.Bind("DoorKeeper", "ClearanceMeters", 3f, new ConfigDescription("Minimum occupancy sphere radius; native door geometry plus player allowance can enlarge it. Restart after edits.", (AcceptableValueBase)(object)new AcceptableValueRange(2f, 10f), Array.Empty())); ScanRangeMeters = config.Bind("DoorKeeper", "ScanRangeMeters", 64f, new ConfigDescription("Range around a rotating ready player. Restart after edits.", (AcceptableValueBase)(object)new AcceptableValueRange(16f, 128f), Array.Empty())); IntervalSeconds = config.Bind("DoorKeeper", "IntervalSeconds", 2f, new ConfigDescription("Processing interval. Restart after edits.", (AcceptableValueBase)(object)new AcceptableValueRange(0.5f, 10f), Array.Empty())); float[] array = new float[4] { CloseDelaySeconds.Value, ClearanceMeters.Value, ScanRangeMeters.Value, IntervalSeconds.Value }; foreach (float f in array) { if (float.IsNaN(f) || float.IsInfinity(f)) { throw new ArgumentException("DoorKeeper settings must be finite."); } } DebugLogging = DebugLoggingResolver.Resolve(config, "DoorKeeper", DiagnosticsSettings.Bind(config), logger, DebugMode); } } } namespace HeimKit.Features.AFKRaidWatch { public sealed class AFKRaidWatch : IServerModule { private readonly AFKRaidWatchSettings _settings; private readonly ManualLogSource _logger; private readonly GameVersionCompatibility _compatibility; private readonly PlayerServices _players; private AFKRaidWatchController? _controller; private IDisposable? _presenceRegistration; private bool _occupied; private readonly PlayerProcessingNotices _processing; public string Name => "AFKRaidWatch"; public bool IsActive { get; private set; } public AFKRaidWatch(ConfigFile config, ManualLogSource logger, PlayerServices players) { _logger = logger; _compatibility = GameVersionCompatibility.Resolve(config, logger); _settings = new AFKRaidWatchSettings(config, logger); _players = players; _processing = new PlayerProcessingNotices(logger, Name, () => _settings.DebugLogging.Enabled); } public void Initialize(string gameVersion) { Shutdown(); Log(_settings.Enabled.Value ? "Enabled." : "Disabled.", (LogLevel)16); _settings.DebugLogging.ReportStartup(_logger, Name, _settings.Enabled.Value); if (!_settings.Enabled.Value) { return; } if (!_compatibility.Supports(gameVersion)) { Log("DISABLED: unsupported game version " + gameVersion + "; required version " + _compatibility.RequiredVersion, (LogLevel)4); return; } IsActive = true; if (_settings.DebugLogging.Enabled) { Log("Waiting for joined players and dedicated-server world", (LogLevel)32); } _presenceRegistration = _players.Events.Subscribe(PresenceChanged, Fail, () => _processing.IsEmptyPaused, () => _processing.IsRunning, () => _processing.IsServerReady); } public void Tick(float now) { if (!IsActive) { return; } if (!_settings.Enabled.Value) { Shutdown(); return; } try { if (PlayerServices.Ready) { _processing.ServerReady(); } if (!_occupied) { StopController(); } else if (!PlayerServices.Ready) { StopController(); _processing.Paused("world services unavailable"); } else { StartController(); _controller?.Tick(now); } } catch (Exception error) { Fail(error); } } private void PresenceChanged(bool? occupied) { _occupied = occupied == true; if (IsActive && !_occupied) { StopController(); if (occupied.HasValue) { _processing.EmptyPaused(); } else { _processing.Unavailable("player presence unavailable"); } } } private void StartController() { if (_settings.Enabled.Value && _controller == null) { _controller = new AFKRaidWatchController(this, _settings, _logger, _players); _processing.Ready(); } } private void StopController() { AFKRaidWatchController controller = _controller; _controller = null; if (controller != null) { ModuleScheduler.Current.Forget(controller); } try { controller?.Dispose(); } finally { WorldObjectProvider.Current?.ReleaseOwner(Name); } } internal void Fail(Exception error) { if (IsActive) { DiagnosticLog.Write(_logger, Name, CoreLogTopics.Lifecycle, "Disabled after a runtime failure.", default(LogFields), (LogLevel)2, verbose: false, error); Shutdown(); } } private void Log(string message, LogLevel level = (LogLevel)16) { //IL_000d: Unknown result type (might be due to invalid IL or missing references) DiagnosticLog.Write(_logger, Name, message, level); } public void Shutdown() { IsActive = false; _occupied = false; _processing.Reset(); IDisposable registration = _presenceRegistration; _presenceRegistration = null; ModuleCleanup.Run(_logger, Name, delegate { registration?.Dispose(); }, StopController); } } public sealed class AFKRaidWatchController : IDisposable { private readonly AFKRaidWatch _module; private readonly ManualLogSource _logger; private readonly PlayerServices _players; private PlayerActivityService.Lease? _lease; private AFKRaidWatchPatches? _patches; private readonly AFKRaidWatchDiagnostics _diagnostics; private readonly AFKRaidWatchSelectionNotices _selectionNotices; private readonly ObservationCounters _hooks = new ObservationCounters(); private long _candidates; private long _suppressed; private RaidStartObservation? _lastOutcome; private RaidScheduleObservation? _schedule; internal static AFKRaidWatchController? Active { get; private set; } internal bool DebugEnabled => _diagnostics.Enabled; public AFKRaidWatchController(AFKRaidWatch module, AFKRaidWatchSettings settings, ManualLogSource logger, PlayerServices players) { _module = module; _logger = logger; _players = players; _diagnostics = new AFKRaidWatchDiagnostics(logger, settings.DebugLogging); _selectionNotices = new AFKRaidWatchSelectionNotices(logger); try { _lease = players.Activity.Acquire(() => _diagnostics.Enabled); _patches = new AFKRaidWatchPatches(logger); Active = this; } catch { Dispose(); throw; } if (DebugEnabled && DiagnosticLog.DebugAvailable(logger, module.Name)) { DiagnosticLog.Write(logger, module.Name, AFKRaidWatchLogTopics.Raids, "Registered native raid hooks.", new(string, object)[1] { ("raid_hooks", _patches.RegisteredHooks) }, (LogLevel)32); } } internal List Filter(RandomEvent ev, List points) { //IL_00a0: Unknown result type (might be due to invalid IL or missing references) //IL_00a5: Unknown result type (might be due to invalid IL or missing references) //IL_0115: Unknown result type (might be due to invalid IL or missing references) //IL_0148: Unknown result type (might be due to invalid IL or missing references) if (_lease == null || !_players.Activity.Available) { _hooks.Hit("filter_not_ready_native_fallback"); return points; } IReadOnlyList players = _lease.Service.Snapshot(Time.unscaledTime); if (!_lease.Service.Reliable) { _hooks.Hit("filter_not_ready_native_fallback"); return points; } List list = new List(points.Count); foreach (Vector3 point in points) { string reason; bool flag = AFKRaidWatchRules.Suppress(point.x, point.z, ev.m_eventRange, players, out reason); _candidates++; if (flag) { _suppressed++; _selectionNotices.Excluded(); } else { list.Add(point); } if (!_diagnostics.Enabled) { continue; } try { _diagnostics.Sample(Time.unscaledTime, ev.m_name, point, flag, reason, () => RaidLocalObservation.Read(point.x, point.z, ev.m_eventRange, players)); } catch (Exception error) { _diagnostics.Warning(Time.unscaledTime, error); } } return list; } internal void ObserveSchedule(RandEventSystem system, float timer) { if (DebugEnabled) { float unscaledTime = Time.unscaledTime; if (_schedule == null || !(unscaledTime >= _schedule.ObservedAt) || !(unscaledTime - _schedule.ObservedAt < 1f)) { _schedule = new RaidScheduleObservation { ObservedAt = unscaledTime, Timer = timer, IntervalMinutes = system.m_eventIntervalMin, EventRate = Game.m_eventRate, Chance = system.m_eventChance }; } } } internal void NativeCandidates(int records, int points) { _hooks.Add("native_candidate_records", records); _hooks.Add("native_valid_points_before_afk", points); _hooks.Add("native_records_rejected_before_afk", Math.Max(0, records - points)); if (points == 0) { _hooks.Hit("empty_native_candidate_results"); } } internal void BeginSelection() { _selectionNotices.Begin(); } internal void EndSelection(bool failed) { _selectionNotices.End(failed); } internal void Hook(string name) { _hooks.Hit(name); } internal void ObserveOutcome(RaidStartObservation outcome) { if (DebugEnabled) { _lastOutcome = outcome; if (outcome.Started) { _hooks.Hit("event_starts_observed"); } _diagnostics.Outcome(outcome); } } internal void ObserveStartReturned(float now, string origin, string? before, string? after, bool changed, bool failed) { _diagnostics.StartReturned(now, origin, before, after, changed, failed); } internal void ObservationFailed(Exception error) { _hooks.Hit("diagnostic_probe_failures"); _diagnostics.Warning(Time.unscaledTime, error); } internal void Fail(Exception error) { _module.Fail(error); } public void Tick(float now) { if (!DebugEnabled) { _lastOutcome = null; _schedule = null; _diagnostics.SuspendReports(); } else if (_diagnostics.ReadyToPoll(now)) { _diagnostics.Report(now, () => new RaidWatchStatus { Connected = _players.Presence.ConnectedCount, Candidates = _candidates, Suppressed = _suppressed, Hooks = _hooks, Outcome = _lastOutcome, Schedule = _schedule }); } } public void Dispose() { _selectionNotices.Reset(); if (Active == this) { Active = null; } AFKRaidWatchPatches patches = _patches; PlayerActivityService.Lease lease = _lease; _patches = null; _lease = null; if (!ModuleCleanup.Run(_logger, _module.Name, delegate { patches?.Dispose(); }, delegate { lease?.Dispose(); })) { throw new InvalidOperationException("Controller cleanup did not complete; paused state cannot be confirmed."); } } } public sealed class AFKRaidWatchDiagnostics : FeatureDiagnostics { private readonly ManualLogSource _log; private readonly DebugLoggingPolicy _policy; private readonly SummaryCadence _summary = new SummaryCadence(); private float _lastWarning = float.NegativeInfinity; private readonly Dictionary<(string, float, float), string> _candidateStates = new Dictionary<(string, float, float), string>(); private long _unchanged; public bool Enabled => base.DiagnosticsEnabled; public AFKRaidWatchDiagnostics(ManualLogSource log, DebugLoggingPolicy policy) { _log = log; _policy = policy; ConfigureDiagnostics(() => policy.Enabled, log, "AFKRaidWatch"); } private void Write(LogTopic topic, string message, LogFields fields = default(LogFields), LogLevel level = (LogLevel)32, bool verbose = false) { //IL_000e: Unknown result type (might be due to invalid IL or missing references) DiagnosticLog.Write(_log, "AFKRaidWatch", topic, message, fields, level, verbose); } public void SuspendReports() { _candidateStates.Clear(); _summary.Reset(); } public bool ReadyToPoll(float now) { if (Enabled) { return _summary.PollReady(now); } return false; } public void Report(float now, Func snapshot) { if (!Enabled) { _candidateStates.Clear(); _summary.Reset(); } else { if (!_summary.CanPoll(now)) { return; } RaidWatchStatus raidWatchStatus = snapshot(); if (raidWatchStatus.Connected == 0 || raidWatchStatus.Candidates == 0L) { _summary.Reset(); return; } string key = $"{raidWatchStatus.Candidates}:{raidWatchStatus.Suppressed}:{raidWatchStatus.Outcome?.Outcome}:{raidWatchStatus.Outcome?.Current}:{raidWatchStatus.Outcome?.Requested}:{raidWatchStatus.Outcome?.Origin}"; if (!_summary.ShouldEmit(now, key)) { return; } if (!_summary.Changed) { Write(CoreLogTopics.Scope, "Relevant observations remain unchanged.", new(string, object)[2] { ("observation_age_s", (raidWatchStatus.Outcome == null) ? ((float?)null) : new float?(Math.Max(0f, now - raidWatchStatus.Outcome.ObservedAt))), ("omitted_messages", _budget.TakeOmitted()) }, (LogLevel)32); return; } Write(CoreLogTopics.Scope, "Evaluated automatic raid locations in the last minute.", new(string, object)[8] { ("lifetime_candidates_evaluated", raidWatchStatus.Candidates), ("lifetime_candidates_excluded", raidWatchStatus.Suppressed), ("native_event_outcome", raidWatchStatus.Outcome?.Outcome ?? "not_observed"), ("native_event_origin", raidWatchStatus.Outcome?.Origin ?? "unknown"), ("native_event_outcome_age_s", (raidWatchStatus.Outcome == null) ? ((float?)null) : new float?(Math.Max(0f, now - raidWatchStatus.Outcome.ObservedAt))), ("cause", "unknown"), ("unchanged_candidate_samples", TakeUnchanged()), ("omitted_messages", _budget.TakeOmitted()) }, (LogLevel)32); if (_budget.Reserve(now, "hook_activity", 1, countOmitted: false)) { Write(AFKRaidWatchLogTopics.Raids, "Observed native raid selection in the last minute.", new(string, object)[4] { ("lifetime_raid_hook_counts", raidWatchStatus.Hooks?.Format() ?? "not_observed"), ("native_schedule_gate", raidWatchStatus.Schedule?.Gate), ("native_schedule_age_s", (raidWatchStatus.Schedule == null) ? ((float?)null) : new float?(Math.Max(0f, now - raidWatchStatus.Schedule.ObservedAt))), ("chance_roll", "unobserved") }, (LogLevel)32); } } } private long TakeUnchanged() { long unchanged = _unchanged; _unchanged = 0L; return unchanged; } public void Sample(float now, string name, Vector3 point, bool suppressed, string reason, Func? population = null) { //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_00db: Unknown result type (might be due to invalid IL or missing references) //IL_00f7: Unknown result type (might be due to invalid IL or missing references) //IL_0113: Unknown result type (might be due to invalid IL or missing references) if (!base.DiagnosticsEnabled) { return; } (string, float, float) key = (name, point.x, point.z); if (_candidateStates.TryGetValue(key, out string value) && value == reason) { _unchanged++; } else if (_budget.Reserve(now, "raid_candidates", 6)) { if (_candidateStates.Count >= 256) { _candidateStates.Clear(); } _candidateStates[key] = reason; RaidLocalObservation raidLocalObservation = null; try { raidLocalObservation = population?.Invoke(); } catch (Exception error) { Warning(now, error); } Write(AFKRaidWatchLogTopics.Raids, suppressed ? "Automatic raid location excluded: all nearby players inferred idle" : "Native raid location retained", new(string, object)[8] { ("event", name), ("x", point.x), ("y", point.y), ("z", point.z), ("suppressed", suppressed), ("reason", reason), ("raid_started", "not_observed"), ("native_candidate_eligible", true) }, (LogLevel)32); if (base.VerboseEnabled) { Write(AFKRaidWatchLogTopics.Raids, "Nearby player evidence for raid location " + name + ".", new(string, object)[8] { ("native_event_range_m", raidLocalObservation?.Range), ("unknown_actors", raidLocalObservation?.Unknown), ("dungeon_actors", raidLocalObservation?.Dungeon), ("outside_actors", raidLocalObservation?.Outside), ("nearby_idle", raidLocalObservation?.NearbyIdle), ("nearby_active", raidLocalObservation?.NearbyActive), ("nearby_bed", raidLocalObservation?.NearbyBed), ("nearby_dead_or_loading", raidLocalObservation?.NearbyDead) }, (LogLevel)32, verbose: true); } } } public void Outcome(RaidStartObservation outcome) { if (base.DiagnosticsEnabled && _budget.Reserve(outcome.ObservedAt, "raid_outcomes", 6)) { Write(AFKRaidWatchLogTopics.Raids, "Observed the native event setter outcome.", new(string, object)[8] { ("outcome", outcome.Outcome), ("requested_event", outcome.Requested), ("current_event", outcome.Current), ("state_changed", outcome.StateChanged), ("native_exception", outcome.Failed), ("origin", outcome.Origin), ("cause", "unknown"), ("enemy_spawns", "unobservable_here") }, (LogLevel)32); if (base.VerboseEnabled) { Write(AFKRaidWatchLogTopics.Raids, "Event setter evidence for outcome " + outcome.Outcome + ".", new(string, object)[1] { ("clients_acknowledged", "unobservable") }, (LogLevel)32, verbose: true); } } } public void StartReturned(float now, string origin, string? before, string? after, bool changed, bool failed) { if (base.DiagnosticsEnabled && _budget.Reserve(now, "raid_outcomes", 6)) { Write(AFKRaidWatchLogTopics.Raids, "The native random-event start request returned.", new(string, object)[6] { ("outcome", failed ? "native_exception" : (changed ? "server_event_state_changed" : "no_event_state_change")), ("origin", origin), ("before_event", before), ("after_event", after), ("cause", "unknown"), ("enemy_spawns", "unobservable_here") }, (LogLevel)32); } } public void Warning(float now, Exception error) { if (!(now >= _lastWarning) || !(now - _lastWarning < 300f)) { _lastWarning = now; Write(CoreLogTopics.Lifecycle, "Diagnostic observation unavailable; native behavior unchanged: " + error.Message, default(LogFields), (LogLevel)4); } } } public static class AFKRaidWatchLogTopics { public static readonly LogTopic Raids = new LogTopic("raids"); } public sealed class AFKRaidWatchPatches : IDisposable { private sealed class SetObservation { public RandomEvent? Before; public RaidStartObservation Evidence = new RaidStartObservation(); } private readonly Harmony _harmony = new Harmony("heimkit.afk_raid_watch"); private readonly Harmony _observers = new Harmony("heimkit.afk_raid_watch.diagnostics"); private readonly List _registered = new List(); [ThreadStatic] private static int _automaticDepth; public string RegisteredHooks => string.Join(",", _registered); public AFKRaidWatchPatches(ManualLogSource? logger = null) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Expected O, but got Unknown //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Expected O, but got Unknown //IL_006f: Unknown result type (might be due to invalid IL or missing references) //IL_0086: Unknown result type (might be due to invalid IL or missing references) //IL_0091: Expected O, but got Unknown //IL_0091: Expected O, but got Unknown //IL_00bf: Unknown result type (might be due to invalid IL or missing references) //IL_00cc: Expected O, but got Unknown try { _harmony.Patch((MethodBase)AccessTools.Method(typeof(RandEventSystem), "UpdateRandomEvent", new Type[1] { typeof(float) }, (Type[])null), new HarmonyMethod(typeof(AFKRaidWatchPatches), "Enter", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(typeof(AFKRaidWatchPatches), "Exit", (Type[])null), (HarmonyMethod)null); _harmony.Patch((MethodBase)AccessTools.Method(typeof(RandEventSystem), "GetValidEventPoints", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(AFKRaidWatchPatches), "Filter", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); _registered.Add("RandEventSystem.UpdateRandomEvent:control_scope"); _registered.Add("RandEventSystem.GetValidEventPoints:control_filter"); } catch { _harmony.UnpatchSelf(); throw; } InstallObserver(logger, "UpdateRandomEvent", "UpdateObserved"); InstallObserver(logger, "GetValidEventPoints", "CandidatesEntered", null, "CandidatesFinished"); InstallObserver(logger, "GetPossibleRandomEvents", null, "PossibleReturned"); InstallObserver(logger, "StartRandomEvent", "StartEntered", null, "StartFinished"); string[] array = new string[3] { "HaveGlobalKeys", "InValidBiome", "CheckBase" }; foreach (string method in array) { InstallObserver(logger, method, null, "EligibilityReturned"); } InstallObserver(logger, "SetRandomEvent", "SetEntered", null, "SetFinished"); } private void InstallObserver(ManualLogSource? logger, string method, string? prefix = null, string? postfix = null, string? finalizer = null) { //IL_0040: 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_0073: Unknown result type (might be due to invalid IL or missing references) MethodInfo methodInfo = null; try { methodInfo = AccessTools.Method(typeof(RandEventSystem), method, (Type[])null, (Type[])null); if (methodInfo == null) { throw new MissingMethodException("RandEventSystem", method); } _observers.Patch((MethodBase)methodInfo, (prefix == null) ? ((HarmonyMethod)null) : new HarmonyMethod(typeof(AFKRaidWatchPatches), prefix, (Type[])null), (postfix == null) ? ((HarmonyMethod)null) : new HarmonyMethod(typeof(AFKRaidWatchPatches), postfix, (Type[])null), (HarmonyMethod)null, (finalizer == null) ? ((HarmonyMethod)null) : new HarmonyMethod(typeof(AFKRaidWatchPatches), finalizer, (Type[])null), (HarmonyMethod)null); _registered.Add("RandEventSystem." + method + ":observation"); } catch (Exception) { if (methodInfo != null) { _observers.Unpatch((MethodBase)methodInfo, (HarmonyPatchType)0, _observers.Id); } if (logger != null) { DiagnosticLog.Write(logger, "AFKRaidWatch", "Diagnostic hook unavailable; gameplay hooks retained", (LogLevel)4); } } } private static void Enter(out int __state) { __state = _automaticDepth; _automaticDepth++; Note("automatic_update_invocations"); if (__state == 0) { AFKRaidWatchController.Active?.BeginSelection(); } } private static Exception? Exit(int __state, Exception? __exception) { try { if (__exception != null) { Note("native_automatic_update_exceptions"); } if (__state == 0) { AFKRaidWatchController.Active?.EndSelection(__exception != null); } } catch (Exception error) { AFKRaidWatchController.Active?.ObservationFailed(error); } finally { _automaticDepth = __state; } return __exception; } private static void Filter(RandomEvent ev, List characters, ref List __result) { Note("get_valid_event_points_results"); try { AFKRaidWatchController.Active?.NativeCandidates(characters.Count, __result.Count); } catch (Exception error) { AFKRaidWatchController.Active?.ObservationFailed(error); } if (_automaticDepth == 0) { Note("outside_automatic_scope_native_retained"); return; } if (!ev.m_random) { Note("non_random_native_retained"); return; } if (ev.m_standaloneInterval > 0f) { Note("standalone_native_retained"); return; } AFKRaidWatchController active = AFKRaidWatchController.Active; try { if (active != null) { __result = active.Filter(ev, __result); } } catch (Exception error2) { active?.Fail(error2); } } private static void Note(string key) { AFKRaidWatchController.Active?.Hook(key); } private static void UpdateObserved(RandEventSystem __instance, float ___m_eventTimer) { try { AFKRaidWatchController.Active?.ObserveSchedule(__instance, ___m_eventTimer); } catch (Exception error) { AFKRaidWatchController.Active?.ObservationFailed(error); } } private static void CandidatesEntered() { Note("get_valid_event_points_invocations"); } private static Exception? CandidatesFinished(Exception? __exception) { if (__exception != null) { Note("native_candidate_exceptions"); } return __exception; } private static void PossibleReturned(List> __result) { Note("possible_events_results"); if (__result == null) { Note("possible_events_result_unknown"); } else if (__result.Count == 0) { Note("empty_possible_events_after_filter"); } } private static void StartEntered(RandEventSystem __instance, out SetObservation? __state) { __state = null; Note((_automaticDepth > 0) ? "automatic_start_requests" : "explicit_or_other_start_requests"); AFKRaidWatchController? active = AFKRaidWatchController.Active; if (active == null || !active.DebugEnabled) { return; } try { __state = new SetObservation { Before = __instance.GetCurrentRandomEvent(), Evidence = new RaidStartObservation { ObservedAt = Time.unscaledTime, Origin = ((_automaticDepth > 0) ? "automatic_random" : "explicit_or_other") } }; } catch (Exception error) { AFKRaidWatchController.Active?.ObservationFailed(error); } } private static Exception? StartFinished(RandEventSystem __instance, SetObservation? __state, Exception? __exception) { if (__exception != null) { Note("native_start_request_exceptions"); } if (__state != null) { try { RandomEvent currentRandomEvent = __instance.GetCurrentRandomEvent(); bool flag = __state.Before != currentRandomEvent; Note(flag ? "start_returned_changed_state" : "start_returned_unchanged_state"); AFKRaidWatchController.Active?.ObserveStartReturned(Time.unscaledTime, __state.Evidence.Origin, __state.Before?.m_name, currentRandomEvent?.m_name, flag, __exception != null); } catch (Exception error) { AFKRaidWatchController.Active?.ObservationFailed(error); } } return __exception; } private static void EligibilityReturned(MethodBase __originalMethod, bool __result) { if (_automaticDepth != 0) { Note((!(__originalMethod.Name == "HaveGlobalKeys")) ? ((!(__originalMethod.Name == "InValidBiome")) ? (__result ? "native_base_passed" : "native_base_rejected") : (__result ? "native_biome_passed" : "native_biome_rejected")) : (__result ? "native_keys_passed" : "native_keys_rejected")); } } private static void SetEntered(RandEventSystem __instance, RandomEvent? ev, out SetObservation? __state) { __state = null; Note("set_random_event_invocations"); AFKRaidWatchController active = AFKRaidWatchController.Active; if (active == null || !active.DebugEnabled) { return; } try { __state = new SetObservation { Before = __instance.GetCurrentRandomEvent(), Evidence = new RaidStartObservation { ObservedAt = Time.unscaledTime, Requested = (ev?.m_name ?? "none"), Origin = ((_automaticDepth == 0) ? "explicit_or_other" : ((ev != null && ev.m_standaloneInterval > 0f) ? "automatic_standalone" : "automatic_random")) } }; } catch (Exception error) { active.ObservationFailed(error); } } private static Exception? SetFinished(RandEventSystem __instance, SetObservation? __state, Exception? __exception) { if (__exception != null) { Note("native_event_setter_exceptions"); } if (__state != null) { try { RandomEvent currentRandomEvent = __instance.GetCurrentRandomEvent(); __state.Evidence.Current = currentRandomEvent?.m_name; __state.Evidence.StateChanged = __state.Before != currentRandomEvent; __state.Evidence.Failed = __exception != null; AFKRaidWatchController.Active?.ObserveOutcome(__state.Evidence); } catch (Exception error) { AFKRaidWatchController.Active?.ObservationFailed(error); } } return __exception; } public void Dispose() { try { _observers.UnpatchSelf(); } finally { try { _harmony.UnpatchSelf(); } finally { _registered.Clear(); } } } } public static class AFKRaidWatchRules { public static bool Suppress(float x, float z, float radius, IEnumerable players) { string reason; return Suppress(x, z, radius, players, out reason); } public static bool Suppress(float x, float z, float radius, IEnumerable players, out string reason) { reason = "invalid_event_geometry"; if (!PlayerActivityTracker.Finite(x) || !PlayerActivityTracker.Finite(z) || !PlayerActivityTracker.Finite(radius) || radius <= 0f) { return false; } bool flag = false; foreach (PlayerActivityView player in players) { if (!player.Known || !PlayerActivityTracker.Finite(player.X) || !PlayerActivityTracker.Finite(player.Y) || !PlayerActivityTracker.Finite(player.Z)) { reason = "unknown_actor_data"; return false; } if (player.Y > 3000f) { continue; } double num = player.X - x; double num2 = player.Z - z; if (!(num * num + num2 * num2 >= (double)radius * (double)radius)) { flag = true; if (!player.Alive || player.InBed || !player.Idle) { reason = ((!player.Alive) ? "nearby_dead_or_loading" : (player.InBed ? "nearby_bed_occupant" : "nearby_active_player")); return false; } } } reason = (flag ? "all_nearby_players_inferred_idle" : "no_nearby_actor_evidence"); return flag; } } public sealed class AFKRaidWatchSelectionNotices { private readonly ManualLogSource _logger; private bool _collecting; private long _excluded; public AFKRaidWatchSelectionNotices(ManualLogSource logger) { _logger = logger; } public void Begin() { _collecting = true; _excluded = 0L; } public void Excluded() { if (_collecting) { _excluded++; } } public void End(bool failed) { long excluded = _excluded; bool collecting = _collecting; Reset(); if (!(!collecting || failed) && excluded != 0L) { DiagnosticLog.Write(_logger, "AFKRaidWatch", string.Format("Excluded {0} automatic raid {1} at AFK-only locations.", excluded, (excluded == 1) ? "candidate" : "candidates"), (LogLevel)16); } } public void Reset() { _collecting = false; _excluded = 0L; } } public sealed class AFKRaidWatchSettings { public ConfigEntry Enabled { get; } public ConfigEntry DebugMode { get; } public DebugLoggingPolicy DebugLogging { get; } public AFKRaidWatchSettings(ConfigFile config, ManualLogSource logger) { Enabled = config.Bind("AFKRaidWatch", "Enabled", true, "Protect inferred-idle-only locations from new normal automatic random raids. Restart after edits."); DebugMode = config.Bind("AFKRaidWatch", "DebugMode", false, "Enable raid diagnostics; hidden suppression takes precedence. Restart after edits."); DebugLogging = DebugLoggingResolver.Resolve(config, "AFKRaidWatch", DiagnosticsSettings.Bind(config), logger, DebugMode); } } } namespace HeimKit.Features.AFKRaidWatch.Models { public sealed class RaidLocalObservation { public int Unknown; public int Dungeon; public int Outside; public int NearbyIdle; public int NearbyActive; public int NearbyBed; public int NearbyDead; public float Range { get; set; } public static RaidLocalObservation Read(float x, float z, float range, IEnumerable players) { RaidLocalObservation raidLocalObservation = new RaidLocalObservation { Range = range }; foreach (PlayerActivityView player in players) { if (!player.Known || !PlayerActivityTracker.Finite(player.X) || !PlayerActivityTracker.Finite(player.Y) || !PlayerActivityTracker.Finite(player.Z)) { raidLocalObservation.Unknown++; continue; } if (player.Y > 3000f) { raidLocalObservation.Dungeon++; continue; } double num = player.X - x; double num2 = player.Z - z; if (num * num + num2 * num2 >= (double)range * (double)range) { raidLocalObservation.Outside++; } else if (!player.Alive) { raidLocalObservation.NearbyDead++; } else if (player.InBed) { raidLocalObservation.NearbyBed++; } else if (player.Idle) { raidLocalObservation.NearbyIdle++; } else { raidLocalObservation.NearbyActive++; } } return raidLocalObservation; } } public sealed class RaidScheduleObservation { public float ObservedAt; public float Timer; public float IntervalMinutes; public float EventRate; public float Chance; public string Gate { get { if (!(EventRate <= 0f)) { if (!(Timer <= IntervalMinutes * 60f * EventRate)) { return "native_interval_threshold_reached"; } return "awaiting_native_interval"; } return "native_automatic_raids_disabled"; } } } public sealed class RaidStartObservation { public float ObservedAt { get; set; } public string Requested { get; set; } = "none"; public string? Current { get; set; } public string Origin { get; set; } = "explicit_or_other"; public bool StateChanged { get; set; } public bool Failed { get; set; } public bool Started { get { if (!Failed && Requested != "none" && Current == Requested) { return StateChanged; } return false; } } public string Outcome { get { if (!Failed) { if (!Started) { if (Current != null || !StateChanged) { return "no_confirmed_event_start"; } return "random_event_cleared"; } return "random_event_started_server_state"; } return "native_exception_partial_state_unknown"; } } } public sealed class RaidWatchStatus { public int? Connected; public long Candidates; public long Suppressed; public ObservationCounters? Hooks; public RaidStartObservation? Outcome; public RaidScheduleObservation? Schedule; } } namespace HeimKit.Features.AFKNightWatch { public sealed class AFKNightWatch : IServerModule { private readonly AFKNightWatchSettings _settings; private readonly ManualLogSource _logger; private readonly GameVersionCompatibility _compatibility; private readonly PlayerServices _players; private AFKNightWatchController? _controller; private IDisposable? _presenceRegistration; private bool _occupied; private readonly PlayerProcessingNotices _processing; public string Name => "AFKNightWatch"; public bool IsActive { get; private set; } public AFKNightWatch(ConfigFile config, ManualLogSource logger, PlayerServices players) { _logger = logger; _compatibility = GameVersionCompatibility.Resolve(config, logger); _settings = new AFKNightWatchSettings(config, logger); _players = players; _processing = new PlayerProcessingNotices(logger, Name, () => _settings.DebugLogging.Enabled); } public void Initialize(string gameVersion) { Shutdown(); Log(_settings.Enabled.Value ? "Enabled." : "Disabled.", (LogLevel)16); _settings.DebugLogging.ReportStartup(_logger, Name, _settings.Enabled.Value); if (!_settings.Enabled.Value) { return; } if (!_settings.MajoritySleepEnabled.Value && !_settings.ExcludeAFKFromSleep.Value) { Log("No behaviors are selected; feature will remain inactive.", (LogLevel)4); return; } if (!_compatibility.Supports(gameVersion)) { Log("DISABLED: unsupported game version " + gameVersion + "; required version " + _compatibility.RequiredVersion, (LogLevel)4); return; } IsActive = true; if (_settings.DebugLogging.Enabled) { Log("Waiting for joined players and dedicated-server world", (LogLevel)32); } _presenceRegistration = _players.Events.Subscribe(PresenceChanged, Fail, () => _processing.IsEmptyPaused, () => _processing.IsRunning, () => _processing.IsServerReady); } public void Tick(float now) { if (!IsActive) { return; } if (!_settings.Enabled.Value) { Shutdown(); return; } try { if (PlayerServices.Ready) { _processing.ServerReady(); } if (!_occupied) { StopController(); } else if (!PlayerServices.Ready) { StopController(); _processing.Paused("world services unavailable"); } else { StartController(); _controller?.Tick(now); } } catch (Exception error) { Fail(error); } } private void PresenceChanged(bool? occupied) { _occupied = occupied == true; if (IsActive && !_occupied) { StopController(); if (occupied.HasValue) { _processing.EmptyPaused(); } else { _processing.Unavailable("player presence unavailable"); } } } private void StartController() { if (_settings.Enabled.Value && _controller == null) { _controller = new AFKNightWatchController(this, _settings, _logger, _players); _processing.Ready(); } } private void StopController() { AFKNightWatchController controller = _controller; _controller = null; if (controller != null) { ModuleScheduler.Current.Forget(controller); } try { controller?.Dispose(); } finally { WorldObjectProvider.Current?.ReleaseOwner(Name); } } internal void Fail(Exception error) { if (IsActive) { DiagnosticLog.Write(_logger, Name, CoreLogTopics.Lifecycle, "Disabled after a runtime failure.", default(LogFields), (LogLevel)2, verbose: false, error); Shutdown(); } } private void Log(string message, LogLevel level = (LogLevel)16) { //IL_000d: Unknown result type (might be due to invalid IL or missing references) DiagnosticLog.Write(_logger, Name, message, level); } public void Shutdown() { IsActive = false; _occupied = false; _processing.Reset(); IDisposable registration = _presenceRegistration; _presenceRegistration = null; ModuleCleanup.Run(_logger, Name, delegate { registration?.Dispose(); }, StopController); } } public sealed class AFKNightWatchController : IDisposable { private readonly AFKNightWatch _module; private readonly ManualLogSource _logger; private PlayerActivityService.Lease? _lease; private readonly AFKNightWatchDiagnostics _diagnostics; private readonly AFKNightWatchSleepNotices _sleepNotices; private long _evaluations; private long _sleepOutcomes; private readonly PlayerServices _players; private IDisposable? _sleepVote; private SleepDecision? _lastVote; private float? _lastVoteAt; private NativeSleepObservation? _nativeSleep; private NativeSleepObservation? _lastSleepOutcome; private readonly AFKNightWatchSettings _settings; private readonly ObservationCounters _hooks = new ObservationCounters(); private float _reportNow; private readonly Func _snapshot; internal bool DebugEnabled => _diagnostics.Enabled; public AFKNightWatchController(AFKNightWatch module, AFKNightWatchSettings settings, ManualLogSource logger, PlayerServices players) { AFKNightWatchController aFKNightWatchController = this; _snapshot = SnapshotStatus; _module = module; _logger = logger; _players = players; _settings = settings; _diagnostics = new AFKNightWatchDiagnostics(logger, settings.DebugLogging); _sleepNotices = new AFKNightWatchSleepNotices(logger, delegate(SleepDecision vote) { aFKNightWatchController._diagnostics.SleepStarted(vote, settings); }); string[] array = new string[14] { "vote_hook_calls", "update_sleeping_invocations", "empty_vote_rosters", "no_living_sleeper_votes", "unknown_actor_native_fallbacks", "vote_not_ready_fallback", "vote_returned_true", "vote_returned_false", "native_vote_exceptions", "native_sleep_update_exceptions", "skip_to_morning_invocations", "sleep_probe_failures", "time_skip_activations_observed", "time_skip_endings_observed" }; foreach (string key in array) { _hooks.Add(key, 0L); } try { if (settings.RequiresActivity) { _lease = players.Activity.Acquire(() => aFKNightWatchController._diagnostics.Enabled); } if (settings.MajoritySleepEnabled.Value || settings.ExcludeAFKFromSleep.Value) { Func<(int, bool)> options = (settings.MajoritySleepEnabled.Value ? ((Func<(int, bool)>)(() => (settings.RequiredSleepingPercent.Value, settings.RequireMoreThanPercent.Value))) : null); _sleepVote = AFKNightWatchSleepVoteCoordinator.Register(options, settings.ExcludeAFKFromSleep.Value ? _lease.Service : null, ObserveVote, module.Fail, () => aFKNightWatchController._diagnostics.Enabled, ObserveSleepHook, logger, module.Name, players.Presence, _sleepNotices.Observe, () => settings.SleepDelaySeconds.Value); } } catch { Dispose(); throw; } if (_diagnostics.Enabled && DiagnosticLog.DebugAvailable(logger, module.Name)) { DiagnosticLog.Write(logger, module.Name, AFKNightWatchLogTopics.Sleep, "Registered native processing hooks.", new(string, object)[3] { ("sleep_hooks", (_sleepVote == null) ? "none" : AFKNightWatchSleepVoteCoordinator.RegisteredHooks), ("registered", true), ("log_schema", 1) }, (LogLevel)32); } } private void ObserveVote(SleepDecision vote) { _lastVote = vote; _lastVoteAt = Time.unscaledTime; _evaluations++; } private void ObserveSleepHook(string hook, NativeSleepObservation? evidence) { _hooks.Hit(hook); if (evidence == null || !_diagnostics.Enabled) { return; } _nativeSleep = evidence; if (evidence.Outcome == "time_skip_became_active" || evidence.Outcome == "time_skip_ended" || evidence.Outcome == "sleep_session_ended_server_state" || evidence.Failed) { _lastSleepOutcome = evidence; if (!evidence.Failed) { _sleepOutcomes++; } _hooks.Hit(evidence.Failed ? "native_failures_observed" : ((evidence.Outcome == "time_skip_became_active") ? "time_skip_activations_observed" : "time_skip_endings_observed")); } _diagnostics.Native(evidence); } public void Tick(float now) { if (!_diagnostics.Enabled) { _nativeSleep = null; _lastSleepOutcome = null; _diagnostics.SuspendReports(); } else if (_diagnostics.ReadyToPoll(now)) { _reportNow = now; _diagnostics.Report(now, _snapshot); } } private NightWatchStatus SnapshotStatus() { return new NightWatchStatus { Vote = _lastVote, VoteAge = ((!_lastVoteAt.HasValue) ? ((float?)null) : new float?(Math.Max(0f, _reportNow - _lastVoteAt.Value))), Votes = _evaluations, Outcomes = _sleepOutcomes, Players = _players.Presence.ConnectedCount, Hooks = _hooks, Sleep = _nativeSleep, SleepOutcome = _lastSleepOutcome, MajorityEnabled = _settings.MajoritySleepEnabled.Value, ExclusionEnabled = _settings.ExcludeAFKFromSleep.Value }; } public void Dispose() { _sleepNotices.Reset(); IDisposable sleepVote = _sleepVote; PlayerActivityService.Lease lease = _lease; _sleepVote = null; _lease = null; if (!ModuleCleanup.Run(_logger, _module.Name, delegate { sleepVote?.Dispose(); }, delegate { lease?.Dispose(); })) { throw new InvalidOperationException("Controller cleanup did not complete; paused state cannot be confirmed."); } } } public sealed class AFKNightWatchDiagnostics : FeatureDiagnostics { private readonly ManualLogSource _log; private readonly DebugLoggingPolicy _policy; private readonly SummaryCadence _summary = new SummaryCadence(); private float _lastWarning = float.NegativeInfinity; private string? _lastNativeKey; private long _unchangedNative; public bool Enabled => base.DiagnosticsEnabled; public AFKNightWatchDiagnostics(ManualLogSource log, DebugLoggingPolicy policy) { _log = log; _policy = policy; ConfigureDiagnostics(() => policy.Enabled, log, "AFKNightWatch"); } private void Write(LogTopic topic, string message, LogFields fields = default(LogFields), LogLevel level = (LogLevel)32, bool verbose = false) { //IL_000e: Unknown result type (might be due to invalid IL or missing references) DiagnosticLog.Write(_log, "AFKNightWatch", topic, message, fields, level, verbose); } public void SuspendReports() { _lastNativeKey = null; _summary.Reset(); } public bool ReadyToPoll(float now) { if (Enabled) { return _summary.PollReady(now); } return false; } public void Report(float now, Func snapshot) { if (!Enabled) { _lastNativeKey = null; _summary.Reset(); } else { if (!_summary.CanPoll(now)) { return; } NightWatchStatus nightWatchStatus = snapshot(); if (nightWatchStatus.Players == 0 || nightWatchStatus.Vote == null) { _summary.Reset(); return; } SleepDecision vote = nightWatchStatus.Vote; NativeSleepObservation sleepOutcome = nightWatchStatus.SleepOutcome; string key = $"{nightWatchStatus.Players}:{vote.Participants}:{vote.Sleepers}:{vote.Required}:{vote.ExcludedIdle}:{vote.Met}:{vote.Unknown}:{sleepOutcome?.Outcome}:{nightWatchStatus.Outcomes}"; if (!_summary.ShouldEmit(now, key)) { return; } if (!_summary.Changed) { Write(CoreLogTopics.Scope, "Relevant observations remain unchanged.", new(string, object)[2] { ("observation_age_s", nightWatchStatus.VoteAge), ("omitted_messages", _budget.TakeOmitted()) }, (LogLevel)32); return; } Write(CoreLogTopics.Scope, vote.Unknown ? "Unknown actor data; native fallback depends on a living sleeper" : (vote.Met ? "Sleep quorum met; native time checks still apply" : "Sleep quorum not met"), new(string, object)[8] { ("majority_enabled", nightWatchStatus.MajorityEnabled), ("afk_sleep_exclusion_enabled", nightWatchStatus.ExclusionEnabled), ("participants_last_vote", vote.Participants), ("sleepers_last_vote", vote.Sleepers), ("required_last_vote", vote.Required), ("excluded_idle_last_vote", vote.ExcludedIdle), ("quorum_met_last_vote", vote.Met), ("delay_remaining_s", vote.DelayRemaining) }, (LogLevel)32); if (base.VerboseEnabled) { Write(CoreLogTopics.Scope, "Sleep vote evidence for the last minute.", new(string, object)[9] { ("allowed_after_delay", vote.AllowedAfterDelay), ("native_vote_fallback", vote.Unknown && vote.Sleepers > 0), ("lifetime_votes_observed", nightWatchStatus.Votes), ("vote_age_s", nightWatchStatus.VoteAge), ("time_skip", sleepOutcome?.Outcome ?? nightWatchStatus.Sleep?.Outcome ?? "not_observed"), ("last_outcome_age_s", (sleepOutcome == null) ? ((float?)null) : new float?(Math.Max(0f, now - sleepOutcome.ObservedAt))), ("native_probe_age_s", (nightWatchStatus.Sleep == null) ? ((float?)null) : new float?(Math.Max(0f, now - nightWatchStatus.Sleep.ObservedAt))), ("unchanged_native_samples", TakeUnchangedNative()), ("omitted_messages", _budget.TakeOmitted()) }, (LogLevel)32, verbose: true); } if (_budget.Reserve(now, "hook_activity", 1, countOmitted: false)) { Write(AFKNightWatchLogTopics.Sleep, "Observed sleep-hook activity in the last minute.", new(string, object)[1] { ("lifetime_sleep_hook_counts", nightWatchStatus.Hooks?.Format() ?? "not_observed") }, (LogLevel)32); } } } public void SleepStarted(SleepDecision vote, AFKNightWatchSettings settings) { if (Enabled) { Write(AFKNightWatchLogTopics.Sleep, "Configured sleep rules permitted the observed sleep start.", new(string, object)[8] { ("majority_enabled", settings.MajoritySleepEnabled.Value), ("required_sleeping_percent", settings.RequiredSleepingPercent.Value), ("require_more_than_percent", settings.RequireMoreThanPercent.Value), ("exclude_afk_from_sleep", settings.ExcludeAFKFromSleep.Value), ("sleep_delay_s", settings.SleepDelaySeconds.Value), ("delay_remaining_s", vote.DelayRemaining), ("joined_players", vote.Participants + vote.ExcludedIdle), ("participants", vote.Participants) }, (LogLevel)32); if (base.VerboseEnabled) { Write(AFKNightWatchLogTopics.Sleep, "Sleep start evidence for the observed vote.", new(string, object)[4] { ("sleepers", vote.Sleepers), ("required_sleepers", vote.Required), ("excluded_afk", vote.ExcludedIdle), ("quorum_met", vote.Met) }, (LogLevel)32, verbose: true); } } } public void Warning(float now, Exception error) { if (!(now >= _lastWarning) || !(now - _lastWarning < 300f)) { _lastWarning = now; Write(CoreLogTopics.Lifecycle, "Diagnostic observation unavailable; native behavior unchanged: " + error.Message, default(LogFields), (LogLevel)4); } } private long TakeUnchangedNative() { long unchangedNative = _unchangedNative; _unchangedNative = 0L; return unchangedNative; } public void Native(NativeSleepObservation evidence) { if (!base.DiagnosticsEnabled) { return; } string text = evidence.Gate + ":" + evidence.Outcome; if (_lastNativeKey == text) { _unchangedNative++; } else if (_budget.Reserve(evidence.ObservedAt, "native_sleep", 6)) { _lastNativeKey = text; Write(AFKNightWatchLogTopics.Sleep, "Observed the native sleep update outcome.", new(string, object)[8] { ("gate", evidence.Gate), ("outcome", evidence.Outcome), ("server", evidence.Server), ("sleeping_before", evidence.Sleeping), ("sleeping_after", evidence.SleepingAfter), ("server_game_time_before_s", evidence.GameTimeBefore), ("server_game_time_after_s", evidence.GameTimeAfter), ("skipping_before", evidence.SkippingBefore) }, (LogLevel)32); if (base.VerboseEnabled) { Write(AFKNightWatchLogTopics.Sleep, "Native sleep update evidence for outcome " + evidence.Outcome + ".", new(string, object)[7] { ("skipping_after", evidence.SkippingAfter), ("afternoon", evidence.Afternoon), ("night", evidence.Night), ("cooldown_remaining_s", evidence.CooldownRemaining), ("native_exception", evidence.Failed), ("cause", "unknown"), ("clients_acknowledged", "unobservable") }, (LogLevel)32, verbose: true); } } } } public static class AFKNightWatchLogTopics { public static readonly LogTopic Sleep = new LogTopic("sleep"); } public sealed class AFKNightWatchSettings { public bool RequiresActivity { get { if (Enabled.Value) { return ExcludeAFKFromSleep.Value; } return false; } } public ConfigEntry Enabled { get; } public ConfigEntry MajoritySleepEnabled { get; } public ConfigEntry ExcludeAFKFromSleep { get; } public ConfigEntry RequiredSleepingPercent { get; } public ConfigEntry RequireMoreThanPercent { get; } public ConfigEntry SleepDelaySeconds { get; } public ConfigEntry DebugMode { get; } public ConfigEntry GlobalDebugMode { get; } public DebugLoggingPolicy DebugLogging { get; } public AFKNightWatchSettings(ConfigFile config, ManualLogSource logger) { //IL_007a: Unknown result type (might be due to invalid IL or missing references) //IL_0084: Expected O, but got Unknown //IL_00c8: Unknown result type (might be due to invalid IL or missing references) //IL_00d2: Expected O, but got Unknown Enabled = config.Bind("AFKNightWatch", "Enabled", true, "Enable majority sleep and AFK sleep exclusion. Restart after edits."); MajoritySleepEnabled = config.Bind("AFKNightWatch", "MajoritySleepEnabled", true, "Use the configured sleep quorum; otherwise require all non-excluded players. Restart after edits."); ExcludeAFKFromSleep = config.Bind("AFKNightWatch", "ExcludeAFKFromSleep", true, "Exclude inferred-idle players from the sleep vote. Restart after edits."); RequiredSleepingPercent = config.Bind("AFKNightWatch", "RequiredSleepingPercent", 50, new ConfigDescription("Sleeping threshold percentage; 100 requires all participants. Restart after edits.", (AcceptableValueBase)(object)new AcceptableValueRange(1, 100), Array.Empty())); RequireMoreThanPercent = config.Bind("AFKNightWatch", "RequireMoreThanPercent", true, "Strictly exceed the threshold below 100 percent. Restart after edits."); SleepDelaySeconds = config.Bind("AFKNightWatch", "SleepDelaySeconds", 30, new ConfigDescription("Wait this many real seconds after the sleep threshold is met while some players are not in bed. Start immediately when everyone is in bed; reset the wait if the threshold is lost. Restart after edits.", (AcceptableValueBase)(object)new AcceptableValueRange(0, 300), Array.Empty())); GlobalDebugMode = DiagnosticsSettings.Bind(config); DebugMode = config.Bind("AFKNightWatch", "DebugMode", false, "Enable diagnostics for this feature even when global DebugMode is off. The hidden suppression override still takes precedence. Restart after edits."); DebugLogging = DebugLoggingResolver.Resolve(config, "AFKNightWatch", GlobalDebugMode, logger, DebugMode); } } public sealed class AFKNightWatchSleepDelay { private float? _metAt; private float? _lastAt; public float Remaining { get; private set; } public bool Allow(float now, bool met, bool everyoneInBed, float delaySeconds) { if (!met || float.IsNaN(now) || float.IsInfinity(now)) { Reset(); return false; } if (everyoneInBed) { Reset(); return true; } if (_lastAt.HasValue && now < _lastAt.Value) { Reset(); } _lastAt = now; float valueOrDefault = _metAt.GetValueOrDefault(); if (!_metAt.HasValue) { valueOrDefault = now; _metAt = valueOrDefault; } Remaining = Math.Max(0f, delaySeconds - (now - _metAt.Value)); return Remaining <= 0f; } public void Reset() { _metAt = null; _lastAt = null; Remaining = 0f; } } public sealed class AFKNightWatchSleepNotices { private readonly ManualLogSource _logger; private readonly Action? _evidence; private bool _known; private bool _skipping; public AFKNightWatchSleepNotices(ManualLogSource logger, Action? evidence = null) { _logger = logger; _evidence = evidence; } public void Observe(bool sleeping, bool? skipping, SleepDecision? vote = null) { if (!skipping.HasValue) { Reset(); return; } bool flag = sleeping && skipping.Value; if (!_known) { _known = true; _skipping = flag; } else if (flag != _skipping) { _skipping = flag; if (flag && vote != null && vote.AllowedAfterDelay && !vote.Unknown && vote.Sleepers < vote.Participants + vote.ExcludedIdle) { DiagnosticLog.Write(_logger, "AFKNightWatch", "Sleep started under the configured rules while some players were not in bed.", (LogLevel)16); _evidence?.Invoke(vote); } } } public void Reset() { _known = false; _skipping = false; } } public static class AFKNightWatchSleepQuorumRules { public static int Required(int participants, int percentage, bool strict) { if (participants <= 0) { return 0; } percentage = Math.Max(1, Math.Min(100, percentage)); if (percentage == 100) { return participants; } double num = (double)participants * (double)percentage / 100.0; return Math.Min(participants, Math.Max(1, strict ? ((int)Math.Floor(num) + 1) : ((int)Math.Ceiling(num)))); } public static SleepDecision Evaluate(IEnumerable players, int percentage, bool strict, bool excludeIdle) { SleepDecision sleepDecision = new SleepDecision(); foreach (PlayerActivityView player in players) { if (!player.Known) { sleepDecision.Unknown = true; } if (excludeIdle && player.Idle && !player.InBed) { sleepDecision.ExcludedIdle++; continue; } sleepDecision.Participants++; if (player.Known && player.Alive && player.InBed) { sleepDecision.Sleepers++; } } sleepDecision.Required = Required(sleepDecision.Participants, percentage, strict); sleepDecision.Met = !sleepDecision.Unknown && sleepDecision.Participants > 0 && sleepDecision.Sleepers > 0 && sleepDecision.Sleepers >= sleepDecision.Required; return sleepDecision; } } public static class AFKNightWatchSleepVoteCoordinator { private sealed class Registration : IDisposable { private Action? _release; public Registration(Action release) { _release = release; } public void Dispose() { Action? release = _release; _release = null; release?.Invoke(); } } private static readonly Harmony Hooks = new Harmony("heimkit.sleep_vote"); private static readonly Harmony Observers = new Harmony("heimkit.sleep_vote.diagnostics"); private static readonly List Registered = new List(); private static readonly List FallbackActors = new List(); private static readonly List FallbackVotes = new List(); private static Func<(int Percentage, bool Strict)>? _majority; private static IPlayerActivityObservations? _activity; private static IPlayerPresence? _presence; private static Action? _result; private static Action? _failure; private static bool _installed; private static Func? _debug; private static Action? _lifecycle; private static readonly AFKNightWatchSleepDelay SleepDelay = new AFKNightWatchSleepDelay(); private static Func? _delaySeconds; private static SleepDecision? _acceptedVote; private static Action? _hook; private static ManualLogSource? _logger; private static string _logName = "SleepVote"; private static float _lastAttemptAt = float.NegativeInfinity; private static float _lastWarning = float.NegativeInfinity; public static string RegisteredHooks => string.Join(",", Registered); private static bool DebugEnabled => _debug?.Invoke() ?? false; private static IReadOnlyList ReadFallback() { PlayerActivityService.ReadActorsInto(_presence, 0, FallbackActors, null); FallbackVotes.Clear(); foreach (PlayerActivityObservation fallbackActor in FallbackActors) { FallbackVotes.Add(new PlayerActivityView { Peer = fallbackActor.Peer, Known = fallbackActor.Known, Alive = fallbackActor.Alive, InBed = fallbackActor.InBed }); } return FallbackVotes; } public static IDisposable Register(Func<(int, bool)>? options, IPlayerActivityObservations? activity, Action result, Action failure, Func? debug = null, Action? hook = null, ManualLogSource? logger = null, string logName = "SleepVote", IPlayerPresence? presence = null, Action? lifecycle = null, Func? delaySeconds = null) { if (_installed) { throw new InvalidOperationException("A sleep-vote owner is already registered."); } _logger = logger; _logName = logName; _presence = presence ?? throw new ArgumentNullException("presence"); try { Install(); _debug = debug; _hook = hook; _lifecycle = lifecycle; _delaySeconds = delaySeconds; SleepDelay.Reset(); _acceptedVote = null; _majority = options; _activity = activity; _result = result; _failure = failure; } catch { _presence = null; _majority = null; _activity = null; _result = null; _failure = null; _debug = null; _hook = null; _lifecycle = null; _delaySeconds = null; SleepDelay.Reset(); _acceptedVote = null; UninstallUnused(); throw; } return new Registration(delegate { _lastAttemptAt = float.NegativeInfinity; _presence = null; _debug = null; _hook = null; _lifecycle = null; _delaySeconds = null; SleepDelay.Reset(); _acceptedVote = null; _majority = null; _activity = null; _result = null; _failure = null; UninstallUnused(); }); } private static void Install() { //IL_0034: Unknown result type (might be due to invalid IL or missing references) //IL_0042: Expected O, but got Unknown if (!_installed) { try { Hooks.Patch((MethodBase)AccessTools.Method(typeof(Game), "EverybodyIsTryingToSleep", (Type[])null, (Type[])null), new HarmonyMethod(typeof(AFKNightWatchSleepVoteCoordinator), "Vote", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); Registered.Clear(); Registered.Add("Game.EverybodyIsTryingToSleep:vote_control"); _installed = true; } catch { Hooks.UnpatchSelf(); throw; } InstallObserver(typeof(Game), "EverybodyIsTryingToSleep", null, "VoteReturned", "VoteFinished"); InstallObserver(typeof(Game), "UpdateSleeping", "UpdateEntered", null, "UpdateFinished"); InstallObserver(typeof(EnvMan), "SkipToMorning", "SkipRequested"); } } private static void InstallObserver(Type type, string method, string? prefix = null, string? postfix = null, string? finalizer = null) { //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_004e: Unknown result type (might be due to invalid IL or missing references) //IL_0068: Unknown result type (might be due to invalid IL or missing references) MethodInfo methodInfo = null; try { methodInfo = AccessTools.Method(type, method, (Type[])null, (Type[])null); if (methodInfo == null) { throw new MissingMethodException(type.Name, method); } Observers.Patch((MethodBase)methodInfo, (prefix == null) ? ((HarmonyMethod)null) : new HarmonyMethod(typeof(AFKNightWatchSleepVoteCoordinator), prefix, (Type[])null), (postfix == null) ? ((HarmonyMethod)null) : new HarmonyMethod(typeof(AFKNightWatchSleepVoteCoordinator), postfix, (Type[])null), (HarmonyMethod)null, (finalizer == null) ? ((HarmonyMethod)null) : new HarmonyMethod(typeof(AFKNightWatchSleepVoteCoordinator), finalizer, (Type[])null), (HarmonyMethod)null); Registered.Add(type.Name + "." + method + ":observation"); } catch (Exception) { if (methodInfo != null) { Observers.Unpatch((MethodBase)methodInfo, (HarmonyPatchType)0, Observers.Id); } if (_logger != null) { DiagnosticLog.Write(_logger, _logName, "Diagnostic hook unavailable; gameplay hook retained", (LogLevel)4); } } } private static void UninstallUnused() { if (_majority != null || _activity != null) { return; } _installed = false; try { Observers.UnpatchSelf(); } finally { try { Hooks.UnpatchSelf(); } finally { Registered.Clear(); FallbackActors.Clear(); FallbackVotes.Clear(); _logger = null; } } } private static bool Vote(ref bool __result) { Notify("vote_hook_calls"); if (PlayerServices.Ready && _installed) { IPlayerPresence? presence = _presence; if (presence != null && presence.HasJoinedPlayers == true && !((Object)(object)EnvMan.instance == (Object)null) && (EnvMan.IsAfternoon() || EnvMan.IsNight())) { try { IReadOnlyList readOnlyList = ((_activity != null) ? _activity.Snapshot(Time.unscaledTime) : ReadFallback()); if (_activity != null && !_activity.Reliable) { SleepDelay.Reset(); _acceptedVote = null; Notify("vote_not_ready_fallback"); return true; } bool flag = false; bool flag2 = true; for (int i = 0; i < readOnlyList.Count; i++) { PlayerActivityView playerActivityView = readOnlyList[i]; flag |= playerActivityView.Known && playerActivityView.Alive && playerActivityView.InBed; flag2 &= playerActivityView.Known && playerActivityView.InBed; } if (!flag) { SleepDelay.Reset(); _acceptedVote = null; Notify("no_living_sleeper_votes"); __result = false; return false; } _lastAttemptAt = Time.unscaledTime; (int, bool) tuple = _majority?.Invoke() ?? (100, false); SleepDecision sleepDecision = AFKNightWatchSleepQuorumRules.Evaluate(readOnlyList, tuple.Item1, tuple.Item2, _activity != null); sleepDecision.AllowedAfterDelay = SleepDelay.Allow(Time.unscaledTime, sleepDecision.Met, flag2, _delaySeconds?.Invoke() ?? 30); sleepDecision.DelayRemaining = SleepDelay.Remaining; _acceptedVote = (sleepDecision.AllowedAfterDelay ? sleepDecision : null); _result?.Invoke(sleepDecision); if (sleepDecision.Participants == 0) { Notify("empty_vote_rosters"); } if (sleepDecision.Sleepers == 0) { SleepDelay.Reset(); _acceptedVote = null; Notify("no_living_sleeper_votes"); __result = false; return false; } if (sleepDecision.Unknown) { Notify("unknown_actor_native_fallbacks"); return true; } __result = sleepDecision.AllowedAfterDelay; return false; } catch (Exception obj) { SleepDelay.Reset(); _acceptedVote = null; Notify("vote_processing_failures"); _failure?.Invoke(obj); return true; } } } SleepDelay.Reset(); _acceptedVote = null; Notify("vote_not_ready_fallback"); return true; } private static void Notify(string hook, NativeSleepObservation? evidence = null) { try { _hook?.Invoke(hook, evidence); } catch (Exception error) { ObservationWarning(error); } } private static void ObservationWarning(Exception error) { float unscaledTime = Time.unscaledTime; if (!(unscaledTime >= _lastWarning) || !(unscaledTime - _lastWarning < 300f)) { _lastWarning = unscaledTime; if (_logger != null) { DiagnosticLog.Write(_logger, _logName, "Diagnostic observation unavailable; native behavior unchanged: " + error.Message, (LogLevel)4); } } } private static void VoteReturned(bool __result) { Notify(__result ? "vote_returned_true" : "vote_returned_false"); } private static Exception? VoteFinished(Exception? __exception) { if (__exception != null) { Notify("native_vote_exceptions"); } return __exception; } private static void SkipRequested() { Notify("skip_to_morning_invocations"); } private static void ObserveLifecycle(bool sleeping, bool failed = false, SleepDecision? vote = null) { try { bool? obj; if (!failed) { IPlayerPresence? presence = _presence; if (presence != null && presence.HasJoinedPlayers == true && (Object)(object)ZNet.instance != (Object)null && ZNet.instance.IsServer() && (Object)(object)EnvMan.instance != (Object)null) { obj = EnvMan.instance.IsTimeSkipping(); goto IL_005e; } } obj = null; goto IL_005e; IL_005e: bool? arg = obj; _lifecycle?.Invoke(sleeping, arg, failed ? null : vote); } catch (Exception error) { ObservationWarning(error); } } private static void UpdateEntered(bool ___m_sleeping, double ___m_lastSleepTime, out NativeSleepObservation? __state) { __state = null; Notify("update_sleeping_invocations"); _acceptedVote = null; if (!___m_sleeping) { IPlayerPresence? presence = _presence; if (presence != null && presence.HasJoinedPlayers == true && !((Object)(object)EnvMan.instance == (Object)null) && !EnvMan.instance.IsTimeSkipping() && (EnvMan.IsAfternoon() || EnvMan.IsNight())) { goto IL_0066; } } SleepDelay.Reset(); goto IL_0066; IL_0066: ObserveLifecycle(___m_sleeping); try { if (!DebugEnabled) { return; } IPlayerPresence? presence2 = _presence; if (presence2 == null || presence2.HasJoinedPlayers != true || (!___m_sleeping && ((Object)(object)EnvMan.instance == (Object)null || (!EnvMan.IsAfternoon() && !EnvMan.IsNight())))) { return; } __state = new NativeSleepObservation { ObservedAt = Time.unscaledTime, Server = (((Object)(object)ZNet.instance != (Object)null) ? new bool?(ZNet.instance.IsServer()) : ((bool?)null)), Sleeping = ___m_sleeping }; if ((Object)(object)EnvMan.instance != (Object)null) { __state.SkippingBefore = EnvMan.instance.IsTimeSkipping(); __state.Afternoon = EnvMan.IsAfternoon(); __state.Night = EnvMan.IsNight(); } if ((Object)(object)ZNet.instance != (Object)null) { double timeSeconds = ZNet.instance.GetTimeSeconds(); if (!double.IsNaN(timeSeconds) && !double.IsInfinity(timeSeconds) && !double.IsNaN(___m_lastSleepTime) && !double.IsInfinity(___m_lastSleepTime)) { __state.GameTimeBefore = timeSeconds; __state.CooldownRemaining = Math.Max(0.0, 10.0 - (timeSeconds - ___m_lastSleepTime)); } } } catch (Exception error) { Notify("sleep_probe_failures"); ObservationWarning(error); } } private static Exception? UpdateFinished(NativeSleepObservation? __state, bool ___m_sleeping, Exception? __exception) { if (__exception != null) { SleepDelay.Reset(); } ObserveLifecycle(___m_sleeping, __exception != null, _acceptedVote); _acceptedVote = null; if (__exception != null) { Notify("native_sleep_update_exceptions"); } if (__state != null) { try { __state.Failed = __exception != null; __state.SleepingAfter = ___m_sleeping; if ((Object)(object)ZNet.instance != (Object)null) { __state.GameTimeAfter = ZNet.instance.GetTimeSeconds(); } __state.SkippingAfter = (((Object)(object)EnvMan.instance != (Object)null) ? new bool?(EnvMan.instance.IsTimeSkipping()) : ((bool?)null)); if (___m_sleeping || __state.Sleeping == true || Time.unscaledTime - _lastAttemptAt <= 2f || __exception != null) { Notify("sleep_update_observed", __state); } } catch (Exception error) { Notify("sleep_probe_failures"); ObservationWarning(error); } } return __exception; } } } namespace HeimKit.Features.AFKNightWatch.Models { public sealed class NativeSleepObservation { public float ObservedAt { get; set; } public bool? Server { get; set; } public bool? Sleeping { get; set; } public bool? SleepingAfter { get; set; } public double? GameTimeBefore { get; set; } public double? GameTimeAfter { get; set; } public bool? Afternoon { get; set; } public bool? Night { get; set; } public bool? SkippingBefore { get; set; } public bool? SkippingAfter { get; set; } public double? CooldownRemaining { get; set; } public bool Failed { get; set; } public string Gate { get { if (Server == true) { if (Sleeping != true) { if (SkippingBefore.HasValue) { if (SkippingBefore != true) { if (Afternoon.HasValue && Night.HasValue) { if (Afternoon == true || Night == true) { if (CooldownRemaining.HasValue) { if (!(CooldownRemaining > 0.0)) { return "time_gates_open_vote_required"; } return "cooldown_pending"; } return "cooldown_unknown"; } return "outside_sleep_time"; } return "time_gate_unknown"; } return "already_time_skipping"; } return "time_skipping_gate_unknown"; } return "already_sleeping"; } return "server_gate_unknown_or_false"; } } public string Outcome { get { if (!Failed) { if (SkippingBefore.HasValue && SkippingAfter.HasValue) { if (SkippingBefore != false || SkippingAfter != true) { if (Sleeping != true || SleepingAfter != false || SkippingAfter != false) { if (SkippingBefore != true || SkippingAfter != false) { return "no_time_skip_state_change"; } return "time_skip_ended"; } return "sleep_session_ended_server_state"; } return "time_skip_became_active"; } return "unknown"; } return "native_exception"; } } } public sealed class NightWatchStatus { public SleepDecision? Vote; public float? VoteAge; public long Votes; public long Outcomes; public int? Players; public bool MajorityEnabled; public bool ExclusionEnabled; public ObservationCounters? Hooks; public NativeSleepObservation? Sleep; public NativeSleepObservation? SleepOutcome; } public sealed class SleepDecision { public int Participants { get; set; } public int Sleepers { get; set; } public int Required { get; set; } public int ExcludedIdle { get; set; } public bool Unknown { get; set; } public bool Met { get; set; } public bool AllowedAfterDelay { get; set; } public float DelayRemaining { get; set; } } } namespace HeimKit.Core.World { internal sealed class AccessOrder where T : notnull { private readonly LinkedList _order = new LinkedList(); private readonly Dictionary> _nodes = new Dictionary>(); private readonly Stack> _spares = new Stack>(); internal int Count => _nodes.Count; internal bool Touch(T key) { if (!_nodes.TryGetValue(key, out LinkedListNode value)) { return false; } if (value != _order.Last) { _order.Remove(value); _order.AddLast(value); } return true; } internal void Add(T key) { LinkedListNode linkedListNode = ((_spares.Count > 0) ? _spares.Pop() : new LinkedListNode(key)); linkedListNode.Value = key; _nodes.Add(key, linkedListNode); _order.AddLast(linkedListNode); } internal T RemoveOldest() { LinkedListNode first = _order.First; T value = first.Value; _order.RemoveFirst(); _nodes.Remove(value); first.Value = default(T); _spares.Push(first); return value; } internal void Clear() { while (_order.Count > 0) { RemoveOldest(); } } } internal sealed class CandidateSubscription : IDisposable { private readonly WorldObjectProvider _provider; private readonly Func _accept; private readonly List _records = new List(); private readonly Dictionary> _cells = new Dictionary>(); private readonly Dictionary _locations = new Dictionary(); private readonly List _expired = new List(); private bool _fallback; private Exception? _failure; private readonly List _ignored = new List(); private bool _disposed; private readonly List _nearby = new List(); private readonly CandidateView _nearbyView; internal string Owner { get; } internal ScanKind Kind { get; } internal bool Broad { get; } internal IReadOnlyList Records => _records; internal CandidateView? Nearby(Vector3 point) { //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_000d: 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) _nearby.Clear(); Query(ZoneSystem.GetZone(point), new SimulationDistance(1, 0, false), _nearby); if (_nearby.Count > 8192) { return null; } return _nearbyView; } internal CandidateSubscription(WorldObjectProvider provider, string owner, Func accept, ScanKind kind, bool broad = false) { _provider = provider; Owner = owner; _accept = accept; Kind = kind; Broad = broad; _nearbyView = new CandidateView(_nearby); } internal void Classify(ZDO record) { //IL_003e: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_0055: Unknown result type (might be due to invalid IL or missing references) //IL_005a: Unknown result type (might be due to invalid IL or missing references) //IL_0062: Unknown result type (might be due to invalid IL or missing references) //IL_007c: Unknown result type (might be due to invalid IL or missing references) //IL_0070: 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_00ac: Unknown result type (might be due to invalid IL or missing references) //IL_00cb: 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_00e2: Unknown result type (might be due to invalid IL or missing references) //IL_00bc: Unknown result type (might be due to invalid IL or missing references) if (Broad || _fallback || _failure != null) { return; } try { if (!_accept(record)) { Remove(record.m_uid); return; } } catch (Exception failure) { Remove(record.m_uid); _failure = failure; return; } Vector2s sector = record.GetSector(); if (_locations.TryGetValue(record.m_uid, out var value) && value == sector) { return; } Remove(record.m_uid); if (_locations.Count >= 131072) { Clear(); _fallback = true; return; } if (!_cells.TryGetValue(sector, out HashSet value2)) { _cells.Add(sector, value2 = new HashSet()); } value2.Add(record.m_uid); _locations.Add(record.m_uid, sector); } internal void Remove(ZDOID id) { //IL_0006: 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_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_0044: Unknown result type (might be due to invalid IL or missing references) if (!_locations.TryGetValue(id, out var value)) { return; } _locations.Remove(id); if (_cells.TryGetValue(value, out HashSet value2)) { value2.Remove(id); if (value2.Count == 0) { _cells.Remove(value); } } } internal void ForgetCell(Vector2s cell) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_0028: Unknown result type (might be due to invalid IL or missing references) //IL_004e: Unknown result type (might be due to invalid IL or missing references) if (!_cells.TryGetValue(cell, out HashSet value)) { return; } foreach (ZDOID item in value) { _locations.Remove(item); } _cells.Remove(cell); } internal void Clear() { _cells.Clear(); _locations.Clear(); _fallback = false; } internal void AppendCell(Vector2s cell, bool near, List result) { //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_0044: Unknown result type (might be due to invalid IL or missing references) //IL_0049: Unknown result type (might be due to invalid IL or missing references) //IL_004f: 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_0062: Unknown result type (might be due to invalid IL or missing references) //IL_0067: Unknown result type (might be due to invalid IL or missing references) //IL_0070: Unknown result type (might be due to invalid IL or missing references) //IL_0075: Unknown result type (might be due to invalid IL or missing references) //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_00cf: Unknown result type (might be due to invalid IL or missing references) if (_fallback) { _provider.FilterCell(cell, _accept, near, result); } else { if (!_cells.TryGetValue(cell, out HashSet value)) { return; } _expired.Clear(); foreach (ZDOID item in value) { ZDO zDO = ZDOMan.instance.GetZDO(item); if (zDO == null || !zDO.IsValid() || zDO.m_uid != item || zDO.GetSector() != cell) { _expired.Add(item); } else if (near || zDO.Distant) { result.Add(zDO); } } foreach (ZDOID item2 in _expired) { Remove(item2); } } } internal void Query(Vector2s sector, SimulationDistance distance, List near, List? distant = null) { //IL_00a4: Unknown result type (might be due to invalid IL or missing references) //IL_00a5: Unknown result type (might be due to invalid IL or missing references) //IL_0081: Unknown result type (might be due to invalid IL or missing references) //IL_0082: Unknown result type (might be due to invalid IL or missing references) if (_disposed) { throw new ObjectDisposedException(Owner); } if (_failure != null) { throw new InvalidOperationException(Owner + " candidate classification failed.", _failure); } if (Broad && Kind == ScanKind.Nearby) { _ignored.Clear(); } _records.Clear(); int count = near.Count; int num = distant?.Count ?? 0; if (Broad) { _provider.Query(sector, distance, near, (Kind == ScanKind.Nearby) ? _ignored : distant); } else { _provider.QueryCandidates(this, sector, distance, near, distant); } if (_failure != null) { throw new InvalidOperationException(Owner + " candidate classification failed.", _failure); } for (int i = count; i < near.Count; i++) { _records.Add(near[i]); } if (distant != null && distant != near) { for (int j = num; j < distant.Count; j++) { _records.Add(distant[j]); } } } internal void Read(Vector3 point, int radius, List records, bool classic = false, bool includeDistant = true) { //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_001c: Unknown result type (might be due to invalid IL or missing references) records.Clear(); _ignored.Clear(); Query(ZoneSystem.GetZone(point), new SimulationDistance(radius, 0, classic), records, includeDistant ? null : _ignored); } public void Dispose() { if (!_disposed) { _disposed = true; Clear(); _records.Clear(); _nearby.Clear(); _ignored.Clear(); _provider.Release(this); } } } internal sealed class CandidateView : IReadOnlyList, IEnumerable, IEnumerable, IReadOnlyCollection { private readonly List _records; public int Count => _records.Count; public ZDO this[int index] => _records[index]; internal CandidateView(List records) { _records = records; } public List.Enumerator GetEnumerator() { return _records.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } internal static class NativeWorldObject { public static ZDO Create(GameObject prefab, Vector3 position, Quaternion rotation) { //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Unknown result type (might be due to invalid IL or missing references) //IL_0050: 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_0092: Unknown result type (might be due to invalid IL or missing references) ZNetView val = PrefabRegistry.Component(prefab); if ((Object)(object)val == (Object)null || !val.m_persistent || !PlayerWorldScope.Finite(position)) { throw new InvalidOperationException("Invalid persistent native prefab."); } ZDO val2 = ZDOMan.instance.CreateNewZDO(position, StringExtensionMethods.GetStableHashCode(((Object)prefab).name)); val2.Persistent = val.m_persistent; val2.Type = val.m_type; val2.Distant = val.m_distant; val2.SetPrefab(StringExtensionMethods.GetStableHashCode(((Object)prefab).name)); val2.SetRotation(rotation); if (val.m_syncInitialScale) { val2.Set(ZDOVars.s_scaleHash, prefab.transform.localScale); } return val2; } } internal sealed class PlayerWorldScope : IDisposable { private readonly IPlayerPresence _presence; private int _cursor; private readonly Dictionary _previous = new Dictionary(); private readonly Dictionary _current = new Dictionary(); private readonly List<(Vector3 Before, Vector3 After)> _segments = new List<(Vector3, Vector3)>(); public readonly List Positions = new List(); public readonly List Records = new List(); private readonly List _context = new List(); private CandidateSubscription? _index; private bool _contextQueried; private float _range; private bool _actorsReliable; internal string Owner { get; } public List Context => _context; public Vector3 Center { get; private set; } public void Index(Func accept) { _index = WorldObjectProvider.Current.Subscribe(Owner, accept); } public bool ContextReady() { //IL_0036: Unknown result type (might be due to invalid IL or missing references) //IL_003b: Unknown result type (might be due to invalid IL or missing references) //IL_0057: Unknown result type (might be due to invalid IL or missing references) if (_contextQueried) { return _context.Count <= 8192; } _contextQueried = true; _context.Clear(); WorldObjectProvider.Current.Query(ZoneSystem.GetZone(Center), new SimulationDistance((int)Math.Ceiling(_range / 64f) + 1, 0, false), _context); return _context.Count <= 8192; } public PlayerWorldScope(IPlayerPresence presence, string owner = "PlayerWorldScope") { _presence = presence; Owner = owner; } public static bool Finite(float n) { if (!float.IsNaN(n)) { return !float.IsInfinity(n); } return false; } public static bool Finite(Vector3 p) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_001a: Unknown result type (might be due to invalid IL or missing references) if (Finite(p.x) && Finite(p.y)) { return Finite(p.z); } return false; } public bool Refresh(float range) { //IL_004a: Unknown result type (might be due to invalid IL or missing references) //IL_004f: Unknown result type (might be due to invalid IL or missing references) //IL_0066: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Unknown result type (might be due to invalid IL or missing references) if (!SampleActors()) { return false; } _range = range; if (_index != null) { _index.Read(Center, (int)Math.Ceiling(range / 64f) + 1, Records); } else { WorldObjectProvider.Current.Query(ZoneSystem.GetZone(Center), new SimulationDistance((int)Math.Ceiling(range / 64f) + 1, 0, false), Records); } if (Records.Count > 8192) { Records.Clear(); return false; } return true; } public bool SampleActors() { //IL_0215: Unknown result type (might be due to invalid IL or missing references) //IL_00ac: Unknown result type (might be due to invalid IL or missing references) //IL_00c0: Unknown result type (might be due to invalid IL or missing references) //IL_0304: Unknown result type (might be due to invalid IL or missing references) //IL_00e6: Unknown result type (might be due to invalid IL or missing references) //IL_00ea: Unknown result type (might be due to invalid IL or missing references) //IL_0364: Unknown result type (might be due to invalid IL or missing references) //IL_0250: Unknown result type (might be due to invalid IL or missing references) //IL_0255: Unknown result type (might be due to invalid IL or missing references) //IL_0383: Unknown result type (might be due to invalid IL or missing references) //IL_0262: Unknown result type (might be due to invalid IL or missing references) //IL_013e: Unknown result type (might be due to invalid IL or missing references) //IL_0197: Unknown result type (might be due to invalid IL or missing references) //IL_028d: Unknown result type (might be due to invalid IL or missing references) //IL_01b6: 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_02b0: Unknown result type (might be due to invalid IL or missing references) //IL_02b2: Unknown result type (might be due to invalid IL or missing references) _contextQueried = false; _context.Clear(); Positions.Clear(); Records.Clear(); _segments.Clear(); Dictionary current = _current; current.Clear(); _actorsReliable = false; if (_presence.HasJoinedPlayers != true) { return false; } if (this != WorldObjectProvider.Current.Scope) { WorldObjectProvider.Current.SamplePlayers(); PlayerWorldScope scope = WorldObjectProvider.Current.Scope; if (!scope._actorsReliable) { return false; } foreach (KeyValuePair item in scope._current) { Positions.Add(item.Value); current[item.Key] = item.Value; if (_previous.TryGetValue(item.Key, out var value)) { _segments.Add((value, item.Value)); } } _previous.Clear(); foreach (KeyValuePair item2 in current) { _previous[item2.Key] = item2.Value; } if (Positions.Count == 0) { return false; } Center = Positions[_cursor++ % Positions.Count]; if (_cursor >= 1000000) { _cursor = 0; } return !Character.InInterior(Center); } float n = default(float); for (int i = 0; i < _presence.Peers.Count; i++) { ZNetPeer val = _presence.Peers[i]; if (!val.IsReady()) { continue; } if (((ZDOID)(ref val.m_characterID)).IsNone()) { return false; } ZDO zDO = ZDOMan.instance.GetZDO(val.m_characterID); if (zDO == null || !zDO.IsValid() || zDO.GetOwner() != val.m_uid) { return false; } bool num = zDO.GetFloat(ZDOVars.s_health, ref n); Vector3 position = zDO.GetPosition(); if ((num && !Finite(n)) || !Finite(position)) { return false; } if (NativeCharacterHealth.IsAlive(zDO)) { if (Positions.Count >= 64) { return false; } Positions.Add(position); if (_previous.TryGetValue(val.m_uid, out var value2)) { _segments.Add((value2, position)); } current[val.m_uid] = position; } } _previous.Clear(); foreach (KeyValuePair item3 in current) { _previous[item3.Key] = item3.Value; } if (Positions.Count == 0) { return false; } _actorsReliable = true; Center = Positions[_cursor++ % Positions.Count]; if (_cursor >= 1000000) { _cursor = 0; } if (Character.InInterior(Center)) { return false; } return true; } public bool InRange(Vector3 point, float range) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Unknown result type (might be due to invalid IL or missing references) if (Finite(point)) { Vector3 val = point - Center; return ((Vector3)(ref val)).sqrMagnitude <= range * range; } return false; } public bool PlayerNear(Vector3 point, float distance) { //IL_0010: 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_0016: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_0064: Unknown result type (might be due to invalid IL or missing references) //IL_006b: Unknown result type (might be due to invalid IL or missing references) //IL_0070: Unknown result type (might be due to invalid IL or missing references) //IL_0075: 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_008f: Unknown result type (might be due to invalid IL or missing references) //IL_0094: Unknown result type (might be due to invalid IL or missing references) //IL_0099: Unknown result type (might be due to invalid IL or missing references) //IL_00af: Unknown result type (might be due to invalid IL or missing references) //IL_00b2: Unknown result type (might be due to invalid IL or missing references) //IL_00b7: 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_00c0: Unknown result type (might be due to invalid IL or missing references) //IL_00c5: Unknown result type (might be due to invalid IL or missing references) //IL_00ca: Unknown result type (might be due to invalid IL or missing references) Vector3 val; foreach (Vector3 position in Positions) { val = position - point; if (((Vector3)(ref val)).sqrMagnitude <= distance * distance) { return true; } } foreach (var segment in _segments) { Vector3 val2 = segment.After - segment.Before; float num = ((((Vector3)(ref val2)).sqrMagnitude > 0f) ? Mathf.Clamp01(Vector3.Dot(point - segment.Before, val2) / ((Vector3)(ref val2)).sqrMagnitude) : 0f); val = point - (segment.Before + val2 * num); if (((Vector3)(ref val)).sqrMagnitude <= distance * distance) { return true; } } return false; } public void ClearActors() { _actorsReliable = false; Positions.Clear(); Records.Clear(); _previous.Clear(); _current.Clear(); _segments.Clear(); } public void Dispose() { _index?.Dispose(); _index = null; WorldObjectProvider.Current?.ReleaseScope(this); ClearActors(); } } internal sealed class TerrainContext : IDisposable { private static class Accessors { internal static readonly Func PopulateZones; internal static readonly Func CreateObject; internal static readonly Action CheckLoad; internal static readonly Action CompilerAwake; internal static readonly FieldRef Initialized; internal static readonly FieldRef CompilerMap; internal static readonly FieldRef ModifiedHeight; internal static readonly FieldRef LevelDelta; internal static readonly FieldRef SmoothDelta; internal static readonly FieldRef ModifiedPaint; internal static readonly FieldRef PaintMask; static Accessors() { PopulateZones = NativeAccess.Method>(typeof(ZoneSystem), "CreateLocalZones", new Type[1] { typeof(Vector3) }); CreateObject = NativeAccess.Method>(typeof(ZNetScene), "CreateObject", new Type[1] { typeof(ZDO) }); CheckLoad = NativeAccess.Method>(typeof(TerrainComp), "CheckLoad", Array.Empty()); CompilerAwake = NativeAccess.Method>(typeof(TerrainComp), "Awake", Array.Empty()); Initialized = NativeAccess.Field("m_initialized"); CompilerMap = NativeAccess.Field("m_hmap"); ModifiedHeight = NativeAccess.Field("m_modifiedHeight"); LevelDelta = NativeAccess.Field("m_levelDelta"); SmoothDelta = NativeAccess.Field("m_smoothDelta"); ModifiedPaint = NativeAccess.Field("m_modifiedPaint"); PaintMask = NativeAccess.Field("m_paintMask"); } } private static readonly List Consumers = new List(); private static readonly Harmony Hooks = new Harmony("heimkit.world_terrain_context"); private static readonly HashSet InstanceIds = new HashSet(); private readonly Dictionary _retained = new Dictionary(); private readonly ZDOMan _world = ZDOMan.instance; private readonly PrefabCatalog _terrainDefinitions = PrefabRegistry.Current.Catalog("Terrain"); private readonly List _expired = new List(); private float _nextPrune; public string? WaitReason { get; private set; } public ZDOID WaitObject { get; private set; } internal static void CheckCompatibility() { ValidateNative(delegate { _ = Accessors.PopulateZones; _ = Accessors.PaintMask; }); } internal static void ValidateNative(Action resolve) { try { resolve(); } catch (Exception inner) { throw new MissingMemberException("Native terrain context APIs.", inner); } } public TerrainContext() { //IL_0093: Unknown result type (might be due to invalid IL or missing references) //IL_00a1: Expected O, but got Unknown CheckCompatibility(); if (Consumers.Count == 0) { try { string[] array = new string[2] { "CreateObjects", "RemoveObjects" }; foreach (string text in array) { Hooks.Patch((MethodBase)AccessTools.Method(typeof(ZNetScene), text, (Type[])null, (Type[])null), new HarmonyMethod(typeof(TerrainContext), "Instances", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } } catch { Hooks.UnpatchSelf(); throw; } } Consumers.Add(this); } public bool Prepare(Vector3 point, IReadOnlyList scope, float now, float radius = 12f) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_0039: 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) //IL_006d: Unknown result type (might be due to invalid IL or missing references) //IL_0072: Unknown result type (might be due to invalid IL or missing references) //IL_0073: Unknown result type (might be due to invalid IL or missing references) //IL_0079: Unknown result type (might be due to invalid IL or missing references) //IL_025e: Unknown result type (might be due to invalid IL or missing references) //IL_0092: Unknown result type (might be due to invalid IL or missing references) //IL_0098: Unknown result type (might be due to invalid IL or missing references) //IL_012a: Unknown result type (might be due to invalid IL or missing references) WaitReason = null; WaitObject = ZDOID.None; Prune(now); if (!ZoneSystem.instance.LocationsGenerated || Character.InInterior(point)) { return false; } Accessors.PopulateZones(ZoneSystem.instance, point); if ((Object)(object)Heightmap.FindHeightmap(point) == (Object)null || !ZoneSystem.instance.IsZoneLoaded(point)) { return false; } for (int i = 0; i < scope.Count; i++) { ZDO val = scope[i]; Vector3 position = val.GetPosition(); if (Math.Abs(position.x - point.x) > 64f + radius || Math.Abs(position.z - point.z) > 64f + radius) { continue; } int prefab = val.GetPrefab(); if (!_terrainDefinitions.TryGetValue(prefab, out var value)) { GameObject val2 = PrefabRegistry.Current.Prefab(prefab); if ((Object)(object)val2 == (Object)null) { continue; } value = (Object)(object)PrefabRegistry.Component(val2) != (Object)null || (Object)(object)PrefabRegistry.Component(val2) != (Object)null; if (_terrainDefinitions.Count < 4096) { _terrainDefinitions[prefab] = value; } } if (!value) { continue; } Heightmap val3 = Heightmap.FindHeightmap(position); if ((Object)(object)val3 == (Object)null || (Object)(object)val3.GetPaintMask() == (Object)null || val3.HaveQueuedRebuild()) { return Wait(val, "terrain_heightmap_unavailable"); } if (!Include(val, now)) { return false; } ZNetView val4 = ZNetScene.instance.FindInstance(val); if ((Object)(object)val4 == (Object)null) { Accessors.CreateObject(ZNetScene.instance, val); val4 = ZNetScene.instance.FindInstance(val); } if ((Object)(object)val4 == (Object)null) { return false; } TerrainComp component = ((Component)val4).GetComponent(); if ((Object)(object)component != (Object)null) { if (!val4.IsValid() || val4.GetZDO() != val) { return Wait(val, "terrain_compiler_record_unavailable"); } if (!Accessors.Initialized.Invoke(component) && Accessors.CompilerMap.Invoke(component) == null) { Accessors.CompilerAwake(component); } if (!CompilerInitialized(component)) { return Wait(val, "terrain_compiler_uninitialized"); } if (Accessors.CompilerMap.Invoke(component) != val3) { return Wait(val, "terrain_compiler_heightmap_changed"); } Accessors.CheckLoad(component); } } return !Heightmap.HaveQueuedRebuild(point, radius); } internal static bool CompilerInitialized(TerrainComp compiler) { if (Accessors.Initialized.Invoke(compiler) && Accessors.CompilerMap.Invoke(compiler) != null) { bool[] obj = Accessors.ModifiedHeight.Invoke(compiler); if (obj != null && obj.Length != 0) { float[] obj2 = Accessors.LevelDelta.Invoke(compiler); if (obj2 != null && obj2.Length != 0) { float[] obj3 = Accessors.SmoothDelta.Invoke(compiler); if (obj3 != null && obj3.Length != 0) { bool[] obj4 = Accessors.ModifiedPaint.Invoke(compiler); if (obj4 != null && obj4.Length != 0) { Color[] obj5 = Accessors.PaintMask.Invoke(compiler); if (obj5 == null) { return false; } return obj5.Length != 0; } } } } } return false; } private bool Wait(ZDO record, string reason) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) WaitObject = record.m_uid; WaitReason = reason; return false; } public bool Include(ZDO record, float now) { //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Unknown result type (might be due to invalid IL or missing references) if (_retained.Count >= 8192 && !_retained.ContainsKey(record.m_uid)) { return false; } _retained[record.m_uid] = (record, now); return true; } private static void Instances(List currentNearObjects, List currentDistantObjects) { //IL_008d: Unknown result type (might be due to invalid IL or missing references) //IL_0113: Unknown result type (might be due to invalid IL or missing references) //IL_011a: Unknown result type (might be due to invalid IL or missing references) //IL_0129: Unknown result type (might be due to invalid IL or missing references) bool flag = false; foreach (TerrainContext consumer in Consumers) { if (consumer._world == ZDOMan.instance) { if (consumer._retained.Count > 0) { consumer.Prune(Time.unscaledTime); } flag |= consumer._retained.Count > 0; } } if (!flag) { return; } HashSet instanceIds = InstanceIds; instanceIds.Clear(); foreach (ZDO currentNearObject in currentNearObjects) { instanceIds.Add(currentNearObject.m_uid); } foreach (TerrainContext consumer2 in Consumers) { if (consumer2._world != ZDOMan.instance) { continue; } foreach (KeyValuePair item in consumer2._retained) { if (item.Value.Item1.IsValid() && item.Value.Item1.m_uid == item.Key && instanceIds.Add(item.Key)) { currentNearObjects.Add(item.Value.Item1); } } } instanceIds.Clear(); } private void Prune(float now) { //IL_0087: Unknown result type (might be due to invalid IL or missing references) //IL_006c: Unknown result type (might be due to invalid IL or missing references) //IL_0073: Unknown result type (might be due to invalid IL or missing references) //IL_00ba: Unknown result type (might be due to invalid IL or missing references) //IL_00bf: Unknown result type (might be due to invalid IL or missing references) //IL_00c6: Unknown result type (might be due to invalid IL or missing references) if (now < _nextPrune) { return; } _nextPrune = now + 1f; _expired.Clear(); foreach (KeyValuePair item in _retained) { if (now - item.Value.Item2 > 10f || !item.Value.Item1.IsValid() || item.Value.Item1.m_uid != item.Key) { _expired.Add(item.Key); } } foreach (ZDOID item2 in _expired) { _retained.Remove(item2); } _expired.Clear(); } public void Clear() { _retained.Clear(); } public void Dispose() { Consumers.Remove(this); _retained.Clear(); if (Consumers.Count == 0) { Hooks.UnpatchSelf(); } } } internal sealed class WorldCandidateIndex : IDisposable { internal const int Capacity = 131072; private readonly ZDOMan _world; private readonly Func _accept; private readonly Action, List?> _query; private readonly bool _observe; private readonly bool _retainCandidates; private readonly Action? _evictCell; private readonly Action? _changed; private readonly Action? _reset; private readonly AccessOrder<(int X, int Z, int Radius, bool Classic, bool Distant)> _areaOrder = new AccessOrder<(int, int, int, bool, bool)>(); private readonly HashSet _changes = new HashSet(); private readonly Dictionary _candidates = new Dictionary(); private readonly Dictionary> _cells = new Dictionary>(); private readonly List _remove = new List(); private readonly List _seed = new List(); private readonly List _distant = new List(); private bool _overflow; private bool _disposed; internal int AreaCapacity { get; set; } internal long Queries { get; private set; } internal WorldCandidateIndex(Func accept, Action, List?>? query = null, bool observe = true, bool retainCandidates = true, int areaCapacity = 1024, Action? evictCell = null, Action? changed = null, Action? reset = null) { _world = ZDOMan.instance; _accept = accept; _query = query ?? throw new ArgumentNullException("query"); _observe = observe; _retainCandidates = retainCandidates; AreaCapacity = areaCapacity; _evictCell = evictCell; _changed = changed; _reset = reset; if (_observe) { WorldRecordChanges.Add(this); } ZDOMan world = _world; world.m_onZDODestroyed = (Action)Delegate.Combine(world.m_onZDODestroyed, new Action(Destroyed)); } internal void Enqueue(ZDOID id) { //IL_003c: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Unknown result type (might be due to invalid IL or missing references) if (!_disposed && _world == ZDOMan.instance) { if (_changes.Count < 131072 || _changes.Contains(id)) { _changes.Add(id); } else { _overflow = true; } } } private void Destroyed(ZDO record) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) Enqueue(record.m_uid); } internal void Invalidate() { _overflow = true; } internal void Read(Vector3 center, int radius, List result, bool classic = false, bool includeDistant = true) { //IL_001b: Unknown result type (might be due to invalid IL or missing references) result.Clear(); RefreshChanges(); if (_world == ZDOMan.instance) { ReadArea(center, radius, result, classic, includeDistant); } } internal void RefreshChanges() { //IL_0093: Unknown result type (might be due to invalid IL or missing references) //IL_0098: Unknown result type (might be due to invalid IL or missing references) //IL_00a5: Unknown result type (might be due to invalid IL or missing references) //IL_00b1: Unknown result type (might be due to invalid IL or missing references) //IL_011a: Unknown result type (might be due to invalid IL or missing references) //IL_00c4: Unknown result type (might be due to invalid IL or missing references) //IL_00c9: Unknown result type (might be due to invalid IL or missing references) //IL_00ff: Unknown result type (might be due to invalid IL or missing references) WorldRecordChanges.Dispatch(); if (_world != ZDOMan.instance) { _areaOrder.Clear(); _candidates.Clear(); _cells.Clear(); _changes.Clear(); return; } if (_overflow) { _areaOrder.Clear(); _candidates.Clear(); _cells.Clear(); _reset?.Invoke(); _overflow = false; } foreach (ZDOID change in _changes) { _changed?.Invoke(change); ZDO zDO = _world.GetZDO(change); if (zDO != null && zDO.IsValid() && zDO.m_uid == change && _accept(zDO)) { if (_retainCandidates) { if (_candidates.Count < 131072 || _candidates.ContainsKey(change)) { Track(zDO); } else { _overflow = true; } } } else { Untrack(change); } } _changes.Clear(); } private void ReadArea(Vector3 center, int radius, List result, bool classic, bool includeDistant) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0009: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_01fc: Unknown result type (might be due to invalid IL or missing references) //IL_00e2: Unknown result type (might be due to invalid IL or missing references) //IL_00e7: Unknown result type (might be due to invalid IL or missing references) //IL_0319: 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_020b: Unknown result type (might be due to invalid IL or missing references) //IL_0304: 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_0337: Unknown result type (might be due to invalid IL or missing references) //IL_033c: Unknown result type (might be due to invalid IL or missing references) //IL_033f: 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_0243: Unknown result type (might be due to invalid IL or missing references) //IL_025e: Unknown result type (might be due to invalid IL or missing references) //IL_025f: Unknown result type (might be due to invalid IL or missing references) //IL_018c: Unknown result type (might be due to invalid IL or missing references) //IL_0288: Unknown result type (might be due to invalid IL or missing references) //IL_028d: 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_02c1: Unknown result type (might be due to invalid IL or missing references) //IL_02ad: Unknown result type (might be due to invalid IL or missing references) //IL_02b2: Unknown result type (might be due to invalid IL or missing references) Vector2s zone = ZoneSystem.GetZone(center); (int, int, int, bool, bool) key = (zone.x, zone.y, radius, classic, includeDistant); if (_overflow || !_areaOrder.Touch(key)) { if (_overflow) { _areaOrder.Clear(); _candidates.Clear(); _cells.Clear(); _reset?.Invoke(); } if (_areaOrder.Count >= AreaCapacity) { (int, int, int, bool, bool) tuple = _areaOrder.RemoveOldest(); _evictCell?.Invoke(new Vector2s(tuple.Item1, tuple.Item2)); } _seed.Clear(); _distant.Clear(); Queries++; _query(zone, new SimulationDistance(radius, 0, classic), _seed, includeDistant ? null : _distant); if (_retainCandidates && _seed.Count > 65536) { _overflow = true; result.AddRange(_seed); ClearSeed(); return; } bool flag = true; foreach (ZDO item in _seed) { if (item.IsValid() && _accept(item) && _retainCandidates) { if (_candidates.Count < 131072 || _candidates.ContainsKey(item.m_uid)) { Track(item); } else { flag = false; } } } _overflow = !flag; if (!flag) { result.AddRange(_seed); ClearSeed(); return; } _areaOrder.Add(key); ClearSeed(); } _remove.Clear(); Vector2s val = default(Vector2s); for (int i = zone.x - radius; i <= zone.x + radius; i++) { for (int j = zone.y - radius; j <= zone.y + radius; j++) { ((Vector2s)(ref val))..ctor(i, j); if (!_cells.TryGetValue(val, out HashSet value)) { continue; } bool flag2 = classic || ZoneSystem.instance.ZonesWithinRadius(zone, val, radius, false); bool flag3 = includeDistant && (classic || ZoneSystem.instance.ZonesWithinRadius(zone, val, radius, true)); if (!flag2 && !flag3) { continue; } foreach (ZDOID item2 in value) { ZDO zDO = _world.GetZDO(item2); if (zDO == null || !zDO.IsValid() || zDO.m_uid != item2) { _remove.Add(item2); } else if (flag2 || (flag3 && zDO.Distant)) { result.Add(zDO); } } } } foreach (ZDOID item3 in _remove) { Untrack(item3); } } private void ClearSeed() { _seed.Clear(); _distant.Clear(); if (_seed.Capacity > 65536) { _seed.Capacity = 65536; } if (_distant.Capacity > 65536) { _distant.Capacity = 65536; } } private void Track(ZDO record) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_0039: Unknown result type (might be due to invalid IL or missing references) //IL_003e: 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_001c: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0069: Unknown result type (might be due to invalid IL or missing references) //IL_005a: Unknown result type (might be due to invalid IL or missing references) //IL_0028: Unknown result type (might be due to invalid IL or missing references) Vector2s sector = record.GetSector(); if (_candidates.TryGetValue(record.m_uid, out var value)) { if (value == sector) { return; } Untrack(record.m_uid); } _candidates[record.m_uid] = sector; if (!_cells.TryGetValue(sector, out HashSet value2)) { value2 = (_cells[sector] = new HashSet()); } value2.Add(record.m_uid); } private void Untrack(ZDOID id) { //IL_0006: 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_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_0044: Unknown result type (might be due to invalid IL or missing references) if (!_candidates.TryGetValue(id, out var value)) { return; } _candidates.Remove(id); if (_cells.TryGetValue(value, out HashSet value2)) { value2.Remove(id); if (value2.Count == 0) { _cells.Remove(value); } } } public void Dispose() { if (!_disposed) { _disposed = true; ZDOMan world = _world; world.m_onZDODestroyed = (Action)Delegate.Remove(world.m_onZDODestroyed, new Action(Destroyed)); if (_observe) { WorldRecordChanges.Remove(this); } _changes.Clear(); _candidates.Clear(); _cells.Clear(); _areaOrder.Clear(); _seed.Clear(); } } } internal enum ScanKind { Nearby, NearbyAndDistant, ServerSimulation } internal sealed class WorldObjectProvider : IDisposable { private static class LiveInstances { internal static readonly FieldRef> Read; static LiveInstances() { Read = NativeAccess.Field>("m_instances"); } } private sealed class BroadView { internal readonly List Near = new List(); internal readonly List Far = new List(); } private readonly IPlayerPresence _presence; private readonly Action, List?>? _nativeQuery; private readonly Func? _geometry; private readonly bool _observe; private const int MaximumCycleCells = 8192; private int _targetedCount; private bool _playersSampled; private ZDOMan? _world; private long _worldIdentity; private WorldCandidateIndex? _index; private readonly Dictionary> _cycle = new Dictionary>(); private readonly Stack> _buffers = new Stack>(); private readonly AccessOrder _cycleOrder = new AccessOrder(); private readonly HashSet _visitedSectors = new HashSet(); private readonly Dictionary _rawLocations = new Dictionary(); private readonly Dictionary _rawObjects = new Dictionary(); private readonly Dictionary<(Vector2s, int, int, bool), BroadView> _views = new Dictionary<(Vector2s, int, int, bool), BroadView>(); private readonly Stack _viewBuffers = new Stack(); private readonly Dictionary _subscriptions = new Dictionary(StringComparer.Ordinal); private readonly List _cell = new List(); private readonly HashSet _seen = new HashSet(); private readonly List _scopes = new List(); private readonly HashSet _leases = new HashSet(); private readonly List _release = new List(); private readonly List _releaseScopes = new List(); internal static WorldObjectProvider Current { get; private set; } internal bool Ready { get; private set; } internal IReadOnlyList PlayerPositions { get { SamplePlayers(); return Scope.Positions; } } internal PlayerWorldScope Scope { get; } private int CellBudget => Math.Min(32768, Math.Max(8192, (_presence.JoinedCount ?? 1) * 512)); private WorldCandidateIndex Index => _index ?? (_index = new WorldCandidateIndex(Classify, NativeCell, _observe, retainCandidates: false, CellBudget, ForgetCell, Changed, ResetSelections)); internal static void CheckLiveInstanceCompatibility() { try { _ = LiveInstances.Read; } catch (Exception inner) { throw new MissingMemberException("WeatherGuard live scene instance access is unavailable.", inner); } } internal WorldObjectProvider(IPlayerPresence presence, Action, List?>? nativeQuery = null, Func? geometry = null, bool observe = true) { _presence = presence; _nativeQuery = nativeQuery; _geometry = geometry; _observe = observe; Current = this; Scope = new PlayerWorldScope(presence); } internal PlayerWorldScope CreateScope(string owner) { PlayerWorldScope playerWorldScope = new PlayerWorldScope(_presence, owner); _scopes.Add(playerWorldScope); return playerWorldScope; } internal void ReleaseScope(PlayerWorldScope scope) { _scopes.Remove(scope); } internal CandidateSubscription Subscribe(string owner, Func accept, ScanKind kind = ScanKind.NearbyAndDistant) { CandidateSubscription candidateSubscription = new CandidateSubscription(this, owner, accept, kind); _leases.Add(candidateSubscription); _targetedCount++; _index?.Invalidate(); return candidateSubscription; } internal void Release(CandidateSubscription subscription) { if (_leases.Remove(subscription) && !subscription.Broad && --_targetedCount == 0) { _index?.Dispose(); _index = null; ResetSelections(); } } internal void ReleaseOwner(string owner) { _release.Clear(); foreach (CandidateSubscription lease in _leases) { if (lease.Owner == owner) { _release.Add(lease); } } foreach (CandidateSubscription item in _release) { item.Dispose(); } _release.Clear(); _subscriptions.Remove(owner); _releaseScopes.Clear(); foreach (PlayerWorldScope scope in _scopes) { if (scope.Owner == owner) { _releaseScopes.Add(scope); } } foreach (PlayerWorldScope releaseScope in _releaseScopes) { releaseScope.Dispose(); } _releaseScopes.Clear(); if (_leases.Count == 0 && _scopes.Count == 0) { _index?.Dispose(); _index = null; } } internal CandidateSubscription For(string owner) { if (!_subscriptions.TryGetValue(owner, out CandidateSubscription value)) { value = new CandidateSubscription(this, owner, AcceptAll, ScanKind.NearbyAndDistant, broad: true); _subscriptions.Add(owner, value); _leases.Add(value); } return value; } private static bool AcceptAll(ZDO record) { return true; } internal void Tick(float now) { WorldServices.Refresh(); BeginCycle(WorldServices.World, (WorldServices.World && WorldServices.Activity) ? ZNet.instance.GetWorldUID() : 0); } internal void SamplePlayers() { if (!_playersSampled) { _playersSampled = true; if (Ready && _presence.HasJoinedPlayers == true && (_leases.Count != 0 || _scopes.Count != 0)) { Scope.SampleActors(); } } } internal void BeginCycle(bool ready, long worldIdentity = 0L) { Ready = ready; _playersSampled = false; foreach (List value in _cycle.Values) { value.Clear(); _buffers.Push(value); } _cycle.Clear(); _cycleOrder.Clear(); _rawLocations.Clear(); _rawObjects.Clear(); ClearViews(); if (Ready && _world == ZDOMan.instance && _worldIdentity == worldIdentity && _presence.HasJoinedPlayers == true) { return; } _index?.Dispose(); _index = null; _world = (Ready ? ZDOMan.instance : null); _worldIdentity = worldIdentity; foreach (CandidateSubscription lease in _leases) { lease.Clear(); } Scope.ClearActors(); foreach (PlayerWorldScope scope in _scopes) { scope.ClearActors(); } if (Ready) { _ = _presence.HasJoinedPlayers == true; } } private void NativeCell(Vector2s sector, SimulationDistance ignored, List records, List? distant) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_00e5: 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_0041: Unknown result type (might be due to invalid IL or missing references) //IL_0046: Unknown result type (might be due to invalid IL or missing references) //IL_004d: Unknown result type (might be due to invalid IL or missing references) //IL_0124: Unknown result type (might be due to invalid IL or missing references) //IL_0131: 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_007c: Unknown result type (might be due to invalid IL or missing references) //IL_007e: Unknown result type (might be due to invalid IL or missing references) //IL_00cb: Unknown result type (might be due to invalid IL or missing references) //IL_0151: 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_0164: 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_00a1: Unknown result type (might be due to invalid IL or missing references) if (_cycle.TryGetValue(sector, out List value)) { _cycleOrder.Touch(sector); records.AddRange(value); return; } if (_cycle.Count >= CellBudget) { Vector2s val = _cycleOrder.RemoveOldest(); List list = _cycle[val]; foreach (ZDO item in list) { if (_rawLocations.TryGetValue(item.m_uid, out var value2) && value2 == val) { _rawLocations.Remove(item.m_uid); _rawObjects.Remove(item.m_uid); } } _cycle.Remove(val); list.Clear(); _buffers.Push(list); } NativeScan(sector, new SimulationDistance(0, 0, true), records, distant); value = (List)((_buffers.Count > 0) ? ((IList)_buffers.Pop()) : ((IList)new List())); value.AddRange(records); _cycle.Add(sector, value); _cycleOrder.Add(sector); foreach (ZDO item2 in value) { _rawLocations[item2.m_uid] = sector; _rawObjects[item2.m_uid] = item2; } } private void NativeScan(Vector2s sector, SimulationDistance distance, List records, List? distant) { //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Unknown result type (might be due to invalid IL or missing references) if (_nativeQuery != null) { _nativeQuery(sector, distance, records, distant); } else { _world.FindSectorObjects(sector, distance, records, distant); } } internal void Enqueue(ZDOID id) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) _index?.Enqueue(id); } private bool Classify(ZDO record) { foreach (CandidateSubscription lease in _leases) { lease.Classify(record); } return false; } private void ForgetCell(Vector2s cell) { //IL_0015: Unknown result type (might be due to invalid IL or missing references) foreach (CandidateSubscription lease in _leases) { lease.ForgetCell(cell); } } private void ResetSelections() { foreach (CandidateSubscription lease in _leases) { lease.Clear(); } foreach (List value in _cycle.Values) { value.Clear(); _buffers.Push(value); } _cycle.Clear(); _cycleOrder.Clear(); _rawLocations.Clear(); _rawObjects.Clear(); ClearViews(); } private void Changed(ZDOID id) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0066: Unknown result type (might be due to invalid IL or missing references) //IL_00ee: Unknown result type (might be due to invalid IL or missing references) //IL_00fb: 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_010c: 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_012a: Unknown result type (might be due to invalid IL or missing references) //IL_013a: Unknown result type (might be due to invalid IL or missing references) //IL_00b3: Unknown result type (might be due to invalid IL or missing references) //IL_0084: Unknown result type (might be due to invalid IL or missing references) //IL_0089: Unknown result type (might be due to invalid IL or missing references) //IL_0041: Unknown result type (might be due to invalid IL or missing references) //IL_0097: Unknown result type (might be due to invalid IL or missing references) ZDO zDO = _world.GetZDO(id); bool flag = zDO != null && zDO.IsValid() && zDO.m_uid == id; if (!flag) { foreach (CandidateSubscription lease in _leases) { lease.Remove(id); } } if (_rawLocations.TryGetValue(id, out var value) && _cycle.TryGetValue(value, out List value2)) { if (flag && zDO.GetSector() == value && _rawObjects.TryGetValue(id, out ZDO value3) && value3 == zDO) { ClearViews(); return; } if (_rawObjects.TryGetValue(id, out ZDO value4)) { for (int i = 0; i < value2.Count; i++) { if (value2[i] == value4) { value2.RemoveAt(i); break; } } } } _rawLocations.Remove(id); _rawObjects.Remove(id); if (flag && _cycle.TryGetValue(zDO.GetSector(), out List value5)) { value5.Add(zDO); _rawLocations[id] = zDO.GetSector(); _rawObjects[id] = zDO; } ClearViews(); } private void ClearViews() { foreach (BroadView value in _views.Values) { value.Near.Clear(); value.Far.Clear(); _viewBuffers.Push(value); } _views.Clear(); } internal void FilterCell(Vector2s cell, Func accept, bool near, List result) { //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_0041: Unknown result type (might be due to invalid IL or missing references) //IL_0046: Unknown result type (might be due to invalid IL or missing references) _cell.Clear(); NativeCell(cell, default(SimulationDistance), _cell, null); foreach (ZDO item in _cell) { if (item.IsValid() && item.GetSector() == cell && (near || item.Distant) && accept(item)) { result.Add(item); } } } private bool Within(Vector2s origin, Vector2s cell, int radius, bool distant) { //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Unknown result type (might be due to invalid IL or missing references) if (_geometry == null) { return ZoneSystem.instance.ZonesWithinRadius(origin, cell, radius, distant); } return _geometry(origin, cell, radius, distant); } internal void Query(Vector2s sector, SimulationDistance distance, List near, List? distant = null) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0003: Unknown result type (might be due to invalid IL or missing references) Compose(null, sector, distance, near, distant); } internal void QueryCandidates(CandidateSubscription selection, Vector2s sector, SimulationDistance distance, List near, List? distant) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0003: Unknown result type (might be due to invalid IL or missing references) Compose(selection, sector, distance, near, distant); } private void Compose(CandidateSubscription? selection, Vector2s sector, SimulationDistance distance, List near, List? distant) { //IL_007d: Unknown result type (might be due to invalid IL or missing references) //IL_0069: Unknown result type (might be due to invalid IL or missing references) //IL_006a: Unknown result type (might be due to invalid IL or missing references) //IL_003d: 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_0198: Unknown result type (might be due to invalid IL or missing references) //IL_008b: Unknown result type (might be due to invalid IL or missing references) //IL_0186: 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_00b0: 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_00d9: Unknown result type (might be due to invalid IL or missing references) //IL_013e: Unknown result type (might be due to invalid IL or missing references) //IL_0140: Unknown result type (might be due to invalid IL or missing references) //IL_0113: 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_0158: 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) if (!Ready || _presence.HasJoinedPlayers != true) { return; } if (_world == null) { _world = ZDOMan.instance; } if (selection == null && _targetedCount == 0) { NativeScan(sector, distance, near, distant); return; } Index.AreaCapacity = CellBudget; Index.RefreshChanges(); if (selection == null) { ComposeBroad(sector, distance, near, distant); return; } int totalSimulationDistance = ((SimulationDistance)(ref distance)).TotalSimulationDistance; Vector2s val = default(Vector2s); for (int i = sector.x - totalSimulationDistance; i <= sector.x + totalSimulationDistance; i++) { for (int j = sector.y - totalSimulationDistance; j <= sector.y + totalSimulationDistance; j++) { ((Vector2s)(ref val))..ctor(i, j); int num = Math.Max(Math.Abs(i - sector.x), Math.Abs(j - sector.y)); bool flag = num <= ((SimulationDistance)(ref distance)).NearSimulationDistance && (((SimulationDistance)(ref distance)).IsClassic || Within(sector, val, ((SimulationDistance)(ref distance)).NearSimulationDistance, distant: false)); bool flag2 = num <= totalSimulationDistance && (!((SimulationDistance)(ref distance)).IsClassic || num > ((SimulationDistance)(ref distance)).NearSimulationDistance) && (((SimulationDistance)(ref distance)).IsClassic || Within(sector, val, totalSimulationDistance, distant: true)); if (flag || flag2) { _cell.Clear(); Index.Read(ZoneSystem.GetZonePos(val), 0, _cell, classic: true); if (flag) { selection.AppendCell(val, near: true, near); } else if (flag2 && selection.Kind != ScanKind.Nearby) { selection.AppendCell(val, near: false, distant ?? near); } } } } } private void ComposeBroad(Vector2s sector, SimulationDistance distance, List near, List? distant) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0092: 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_00de: Unknown result type (might be due to invalid IL or missing references) (Vector2s, int, int, bool) key = (sector, ((SimulationDistance)(ref distance)).NearSimulationDistance, ((SimulationDistance)(ref distance)).TotalSimulationDistance, ((SimulationDistance)(ref distance)).IsClassic); if (_views.TryGetValue(key, out BroadView value)) { near.AddRange(value.Near); (distant ?? near).AddRange(value.Far); return; } if (_views.Count >= CellBudget) { ClearViews(); } BroadView broadView = ((_viewBuffers.Count > 0) ? _viewBuffers.Pop() : new BroadView()); _visitedSectors.Clear(); AppendBroadCell(sector, broadView, near: true); for (int i = 1; i <= ((SimulationDistance)(ref distance)).NearSimulationDistance; i++) { AppendBroadRing(sector, i, ((SimulationDistance)(ref distance)).NearSimulationDistance, ((SimulationDistance)(ref distance)).IsClassic, broadView, near: true); } for (int j = ((!((SimulationDistance)(ref distance)).IsClassic) ? 1 : (((SimulationDistance)(ref distance)).NearSimulationDistance + 1)); j <= ((SimulationDistance)(ref distance)).TotalSimulationDistance; j++) { AppendBroadRing(sector, j, ((SimulationDistance)(ref distance)).TotalSimulationDistance, ((SimulationDistance)(ref distance)).IsClassic, broadView, near: false); } _views.Add(key, broadView); near.AddRange(broadView.Near); (distant ?? near).AddRange(broadView.Far); } private void AppendBroadRing(Vector2s center, int radius, int limit, bool classic, BroadView view, bool near) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0079: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0083: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Unknown result type (might be due to invalid IL or missing references) //IL_0031: Unknown result type (might be due to invalid IL or missing references) //IL_010b: Unknown result type (might be due to invalid IL or missing references) //IL_0093: 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_0045: Unknown result type (might be due to invalid IL or missing references) //IL_00b8: Unknown result type (might be due to invalid IL or missing references) //IL_00b9: Unknown result type (might be due to invalid IL or missing references) //IL_005b: Unknown result type (might be due to invalid IL or missing references) //IL_005c: Unknown result type (might be due to invalid IL or missing references) //IL_00d0: Unknown result type (might be due to invalid IL or missing references) //IL_006a: Unknown result type (might be due to invalid IL or missing references) //IL_00e8: Unknown result type (might be due to invalid IL or missing references) //IL_00e9: Unknown result type (might be due to invalid IL or missing references) //IL_00f8: Unknown result type (might be due to invalid IL or missing references) Vector2s cell = default(Vector2s); Vector2s cell2 = default(Vector2s); for (int i = center.x - radius; i <= center.x + radius; i++) { ((Vector2s)(ref cell))..ctor(i, center.y - radius); ((Vector2s)(ref cell2))..ctor(i, center.y + radius); bool flag = classic || Within(center, cell, limit, !near); if (flag) { AppendBroadCell(cell, view, near); } bool num; if (!near) { num = flag; } else { if (classic) { goto IL_0069; } num = Within(center, cell2, limit, distant: false); } if (!num) { continue; } goto IL_0069; IL_0069: AppendBroadCell(cell2, view, near); } Vector2s cell3 = default(Vector2s); Vector2s cell4 = default(Vector2s); for (int j = center.y - radius + 1; j <= center.y + radius - 1; j++) { ((Vector2s)(ref cell3))..ctor(center.x - radius, j); ((Vector2s)(ref cell4))..ctor(center.x + radius, j); bool flag2 = classic || Within(center, cell3, limit, !near); if (flag2) { AppendBroadCell(cell3, view, near); } bool num2; if (!near) { num2 = flag2; } else { if (classic) { goto IL_00f7; } num2 = Within(center, cell4, limit, distant: false); } if (!num2) { continue; } goto IL_00f7; IL_00f7: AppendBroadCell(cell4, view, near); } } private void AppendBroadCell(Vector2s cell, BroadView view, bool near) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_0028: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Unknown result type (might be due to invalid IL or missing references) if (!_visitedSectors.Add(ZoneSystem.SectorToIndex(cell).Sector)) { return; } _cell.Clear(); NativeCell(cell, default(SimulationDistance), _cell, null); Game instance = Game.instance; List list = (((Object)(object)instance == (Object)null) ? null : instance.PortalPrefabHash); foreach (ZDO item in _cell) { if (item.IsValid()) { if (near) { view.Near.Add(item); } else if (item.Distant && (list == null || !list.Contains(item.GetPrefab()))) { view.Far.Add(item); } } } } internal void IncludeLiveInstances(List near, List distant, IReadOnlyList positions) { //IL_0023: 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_00c1: Unknown result type (might be due to invalid IL or missing references) //IL_00d9: Unknown result type (might be due to invalid IL or missing references) //IL_00de: Unknown result type (might be due to invalid IL or missing references) //IL_00e2: Unknown result type (might be due to invalid IL or missing references) //IL_00e7: Unknown result type (might be due to invalid IL or missing references) //IL_00f8: Unknown result type (might be due to invalid IL or missing references) _seen.Clear(); foreach (ZDO item in near) { _seen.Add(item.m_uid); } foreach (ZDO item2 in distant) { _seen.Add(item2.m_uid); } foreach (KeyValuePair item3 in LiveInstances.Read.Invoke(ZNetScene.instance)) { ZDO key = item3.Key; if (!key.IsValid() || _seen.Contains(key.m_uid)) { continue; } foreach (Vector3 position in positions) { if (ZNetScene.InActiveArea(key.GetPosition(), position)) { _seen.Add(key.m_uid); near.Add(key); break; } } } } public void Dispose() { _index?.Dispose(); _index = null; foreach (CandidateSubscription value in _subscriptions.Values) { value.Dispose(); } _subscriptions.Clear(); _leases.Clear(); _targetedCount = 0; _cycle.Clear(); _buffers.Clear(); _cycleOrder.Clear(); _rawLocations.Clear(); _rawObjects.Clear(); _visitedSectors.Clear(); ClearViews(); _viewBuffers.Clear(); _scopes.Clear(); Scope.ClearActors(); if (Current == this) { Current = null; } } } internal static class WorldRecordChanges { private static readonly Harmony Hooks = new Harmony("heimkit.world-record-changes"); private static readonly List Consumers = new List(); private static readonly HashSet Pending = new HashSet(); private static bool _overflow; internal static void Add(WorldCandidateIndex consumer) { //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Expected O, but got Unknown if (Consumers.Count == 0) { try { HarmonyMethod val = new HarmonyMethod(typeof(WorldRecordChanges), "Changed", (Type[])null); foreach (MethodInfo item in NativeTargets()) { Hooks.Patch((MethodBase)item, (HarmonyMethod)null, val, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } } catch { Hooks.UnpatchSelf(); throw; } } Consumers.Add(consumer); } internal static IEnumerable NativeTargets() { MethodInfo[] methods = typeof(ZDO).GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); foreach (MethodInfo methodInfo in methods) { if (methodInfo.Name == "Deserialize" || methodInfo.Name == "SetPrefab" || methodInfo.Name == "InternalSetPosition" || methodInfo.Name == "SetOwnerInternal" || methodInfo.Name == "SetRotation" || methodInfo.Name == "SetDistant" || (methodInfo.Name == "Set" && methodInfo.GetParameters()[0].ParameterType == typeof(int)) || methodInfo.Name.StartsWith("Remove", StringComparison.Ordinal)) { yield return methodInfo; } } } internal static void Remove(WorldCandidateIndex consumer) { Consumers.Remove(consumer); if (Consumers.Count == 0) { Pending.Clear(); _overflow = false; Hooks.UnpatchSelf(); } } internal static void Dispatch() { //IL_0048: Unknown result type (might be due to invalid IL or missing references) //IL_004d: Unknown result type (might be due to invalid IL or missing references) //IL_0062: Unknown result type (might be due to invalid IL or missing references) if (_overflow) { foreach (WorldCandidateIndex consumer in Consumers) { consumer.Invalidate(); } } foreach (ZDOID item in Pending) { foreach (WorldCandidateIndex consumer2 in Consumers) { consumer2.Enqueue(item); } } Pending.Clear(); _overflow = false; } private static void Changed(ZDO __instance) { //IL_0046: 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) if (Consumers.Count != 0 && __instance != null && !((ZDOID)(ref __instance.m_uid)).IsNone()) { if (Pending.Count < 131072 || Pending.Contains(__instance.m_uid)) { Pending.Add(__instance.m_uid); } else { _overflow = true; } } } } internal static class WorldServices { internal static bool Network { get; private set; } internal static bool Activity { get; private set; } internal static bool World { get; private set; } internal static bool Terrain { get; private set; } internal static void Refresh() { ZNet instance = ZNet.instance; Network = (Object)(object)instance != (Object)null && instance.IsServer() && instance.IsDedicated() && ZDOMan.instance != null; Activity = Network && (Object)(object)Game.instance != (Object)null; World = Network && (Object)(object)ZNetScene.instance != (Object)null && ZRoutedRpc.instance != null; Terrain = World && (Object)(object)ZoneSystem.instance != (Object)null; } } } namespace HeimKit.Core.Scheduling { public interface IServerModule { string Name { get; } bool IsActive { get; } void Initialize(string gameVersion); void Tick(float now); void Shutdown(); } internal sealed class ModuleHost : IDisposable { private sealed class FailureIncident { internal string Stage = ""; internal Type OuterType; internal Type CauseType; internal MethodBase? Location; internal float Next; internal long Suppressed; } private readonly ManualLogSource _log; private readonly List _modules = new List(); private readonly Dictionary _failures = new Dictionary(); internal ModuleHost(ManualLogSource log) { _log = log; } internal void Register(Func create, string name) { try { _modules.Add(create()); } catch (Exception ex) { ManualLogSource log = _log; LogTopic lifecycle = CoreLogTopics.Lifecycle; Exception error = ex; DiagnosticLog.Write(log, name, lifecycle, "Disabled after configuration construction error.", default(LogFields), (LogLevel)2, verbose: false, error); } } internal void Initialize(string version) { _failures.Clear(); foreach (IServerModule module in _modules) { try { module.Initialize(version); } catch (Exception error) { Fail(module, error, "startup", 0f); } } } internal void Tick(float now) { foreach (IServerModule module in _modules) { try { module.Tick(now); if (_failures.Count > 0 && module.IsActive) { _failures.Remove(module); } } catch (Exception error) { Fail(module, error, "runtime", now); } } } private void Fail(IServerModule module, Exception error, string stage, float now) { ModuleCleanup.Run(_log, module.Name, module.Shutdown); Exception baseException = error.GetBaseException(); if (!_failures.TryGetValue(module, out FailureIncident value) || value.Stage != stage || value.OuterType != error.GetType() || value.CauseType != baseException.GetType() || !object.Equals(value.Location, baseException.TargetSite)) { _failures[module] = new FailureIncident { Stage = stage, OuterType = error.GetType(), CauseType = baseException.GetType(), Location = baseException.TargetSite, Next = now + 60f }; DiagnosticLog.Write(_log, module.Name, CoreLogTopics.Lifecycle, "Disabled after " + stage + " error.", default(LogFields), (LogLevel)2, verbose: false, error); return; } FailureIncident failureIncident = value; if (now < failureIncident.Next && now >= failureIncident.Next - 60f) { failureIncident.Suppressed++; return; } DiagnosticLog.Write(_log, module.Name, CoreLogTopics.Lifecycle, "Module remains disabled after an unresolved error", new(string, object)[4] { ("operation", stage), ("error_type", baseException.GetType().FullName), ("error_location", baseException.TargetSite), ("repeats_suppressed", failureIncident.Suppressed) }, (LogLevel)2); failureIncident.Next = now + 60f; failureIncident.Suppressed = 0L; } public void Dispose() { foreach (IServerModule module in _modules) { ModuleCleanup.Run(_log, module.Name, module.Shutdown); } _modules.Clear(); _failures.Clear(); ModuleScheduler.Current.Clear(); } } internal sealed class ModuleScheduler { private sealed class Schedule { internal float Next; internal float Interval; internal float Phase; internal bool Started; } private readonly Dictionary<(object Owner, string Work), Schedule> _work = new Dictionary<(object, string), Schedule>(); private readonly List<(object, string)> _remove = new List<(object, string)>(); private int _phase; internal static ModuleScheduler Current { get; } = new ModuleScheduler(); internal bool Due(object owner, string work, float now, float interval) { (object, string) key = (owner, work); if (!_work.TryGetValue(key, out Schedule value)) { value = new Schedule { Next = now, Interval = interval, Phase = (float)(_phase++ % 10) * 0.025f }; _work.Add(key, value); } if (!value.Started) { value.Started = true; value.Next = now + Math.Min(value.Phase, interval * 0.1f); } if (value.Interval != interval) { value.Interval = interval; value.Next = now + interval; } if (now < value.Next) { return false; } value.Next = now + interval; return true; } internal void Forget(object owner) { _remove.Clear(); foreach (var key in _work.Keys) { if (key.Owner == owner) { _remove.Add(key); } } foreach (var item in _remove) { _work.Remove(item); } _remove.Clear(); } internal void Clear() { _work.Clear(); _phase = 0; } } internal sealed class ScheduleToken { private float _next; internal bool Ready(float now) { return now >= _next; } internal void Postpone(float now, float interval) { _next = now + interval; } } } namespace HeimKit.Core.Prefabs { internal static class PrefabCollisionBounds { public static Bounds? Read(GameObject prefab) { //IL_000e: 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_0018: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0189: 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_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) //IL_00ad: Unknown result type (might be due to invalid IL or missing references) //IL_00b7: Unknown result type (might be due to invalid IL or missing references) //IL_0168: 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_00e3: 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_00f2: 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_0124: Unknown result type (might be due to invalid IL or missing references) //IL_0154: Unknown result type (might be due to invalid IL or missing references) //IL_0159: Unknown result type (might be due to invalid IL or missing references) Bounds result = new Bounds(Vector3.zero, Vector3.zero); Collider[] componentsInChildren = prefab.GetComponentsInChildren(true); Bounds bounds = default(Bounds); foreach (Collider collider in componentsInChildren) { if (collider.isTrigger) { continue; } Collider obj = collider; BoxCollider val = (BoxCollider)(object)((obj is BoxCollider) ? obj : null); if (val != null) { ((Bounds)(ref bounds))..ctor(val.center, val.size); } else { Collider obj2 = collider; SphereCollider val2 = (SphereCollider)(object)((obj2 is SphereCollider) ? obj2 : null); if (val2 != null) { ((Bounds)(ref bounds))..ctor(val2.center, Vector3.one * val2.radius * 2f); } else { Collider obj3 = collider; CapsuleCollider val3 = (CapsuleCollider)(object)((obj3 is CapsuleCollider) ? obj3 : null); if (val3 != null) { Vector3 val4 = Vector3.one * val3.radius * 2f; ((Vector3)(ref val4))[val3.direction] = Math.Max(val3.height, val3.radius * 2f); ((Bounds)(ref bounds))..ctor(val3.center, val4); } else { Collider obj4 = collider; MeshCollider val5 = (MeshCollider)(object)((obj4 is MeshCollider) ? obj4 : null); if (val5 == null || !((Object)(object)val5.sharedMesh != (Object)null)) { return null; } bounds = val5.sharedMesh.bounds; } } } Corners(bounds, delegate(Vector3 corner) { //IL_0026: 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_002c: Unknown result type (might be due to invalid IL or missing references) ((Bounds)(ref result)).Encapsulate(prefab.transform.InverseTransformPoint(((Component)collider).transform.TransformPoint(corner))); }); } return result; } public static void Corners(Bounds bounds, Action visit) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) for (int i = 0; i < 8; i++) { visit(Corner(bounds, i)); } } public static Vector3 Corner(Bounds bounds, int i) { //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0034: 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_0053: 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_005d: Unknown result type (might be due to invalid IL or missing references) return new Vector3(((i & 1) == 0) ? ((Bounds)(ref bounds)).min.x : ((Bounds)(ref bounds)).max.x, ((i & 2) == 0) ? ((Bounds)(ref bounds)).min.y : ((Bounds)(ref bounds)).max.y, ((i & 4) == 0) ? ((Bounds)(ref bounds)).min.z : ((Bounds)(ref bounds)).max.z); } } internal sealed class PrefabRegistry { internal const int Capacity = 65536; private ZNetScene? _scene; private readonly Dictionary _prefabs = new Dictionary(); private readonly Dictionary _objects = new Dictionary(); internal static PrefabRegistry Current { get; } = new PrefabRegistry(); internal PrefabCatalog Catalog(string name) { return new PrefabCatalog(this, name); } internal GameObject? Prefab(int hash) { if (!TryGet(hash, out PrefabInfo info)) { return null; } return info.Prefab; } internal GameObject? Prefab(string name) { return Prefab(StringExtensionMethods.GetStableHashCode(name)); } internal PrefabInfo Get(int hash) { if (!TryGet(hash, out PrefabInfo info)) { throw new InvalidOperationException("Native prefab is unavailable: " + hash); } return info; } internal bool TryGet(int hash, out PrefabInfo info) { if (_scene != ZNetScene.instance) { Clear(); _scene = ZNetScene.instance; } if (_prefabs.TryGetValue(hash, out info) && (Object)(object)info.Prefab != (Object)null) { return true; } ZNetScene? scene = _scene; GameObject val = ((scene != null) ? scene.GetPrefab(hash) : null); if ((Object)(object)val == (Object)null) { info = null; return false; } if (_prefabs.Count >= 65536) { throw new InvalidOperationException("Shared prefab classification capacity exceeded."); } info = Entry(hash); info.Prefab = val; Register(val, info); return true; } internal PrefabInfo Entry(int hash) { if (!_prefabs.TryGetValue(hash, out PrefabInfo value)) { if (_prefabs.Count >= 65536) { throw new InvalidOperationException("Shared prefab classification capacity exceeded."); } _prefabs.Add(hash, value = new PrefabInfo(null)); } return value; } internal void Observe(GameObject prefab) { if (!_objects.ContainsKey(prefab)) { PrefabInfo prefabInfo = Entry(StringExtensionMethods.GetStableHashCode(((Object)prefab).name)); prefabInfo.Prefab = prefab; Register(prefab, prefabInfo); } } private void Register(GameObject obj, PrefabInfo info) { //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_0027: Expected O, but got Unknown _objects[obj] = info; foreach (Transform item in obj.transform) { Transform val = item; Register(((Component)val).gameObject, info); } } internal static T? Component(GameObject? obj) where T : Component { if ((Object)(object)obj == (Object)null) { return default(T); } if (!Current._objects.TryGetValue(obj, out PrefabInfo value)) { return obj.GetComponent(); } return value.Component(obj); } internal static T? Component(Component? obj) where T : Component { return Component(((Object)(object)obj == (Object)null) ? null : obj.gameObject); } internal static T[] Children(GameObject obj, bool inactive = false) where T : Component { if (!Current._objects.TryGetValue(obj, out PrefabInfo value)) { return obj.GetComponentsInChildren(inactive); } return value.Children(obj, inactive); } internal static T[] Children(Component obj, bool inactive = false) where T : Component { return Children(obj.gameObject, inactive); } internal static T[] Components(Component obj) where T : Component { GameObject gameObject = obj.gameObject; if (!Current._objects.TryGetValue(gameObject, out PrefabInfo value)) { return gameObject.GetComponents(); } return value.Components(gameObject); } internal bool Solid(int hash) { PrefabInfo prefabInfo = Get(hash); if (!prefabInfo.SolidRead) { prefabInfo.SolidRead = true; Collider[] array = prefabInfo.Children(prefabInfo.Prefab, inactive: true); foreach (Collider val in array) { if (val.enabled && !val.isTrigger) { prefabInfo.Solid = true; break; } } } return prefabInfo.Solid; } internal Bounds? Bounds(GameObject obj) { PrefabInfo prefabInfo = Get(StringExtensionMethods.GetStableHashCode(((Object)obj).name)); if (!prefabInfo.BoundsRead) { prefabInfo.BoundsRead = true; prefabInfo.Bounds = PrefabCollisionBounds.Read(obj); } return prefabInfo.Bounds; } internal void Clear() { _prefabs.Clear(); _objects.Clear(); _scene = null; } } internal sealed class PrefabInfo { internal GameObject Prefab; internal readonly Dictionary<(string, Type), object?> Metadata = new Dictionary<(string, Type), object>(); private readonly Dictionary<(GameObject, Type), object?> _components = new Dictionary<(GameObject, Type), object>(); private readonly Dictionary<(GameObject, Type, bool), object> _children = new Dictionary<(GameObject, Type, bool), object>(); private readonly Dictionary<(GameObject, Type), object> _all = new Dictionary<(GameObject, Type), object>(); internal bool BoundsRead; internal bool SolidRead; internal bool Solid; internal Bounds? Bounds; internal string Name => ((Object)Prefab).name; internal PrefabInfo(GameObject prefab) { Prefab = prefab; } internal T? Component(GameObject obj) where T : Component { (GameObject, Type) key = (obj, typeof(T)); if (!_components.TryGetValue(key, out object value)) { value = (_components[key] = obj.GetComponent()); } return (T)value; } internal T[] Children(GameObject obj, bool inactive) where T : Component { (GameObject, Type, bool) key = (obj, typeof(T), inactive); if (!_children.TryGetValue(key, out object value)) { value = (_children[key] = obj.GetComponentsInChildren(inactive)); } return (T[])value; } internal T? Component() where T : Component { return Component(Prefab); } internal T[] Components(GameObject obj) where T : Component { (GameObject, Type) key = (obj, typeof(T)); if (!_all.TryGetValue(key, out object value)) { value = (_all[key] = obj.GetComponents()); } return (T[])value; } } internal sealed class PrefabCatalog { private readonly PrefabRegistry _registry; private readonly string _name; private readonly HashSet _selected = new HashSet(); internal int Count => _selected.Count; internal IEnumerable Keys => _selected; internal IEnumerable Values { get { foreach (int item in _selected) { yield return this[item]; } } } internal T this[int hash] { get { return (T)_registry.Entry(hash).Metadata[(_name, typeof(T))]; } set { _registry.Entry(hash).Metadata[(_name, typeof(T))] = value; _selected.Add(hash); } } internal PrefabCatalog(PrefabRegistry registry, string name) { _registry = registry; _name = name; } internal bool ContainsKey(int hash) { return _selected.Contains(hash); } internal bool TryGetValue(int hash, out T value) { if (_selected.Contains(hash) && _registry.Entry(hash).Metadata.TryGetValue((_name, typeof(T)), out object value2)) { value = (T)value2; return true; } value = default(T); return false; } internal void Add(int hash, T value) { this[hash] = value; } internal void Clear() { _selected.Clear(); } internal IEnumerator> GetEnumerator() { foreach (int item in _selected) { yield return new KeyValuePair(item, this[item]); } } } } namespace HeimKit.Core.Players { public sealed class ActivitySamples { private readonly Dictionary _seen = new Dictionary(); private readonly Dictionary _pending = new Dictionary(); private readonly HashSet _peers = new HashSet(); private readonly List _departed = new List(); private readonly List _chosen = new List(); private readonly List _ordered = new List(); private float _last = float.NegativeInfinity; public long TransitionsInterval { get; private set; } public long ReplacedPendingInterval { get; private set; } public int Pending => _pending.Count; public void Capture(float now, IEnumerable players) { if (now >= _last && now - _last < 0.5f) { return; } if (now < _last) { Reset(); } _last = now; HashSet peers = _peers; peers.Clear(); int num = 0; foreach (PlayerActivityView player in players) { if (num++ >= 4096) { break; } peers.Add(player.Peer); if (!_seen.TryGetValue(player.Peer, out PlayerActivityView value) || value.Session != player.Session || value.StateRevision != player.StateRevision) { if (value != null) { TransitionsInterval += ((value.Session != player.Session) ? 1 : Math.Max(1L, player.StateRevision - value.StateRevision)); } Queue(player); } _seen[player.Peer] = Copy(player, value); } _departed.Clear(); foreach (long key in _seen.Keys) { if (!peers.Contains(key)) { _departed.Add(key); } } foreach (long item in _departed) { PlayerActivityView playerActivityView = _seen[item]; playerActivityView.ObservedAt = now; playerActivityView.Known = false; playerActivityView.Alive = false; playerActivityView.Idle = false; playerActivityView.Reason = "disconnected_or_outside_observed_scope"; TransitionsInterval++; Queue(playerActivityView); _seen.Remove(item); } } private void Queue(PlayerActivityView current) { if (_pending.ContainsKey(current.Peer)) { ReplacedPendingInterval++; } if (_pending.Count < 4096 || _pending.ContainsKey(current.Peer)) { _pending[current.Peer] = Copy(current); } else { ReplacedPendingInterval++; } } public IReadOnlyList Drain(int maximum) { List chosen = _chosen; chosen.Clear(); _ordered.Clear(); foreach (PlayerActivityView value in _pending.Values) { _ordered.Add(value); } int num = Math.Min(Math.Max(0, maximum), _ordered.Count); for (int i = 0; i < 4; i++) { if (chosen.Count >= num) { break; } foreach (PlayerActivityView item in _ordered) { if ((item.Known ? 2 : 0) + ((!item.Idle) ? 1 : 0) == i) { chosen.Add(item); if (chosen.Count == num) { break; } } } } foreach (PlayerActivityView item2 in chosen) { _pending.Remove(item2.Peer); } return chosen; } public void IntervalReported() { TransitionsInterval = 0L; ReplacedPendingInterval = 0L; } public void Reset() { _seen.Clear(); _pending.Clear(); _ordered.Clear(); _chosen.Clear(); _last = float.NegativeInfinity; IntervalReported(); } private static PlayerActivityView Copy(PlayerActivityView p, PlayerActivityView? output = null) { if (output == null) { output = new PlayerActivityView(); } output.Peer = p.Peer; output.Name = p.Name; output.Session = p.Session; output.StateRevision = p.StateRevision; output.Known = p.Known; output.Alive = p.Alive; output.InBed = p.InBed; output.Idle = p.Idle; output.ObservedAt = p.ObservedAt; output.Reason = p.Reason; output.LastSignal = p.LastSignal; output.LastActivityAt = p.LastActivityAt; output.Recovery = p.Recovery; output.GraceRemaining = p.GraceRemaining; output.IdleSeconds = p.IdleSeconds; return output; } } public interface IPlayerActivityObservations { bool Reliable { get; } IReadOnlyList Snapshot(float now); } public interface IPlayerPresence { bool? HasConnectedPlayers { get; } int? ConnectedCount { get; } int? ReadyCount { get; } int? JoinedCount { get; } bool? HasJoinedPlayers { get; } IReadOnlyList Peers { get; } void Refresh(); void Clear(); } public sealed class ObservationCounters { private readonly Dictionary _counts = new Dictionary(); public void Hit(string key) { Add(key, 1L); } public void Add(string key, long amount) { _counts.TryGetValue(key, out var value); _counts[key] = value + amount; } public long Get(string key) { if (!_counts.TryGetValue(key, out var value)) { return 0L; } return value; } public string Format() { if (_counts.Count != 0) { return string.Join(",", from p in _counts orderby p.Key select p.Key + ":" + p.Value); } return "none_observed"; } } public sealed class PlayerActivityDiagnostics { private readonly ManualLogSource _log; private readonly Func _enabled; private readonly ActivitySamples _samples = new ActivitySamples(); private readonly DiagnosticBudget _budget = new DiagnosticBudget(); public PlayerActivityDiagnostics(ManualLogSource log, Func enabled) { _log = log; _enabled = enabled; } public void Players(float now, IEnumerable players) { if (!_enabled() || !DiagnosticLog.ServerActivity.Allowed) { Reset(); return; } _samples.Capture(now, players); if (!_budget.Reserve(now, "players", 1, countOmitted: false)) { return; } IReadOnlyList readOnlyList = _samples.Drain(6); if (readOnlyList.Count == 0) { return; } if (DiagnosticLog.DebugAvailable(_log, "PlayerActivity")) { DiagnosticLog.Write(_log, "PlayerActivity", CoreLogTopics.Scope, "Observed player activity transitions in the last minute.", new(string, object)[4] { ("transitions", _samples.TransitionsInterval), ("pending_states_replaced", _samples.ReplacedPendingInterval), ("pending_states", _samples.Pending), ("actor_samples", readOnlyList.Count) }, (LogLevel)32); } _samples.IntervalReported(); foreach (PlayerActivityView item in readOnlyList) { if (DiagnosticLog.DebugAvailable(_log, "PlayerActivity")) { DiagnosticLog.Write(_log, "PlayerActivity", PlayerLogTopics.Afk, item.Name + "'s activity state changed — " + item.Reason.Replace('_', ' ') + ".", new(string, object)[8] { ("peer", item.Peer), ("session", item.Session), ("state_revision", item.StateRevision), ("known", item.Known), ("alive", item.Alive), ("in_bed", item.InBed), ("inferred_idle", item.Idle), ("idle_observed_s", item.IdleSeconds) }, (LogLevel)32); } if (DiagnosticLog.VerboseConfigured && DiagnosticLog.DebugAvailable(_log, "PlayerActivity", verbose: true)) { DiagnosticLog.Write(_log, "PlayerActivity", PlayerLogTopics.Afk, "Activity evidence for " + item.Name + ".", new(string, object)[4] { ("last_observed_signal", item.LastSignal), ("grace_remaining_s_at_sample", item.GraceRemaining), ("state_sample_age_s", Math.Max(0f, now - item.ObservedAt)), ("recovery", item.Recovery) }, (LogLevel)32, verbose: true); } } } public void Reset() { _samples.Reset(); } } public sealed class PlayerActivityNotices { private readonly ManualLogSource _logger; private readonly Dictionary _idle = new Dictionary(); private readonly Dictionary _current = new Dictionary(); private readonly List> _prior = new List>(); public PlayerActivityNotices(ManualLogSource logger) { _logger = logger; } public void Observe(IReadOnlyList players, int? joinedCount) { Dictionary current = _current; current.Clear(); for (int i = 0; i < Math.Min(4096, players.Count); i++) { PlayerActivityView playerActivityView = players[i]; if (!current.ContainsKey(playerActivityView.Peer)) { current.Add(playerActivityView.Peer, playerActivityView); } } int num = 0; foreach (PlayerActivityView value2 in current.Values) { if (value2.Known && value2.Alive && value2.Idle) { num++; } } _prior.Clear(); foreach (KeyValuePair item in _idle) { _prior.Add(item); } foreach (KeyValuePair item2 in _prior) { current.TryGetValue(item2.Key, out var value); if (value == null || value.Session != item2.Value.Item1 || !value.Known || !value.Alive || !value.Idle) { _idle.Remove(item2.Key); string text = ((value == null) ? "disconnected or no longer observed" : ((value.Session != item2.Value.Item1) ? "player session changed" : ((!value.Known) ? "player data unavailable" : ((!value.Alive) ? "player died" : (value.InBed ? "entered a bed" : ((value.Reason == "join_or_observation_grace") ? "activity tracking restarted" : "activity detected")))))); Write(item2.Key, item2.Value.Item2, "left AFK status (" + text + ")", num, joinedCount); } } foreach (PlayerActivityView value3 in current.Values) { if (value3.Known && value3.Alive && value3.Idle) { bool num2 = !_idle.ContainsKey(value3.Peer); _idle[value3.Peer] = (value3.Session, value3.Name); if (num2) { Write(value3.Peer, value3.Name, "became AFK", num, joinedCount); } } } } public void Reset(string reason, int? joinedCount) { List> prior = _prior; prior.Clear(); foreach (KeyValuePair item in _idle) { prior.Add(item); } _idle.Clear(); foreach (KeyValuePair item2 in prior) { Write(item2.Key, item2.Value.Item2, "left AFK status (" + reason + ")", (joinedCount == 0) ? new int?(0) : ((int?)null), joinedCount); } } private void Write(long peer, string name, string transition, int? count, int? joinedCount) { name = new string((from c in (name ?? "").Take(128) select (!char.IsControl(c)) ? c : ' ').ToArray()).Trim(); string text = ((name.Length == 0) ? ("Peer " + peer) : ("Player \"" + name.Replace("\"", "\\\"") + "\" (peer " + peer + ")")); string text2 = (count.HasValue ? (count.Value + (joinedCount.HasValue ? (" of " + joinedCount.Value + " joined") : "; joined count unavailable")) : "unavailable (tracking stopped)"); DiagnosticLog.Write(_logger, "PlayerActivity", text + " " + transition + ". Current AFK players: " + text2 + ".", (LogLevel)16); } } public sealed class PlayerActivityService : IPlayerActivityObservations, IDisposable { public sealed class Lease : IDisposable { private bool _released; public PlayerActivityService Service { get; } internal Lease(PlayerActivityService service) { Service = service; } public void Dispose() { if (!_released) { _released = true; Service.Release(this); } } } private static PlayerActivityService? _current; private readonly PlayerActivityTracker _tracker; private readonly PlayerActivityOptions _options; private readonly Harmony _harmony = new Harmony("heimkit.player_activity"); private readonly PlayerRoutedMessages? _routedMessages; private IDisposable? _routedSubscription; private readonly Dictionary _containers = new Dictionary(); private int _craftingKey; private readonly List _actors = new List(); private readonly Dictionary _actorPool = new Dictionary(); private readonly HashSet _connected = new HashSet(); private readonly List _expiredPeers = new List(); private readonly List _recovered = new List(); private readonly Dictionary _equipment = new Dictionary(); private readonly Dictionary> _consumers = new Dictionary>(); private readonly IPlayerPresence _presence; private readonly Func _ready; private readonly Func> _readActors; private readonly Action _observer; private readonly PlayerActivityDiagnostics _diagnostics; private readonly PlayerActivityNotices _notices; private float _last = -1f; private ZDOMan? _world; private IReadOnlyList _views = Array.Empty(); private readonly ManualLogSource _logger; private readonly string _logName; private readonly Dictionary _incidents = new Dictionary(); private float _lastWarning = float.NegativeInfinity; public bool Reliable { get; private set; } public int Consumers => _consumers.Count; public long Samples { get; private set; } public bool Available { get { if (_ready()) { return _presence.HasJoinedPlayers == true; } return false; } } public ObservationCounters Hooks { get; } = new ObservationCounters(); public static bool Ready => WorldServices.Activity; private void Incident(float now, string operation, Exception error) { string key = operation + ":" + error.GetType().FullName; (float, long) value; bool flag = !_incidents.TryGetValue(key, out value); if (!flag && now >= value.Item1 && now - value.Item1 < 60f) { _incidents[key] = (value.Item1, value.Item2 + 1); return; } if (_incidents.Count >= 16 && flag) { _incidents.Clear(); } _incidents[key] = (now, 0L); Warn(now, "Activity observation unavailable; native eligibility retained and idle inference reset."); DiagnosticLog.Write(_logger, _logName, CoreLogTopics.Lifecycle, flag ? "Activity observation failed" : "Activity observation still unavailable", new(string, object)[3] { ("operation", operation), ("error_type", error.GetType().FullName), ("repeats_suppressed", value.Item2) }, (LogLevel)2, verbose: false, flag ? error : null); } public Lease Acquire(Func? debug = null) { if (_consumers.Count == 0) { try { _observer(obj: true); } catch { try { _observer(obj: false); } finally { Reset(); } throw; } } Lease lease = new Lease(this); _consumers.Add(lease, debug ?? ((Func)(() => false))); return lease; } public PlayerActivityService(PlayerActivityOptions options, ManualLogSource logger, IPlayerPresence presence, Func? ready = null, Func>? readActors = null, Action? observer = null, DebugLoggingPolicy? debugPolicy = null, PlayerRoutedMessages? routedMessages = null) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Expected O, but got Unknown PlayerActivityService playerActivityService = this; _logName = "PlayerActivity"; _options = options; _tracker = new PlayerActivityTracker(options); _logger = logger; _presence = presence; _ready = ready ?? ((Func)(() => Ready)); _readActors = readActors ?? ((Func>)(() => ReadActorsInto(playerActivityService._presence, playerActivityService._craftingKey, playerActivityService._actors, playerActivityService._equipment, playerActivityService._actorPool))); _notices = new PlayerActivityNotices(logger); _observer = observer ?? new Action(SetObserver); _routedMessages = routedMessages; _diagnostics = new PlayerActivityDiagnostics(logger, delegate { DebugLoggingPolicy? debugLoggingPolicy = debugPolicy; if (debugLoggingPolicy == null || !debugLoggingPolicy.Suppressed) { DebugLoggingPolicy? debugLoggingPolicy2 = debugPolicy; if (debugLoggingPolicy2 == null || !debugLoggingPolicy2.Enabled) { return playerActivityService.ConsumersDebugEnabled(); } return true; } return false; }); Hooks.Add("routed_hook_calls", 0L); Hooks.Add("routed_not_ready", 0L); Hooks.Add("authenticated_activity_signals", 0L); } private bool ConsumersDebugEnabled() { foreach (Func value in _consumers.Values) { if (value()) { return true; } } return false; } private void SetObserver(bool install) { //IL_0134: Unknown result type (might be due to invalid IL or missing references) //IL_0142: Expected O, but got Unknown if (_routedMessages != null) { if (!install) { try { _routedSubscription?.Dispose(); return; } finally { _routedSubscription = null; if (_current == this) { _current = null; } } } if (_current != null && _current != this) { throw new InvalidOperationException("An activity observer is already registered."); } _craftingKey = 438569 + ZSyncAnimation.GetHash("crafting"); _current = this; _routedSubscription = _routedMessages.Subscribe(Observe, delegate(Exception error) { Reset("routed observation unavailable"); Incident(Time.unscaledTime, "routed_observation", error); }); } else { if (!install) { if (_current != null && _current != this) { return; } try { _harmony.UnpatchSelf(); return; } finally { if (_current == this) { _current = null; } } } if (_current != null && _current != this) { throw new InvalidOperationException("An activity observer is already registered."); } _craftingKey = 438569 + ZSyncAnimation.GetHash("crafting"); _harmony.Patch((MethodBase)AccessTools.Method(typeof(ZRoutedRpc), "RPC_RoutedRPC", (Type[])null, (Type[])null), new HarmonyMethod(typeof(PlayerActivityService), "Observe", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); _current = this; } } private void Reset(string reason = "activity tracking stopped") { Reliable = false; _actors.Clear(); _actorPool.Clear(); _equipment.Clear(); _connected.Clear(); _expiredPeers.Clear(); _recovered.Clear(); _tracker.Clear(); _containers.Clear(); _views = Array.Empty(); _last = -1f; _diagnostics.Reset(); try { _notices.Reset(reason, _presence.JoinedCount); } catch (Exception error) { Incident(0f, "diagnostics:afk_notices", error); } } private void Release(Lease lease) { if (!_consumers.Remove(lease) || _consumers.Count != 0) { return; } try { _observer(obj: false); } finally { Reset(); _incidents.Clear(); _lastWarning = float.NegativeInfinity; } } public void Dispose() { bool flag = _consumers.Count > 0; _consumers.Clear(); try { if (flag) { _observer(obj: false); } } finally { Reset(); _incidents.Clear(); _lastWarning = float.NegativeInfinity; } } public void Tick(float now) { if (_consumers.Count == 0) { return; } Snapshot(now); try { _diagnostics.Players(now, _views); } catch (Exception error) { Incident(now, "diagnostics", error); } } public IReadOnlyList Snapshot(float now) { try { Sample(now); } catch (Exception error) { Reset("activity observations unavailable"); _last = now; Incident(now, "sampling", error); } return _views; } private void ReportAFK(float now) { try { _notices.Observe(_views, _presence.JoinedCount); } catch (Exception error) { Incident(now, "diagnostics:afk_notices", error); } } private IReadOnlyList Sample(float now) { //IL_0325: Unknown result type (might be due to invalid IL or missing references) if (_consumers.Count == 0 || !Available) { Reset((_presence.HasJoinedPlayers == false) ? "server empty" : "player or world observations unavailable"); return _views; } if (_world != ZDOMan.instance) { Reset("world changed"); _world = ZDOMan.instance; } if (_last >= 0f && now >= _last && now - _last < _options.Interval) { return _views; } _last = now; List list = _readActors(); Samples++; if (list.Count > 4096) { Warn(now, "Connected-player capacity exceeded; native behavior retained"); } HashSet connected = _connected; connected.Clear(); foreach (PlayerActivityObservation item in list) { connected.Add(item.Peer); } _expiredPeers.Clear(); foreach (long key in _containers.Keys) { if (!connected.Contains(key)) { _expiredPeers.Add(key); } } foreach (long expiredPeer in _expiredPeers) { _containers.Remove(expiredPeer); } _expiredPeers.Clear(); foreach (long key2 in _equipment.Keys) { if (!connected.Contains(key2)) { _expiredPeers.Add(key2); } } foreach (long expiredPeer2 in _expiredPeers) { _equipment.Remove(expiredPeer2); } _expiredPeers.Clear(); foreach (long key3 in _actorPool.Keys) { if (!connected.Contains(key3)) { _expiredPeers.Add(key3); } } foreach (long expiredPeer3 in _expiredPeers) { _actorPool.Remove(expiredPeer3); } foreach (PlayerActivityObservation item2 in list) { if (_containers.TryGetValue(item2.Peer, out (ZDOID, float) value)) { ZDO zDO = ZDOMan.instance.GetZDO(value.Item1); if (zDO != null && zDO.GetOwner() == item2.Peer && zDO.GetInt(ZDOVars.s_inUse, 0) != 0) { item2.Busy = true; } else if (now - value.Item2 < 10f && now >= value.Item2) { item2.Busy = true; } else { _containers.Remove(item2.Peer); } } } _views = _tracker.Update(now, list); Reliable = true; List recovered = _recovered; recovered.Clear(); foreach (string key4 in _incidents.Keys) { if (!key4.StartsWith("diagnostics:", StringComparison.Ordinal)) { recovered.Add(key4); } } if (recovered.Count > 0) { foreach (string item3 in recovered) { _incidents.Remove(item3); } DiagnosticLog.Write(_logger, _logName, "Activity observations recovered; idle grace restarted.", (LogLevel)16); } ReportAFK(now); return _views; } public static List ReadActors(IPlayerPresence presence, int craftingKey = 0) { return ReadActorsInto(presence, craftingKey, new List(), null); } internal static List ReadActorsInto(IPlayerPresence presence, int craftingKey, List result, Dictionary? equipment, Dictionary? pool = null) { //IL_0149: Unknown result type (might be due to invalid IL or missing references) //IL_014f: Unknown result type (might be due to invalid IL or missing references) //IL_0132: Unknown result type (might be due to invalid IL or missing references) //IL_0137: Unknown result type (might be due to invalid IL or missing references) //IL_016a: 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_0193: Unknown result type (might be due to invalid IL or missing references) //IL_0198: Unknown result type (might be due to invalid IL or missing references) //IL_01ad: Unknown result type (might be due to invalid IL or missing references) //IL_01db: 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_01e3: Unknown result type (might be due to invalid IL or missing references) //IL_01f0: 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_020b: Unknown result type (might be due to invalid IL or missing references) //IL_0210: 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) result.Clear(); if (!Ready) { return result; } for (int i = 0; i < presence.Peers.Count; i++) { ZNetPeer val = presence.Peers[i]; if (result.Count >= 4096) { result.Add(new PlayerActivityObservation { Peer = long.MinValue }); break; } PlayerActivityObservation value = null; pool?.TryGetValue(val.m_uid, out value); if (value == null) { value = new PlayerActivityObservation(); if (pool != null) { pool[val.m_uid] = value; } } value.Peer = val.m_uid; value.Name = val.m_playerName ?? ""; PlayerActivityObservation playerActivityObservation = value; PlayerActivityObservation playerActivityObservation2 = value; PlayerActivityObservation playerActivityObservation3 = value; bool flag = (value.Busy = false); bool flag3 = (playerActivityObservation3.InBed = flag); bool known = (playerActivityObservation2.Alive = flag3); playerActivityObservation.Known = known; PlayerActivityObservation playerActivityObservation4 = value; PlayerActivityObservation playerActivityObservation5 = value; PlayerActivityObservation playerActivityObservation6 = value; PlayerActivityObservation playerActivityObservation7 = value; float num = (value.Health = 0f); float num3 = (playerActivityObservation7.Heading = num); float num5 = (playerActivityObservation6.Z = num3); float x = (playerActivityObservation5.Y = num5); playerActivityObservation4.X = x; value.Equipment = ""; value.Emote = 0; if (!val.IsReady()) { value.Character = ""; value.NativeCharacter = ZDOID.None; result.Add(value); continue; } if (value.NativeCharacter != val.m_characterID || value.Character.Length == 0) { value.NativeCharacter = val.m_characterID; value.Character = ((object)Unsafe.As(ref val.m_characterID)/*cast due to .constrained prefix*/).ToString(); } result.Add(value); if (val.m_characterID == ZDOID.None) { continue; } ZDO zDO = ZDOMan.instance.GetZDO(val.m_characterID); if (zDO == null || !zDO.IsValid() || zDO.GetOwner() != val.m_uid) { continue; } Vector3 position = zDO.GetPosition(); value.X = position.x; value.Y = position.y; value.Z = position.z; PlayerActivityObservation playerActivityObservation8 = value; Quaternion rotation = zDO.GetRotation(); playerActivityObservation8.Heading = ((Quaternion)(ref rotation)).eulerAngles.y; value.Health = zDO.GetFloat(ZDOVars.s_health, float.NaN); value.Known = PlayerActivityTracker.Finite(value.Health) && PlayerActivityTracker.Finite(value.X) && PlayerActivityTracker.Finite(value.Y) && PlayerActivityTracker.Finite(value.Z) && PlayerActivityTracker.Finite(value.Heading); value.Alive = value.Health > 0f && !zDO.GetBool(ZDOVars.s_dead, false); value.InBed = zDO.GetBool(ZDOVars.s_inBed, false); value.Busy = craftingKey != 0 && zDO.GetInt(craftingKey, 0) != 0; if (equipment != null) { if (!equipment.TryGetValue(val.m_uid, out PlayerEquipment value2)) { value2 = (equipment[val.m_uid] = new PlayerEquipment()); } value.Equipment = value2.Read(zDO); } else { value.Equipment = $"{zDO.GetInt(ZDOVars.s_rightItem, 0)}:{zDO.GetInt(ZDOVars.s_leftItem, 0)}:{zDO.GetInt(ZDOVars.s_chestItem, 0)}:{zDO.GetInt(ZDOVars.s_helmetItem, 0)}:{zDO.GetInt(ZDOVars.s_legItem, 0)}:{zDO.GetInt(ZDOVars.s_shoulderItem, 0)}:{zDO.GetInt(ZDOVars.s_utilityItem, 0)}:{zDO.GetInt(ZDOVars.s_rightBackItem, 0)}:{zDO.GetInt(ZDOVars.s_leftBackItem, 0)}"; } value.Emote = zDO.GetInt(ZDOVars.s_emoteID, 0); } return result; } private static void Observe(ZRpc rpc, ZPackage pkg) { //IL_004a: Unknown result type (might be due to invalid IL or missing references) //IL_004f: Unknown result type (might be due to invalid IL or missing references) //IL_0066: Unknown result type (might be due to invalid IL or missing references) //IL_00bd: Unknown result type (might be due to invalid IL or missing references) //IL_00bf: Unknown result type (might be due to invalid IL or missing references) //IL_011e: Unknown result type (might be due to invalid IL or missing references) //IL_011f: Unknown result type (might be due to invalid IL or missing references) //IL_0149: Unknown result type (might be due to invalid IL or missing references) PlayerActivityService current = _current; if (current == null) { return; } current.Hooks.Hit("routed_hook_calls"); if (!current.Available) { current.Hooks.Hit("routed_not_ready"); return; } try { ZNetPeer val = PlayerPeerLookup.Ready(current._presence.Peers, rpc); if (val == null || val.m_characterID == ZDOID.None) { return; } ZDO zDO = ZDOMan.instance.GetZDO(val.m_characterID); if (zDO != null && zDO.IsValid() && zDO.GetOwner() == val.m_uid && RoutedActivityReader.TryRead(pkg, val.m_uid, out var target, out var method) && RoutedActivityReader.IsActivity(method) && (method != StringExtensionMethods.GetStableHashCode("SetTrigger") || !(target != val.m_characterID))) { current.Hooks.Hit("authenticated_activity_signals"); current._tracker.Signal(val.m_uid, Time.unscaledTime, RoutedActivityReader.ActivityName(method)); if (current.Reliable) { current.ReportAFK(Time.unscaledTime); } if (method == StringExtensionMethods.GetStableHashCode("RPC_RequestOpen") && target != ZDOID.None && current._containers.Count < 4096) { current._containers[val.m_uid] = (target, Time.unscaledTime); } } } catch (Exception error) { current.Reset("activity observations unavailable"); current.Incident(Time.unscaledTime, "routed_observation", error); } } private void Warn(float now, string message) { if (!(now >= _lastWarning) || !(now - _lastWarning < 300f)) { _lastWarning = now; DiagnosticLog.Write(_logger, _logName, message, (LogLevel)4); } } } public sealed class PlayerActivityTracker { private sealed class Session { public string Character = ""; public float Joined; public float LastActivity; public float LastSample; public PlayerActivityObservation? Anchor; public PlayerActivityObservation? Previous; public PlayerActivityView View = new PlayerActivityView(); public bool WasReliable; } private readonly Dictionary _sessions = new Dictionary(); private readonly PlayerActivityOptions _options; private long _sessionSequence; private readonly HashSet _connected = new HashSet(); private readonly List _departed = new List(); private PlayerActivityView[] _views = Array.Empty(); public PlayerActivityTracker(PlayerActivityOptions options) { _options = options; } public IReadOnlyList Update(float now, IReadOnlyList observations) { HashSet connected = _connected; connected.Clear(); bool flag = false; for (int i = 0; i < observations.Count; i++) { PlayerActivityObservation playerActivityObservation = observations[i]; if (!connected.Add(playerActivityObservation.Peer)) { continue; } if (!_sessions.TryGetValue(playerActivityObservation.Peer, out Session value)) { value = new Session(); flag = true; value.View.Session = ++_sessionSequence; _sessions.Add(playerActivityObservation.Peer, value); } bool flag2 = value.Character != playerActivityObservation.Character || value.Previous == null || !value.WasReliable || now < value.LastSample || now - value.LastSample > _options.Interval * 3f + 1f; if (flag2) { value.View.Recovery = ((value.Previous == null) ? "join" : ((value.Character != playerActivityObservation.Character) ? "character_changed" : ((!value.WasReliable) ? "unreliable_actor_recovery" : ((now < value.LastSample) ? "clock_rollback" : "observation_gap")))); value.View.LastSignal = "none_observed"; value.Joined = (value.LastActivity = now); value.Anchor = Copy(playerActivityObservation, value.Anchor); } string text = (flag2 ? "join_or_observation_grace" : "no_observed_activity"); bool flag3 = playerActivityObservation.Known && Finite(now) && Finite(playerActivityObservation.X) && Finite(playerActivityObservation.Y) && Finite(playerActivityObservation.Z) && Finite(playerActivityObservation.Heading) && Finite(playerActivityObservation.Health); if (!flag3 || !playerActivityObservation.Alive) { value.LastActivity = now; text = ((!flag3) ? "unknown_actor_data" : "dead_or_loading"); } else if (playerActivityObservation.InBed || playerActivityObservation.Busy) { value.LastActivity = now; text = (playerActivityObservation.InBed ? "in_bed" : "station_or_container_use"); value.View.LastSignal = text; } else if (!flag2 && value.Anchor != null && value.Previous != null) { double num = playerActivityObservation.X - value.Anchor.X; double num2 = playerActivityObservation.Y - value.Anchor.Y; double num3 = playerActivityObservation.Z - value.Anchor.Z; double num4 = Math.Abs(playerActivityObservation.Heading - value.Anchor.Heading) % 360f; if (num4 > 180.0) { num4 = 360.0 - num4; } if (num * num + num2 * num2 + num3 * num3 >= (double)(_options.Movement * _options.Movement) || num4 >= (double)_options.Look || playerActivityObservation.Equipment != value.Previous.Equipment || playerActivityObservation.Emote != value.Previous.Emote || value.Previous.InBed) { value.LastActivity = now; value.Anchor = Copy(playerActivityObservation, value.Anchor); text = "movement_rotation_equipment_or_emote"; value.View.LastSignal = ((playerActivityObservation.Equipment != value.Previous.Equipment) ? "equipment_changed" : ((playerActivityObservation.Emote != value.Previous.Emote) ? "emote_changed" : (value.Previous.InBed ? "left_bed" : ((num4 >= (double)_options.Look) ? "body_rotation" : "movement")))); } } if (playerActivityObservation.Busy || playerActivityObservation.InBed || !flag3 || !playerActivityObservation.Alive) { value.Anchor = Copy(playerActivityObservation, value.Anchor); } value.Character = playerActivityObservation.Character; value.LastSample = now; value.Previous = Copy(playerActivityObservation, value.Previous); value.WasReliable = flag3 && playerActivityObservation.Alive; PlayerActivityView view = value.View; bool known = view.Known; bool alive = view.Alive; bool inBed = view.InBed; bool idle = view.Idle; view.Peer = playerActivityObservation.Peer; view.Name = playerActivityObservation.Name; view.Known = flag3; view.Alive = playerActivityObservation.Alive; view.InBed = flag3 && playerActivityObservation.Alive && playerActivityObservation.InBed; view.X = playerActivityObservation.X; view.Y = playerActivityObservation.Y; view.Z = playerActivityObservation.Z; view.IdleSeconds = Math.Max(0f, now - value.LastActivity); view.Idle = flag3 && playerActivityObservation.Alive && !playerActivityObservation.InBed && !playerActivityObservation.Busy && now - value.Joined >= _options.Grace && view.IdleSeconds >= _options.Timeout; view.Reason = (view.Idle ? "inferred_idle" : text); view.ObservedAt = now; view.LastActivityAt = value.LastActivity; view.GraceRemaining = Math.Max(0f, _options.Grace - (now - value.Joined)); if (flag2 || known != view.Known || alive != view.Alive || inBed != view.InBed || idle != view.Idle) { view.StateRevision++; } } _departed.Clear(); foreach (long key in _sessions.Keys) { if (!connected.Contains(key)) { _departed.Add(key); } } foreach (long item in _departed) { _sessions.Remove(item); flag = true; } if (flag) { _views = new PlayerActivityView[_sessions.Count]; int num5 = 0; foreach (Session value2 in _sessions.Values) { _views[num5++] = value2.View; } } return _views; } public void Signal(long peer, float now, string signal = "routed_activity") { if (_sessions.TryGetValue(peer, out Session value) && Finite(now)) { value.LastActivity = now; value.Anchor = ((value.Previous == null) ? null : Copy(value.Previous, value.Anchor)); if (value.View.Idle) { value.View.StateRevision++; } value.View.ObservedAt = now; value.View.LastSignal = signal; value.View.LastActivityAt = now; value.View.Idle = false; value.View.IdleSeconds = 0f; value.View.Reason = "observed_routed_activity"; } } public IReadOnlyList Update(float now, IEnumerable observations) { return Update(now, (observations as IReadOnlyList) ?? new List(observations)); } private static PlayerActivityObservation Copy(PlayerActivityObservation input, PlayerActivityObservation? output) { if (output == null) { output = new PlayerActivityObservation(); } output.Peer = input.Peer; output.Name = input.Name; output.Character = input.Character; output.Known = input.Known; output.Alive = input.Alive; output.InBed = input.InBed; output.Busy = input.Busy; output.X = input.X; output.Y = input.Y; output.Z = input.Z; output.Heading = input.Heading; output.Health = input.Health; output.Equipment = input.Equipment; output.Emote = input.Emote; return output; } public void Clear() { _sessions.Clear(); _connected.Clear(); _departed.Clear(); _views = Array.Empty(); } public static bool Finite(float value) { if (!float.IsNaN(value)) { return !float.IsInfinity(value); } return false; } } public sealed class PlayerConnectionNotices { private readonly ManualLogSource _logger; private readonly Dictionary _sessions = new Dictionary(); private readonly HashSet _present = new HashSet(); private readonly List _departed = new List(); public PlayerConnectionNotices(ManualLogSource logger) { _logger = logger; } public void Observe(IReadOnlyList connected, IEnumerable joined) { _present.Clear(); foreach (ZNetPeer item in connected) { _present.Add(item); } _departed.Clear(); foreach (KeyValuePair session in _sessions) { if (!_present.Contains(session.Key)) { _departed.Add(session.Key); } } foreach (ZNetPeer item2 in _departed) { (long, string, string) tuple = _sessions[item2]; _sessions.Remove(item2); Write(tuple.Item1, tuple.Item2, "disconnected"); } foreach (ZNetPeer item3 in joined) { (long, string, string) value; bool flag = _sessions.TryGetValue(item3, out value); if (!flag || !(value.Item3 == item3.m_playerName)) { string text = CleanName(item3.m_playerName); if (flag && text.Length == 0) { text = value.Item2; } long num; if (flag) { (num, _, _) = value; } else { num = item3.m_uid; } long num2 = num; _sessions[item3] = (num2, text, item3.m_playerName); if (!flag) { Write(num2, text, "connected"); } } } } private static string CleanName(string? name) { return new string((from c in (name ?? "").Take(128) select (!char.IsControl(c)) ? c : ' ').ToArray()).Trim(); } private void Write(long id, string name, string action) { string text = ((name.Length == 0) ? ("Peer " + id) : ("Player \"" + name.Replace("\"", "\\\"") + "\" (peer " + id + ")")); DiagnosticLog.Write(_logger, "PlayerPresence", text + " " + action + ".", (LogLevel)16); } public void Clear() { _sessions.Clear(); _present.Clear(); _departed.Clear(); } } internal sealed class PlayerEquipment { private (int, int, int, int, int, int, int, int, int) _items; private ZDOID _character; private string? _text; internal string Read(ZDO actor) { //IL_00ad: Unknown result type (might be due to invalid IL or missing references) //IL_00b2: Unknown result type (might be due to invalid IL or missing references) //IL_0081: 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) (int, int, int, int, int, int, int, int, int) tuple = (actor.GetInt(ZDOVars.s_rightItem, 0), actor.GetInt(ZDOVars.s_leftItem, 0), actor.GetInt(ZDOVars.s_chestItem, 0), actor.GetInt(ZDOVars.s_helmetItem, 0), actor.GetInt(ZDOVars.s_legItem, 0), actor.GetInt(ZDOVars.s_shoulderItem, 0), actor.GetInt(ZDOVars.s_utilityItem, 0), actor.GetInt(ZDOVars.s_rightBackItem, 0), actor.GetInt(ZDOVars.s_leftBackItem, 0)); if (_text == null || _character != actor.m_uid || !_items.Equals(tuple)) { _items = tuple; _character = actor.m_uid; _text = $"{tuple.Item1}:{tuple.Item2}:{tuple.Item3}:{tuple.Item4}:{tuple.Item5}:{tuple.Item6}:{tuple.Item7}:{tuple.Rest.Item1}:{tuple.Rest.Item2}"; } return _text; } } public static class PlayerLogTopics { public static readonly LogTopic Presence = new LogTopic("presence"); public static readonly LogTopic Afk = new LogTopic("afk"); } internal static class PlayerPeerLookup { public static ZNetPeer? Ready(IReadOnlyList peers, ZRpc rpc) { for (int i = 0; i < peers.Count; i++) { if (peers[i].m_rpc == rpc) { if (!peers[i].IsReady()) { return null; } return peers[i]; } } return null; } } public sealed class PlayerPresence : IPlayerPresence { private readonly Func?> _read; private readonly HashSet _joined = new HashSet(); private readonly List _departed = new List(); private ZDOMan? _world; private readonly PlayerConnectionNotices? _connections; public IReadOnlyList Peers { get; private set; } = Array.Empty(); public int? ConnectedCount { get; private set; } public int? ReadyCount { get; private set; } public int? JoinedCount { get; private set; } public bool? HasConnectedPlayers { get { if (!ConnectedCount.HasValue) { return null; } return ConnectedCount.Value > 0; } } public bool? HasJoinedPlayers { get { if (!JoinedCount.HasValue) { return null; } return JoinedCount.Value > 0; } } public PlayerPresence(Func?>? read = null, PlayerConnectionNotices? connections = null) { _read = read ?? new Func>(ReadPeers); _connections = connections; } private IReadOnlyList? ReadPeers() { if ((Object)(object)ZNet.instance == (Object)null) { return null; } List peers = ZNet.instance.GetPeers(); if (peers.Count == Peers.Count) { bool flag = true; for (int i = 0; i < peers.Count; i++) { if (peers[i] != Peers[i]) { flag = false; break; } } if (flag) { return Peers; } } return peers.ToArray(); } public void Refresh() { try { IReadOnlyList readOnlyList = _read(); if (readOnlyList == null) { Unavailable(); return; } if (_world != ZDOMan.instance) { _joined.Clear(); _connections?.Clear(); _world = ZDOMan.instance; } _departed.Clear(); foreach (ZNetPeer item in _joined) { if (!readOnlyList.Contains(item) || !item.IsReady()) { _departed.Add(item); } } foreach (ZNetPeer item2 in _departed) { _joined.Remove(item2); } int num = 0; foreach (ZNetPeer item3 in readOnlyList) { if (item3.IsReady()) { num++; if (!((ZDOID)(ref item3.m_characterID)).IsNone()) { _joined.Add(item3); } } } Peers = readOnlyList; ConnectedCount = readOnlyList.Count; ReadyCount = num; JoinedCount = _joined.Count; _connections?.Observe(readOnlyList, _joined); } catch { Unavailable(); } } public void Clear() { Unavailable(); _joined.Clear(); _departed.Clear(); _connections?.Clear(); _world = null; } private void Unavailable() { Peers = Array.Empty(); ConnectedCount = null; ReadyCount = null; JoinedCount = null; } } public sealed class PlayerPresenceDiagnostics { private readonly ManualLogSource _logger; private bool? _lastKnownOccupied; private bool _emptyAnnounced; private bool _activeAnnounced; public PlayerPresenceDiagnostics(ManualLogSource logger) { _logger = logger; } public void Observe(bool? occupied, bool allEnabledPaused, bool allEnabledActive = true) { if (!occupied.HasValue) { return; } bool flag = occupied != _lastKnownOccupied; _lastKnownOccupied = occupied; if (occupied.Value) { if (flag) { _activeAnnounced = false; } if (allEnabledActive && !_activeAnnounced) { _activeAnnounced = true; DiagnosticLog.Write(_logger, "PlayerPresence", "Players have joined the world; all enabled features are active.", (LogLevel)16); } } else { if (flag) { _emptyAnnounced = false; } if (allEnabledPaused && !_emptyAnnounced) { _emptyAnnounced = true; DiagnosticLog.Write(_logger, "PlayerPresence", "No players have joined the world; all features are inactive until a player joins.", (LogLevel)16); } } } } public sealed class PlayerPresenceEvents : IDisposable { private sealed class Registration : IDisposable { private PlayerPresenceEvents? _owner; public readonly Action Changed; public readonly Action Failed; public readonly Func? EmptyPaused; public readonly Func? Active; public readonly Func? ServerReady; public Registration(PlayerPresenceEvents owner, Action changed, Action failed, Func? emptyPaused = null, Func? active = null, Func? serverReady = null) { _owner = owner; Changed = changed; Failed = failed; EmptyPaused = emptyPaused; Active = active; ServerReady = serverReady; } public void Dispose() { PlayerPresenceEvents owner = _owner; _owner = null; if (owner != null) { if (owner.Occupied == true && Active != null && !Active()) { owner._activationFailed = true; } owner._registrations.Remove(this); owner._snapshot = new Registration[owner._registrations.Count]; owner._registrations.CopyTo(owner._snapshot); } } } private readonly ManualLogSource _logger; private readonly PlayerPresenceDiagnostics _notices; private bool _emptyPauseFailed; private bool _activationFailed; private readonly HashSet _registrations = new HashSet(); private Registration[] _snapshot = Array.Empty(); public bool? Occupied { get; private set; } public int Subscribers => _registrations.Count; public PlayerPresenceEvents(ManualLogSource logger) { _logger = logger; _notices = new PlayerPresenceDiagnostics(logger); } public IDisposable Subscribe(Action changed, Action failed, Func? emptyPaused = null, Func? active = null, Func? serverReady = null) { Registration registration = new Registration(this, changed, failed, emptyPaused, active, serverReady); _registrations.Add(registration); _snapshot = new Registration[_registrations.Count]; _registrations.CopyTo(_snapshot); Notify(registration); return registration; } public void Observe(bool? occupied) { _notices.Observe(occupied, allEnabledPaused: false, allEnabledActive: false); if (occupied != Occupied) { if (occupied == true) { _emptyPauseFailed = false; } if (occupied == false) { _activationFailed = false; } Occupied = occupied; Registration[] snapshot = _snapshot; foreach (Registration registration in snapshot) { Notify(registration); } } ReportProcessing(); } public void ReportProcessing() { bool allEnabledPaused = !_emptyPauseFailed; bool allEnabledActive = !_activationFailed; foreach (Registration registration in _registrations) { if (registration.ServerReady != null && !registration.ServerReady()) { return; } if (registration.EmptyPaused != null && !registration.EmptyPaused()) { allEnabledPaused = false; } if (registration.Active != null && !registration.Active()) { allEnabledActive = false; } } _notices.Observe(Occupied, allEnabledPaused, allEnabledActive); } private void Notify(Registration registration) { if (!_registrations.Contains(registration)) { return; } try { registration.Changed(Occupied); } catch (Exception obj) { if (Occupied != true) { _emptyPauseFailed = true; } else { _activationFailed = true; } registration.Dispose(); try { registration.Failed(obj); } catch (Exception ex) { ManualLogSource logger = _logger; LogTopic lifecycle = CoreLogTopics.Lifecycle; Exception error = ex; DiagnosticLog.Write(logger, "PlayerPresence", lifecycle, "Consumer failure handling failed; other subscribers continue.", default(LogFields), (LogLevel)2, verbose: false, error); } } } public void Dispose() { Registration[] snapshot = _snapshot; for (int i = 0; i < snapshot.Length; i++) { snapshot[i].Dispose(); } Occupied = null; } } public sealed class PlayerProcessingNotices { private readonly ManualLogSource _logger; private readonly string _name; private readonly Func _debug; private bool _running; private string? _pauseReason; public bool IsServerReady { get; private set; } public bool IsRunning => _running; public bool IsEmptyPaused { get; private set; } public PlayerProcessingNotices(ManualLogSource logger, string name, Func? debug = null) { _logger = logger; _name = name; _debug = debug ?? ((Func)(() => false)); } public void ServerReady() { if (!IsServerReady) { IsServerReady = true; DiagnosticLog.Write(_logger, _name, "Ready.", (LogLevel)16); } } public void EmptyPaused() { bool num = !IsEmptyPaused; _running = false; _pauseReason = "no players have joined the world"; IsEmptyPaused = true; if (num) { Debug("Processing inactive: no players have joined the world."); } } public void Ready() { if (!_running) { _running = true; _pauseReason = null; IsEmptyPaused = false; Debug("Processing active."); } } public void Paused(string reason) { if (_running || !(_pauseReason == reason)) { _running = false; _pauseReason = reason; IsEmptyPaused = false; if (_debug() && DiagnosticLog.DebugAvailable(_logger, _name)) { Debug("Processing inactive: " + reason + "."); } } } public void Unavailable(string reason) { Paused(reason); } private void Debug(string message) { if (_debug()) { DiagnosticLog.Write(_logger, _name, message, (LogLevel)32); } } public void Reset() { IsServerReady = false; _running = false; _pauseReason = null; IsEmptyPaused = false; } } public sealed class PlayerRoutedMessages : IDisposable { private sealed class Subscription : IDisposable { private readonly PlayerRoutedMessages _owner; public Action Observed { get; } public Action Failed { get; } public Subscription(PlayerRoutedMessages owner, Action observed, Action failed) { _owner = owner; Observed = observed; Failed = failed; } public void Dispose() { _owner.Remove(this); } } private static PlayerRoutedMessages? _current; private readonly Harmony _harmony = new Harmony("heimkit.player_routed_messages"); private readonly List _subscriptions = new List(); private Subscription[] _snapshot = Array.Empty(); public IDisposable Subscribe(Action observed, Action failed) { //IL_005a: Unknown result type (might be due to invalid IL or missing references) //IL_0068: Expected O, but got Unknown if (_subscriptions.Count == 0) { if (_current != null && _current != this) { throw new InvalidOperationException("A routed-message observer is already active."); } try { _current = this; _harmony.Patch((MethodBase)AccessTools.Method(typeof(ZRoutedRpc), "RPC_RoutedRPC", (Type[])null, (Type[])null), new HarmonyMethod(typeof(PlayerRoutedMessages), "Observe", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } catch { _harmony.UnpatchSelf(); _current = null; throw; } } Subscription subscription = new Subscription(this, observed, failed); _subscriptions.Add(subscription); _snapshot = _subscriptions.ToArray(); return subscription; } private static void Observe(ZRpc rpc, ZPackage pkg) { PlayerRoutedMessages current = _current; if (current == null) { return; } Subscription[] snapshot = current._snapshot; foreach (Subscription subscription in snapshot) { if (!current._subscriptions.Contains(subscription)) { continue; } int pos = pkg.GetPos(); try { subscription.Observed(rpc, pkg); } catch (Exception obj) { subscription.Dispose(); try { subscription.Failed(obj); } catch { } } finally { pkg.SetPos(pos); } } } private void Remove(Subscription subscription) { if (!_subscriptions.Remove(subscription)) { return; } _snapshot = _subscriptions.ToArray(); if (_subscriptions.Count != 0) { return; } try { _harmony.UnpatchSelf(); } finally { if (_current == this) { _current = null; } } } public void Dispose() { _subscriptions.Clear(); _snapshot = Array.Empty(); try { _harmony.UnpatchSelf(); } finally { if (_current == this) { _current = null; } } } } public sealed class PlayerServices : IDisposable { private readonly DebugLoggingPolicy _debug; private readonly ManualLogSource _logger; private bool _debugReported; public IPlayerPresence Presence { get; } public PlayerPresenceEvents Events { get; } public PlayerActivityService Activity { get; } public PlayerRoutedMessages RoutedMessages { get; } = new PlayerRoutedMessages(); public static bool Ready => PlayerActivityService.Ready; public PlayerServices(ConfigFile config, ManualLogSource logger) { Presence = new PlayerPresence(null, new PlayerConnectionNotices(logger)); Events = new PlayerPresenceEvents(logger); PlayerActivitySettings playerActivitySettings = new PlayerActivitySettings(config, logger); _debug = playerActivitySettings.DebugLogging; _logger = logger; Activity = new PlayerActivityService(playerActivitySettings.Options(), logger, Presence, null, null, null, _debug, RoutedMessages); } public void Tick(float now) { if (!_debugReported) { _debugReported = true; _debug.ReportStartup(_logger, "PlayerActivity", Activity.Consumers > 0); } Presence.Refresh(); DiagnosticLog.ObservePlayers(Presence.HasConnectedPlayers); Events.Observe(Presence.HasJoinedPlayers); Activity.Tick(now); } public void Dispose() { try { Events.Dispose(); } finally { try { Activity.Dispose(); } finally { try { RoutedMessages.Dispose(); } finally { Presence.Clear(); } } } } } public static class RoutedActivityReader { private static readonly string[] Names = new string[9] { "Say", "ChatMessage", "SetTrigger", "RPC_Damage", "RPC_Repair", "RPC_Remove", "RPC_RequestOpen", "RPC_RequestStack", "RPC_RequestTakeAll" }; public static bool TryRead(ZPackage packet, long authenticatedPeer, out ZDOID target, out int method) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_0045: Unknown result type (might be due to invalid IL or missing references) //IL_004a: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Unknown result type (might be due to invalid IL or missing references) int pos = packet.GetPos(); target = ZDOID.None; method = 0; try { packet.ReadLong(); long num = packet.ReadLong(); packet.ReadLong(); target = packet.ReadZDOID(); method = packet.ReadInt(); return num == authenticatedPeer; } catch (Exception) { target = ZDOID.None; method = 0; return false; } finally { packet.SetPos(pos); } } public static bool IsActivity(int method) { if (method != StringExtensionMethods.GetStableHashCode("Say") && method != StringExtensionMethods.GetStableHashCode("ChatMessage") && method != StringExtensionMethods.GetStableHashCode("SetTrigger") && method != StringExtensionMethods.GetStableHashCode("RPC_Damage") && method != StringExtensionMethods.GetStableHashCode("RPC_Repair") && method != StringExtensionMethods.GetStableHashCode("RPC_Remove") && method != StringExtensionMethods.GetStableHashCode("RPC_RequestOpen") && method != StringExtensionMethods.GetStableHashCode("RPC_RequestStack")) { return method == StringExtensionMethods.GetStableHashCode("RPC_RequestTakeAll"); } return true; } public static bool TryReadParameters(ZPackage packet, long authenticatedPeer, out ZDOID target, out int method, out ZPackage? parameters) { //IL_002e: Unknown result type (might be due to invalid IL or missing references) parameters = null; if (!TryRead(packet, authenticatedPeer, out target, out method)) { return false; } int pos = packet.GetPos(); try { packet.ReadLong(); packet.ReadLong(); packet.ReadLong(); packet.ReadZDOID(); packet.ReadInt(); int pos2 = packet.GetPos(); int num = packet.ReadInt(); if (num < 0 || num > 8192 || packet.Size() - packet.GetPos() != num) { return false; } packet.SetPos(pos2); parameters = packet.ReadPackage(); return true; } catch (Exception) { parameters = null; return false; } finally { packet.SetPos(pos); } } public static string ActivityName(int method) { string[] names = Names; foreach (string text in names) { if (method == StringExtensionMethods.GetStableHashCode(text)) { return text; } } return "unrecognized"; } } } namespace HeimKit.Core.Players.Models { public sealed class PlayerActivityObservation { internal ZDOID NativeCharacter; public long Peer { get; set; } public string Name { get; set; } = ""; public string Character { get; set; } = ""; public bool Known { get; set; } public bool Alive { get; set; } public bool InBed { get; set; } public bool Busy { get; set; } public float X { get; set; } public float Y { get; set; } public float Z { get; set; } public float Heading { get; set; } public float Health { get; set; } public string Equipment { get; set; } = ""; public int Emote { get; set; } } public sealed class PlayerActivityOptions { public float Timeout { get; } public float Grace { get; } public float Movement { get; } public float Look { get; } public float Interval { get; } public PlayerActivityOptions(float timeout, float grace, float movement, float look, float interval) { if (!PlayerActivityTracker.Finite(timeout) || !PlayerActivityTracker.Finite(grace) || !PlayerActivityTracker.Finite(movement) || !PlayerActivityTracker.Finite(look) || !PlayerActivityTracker.Finite(interval) || timeout <= 0f || grace < 0f || movement <= 0f || look <= 0f || interval <= 0f) { throw new ArgumentOutOfRangeException("timeout", "Activity settings must be finite with positive thresholds and a nonnegative grace."); } Timeout = timeout; Grace = grace; Movement = movement; Look = look; Interval = interval; } } public sealed class PlayerActivityView { public long Peer { get; set; } public string Name { get; set; } = ""; public bool Known { get; set; } public bool Alive { get; set; } public bool InBed { get; set; } public bool Idle { get; set; } public float IdleSeconds { get; set; } public string Reason { get; set; } = "unknown"; public long Session { get; set; } public long StateRevision { get; set; } public string LastSignal { get; set; } = "none_observed"; public string Recovery { get; set; } = "not_observed"; public float GraceRemaining { get; set; } public float ObservedAt { get; set; } public float LastActivityAt { get; set; } public float X { get; set; } public float Y { get; set; } public float Z { get; set; } } } namespace HeimKit.Core.Ownership { internal sealed class ObjectAuthority : IDisposable { private static readonly List Consumers = new List(); private static readonly Harmony Hooks = new Harmony("heimkit.server_object_authority"); private static readonly HashSet InstanceIds = new HashSet(); private readonly Dictionary _records = new Dictionary(); private readonly Dictionary<(int X, int Y, int Z), HashSet> _points = new Dictionary<(int, int, int), HashSet>(); private readonly Dictionary _cells = new Dictionary(); private readonly HashSet _commands; private readonly Action _failed; private readonly IPlayerPresence _presence; private readonly ManualLogSource _log; private static readonly Dictionary PacketIncidents = new Dictionary(); private readonly bool _instances; private readonly ZDOMan _world = ZDOMan.instance; private bool _disposed; private static bool HasRecords { get { foreach (ObjectAuthority consumer in Consumers) { if (consumer._records.Count != 0 && consumer._world == ZDOMan.instance) { return true; } } return false; } } public bool Contains(ZDOID id) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) return _records.ContainsKey(id); } internal static void Assign(ZDO record, long owner) { record.SetOwner(owner); } public ObjectAuthority(Action failed, ManualLogSource log, IPlayerPresence presence, bool instances, params string[] commands) { //IL_00ba: Unknown result type (might be due to invalid IL or missing references) //IL_00c8: Expected O, but got Unknown _log = log; _presence = presence; _failed = failed; _instances = instances; _commands = new HashSet(commands.Select((string s) => StringExtensionMethods.GetStableHashCode(s))); if (Consumers.Count == 0) { try { (MethodInfo, string)[] array = NativePatches(); for (int num = 0; num < array.Length; num++) { (MethodInfo, string) tuple = array[num]; Hooks.Patch((MethodBase)tuple.Item1, new HarmonyMethod(typeof(ObjectAuthority), tuple.Item2, (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } } catch { Hooks.UnpatchSelf(); throw; } } Consumers.Add(this); } internal static (MethodInfo Target, string Prefix)[] NativePatches() { return new(MethodInfo, string)[6] { (Target(typeof(ZDO), "SetOwner", new Type[1] { typeof(long) }), "Owner"), (Target(typeof(ZDOMan), "RPC_ZDOData", new Type[2] { typeof(ZRpc), typeof(ZPackage) }), "Data"), (Target(typeof(ZRoutedRpc), "RPC_RoutedRPC", new Type[2] { typeof(ZRpc), typeof(ZPackage) }), "Routed"), (Target(typeof(ZNetScene), "CreateObjects", new Type[2] { typeof(List), typeof(List) }), "Instances"), (Target(typeof(ZNetScene), "RemoveObjects", new Type[2] { typeof(List), typeof(List) }), "Instances"), (Target(typeof(ZNetScene), "OutsideActiveArea", new Type[1] { typeof(Vector3) }), "ActiveArea") }; static MethodInfo Target(Type type, string name, params Type[] parameters) { return type.GetMethod(name, BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, parameters, null) ?? throw new MissingMethodException(type.Name, name); } } public void Retain(ZDO zdo) { //IL_0057: Unknown result type (might be due to invalid IL or missing references) //IL_0039: Unknown result type (might be due to invalid IL or missing references) //IL_00dd: 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_007e: Unknown result type (might be due to invalid IL or missing references) //IL_0090: Unknown result type (might be due to invalid IL or missing references) //IL_00c0: Unknown result type (might be due to invalid IL or missing references) if (_disposed || _world != ZDOMan.instance) { throw new InvalidOperationException("Authority belongs to another world."); } if (_records.Count >= 4096 && !_records.ContainsKey(zdo.m_uid)) { throw new InvalidOperationException("Authority capacity exceeded."); } _records[zdo.m_uid] = zdo; if (_instances && !_cells.ContainsKey(zdo.m_uid)) { (int, int, int) tuple = Cell(zdo.GetPosition()); _cells[zdo.m_uid] = tuple; if (!_points.TryGetValue(tuple, out HashSet value)) { value = (_points[tuple] = new HashSet()); } value.Add(zdo.m_uid); } zdo.SetOwner(ZDOMan.GetSessionID()); _world.ForceSendZDO(zdo.m_uid); } public void Release(ZDOID id) { //IL_0006: 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_0024: 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_004c: Unknown result type (might be due to invalid IL or missing references) //IL_007e: Unknown result type (might be due to invalid IL or missing references) //IL_0083: Unknown result type (might be due to invalid IL or missing references) //IL_00a7: Unknown result type (might be due to invalid IL or missing references) if (!_records.TryGetValue(id, out ZDO value)) { return; } _records.Remove(id); if (_cells.TryGetValue(id, out (int, int, int) value2)) { _cells.Remove(id); if (_points.TryGetValue(value2, out HashSet value3)) { value3.Remove(id); if (value3.Count == 0) { _points.Remove(value2); } } } if (_world == ZDOMan.instance && value.IsValid() && !(value.m_uid != id)) { if (value.GetOwner() == ZDOMan.GetSessionID()) { value.SetOwner(0L); } _world.ForceSendZDO(id); } } private static ObjectAuthority? For(ZDOID id) { //IL_0028: Unknown result type (might be due to invalid IL or missing references) //IL_003b: Unknown result type (might be due to invalid IL or missing references) //IL_0040: Unknown result type (might be due to invalid IL or missing references) foreach (ObjectAuthority consumer in Consumers) { if (consumer._world == ZDOMan.instance && consumer._records.TryGetValue(id, out ZDO value) && value.IsValid() && value.m_uid == id) { return consumer; } } return null; } private static bool Protected(ZDOID id) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) return For(id) != null; } private static void Owner(ZDO __instance, ref long uid) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) if (Protected(__instance.m_uid)) { uid = ZDOMan.GetSessionID(); } } private static void Reassert(ZDOID id, uint data, ushort owner) { //IL_0000: 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_0088: Unknown result type (might be due to invalid IL or missing references) ObjectAuthority objectAuthority = For(id); ZDO val = ((objectAuthority != null) ? objectAuthority._world.GetZDO(id) : null); if (val != null) { if (Math.Max(val.DataRevision, data) == uint.MaxValue || Math.Max((int)val.OwnerRevision, (int)owner) == 65535) { InvalidOperationException ex = new InvalidOperationException("Network revision exhausted."); objectAuthority._failed(ex); throw ex; } val.DataRevision = Math.Max(val.DataRevision, data) + 1; val.OwnerRevision = (ushort)(Math.Max((int)val.OwnerRevision, (int)owner) + 1); objectAuthority._world.ForceSendZDO(id); } } private static bool Data(ZRpc rpc, ref ZPackage pkg) { if (!HasRecords || !Connected(rpc)) { return true; } try { pkg = ZdoPackets.FilterData(pkg, Protected, out var _, Reassert); return true; } catch (Exception error) { RejectPacket("zdo_data", error); return false; } } private static bool Connected(ZRpc rpc, long? sender = null) { foreach (ObjectAuthority consumer in Consumers) { ZNetPeer val = PlayerPeerLookup.Ready(consumer._presence.Peers, rpc); if (val != null) { return !sender.HasValue || val.m_uid == sender.Value; } } return false; } private static bool Routed(ZRpc rpc, ref ZPackage pkg) { //IL_00eb: Unknown result type (might be due to invalid IL or missing references) //IL_0122: Unknown result type (might be due to invalid IL or missing references) //IL_0128: Expected O, but got Unknown //IL_00d1: Unknown result type (might be due to invalid IL or missing references) //IL_00db: Expected O, but got Unknown if (!HasRecords || !Connected(rpc)) { return true; } try { if (!ZdoPackets.RelevantRouted(pkg, Protected)) { return true; } RoutedRPCData val = ZdoPackets.ReadRouted(pkg); if (!Connected(rpc, val.m_senderPeerID)) { return false; } if (((ZDOID)(ref val.m_targetZDO)).IsNone()) { ZPackage original = ZdoPackets.ReadPackage(val.m_parameters); if (val.m_parameters.GetPos() != val.m_parameters.Size()) { throw new InvalidDataException("Trailing destruction data."); } int blocked; ZPackage val2 = ZdoPackets.FilterDestroyed(original, Protected, out blocked); if (blocked == 0) { return true; } val.m_parameters = new ZPackage(); val.m_parameters.Write(val2); } else { ObjectAuthority objectAuthority = For(val.m_targetZDO); if (objectAuthority == null) { return true; } if (!objectAuthority._commands.Contains(val.m_methodHash)) { return false; } val.m_targetPeerID = ZDOMan.GetSessionID(); } ZPackage val3 = new ZPackage(); val.Serialize(val3); val3.SetPos(0); pkg = val3; return true; } catch (Exception error) { RejectPacket("routed", error); return false; } } private static bool ActiveArea(Vector3 point, ref bool __result) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_00a6: Unknown result type (might be due to invalid IL or missing references) //IL_00ab: 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_00c9: Unknown result type (might be due to invalid IL or missing references) //IL_00ce: Unknown result type (might be due to invalid IL or missing references) //IL_00d9: Unknown result type (might be due to invalid IL or missing references) //IL_00de: Unknown result type (might be due to invalid IL or missing references) //IL_00df: 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) if (!PlayerWorldScope.Finite(point)) { return true; } (int, int, int) tuple = Cell(point); foreach (ObjectAuthority consumer in Consumers) { if (consumer._points.Count == 0 || !consumer._instances || consumer._world != ZDOMan.instance) { continue; } for (int i = -1; i <= 1; i++) { for (int j = -1; j <= 1; j++) { for (int k = -1; k <= 1; k++) { if (!consumer._points.TryGetValue((tuple.Item1 + i, tuple.Item2 + j, tuple.Item3 + k), out HashSet value)) { continue; } foreach (ZDOID item in value) { if (consumer._records.TryGetValue(item, out ZDO value2) && value2.IsValid() && value2.m_uid == item) { Vector3 val = value2.GetPosition() - point; if (((Vector3)(ref val)).sqrMagnitude < 0.001f) { __result = false; return false; } } } } } } } return true; } private static (int X, int Y, int Z) Cell(Vector3 point) { //IL_0000: 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_0026: Unknown result type (might be due to invalid IL or missing references) return (X: (int)Math.Floor(point.x * 8f), Y: (int)Math.Floor(point.y * 8f), Z: (int)Math.Floor(point.z * 8f)); } private static void Instances(List currentNearObjects, List currentDistantObjects) { //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_00ac: 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_00c2: Unknown result type (might be due to invalid IL or missing references) if (!HasRecords) { return; } HashSet instanceIds = InstanceIds; instanceIds.Clear(); foreach (ZDO currentNearObject in currentNearObjects) { instanceIds.Add(currentNearObject.m_uid); } foreach (ObjectAuthority consumer in Consumers) { if (!consumer._instances || consumer._world != ZDOMan.instance) { continue; } foreach (KeyValuePair record in consumer._records) { if (record.Value.IsValid() && record.Value.m_uid == record.Key && instanceIds.Add(record.Key)) { currentNearObjects.Add(record.Value); } } } instanceIds.Clear(); } private static void RejectPacket(string operation, Exception error) { float unscaledTime = Time.unscaledTime; PacketIncidents.TryGetValue(operation, out (float, int) value); if (unscaledTime < value.Item1) { PacketIncidents[operation] = (value.Item1, value.Item2 + 1); return; } ManualLogSource val = Consumers.FirstOrDefault()?._log; if (val != null) { DiagnosticLog.Write(val, "HeimKit", CoreLogTopics.Lifecycle, "Rejected protected-object network data; other packets remain active.", new(string, object)[3] { ("operation", operation), ("error_type", error.GetType().FullName), ("repeats_suppressed", value.Item2) }, (LogLevel)2, verbose: false, (value.Item1 == 0f) ? error : null); } PacketIncidents[operation] = (unscaledTime + 60f, 0); } public void Dispose() { //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_0034: Unknown result type (might be due to invalid IL or missing references) if (_disposed) { return; } _disposed = true; List list = new List(); ZDOID[] array = _records.Keys.ToArray(); foreach (ZDOID id in array) { try { Release(id); } catch (Exception item) { list.Add(item); } } Consumers.Remove(this); if (Consumers.Count == 0) { PacketIncidents.Clear(); try { Hooks.UnpatchSelf(); } catch (Exception item2) { list.Add(item2); } } if (list.Count <= 0) { return; } throw new AggregateException("Authority cleanup failed.", list); } } internal sealed class ObjectTransferAuthority : IDisposable { private static ObjectTransferAuthority? _current; private readonly Harmony _hooks = new Harmony("heimkit.tametravel.authority"); private readonly IPlayerPresence _presence; private readonly Action _failed; private readonly Func _contains; private readonly ZDOMan _world = ZDOMan.instance; private readonly Dictionary _leases = new Dictionary(); private readonly Dictionary _barriers = new Dictionary(); private readonly Dictionary _bodies = new Dictionary(); private readonly HashSet _instanceIds = new HashSet(); private readonly List _expiredBarriers = new List(); private static int _nonce = 10000000; private bool _disposed; public ObjectTransferAuthority(IPlayerPresence presence, Action failed) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Expected O, but got Unknown //IL_010d: Unknown result type (might be due to invalid IL or missing references) //IL_0122: Unknown result type (might be due to invalid IL or missing references) //IL_012f: Expected O, but got Unknown //IL_012f: Expected O, but got Unknown ZdoReplication.CheckCompatibility(); _presence = presence; _failed = failed; _contains = Contains; if (_current != null) { throw new InvalidOperationException("TameTravel authority is already active."); } _current = this; try { Patch(typeof(ZDO), "SetOwner", "Owner", typeof(long)); _hooks.Patch((MethodBase)AccessTools.Method(typeof(ZDOMan), "RPC_ZDOData", new Type[2] { typeof(ZRpc), typeof(ZPackage) }, (Type[])null), new HarmonyMethod(typeof(ObjectTransferAuthority), "Data", (Type[])null), new HarmonyMethod(typeof(ObjectTransferAuthority), "DataApplied", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); Patch(typeof(ZRoutedRpc), "RPC_RoutedRPC", "Routed", typeof(ZRpc), typeof(ZPackage)); Patch(typeof(Game), "RPC_Pong", "Pong", typeof(long), typeof(float)); Patch(typeof(ZNetScene), "CreateObjects", "Instances", typeof(List), typeof(List)); Patch(typeof(ZNetScene), "RemoveObjects", "Instances", typeof(List), typeof(List)); Patch(typeof(Character), "CustomFixedUpdate", "Pause", typeof(float)); Patch(typeof(Humanoid), "CustomFixedUpdate", "Pause", typeof(float)); Patch(typeof(MonsterAI), "UpdateAI", "Pause", typeof(float)); Patch(typeof(Tameable), "Update", "Pause"); Patch(typeof(Tameable), "TamingUpdate", "Pause"); Patch(typeof(Procreation), "Procreate", "Pause"); Patch(typeof(ZSyncTransform), "CustomFixedUpdate", "Pause", typeof(float)); Patch(typeof(ZSyncTransform), "CustomLateUpdate", "Pause", typeof(float)); Patch(typeof(ZSyncTransform), "SyncNow", "Pause"); } catch { try { _hooks.UnpatchSelf(); } finally { _current = null; } throw; } } private void Patch(Type type, string method, string prefix, params Type[] parameters) { //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_003b: Expected O, but got Unknown _hooks.Patch((MethodBase)(AccessTools.Method(type, method, parameters, (Type[])null) ?? throw new MissingMethodException(type.Name, method)), new HarmonyMethod(typeof(ObjectTransferAuthority), prefix, (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } private static void Instances(List currentNearObjects, List currentDistantObjects) { //IL_0044: Unknown result type (might be due to invalid IL or missing references) //IL_00a2: 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_00e4: Unknown result type (might be due to invalid IL or missing references) ObjectTransferAuthority current = _current; if (current == null || current._leases.Count == 0 || current._world != ZDOMan.instance) { return; } HashSet instanceIds = current._instanceIds; instanceIds.Clear(); foreach (ZDO currentNearObject in currentNearObjects) { instanceIds.Add(currentNearObject.m_uid); } foreach (KeyValuePair lease in current._leases) { if (lease.Value.Record.IsValid() && lease.Value.Record.m_uid == lease.Key && (lease.Value.Moved || (Object)(object)ZNetScene.instance.FindInstance(lease.Value.Record) != (Object)null) && instanceIds.Add(lease.Key)) { currentNearObjects.Add(lease.Value.Record); } } instanceIds.Clear(); } public bool Contains(ZDOID id) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) return _leases.ContainsKey(id); } public bool RunningFollow(ZDOID id) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) if (_leases.TryGetValue(id, out OwnershipLease value) && value.FollowControl) { return value.Phase == 5; } return false; } public bool Holds(OwnershipLease t) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) if (_leases.TryGetValue(t.Id, out OwnershipLease value)) { return value == t; } return false; } public bool Acquire(OwnershipLease transfer, float now, bool allowDisconnectedOwner = false) { //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_003b: Unknown result type (might be due to invalid IL or missing references) //IL_008a: Unknown result type (might be due to invalid IL or missing references) //IL_008f: Unknown result type (might be due to invalid IL or missing references) //IL_0113: Unknown result type (might be due to invalid IL or missing references) //IL_013a: Unknown result type (might be due to invalid IL or missing references) if (_leases.Count >= 64 || Contains(transfer.Id) || _world.GetZDO(transfer.Id) != transfer.Record || !transfer.Record.IsValid()) { return false; } ZDO record = transfer.Record; transfer.PreviousOwner = record.GetOwner(); transfer.Source = record.GetPosition(); CheckRevisions(record.DataRevision, record.OwnerRevision); if (record.DataRevision == 0) { return false; } if (transfer.PreviousOwner != 0L && transfer.PreviousOwner != ZDOMan.GetSessionID()) { transfer.PreviousPeer = ((IEnumerable)_presence.Peers).FirstOrDefault((Func)((ZNetPeer p) => p.IsReady() && p.m_uid == transfer.PreviousOwner)); if (transfer.PreviousPeer == null && !allowDisconnectedOwner) { return false; } } _leases.Add(transfer.Id, transfer); record.SetOwner(ZDOMan.GetSessionID()); _world.ForceSendZDO(transfer.Id); Freeze(record); if (transfer.PreviousPeer != null) { RequestSourceState(transfer, now); } else { transfer.Phase = 1; } return true; } public float SendBarrier(ZNetPeer peer, ZDO? z, float now) { Prune(now); if (_barriers.Count >= 512) { return 0f; } if (++_nonce >= 16000000) { throw new InvalidOperationException("TameTravel ordering-barrier nonce exhausted."); } float num = -_nonce; _barriers.Add(num, (peer, now, false)); if (z != null) { Send(peer, z); } ZRoutedRpc.instance.InvokeRoutedRPC(peer.m_uid, "RPC_Ping", new object[1] { num }); return num; } public void RequestSourceState(OwnershipLease t, float now) { //IL_0089: Unknown result type (might be due to invalid IL or missing references) CheckRevisions(t.Record.DataRevision, t.Record.OwnerRevision); ZDO record = t.Record; ushort ownerRevision = record.OwnerRevision; record.OwnerRevision = (ushort)(ownerRevision + 1); t.SourceOwnerRevision = t.Record.OwnerRevision; t.SourceStateObserved = false; t.SourceEchoTime = 0f; Send(t.PreviousPeer, t.Record, 0u); ZRoutedRpc.instance.InvokeRoutedRPC(t.PreviousPeer.m_uid, "RequestZDO", new object[1] { t.Id }); t.Barrier = SendBarrier(t.PreviousPeer, null, now); } public void ObservePong(ZNetPeer peer, float nonce) { if (_barriers.TryGetValue(nonce, out (ZNetPeer, float, bool) value) && peer == value.Item1) { _barriers[nonce] = (value.Item1, value.Item2, true); } } public bool Echoed(float nonce) { if (_barriers.TryGetValue(nonce, out (ZNetPeer, float, bool) value)) { return value.Item3; } return false; } public float ResetClientInstance(ZNetPeer peer, OwnershipLease lease, float now) { //IL_004a: Unknown result type (might be due to invalid IL or missing references) if (!Holds(lease) || lease.Record.GetOwner() != ZDOMan.GetSessionID()) { throw new InvalidOperationException("Client refresh requires fenced server ownership."); } ZdoReplication.ResetClientCache(lease.Id, delegate(ZPackage packet) { ZRoutedRpc.instance.InvokeRoutedRPC(peer.m_uid, "DestroyZDO", new object[1] { packet }); }, delegate { Send(peer, lease.Record); }); return SendBarrier(peer, null, now); } private void Prune(float now) { _expiredBarriers.Clear(); foreach (KeyValuePair barrier in _barriers) { if (now - barrier.Value.Item2 > 15f) { _expiredBarriers.Add(barrier.Key); } } foreach (float expiredBarrier in _expiredBarriers) { _barriers.Remove(expiredBarrier); } _expiredBarriers.Clear(); } public void Tick(float now) { Prune(now); foreach (OwnershipLease value in _leases.Values) { if (value.FollowControl ? (value.Phase != 5) : (value.Phase < 3)) { Freeze(value.Record); } } } public void RunFollow(OwnershipLease t) { //IL_000f: Unknown result type (might be due to invalid IL or missing references) if (!t.FollowControl || !_leases.TryGetValue(t.Id, out OwnershipLease value) || t != value) { throw new InvalidOperationException("Following lease is no longer held."); } t.Phase = 5; RestoreBody(t.Record); } public void PauseFollow(OwnershipLease t) { //IL_000f: Unknown result type (might be due to invalid IL or missing references) if (t.FollowControl && _leases.ContainsKey(t.Id)) { t.Phase = 6; Freeze(t.Record); } } private void Freeze(ZDO z) { //IL_005d: Unknown result type (might be due to invalid IL or missing references) //IL_0068: Unknown result type (might be due to invalid IL or missing references) ZNetView val = ZNetScene.instance.FindInstance(z); Rigidbody val2 = (((Object)(object)val == (Object)null) ? null : ((Component)val).GetComponent()); if (!((Object)(object)val2 == (Object)null)) { if (!_bodies.ContainsKey(val2)) { _bodies.Add(val2, (val2.isKinematic, val2.useGravity)); } if (!val2.isKinematic) { val2.linearVelocity = Vector3.zero; val2.angularVelocity = Vector3.zero; } val2.isKinematic = true; val2.useGravity = false; } } public void Handoff(OwnershipLease t) { //IL_006d: Unknown result type (might be due to invalid IL or missing references) CheckRevisions(t.Record.DataRevision, t.Record.OwnerRevision); t.Phase = 3; t.Record.SetOwner(t.DestinationPeer.m_uid); t.PublishedOwnerRevision = t.Record.OwnerRevision; t.PublishedRevision = t.Record.DataRevision; RestoreBody(t.Record); _world.ForceSendZDO(t.Id); Send(t.DestinationPeer, t.Record); } public void RefreshDestination(OwnershipLease t, float now) { //IL_0077: Unknown result type (might be due to invalid IL or missing references) if (t.Phase == 3 && !t.OwnerObserved && !(now < t.NextDestinationSend) && t.DestinationRetries < 3) { t.NextDestinationSend = now + 2f; t.DestinationRetries++; Send(t.DestinationPeer, t.Record); ZRoutedRpc.instance.InvokeRoutedRPC(t.DestinationPeer.m_uid, "RequestZDO", new object[1] { t.Id }); } } private void RestoreBody(ZDO z) { ZNetView obj = ZNetScene.instance.FindInstance(z); Rigidbody val = ((obj != null) ? ((Component)obj).GetComponent() : null); if ((Object)(object)val != (Object)null && _bodies.TryGetValue(val, out (bool, bool) value)) { _bodies.Remove(val); val.isKinematic = value.Item1; val.useGravity = value.Item2; } } public void Release(ZDOID id, bool keepServerOwner = false, bool resetDestination = false) { //IL_0006: 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_0031: Unknown result type (might be due to invalid IL or missing references) //IL_00ac: Unknown result type (might be due to invalid IL or missing references) if (!_leases.TryGetValue(id, out OwnershipLease value)) { return; } _leases.Remove(id); if (_world == ZDOMan.instance && _world.GetZDO(id) == value.Record && value.Record.IsValid()) { RestoreBody(value.Record); if (!keepServerOwner && (value.Record.GetOwner() == ZDOMan.GetSessionID() || (resetDestination && value.Moved && !value.FollowControl && value.Record.GetOwner() == value.DestinationPeer.m_uid))) { value.Record.SetOwner(0L); } _world.ForceSendZDO(id); } } public static void Send(ZNetPeer peer, ZDO z, uint? wireRevision = null) { ZdoReplication.Send(peer, z, wireRevision); } private static void CheckRevisions(uint data, ushort owner) { if (data > 4294967263u || owner > 65527) { throw new InvalidOperationException("TameTravel cannot safely advance exhausted native record revisions."); } } private static void Owner(ZDO __instance, ref long uid) { //IL_0010: Unknown result type (might be due to invalid IL or missing references) ObjectTransferAuthority current = _current; if (current != null && current._leases.TryGetValue(__instance.m_uid, out OwnershipLease value)) { uid = ((!value.FollowControl && value.Phase >= 3) ? value.DestinationPeer.m_uid : ZDOMan.GetSessionID()); } } private static bool Pause(Component __instance) { //IL_0042: Unknown result type (might be due to invalid IL or missing references) if (_current == null || _current._leases.Count == 0) { return true; } ZNetView component = __instance.GetComponent(); ZDO val = ((component != null) ? component.GetZDO() : null); if (val != null && _current != null && _current._leases.TryGetValue(val.m_uid, out OwnershipLease value)) { if (!value.FollowControl) { return value.Phase >= 3; } return value.Phase == 5; } return true; } private static bool Pong(long sender, float time) { if (_current != null && _current._barriers.TryGetValue(time, out (ZNetPeer, float, bool) value)) { return value.Item1.m_uid != sender; } return true; } private static bool Data(ZRpc rpc, ref ZPackage pkg, out List<(OwnershipLease Transfer, bool Source, uint Revision)>? __state) { //IL_006a: Unknown result type (might be due to invalid IL or missing references) //IL_0070: Expected O, but got Unknown //IL_00a0: Unknown result type (might be due to invalid IL or missing references) //IL_00a5: Unknown result type (might be due to invalid IL or missing references) //IL_00a8: 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_00e0: Unknown result type (might be due to invalid IL or missing references) //IL_00e5: Unknown result type (might be due to invalid IL or missing references) //IL_00e8: Unknown result type (might be due to invalid IL or missing references) //IL_0122: Unknown result type (might be due to invalid IL or missing references) //IL_0127: Unknown result type (might be due to invalid IL or missing references) //IL_0376: Unknown result type (might be due to invalid IL or missing references) //IL_016b: Unknown result type (might be due to invalid IL or missing references) //IL_0170: Unknown result type (might be due to invalid IL or missing references) //IL_0181: Unknown result type (might be due to invalid IL or missing references) //IL_0326: Unknown result type (might be due to invalid IL or missing references) //IL_0346: Unknown result type (might be due to invalid IL or missing references) //IL_0195: Unknown result type (might be due to invalid IL or missing references) //IL_01af: Unknown result type (might be due to invalid IL or missing references) //IL_01b4: 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_01f0: 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_01f9: Unknown result type (might be due to invalid IL or missing references) //IL_01fe: Unknown result type (might be due to invalid IL or missing references) //IL_048f: 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_025c: Unknown result type (might be due to invalid IL or missing references) //IL_0260: Unknown result type (might be due to invalid IL or missing references) //IL_0265: 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) __state = null; ObjectTransferAuthority current = _current; if (current == null || current._leases.Count == 0) { return true; } ZNetPeer val = PlayerPeerLookup.Ready(current._presence.Peers, rpc); if (val == null) { return true; } int pos = pkg.GetPos(); try { if (!ZdoPackets.ContainsData(pkg, current._contains)) { return true; } if (pkg.Size() > 2097152) { throw new InvalidDataException("Oversized ZDO packet."); } ZPackage val2 = new ZPackage(); List list = new List(); int num = pkg.ReadInt(); if (num < 0 || num > 32768) { throw new InvalidDataException("Invalid sector count."); } for (int i = 0; i < num; i++) { ZDOID val3 = pkg.ReadZDOID(); if (!current.Contains(val3)) { list.Add(val3); } } val2.Write(list.Count); foreach (ZDOID item in list) { val2.Write(item); } List<(OwnershipLease, uint, ushort)> list2 = new List<(OwnershipLease, uint, ushort)>(); List<(OwnershipLease, ushort)> list3 = new List<(OwnershipLease, ushort)>(); List<(OwnershipLease, bool, uint)> list4 = new List<(OwnershipLease, bool, uint)>(); int num2 = 0; while (true) { ZDOID val4 = pkg.ReadZDOID(); if (((ZDOID)(ref val4)).IsNone()) { break; } if (++num2 > 32768) { throw new InvalidDataException("Too many ZDO records."); } ushort num3 = pkg.ReadUShort(); uint num4 = pkg.ReadUInt(); long num5 = pkg.ReadLong(); Vector3 val5 = pkg.ReadVector3(); ZPackage val6 = ZdoPackets.ReadPackage(pkg); if (current._leases.TryGetValue(val4, out OwnershipLease value)) { if (current._world.GetZDO(val4) != value.Record || value.Record.m_uid != val4) { continue; } Vector3 val7; int num6; if (value.Phase == 0 && val == value.PreviousPeer && (num5 == value.PreviousOwner || num5 == ZDOMan.GetSessionID()) && PlayerWorldScope.Finite(val5)) { val7 = val5 - value.Source; num6 = ((((Vector3)(ref val7)).sqrMagnitude <= 144f) ? 1 : 0); } else { num6 = 0; } bool flag = (byte)num6 != 0; int num7; if (!value.FollowControl && value.Phase >= 3 && val == value.DestinationPeer && num5 == val.m_uid && num3 >= value.PublishedOwnerRevision && num4 > value.PublishedRevision && PlayerWorldScope.Finite(val5)) { val7 = val5 - value.Placement; num7 = ((((Vector3)(ref val7)).sqrMagnitude <= 144f) ? 1 : 0); } else { num7 = 0; } bool flag2 = (byte)num7 != 0; if (!flag && !flag2) { list2.Add((value, num4, num3)); continue; } if (flag) { CheckRevisions(num4, num3); if (num5 == ZDOMan.GetSessionID() && num3 >= value.SourceOwnerRevision) { list4.Add((value, true, num4)); } num3 = (ushort)Math.Max(value.Record.OwnerRevision, num3 + 1); num5 = ZDOMan.GetSessionID(); list3.Add((value, num3)); } else if (num4 > value.Record.DataRevision) { list4.Add((value, false, num4)); } } val2.Write(val4); val2.Write(num3); val2.Write(num4); val2.Write(num5); val2.Write(val5); val2.Write(val6); } if (pkg.GetPos() != pkg.Size()) { throw new InvalidDataException("Trailing ZDO bytes."); } val2.Write(ZDOID.None); val2.SetPos(0); foreach (var item2 in list3) { item2.Item1.Record.OwnerRevision = item2.Item2; } foreach (var item3 in list2) { ZDO record = item3.Item1.Record; if (item3.Item1.Phase != 0 && (item3.Item2 > record.DataRevision || item3.Item3 > record.OwnerRevision)) { CheckRevisions(Math.Max(item3.Item2, record.DataRevision), (ushort)Math.Max((int)item3.Item3, (int)record.OwnerRevision)); record.DataRevision = Math.Max(item3.Item2, record.DataRevision) + 1; record.OwnerRevision = (ushort)(Math.Max((int)item3.Item3, (int)record.OwnerRevision) + 1); current._world.ForceSendZDO(record.m_uid); } } pkg.SetPos(pos); pkg = val2; __state = list4; return true; } catch (Exception obj) { pkg.SetPos(pos); current._failed(obj); return false; } } private static void DataApplied(List<(OwnershipLease Transfer, bool Source, uint Revision)>? __state) { //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_003b: Unknown result type (might be due to invalid IL or missing references) //IL_00bc: Unknown result type (might be due to invalid IL or missing references) //IL_00c2: Unknown result type (might be due to invalid IL or missing references) //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) if (__state == null) { return; } foreach (var item in __state) { var (ownershipLease, _, _) = item; if (!ownershipLease.Record.IsValid() || ownershipLease.Record.m_uid != ownershipLease.Id) { continue; } if (item.Source) { if (ownershipLease.Phase == 0 && ownershipLease.Record.GetOwner() == ZDOMan.GetSessionID() && ownershipLease.Record.DataRevision >= item.Revision) { ownershipLease.SourceStateObserved = true; } } else if (ownershipLease.Record.GetOwner() == ownershipLease.DestinationPeer.m_uid && ownershipLease.Record.DataRevision > ownershipLease.PublishedRevision) { Vector3 val = ownershipLease.Record.GetPosition() - ownershipLease.Placement; if (((Vector3)(ref val)).sqrMagnitude <= 144f) { ownershipLease.OwnerObserved = true; } } } } private static bool Routed(ZRpc rpc, ref ZPackage pkg) { //IL_0079: Unknown result type (might be due to invalid IL or missing references) //IL_0138: Unknown result type (might be due to invalid IL or missing references) //IL_0142: Expected O, but got Unknown //IL_014e: Unknown result type (might be due to invalid IL or missing references) //IL_0155: Expected O, but got Unknown //IL_00ce: Unknown result type (might be due to invalid IL or missing references) //IL_00d5: Expected O, but got Unknown //IL_00b7: Unknown result type (might be due to invalid IL or missing references) ObjectTransferAuthority current = _current; if (current == null || current._leases.Count == 0) { return true; } ZNetPeer val = PlayerPeerLookup.Ready(current._presence.Peers, rpc); if (val == null) { return true; } try { if (!ZdoPackets.RelevantRouted(pkg, current._contains)) { return true; } RoutedRPCData val2 = ZdoPackets.ReadRouted(pkg); if (val.m_uid != val2.m_senderPeerID) { return false; } if (!((ZDOID)(ref val2.m_targetZDO)).IsNone()) { if (!current._leases.TryGetValue(val2.m_targetZDO, out OwnershipLease value) || !value.FollowControl || value.Phase != 5) { return false; } if (val2.m_methodHash == StringExtensionMethods.GetStableHashCode("RequestControl")) { current.Release(value.Id, keepServerOwner: true); } val2.m_targetPeerID = ZDOMan.GetSessionID(); ZPackage val3 = new ZPackage(); val2.Serialize(val3); val3.SetPos(0); pkg = val3; return true; } ZPackage original = ZdoPackets.ReadPackage(val2.m_parameters); if (val2.m_parameters.GetPos() != val2.m_parameters.Size()) { throw new InvalidDataException("Trailing destruction bytes."); } int blocked; ZPackage val4 = ZdoPackets.FilterDestroyed(original, current._contains, out blocked); if (blocked == 0) { return true; } val2.m_parameters = new ZPackage(); val2.m_parameters.Write(val4); ZPackage val5 = new ZPackage(); val2.Serialize(val5); val5.SetPos(0); pkg = val5; return true; } catch (Exception obj) { current._failed(obj); return false; } } public void Dispose() { //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_0034: Unknown result type (might be due to invalid IL or missing references) if (_disposed) { return; } _disposed = true; List list = new List(); ZDOID[] array = _leases.Keys.ToArray(); foreach (ZDOID id in array) { try { Release(id); } catch (Exception item) { list.Add(item); } } foreach (KeyValuePair body in _bodies) { try { if ((Object)(object)body.Key != (Object)null) { body.Key.isKinematic = body.Value.Item1; body.Key.useGravity = body.Value.Item2; } } catch (Exception item2) { list.Add(item2); } } _bodies.Clear(); _barriers.Clear(); _leases.Clear(); try { _hooks.UnpatchSelf(); } catch (Exception item3) { list.Add(item3); } if (_current == this) { _current = null; } if (list.Count <= 0) { return; } throw new AggregateException("TameTravel authority cleanup failed.", list); } } internal abstract class OwnershipLease { public ZDO Record; public ZDOID Id; public long PreviousOwner; public ZNetPeer? PreviousPeer; public int Phase; public float Barrier; public Vector3 Source; public Vector3 Placement; public uint PublishedRevision; public ushort PublishedOwnerRevision; public ushort SourceOwnerRevision; public float SourceEchoTime; public bool SourceStateObserved; public bool Moved; public bool OwnerObserved; public float NextDestinationSend; public int DestinationRetries; public bool FollowControl; public abstract ZNetPeer DestinationPeer { get; } } internal static class ZdoPackets { public const int MaximumPacketBytes = 2097152; public const int MaximumRecords = 32768; private static readonly int DestroyMethod = StringExtensionMethods.GetStableHashCode("DestroyZDO"); public static bool ContainsData(ZPackage packet, Func relevant) { //IL_0046: Unknown result type (might be due to invalid IL or missing references) //IL_0062: Unknown result type (might be due to invalid IL or missing references) //IL_0067: Unknown result type (might be due to invalid IL or missing references) //IL_008d: Unknown result type (might be due to invalid IL or missing references) //IL_00ae: Unknown result type (might be due to invalid IL or missing references) int pos = packet.GetPos(); bool result = false; try { if (packet.Size() > 2097152) { throw new InvalidDataException("Oversized ZDO packet."); } int num = packet.ReadInt(); if (num < 0 || num > 32768) { throw new InvalidDataException("Invalid sector count."); } for (int i = 0; i < num; i++) { if (relevant(packet.ReadZDOID())) { result = true; } } int num2 = 0; while (true) { ZDOID arg = packet.ReadZDOID(); if (((ZDOID)(ref arg)).IsNone()) { break; } if (++num2 > 32768) { throw new InvalidDataException("Too many ZDO records."); } if (relevant(arg)) { result = true; } packet.ReadUShort(); packet.ReadUInt(); packet.ReadLong(); packet.ReadVector3(); int num3 = packet.ReadInt(); if (num3 < 0 || num3 > 2097152 || num3 > packet.Size() - packet.GetPos()) { throw new InvalidDataException("Invalid embedded package length."); } packet.SetPos(packet.GetPos() + num3); } if (packet.GetPos() != packet.Size()) { throw new InvalidDataException("Trailing ZDO data."); } return result; } finally { packet.SetPos(pos); } } internal static ZPackage ReadPackage(ZPackage packet) { //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_003b: Expected O, but got Unknown int num = packet.ReadInt(); if (num < 0 || num > 2097152 || num > packet.Size() - packet.GetPos()) { throw new InvalidDataException("Invalid embedded package length."); } return new ZPackage(packet.ReadByteArray(num)); } public static RoutedRPCData ReadRouted(ZPackage packet) { //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Unknown result type (might be due to invalid IL or missing references) //IL_003c: Unknown result type (might be due to invalid IL or missing references) //IL_0048: 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_004f: Unknown result type (might be due to invalid IL or missing references) //IL_0054: Unknown result type (might be due to invalid IL or missing references) //IL_0060: Unknown result type (might be due to invalid IL or missing references) //IL_0086: Expected O, but got Unknown int pos = packet.GetPos(); try { if (packet.Size() > 2097152) { throw new InvalidDataException("Oversized routed packet."); } RoutedRPCData val = new RoutedRPCData { m_msgID = packet.ReadLong(), m_senderPeerID = packet.ReadLong(), m_targetPeerID = packet.ReadLong(), m_targetZDO = packet.ReadZDOID(), m_methodHash = packet.ReadInt(), m_parameters = ReadPackage(packet) }; if (packet.GetPos() != packet.Size()) { throw new InvalidDataException("Trailing routed data."); } return val; } finally { packet.SetPos(pos); } } public static bool RelevantRouted(ZPackage packet, Func protectedId) { //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Unknown result type (might be due to invalid IL or missing references) int pos = packet.GetPos(); try { packet.ReadLong(); packet.ReadLong(); packet.ReadLong(); ZDOID arg = packet.ReadZDOID(); int num = packet.ReadInt(); return protectedId(arg) || (((ZDOID)(ref arg)).IsNone() && num == DestroyMethod); } finally { packet.SetPos(pos); } } public static ZPackage FilterData(ZPackage original, Func protectedId, out int blocked, Action? rejected = null) { //IL_0055: Unknown result type (might be due to invalid IL or missing references) //IL_005a: Unknown result type (might be due to invalid IL or missing references) //IL_005d: Unknown result type (might be due to invalid IL or missing references) //IL_00aa: Unknown result type (might be due to invalid IL or missing references) //IL_00af: Unknown result type (might be due to invalid IL or missing references) //IL_00ee: Unknown result type (might be due to invalid IL or missing references) //IL_0136: Unknown result type (might be due to invalid IL or missing references) //IL_0175: 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_0249: Expected O, but got Unknown //IL_0265: Unknown result type (might be due to invalid IL or missing references) int pos = original.GetPos(); blocked = 0; try { if (original.Size() > 2097152) { throw new InvalidDataException("Oversized ZDO packet."); } List<(int, int)> list = null; List<(ZDOID, uint, ushort)> list2 = null; int num = original.ReadInt(); if (num < 0 || num > 32768) { throw new InvalidDataException("Invalid sector count."); } int num2 = 0; for (int i = 0; i < num; i++) { int pos2 = original.GetPos(); ZDOID arg = original.ReadZDOID(); if (protectedId(arg)) { blocked++; num2++; (list ?? (list = new List<(int, int)>())).Add((pos2, original.GetPos() - pos2)); } } int num3 = 0; while (true) { int pos3 = original.GetPos(); ZDOID val = original.ReadZDOID(); if (((ZDOID)(ref val)).IsNone()) { break; } if (++num3 > 32768) { throw new InvalidDataException("Too many ZDO records."); } ushort item = original.ReadUShort(); uint item2 = original.ReadUInt(); original.ReadLong(); original.ReadVector3(); int num4 = original.ReadInt(); if (num4 < 0 || num4 > 2097152 || num4 > original.Size() - original.GetPos()) { throw new InvalidDataException("Invalid embedded package length."); } original.SetPos(original.GetPos() + num4); if (protectedId(val)) { blocked++; (list ?? (list = new List<(int, int)>())).Add((pos3, original.GetPos() - pos3)); (list2 ?? (list2 = new List<(ZDOID, uint, ushort)>())).Add((val, item2, item)); } } if (original.GetPos() != original.Size()) { throw new InvalidDataException("Trailing ZDO data."); } if (blocked == 0) { return original; } byte[] array = original.GetArray(); using MemoryStream memoryStream = new MemoryStream(); using BinaryWriter binaryWriter = new BinaryWriter(memoryStream); binaryWriter.Write(num - num2); int num5 = pos + 4; foreach (var item3 in list) { binaryWriter.Write(array, num5, item3.Item1 - num5); num5 = item3.Item1 + item3.Item2; } binaryWriter.Write(array, num5, array.Length - num5); ZPackage result = new ZPackage(memoryStream.ToArray()); if (rejected != null && list2 != null) { foreach (var item4 in list2) { rejected(item4.Item1, item4.Item2, item4.Item3); } } return result; } finally { original.SetPos(pos); } } public static ZPackage FilterDestroyed(ZPackage original, Func protectedId, out int blocked, Action? rejected = null) { //IL_0047: Unknown result type (might be due to invalid IL or missing references) //IL_004c: Unknown result type (might be due to invalid IL or missing references) //IL_004f: Unknown result type (might be due to invalid IL or missing references) //IL_0069: Unknown result type (might be due to invalid IL or missing references) //IL_005f: Unknown result type (might be due to invalid IL or missing references) //IL_0094: Unknown result type (might be due to invalid IL or missing references) //IL_009b: Expected O, but got Unknown //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) //IL_00bd: Unknown result type (might be due to invalid IL or missing references) //IL_00f4: Unknown result type (might be due to invalid IL or missing references) //IL_00f9: Unknown result type (might be due to invalid IL or missing references) //IL_00fc: Unknown result type (might be due to invalid IL or missing references) int pos = original.GetPos(); blocked = 0; try { int num = original.ReadInt(); if (num < 0 || num > 32768 || original.Size() > 2097152) { throw new InvalidDataException("Invalid destroyed-object list."); } List list = new List(); List list2 = new List(); for (int i = 0; i < num; i++) { ZDOID val = original.ReadZDOID(); if (protectedId(val)) { blocked++; list2.Add(val); } else { list.Add(val); } } if (original.GetPos() != original.Size()) { throw new InvalidDataException("Trailing destroyed-object data."); } ZPackage val2 = new ZPackage(); val2.Write(list.Count); foreach (ZDOID item in list) { val2.Write(item); } val2.SetPos(0); if (rejected != null) { foreach (ZDOID item2 in list2) { rejected(item2); } } return val2; } finally { original.SetPos(pos); } } } internal static class ZdoReplication { private static class Accessors { internal static readonly Type PeerType; internal static readonly Func GetPeer; internal static readonly Func Peer; internal static readonly Func> Invalid; internal static readonly Func> Forced; internal static readonly Func Known; internal static readonly Type InfoType; internal static readonly Func Info; static Accessors() { PeerType = typeof(ZDOMan).GetNestedType("ZDOPeer", BindingFlags.NonPublic); GetPeer = NativeAccess.PeerGetter(); Peer = NativeAccess.ObjectField(PeerType, "m_peer"); Invalid = NativeAccess.ObjectField>(PeerType, "m_invalidSector"); Forced = NativeAccess.ObjectField>(PeerType, "m_forceSend"); Known = NativeAccess.ObjectField(PeerType, "m_zdos"); InfoType = PeerType.GetNestedType("PeerZDOInfo", BindingFlags.Public | BindingFlags.NonPublic); Info = NativeAccess.PeerInfo(InfoType); } } internal static void CheckCompatibility() { try { _ = Accessors.GetPeer; _ = Accessors.Info; } catch (Exception innerException) { throw new InvalidOperationException("Native animal replication peer bookkeeping is unavailable.", innerException); } } internal static void ResetClientCache(ZDOID id, Action removeRemoteCache, Action sendSnapshot) { //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Expected O, but got Unknown //IL_0027: Unknown result type (might be due to invalid IL or missing references) if (((ZDOID)(ref id)).IsNone()) { throw new ArgumentException("A client cache reset requires an original record ID.", "id"); } ZPackage val = new ZPackage(); val.Write(1); val.Write(id); removeRemoteCache(val); sendSnapshot(); } internal static void Send(ZNetPeer peer, ZDO record, uint? wireRevision = null) { //IL_0065: Unknown result type (might be due to invalid IL or missing references) //IL_006b: Expected O, but got Unknown //IL_0074: 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_00a9: Unknown result type (might be due to invalid IL or missing references) //IL_00b0: Expected O, but got Unknown //IL_00c1: Unknown result type (might be due to invalid IL or missing references) //IL_00cd: Unknown result type (might be due to invalid IL or missing references) object obj = Accessors.GetPeer(ZDOMan.instance, peer.m_uid); if (obj == null || Accessors.Peer(obj) != peer) { throw new InvalidOperationException("Animal replication peer is no longer the joined connection."); } uint num = wireRevision ?? record.DataRevision; ZPackage val = new ZPackage(); val.Write(0); val.Write(record.m_uid); val.Write(record.OwnerRevision); val.Write(num); val.Write(record.GetOwner()); val.Write(record.GetPosition()); ZPackage val2 = new ZPackage(); record.Serialize(val2); val.Write(val2); val.Write(ZDOID.None); Transmit(obj, record.m_uid, num, record.OwnerRevision, Time.time, val, delegate(ZPackage p) { peer.m_rpc.Invoke("ZDOData", new object[1] { p }); }); } internal static void Transmit(object native, ZDOID id, uint data, ushort owner, float now, ZPackage packet, Action send) { //IL_003c: Unknown result type (might be due to invalid IL or missing references) //IL_0044: Unknown result type (might be due to invalid IL or missing references) //IL_004b: Unknown result type (might be due to invalid IL or missing references) HashSet hashSet = Accessors.Invalid(native); HashSet hashSet2 = Accessors.Forced(native); IDictionary dictionary = Accessors.Known(native); object value = Accessors.Info(data, owner, now); send(packet); hashSet.Remove(id); hashSet2.Remove(id); dictionary[id] = value; } } } namespace HeimKit.Core.Native { internal static class NativeAccess { private static readonly bool IsMono = Type.GetType("Mono.Runtime") != null; private static readonly Dictionary<(Type, string, Type), object> Fields = new Dictionary<(Type, string, Type), object>(); private static readonly Dictionary<(Type, string, Type), Delegate> Methods = new Dictionary<(Type, string, Type), Delegate>(); internal static FieldRef Field(string name) { (Type, string, Type) key = (typeof(T), name, typeof(V)); if (!Fields.TryGetValue(key, out object value)) { FieldInfo fieldInfo = ResolveField(typeof(T), name); if (fieldInfo.FieldType != typeof(V)) { throw new MissingFieldException(typeof(T).FullName, name + " has an incompatible type"); } if (IsMono) { value = AccessTools.FieldRefAccess(fieldInfo); } else { DynamicMethod dynamicMethod = new DynamicMethod("fieldref_" + name, typeof(V).MakeByRefType(), new Type[1] { typeof(T) }, typeof(NativeAccess).Module, skipVisibility: true); ILGenerator iLGenerator = dynamicMethod.GetILGenerator(); iLGenerator.Emit(OpCodes.Ldarg_0); iLGenerator.Emit(OpCodes.Ldflda, fieldInfo); iLGenerator.Emit(OpCodes.Ret); value = dynamicMethod.CreateDelegate(typeof(FieldRef)); } Fields[key] = value; } return (FieldRef)value; } internal static T Method(Type owner, string name, params Type[] parameters) where T : Delegate { (Type, string, Type) key = (owner, name, typeof(T)); if (!Methods.TryGetValue(key, out Delegate value)) { value = (Methods[key] = Target(owner, name, parameters).CreateDelegate(typeof(T))); } return (T)value; } internal static MethodInfo Target(Type owner, string name, params Type[] parameters) { Type type = owner; while (type != null) { MethodInfo method = type.GetMethod(name, BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, parameters, null); if (method != null) { return method; } type = type.BaseType; } throw new MissingMethodException(owner.FullName, name); } private static FieldInfo ResolveField(Type owner, string name) { Type type = owner; while (type != null) { FieldInfo field = type.GetField(name, BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); if (field != null) { return field; } type = type.BaseType; } throw new MissingFieldException(owner.FullName, name); } internal static Func StaticField(Type owner, string name) { FieldInfo field = ResolveField(owner, name); return Expression.Lambda>(Expression.Convert(Expression.Field(null, field), typeof(V)), Array.Empty()).Compile(); } internal static Func ObjectField(Type owner, string name) { (Type, string, Type) key = (owner, name, typeof(Func)); if (!Fields.TryGetValue(key, out object value)) { ParameterExpression parameterExpression = Expression.Parameter(typeof(object)); FieldInfo field = ResolveField(owner, name); value = (Fields[key] = Expression.Lambda>(Expression.Convert(Expression.Field(Expression.Convert(parameterExpression, owner), field), typeof(V)), new ParameterExpression[1] { parameterExpression }).Compile()); } return (Func)value; } internal static Func PeerGetter() { ParameterExpression parameterExpression = Expression.Parameter(typeof(ZDOMan)); ParameterExpression parameterExpression2 = Expression.Parameter(typeof(long)); return Expression.Lambda>(Expression.Convert(Expression.Call(parameterExpression, Target(typeof(ZDOMan), "GetPeer", typeof(long)), parameterExpression2), typeof(object)), new ParameterExpression[2] { parameterExpression, parameterExpression2 }).Compile(); } internal static Func PeerInfo(Type type) { ParameterExpression parameterExpression = Expression.Parameter(typeof(uint)); ParameterExpression parameterExpression2 = Expression.Parameter(typeof(ushort)); ParameterExpression parameterExpression3 = Expression.Parameter(typeof(float)); return Expression.Lambda>(Expression.Convert(Expression.New(type.GetConstructor(new Type[3] { typeof(uint), typeof(ushort), typeof(float) }) ?? throw new MissingMethodException(type.FullName, ".ctor"), parameterExpression, parameterExpression2, parameterExpression3), typeof(object)), new ParameterExpression[3] { parameterExpression, parameterExpression2, parameterExpression3 }).Compile(); } } internal static class NativeCharacterHealth { public static bool IsAlive(ZDO record) { if (!record.GetBool(ZDOVars.s_dead, false)) { float num = default(float); if (record.GetFloat(ZDOVars.s_health, ref num)) { if (PlayerWorldScope.Finite(num)) { return num > 0f; } return false; } return true; } return false; } } internal static class NativeIdentity { internal static int Compare(ZDOID a, ZDOID b) { //IL_001a: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Unknown result type (might be due to invalid IL or missing references) Span buffer = stackalloc char[32]; Span buffer2 = stackalloc char[32]; int length = Format(a, buffer); int length2 = Format(b, buffer2); return MemoryExtensions.CompareTo(buffer.Slice(0, length), buffer2.Slice(0, length2), StringComparison.CurrentCulture); } internal static int CompareOrdinal(ZDOID a, ZDOID b) { //IL_001a: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Unknown result type (might be due to invalid IL or missing references) Span buffer = stackalloc char[32]; Span buffer2 = stackalloc char[32]; int length = Format(a, buffer); int length2 = Format(b, buffer2); return buffer.Slice(0, length).SequenceCompareTo(buffer2.Slice(0, length2)); } private static int Format(ZDOID id, Span buffer) { long userID = ((ZDOID)(ref id)).UserID; Span destination = buffer; IFormatProvider currentCulture = CultureInfo.CurrentCulture; userID.TryFormat(destination, out var charsWritten, default(ReadOnlySpan), currentCulture); buffer[charsWritten++] = ':'; uint iD = ((ZDOID)(ref id)).ID; Span destination2 = buffer.Slice(charsWritten); currentCulture = CultureInfo.CurrentCulture; iD.TryFormat(destination2, out var charsWritten2, default(ReadOnlySpan), currentCulture); return charsWritten + charsWritten2; } } } namespace HeimKit.Core.Lifecycle { public static class ModuleCleanup { public static bool Run(ManualLogSource logger, string name, params Action[] steps) { bool result = true; foreach (Action action in steps) { try { action(); } catch (Exception ex) { result = false; LogTopic lifecycle = CoreLogTopics.Lifecycle; Exception error = ex; DiagnosticLog.Write(logger, name, lifecycle, "Cleanup failed; remaining cleanup continues.", default(LogFields), (LogLevel)2, verbose: false, error); } } return result; } } public sealed class ServerDebugActivity { public const double EmptyGraceSeconds = 300.0; private double? _emptySince = 0.0; private double _lastObserved; public bool Allowed { get; private set; } = true; public void Observe(double now, bool? hasConnectedPlayers) { if (double.IsNaN(now) || double.IsInfinity(now)) { return; } if (now < _lastObserved) { Reset(now); } _lastObserved = now; if (hasConnectedPlayers == true) { _emptySince = null; Allowed = true; return; } if (hasConnectedPlayers == false && !_emptySince.HasValue) { _emptySince = now; } if (_emptySince.HasValue) { Allowed = now - _emptySince.Value < 300.0; } } public void Reset(double now = 0.0) { _emptySince = now; _lastObserved = now; Allowed = true; } } } namespace HeimKit.Core.Diagnostics { public static class DebugLoggingDelivery { public static void Report(ManualLogSource logger, string feature) { //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_002c: 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_007b: Unknown result type (might be due to invalid IL or missing references) List list = new List(); foreach (ILogListener listener in Logger.Listeners) { DiskLogListener val = (DiskLogListener)(object)((listener is DiskLogListener) ? listener : null); if (val != null) { if ((val.DisplayedLogLevel & 0x20) == 0) { list.Add("Logging.Disk.LogLevels"); } } else if (listener is ConsoleLogListener && typeof(ConsoleLogListener).GetField("ConfigConsoleDisplayedLevel", BindingFlags.Static | BindingFlags.NonPublic)?.GetValue(null) is ConfigEntry val2 && (val2.Value & 0x20) == 0) { list.Add("Logging.Console.LogLevels"); } } if (list.Count == 0) { return; } DiagnosticLog.Write(logger, feature, "Debug logging is enabled, but an active loader output filters out Debug. Add Debug to " + string.Join(" and ", list) + " in BepInEx.cfg and restart.", (LogLevel)4); DiagnosticLog.Write(logger, feature, "HeimKit DebugMode enables diagnostic messages; BepInEx separately controls which log levels reach each output.", (LogLevel)16); foreach (string item in list) { string text = item.Substring(0, item.LastIndexOf('.')); DiagnosticLog.Write(logger, feature, "In BepInEx/config/BepInEx.cfg, add Debug to [" + text + "] LogLevels. Example: LogLevels = Fatal, Error, Warning, Message, Info, Debug.", (LogLevel)16); } DiagnosticLog.Write(logger, feature, "Preserve the other enabled log levels and restart the server to apply the output filters. Global HeimKit DebugMode can remain off when feature DebugMode is on.", (LogLevel)16); } } public sealed class DiagnosticBudget { private readonly Dictionary _windows = new Dictionary(); private readonly Dictionary _omitted = new Dictionary(); public bool Available(float now, string stream, int limit) { if (_windows.TryGetValue(stream, out (float, int) value) && !(now < value.Item1) && !(now - value.Item1 >= 60f)) { return value.Item2 < limit; } return true; } public bool Reserve(float now, string stream, int limit, bool countOmitted = true) { if (!_windows.TryGetValue(stream, out (float, int) value) || now < value.Item1 || now - value.Item1 >= 60f) { value = (now, 0); } if (value.Item2 >= limit) { if (countOmitted) { _omitted.TryGetValue(stream, out var value2); _omitted[stream] = value2 + 1; } return false; } _windows[stream] = (value.Item1, value.Item2 + 1); return true; } public string TakeOmitted() { if (_omitted.Count == 0) { return ""; } string result = string.Join(",", from p in _omitted orderby p.Key select $"{p.Key}:{p.Value}"); _omitted.Clear(); return result; } public void Reset() { _windows.Clear(); _omitted.Clear(); } } public static class DiagnosticLog { private static readonly Stopwatch Clock = Stopwatch.StartNew(); private static ConditionalWeakTable> _budgets = new ConditionalWeakTable>(); [ThreadStatic] private static StringBuilder? _builder; [ThreadStatic] private static string?[]? _names; [ThreadStatic] private static Dictionary? _enums; public static Func WallClock { get; set; } = () => DateTime.Now; public static ServerDebugActivity ServerActivity { get; } = new ServerDebugActivity(); public static bool VerboseConfigured => DiagnosticsSettings.Verbosity == DebugVerbosity.Verbose; public static LogField Field(string key, object? value) { return new LogField(key, value); } public static LogField FieldAlways(string key, object? value) { return new LogField(key, value, always: true); } public static object Kept(object? value) { return new LogField("", value, always: true); } public static void StartSession() { Clock.Restart(); ServerActivity.Reset(); _budgets = new ConditionalWeakTable>(); } public static void ObservePlayers(bool? hasConnectedPlayers) { ServerActivity.Observe(Clock.Elapsed.TotalSeconds, hasConnectedPlayers); } private static DiagnosticBudget Budget(ManualLogSource logger, string feature) { Dictionary orCreateValue = _budgets.GetOrCreateValue(logger); if (!orCreateValue.TryGetValue(feature, out var value)) { orCreateValue.Add(feature, value = new DiagnosticBudget()); } return value; } public static bool DebugAvailable(ManualLogSource logger, string feature, bool verbose = false, int requiredSlots = 1) { if (ServerActivity.Allowed && (!verbose || VerboseConfigured)) { return Budget(logger, feature).Available((float)Clock.Elapsed.TotalSeconds, "optional", 61 - Math.Max(1, requiredSlots)); } return false; } public static void Write(ManualLogSource logger, string feature, string message, LogLevel level = (LogLevel)16) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_0009: Unknown result type (might be due to invalid IL or missing references) //IL_0013: Unknown result type (might be due to invalid IL or missing references) Write(logger, feature, CoreLogTopics.Lifecycle, message, default(LogFields), level); } public static void Write(ManualLogSource logger, string feature, LogTopic topic, string message, LogFields fields = default(LogFields), LogLevel level = (LogLevel)16, bool verbose = false, Exception? error = null) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0004: Invalid comparison between Unknown and I4 //IL_003d: Unknown result type (might be due to invalid IL or missing references) //IL_0044: Unknown result type (might be due to invalid IL or missing references) if ((int)level != 32 || (DebugAvailable(logger, feature, verbose) && Budget(logger, feature).Reserve((float)Clock.Elapsed.TotalSeconds, "optional", 60, countOmitted: false))) { logger.Log(level, (object)Format(feature, topic, message, fields, level, verbose, error)); } } public static string Format(string feature, LogTopic topic, string message, LogFields fields = default(LogFields), LogLevel level = (LogLevel)32, bool verbose = false, Exception? error = null) { //IL_007f: Unknown result type (might be due to invalid IL or missing references) //IL_0083: Invalid comparison between Unknown and I4 //IL_0085: Unknown result type (might be due to invalid IL or missing references) //IL_0088: Invalid comparison between Unknown and I4 //IL_008a: Unknown result type (might be due to invalid IL or missing references) //IL_008d: Invalid comparison between Unknown and I4 StringBuilder stringBuilder = _builder ?? (_builder = new StringBuilder(1024)); stringBuilder.Clear(); Span span = stackalloc char[512]; WallClock().TryFormat(span, out var charsWritten, "HH:mm:ss".AsSpan(), CultureInfo.InvariantCulture); stringBuilder.Append(span.Slice(0, charsWritten)); stringBuilder.Append(' '); Plain(stringBuilder, feature); int num; if ((int)level != 32 && (int)level != 2) { num = (((int)level == 1) ? 1 : 0); if (num == 0) { goto IL_00b5; } } else { num = 1; } stringBuilder.Append('.'); stringBuilder.Append(topic.Name ?? "lifecycle"); goto IL_00b5; IL_00b5: stringBuilder.Append(": "); Plain(stringBuilder, message); if (stringBuilder.Length > 0 && stringBuilder[stringBuilder.Length - 1] != '.' && stringBuilder[stringBuilder.Length - 1] != '!' && stringBuilder[stringBuilder.Length - 1] != '?') { stringBuilder.Append('.'); } if (num == 0) { return stringBuilder.ToString(); } string[] array = _names ?? (_names = new string[64]); int num2 = 0; int num3 = 0; int num4 = 0; int num5 = (verbose ? int.MaxValue : ((error == null) ? 8 : 5)); LogFields.Enumerator enumerator = fields.GetEnumerator(); while (enumerator.MoveNext()) { LogField current = enumerator.Current; if (current.Key == "omitted_fields" || (error != null && (current.Key == "error_type" || current.Key == "error" || current.Key == "stack"))) { continue; } object value = current.Value; bool flag = current.Always; if (value is LogField logField) { value = logField.Value; flag |= logField.Always; } if (LogTopic.Valid(current.Key) && (flag || !Empty(value)) && value != null && !Duplicate(array, num2, current.Key)) { if (num2 == array.Length) { Array.Resize(ref array, array.Length * 2); _names = array; } array[num2++] = current.Key; if (num3 >= num5) { num4++; continue; } AppendField(stringBuilder, current.Key, value, span); num3++; } } if (error != null) { AppendField(stringBuilder, "error_type", error.GetType().FullName, span); AppendField(stringBuilder, "error", error.Message, span); string value2 = ((error.InnerException == null) ? error.StackTrace : error.ToString()); if (!string.IsNullOrEmpty(value2)) { AppendField(stringBuilder, "stack", value2, span); } } if (num4 > 0) { stringBuilder.Append(" omitted_fields="); Span destination = span; IFormatProvider invariantCulture = CultureInfo.InvariantCulture; num4.TryFormat(destination, out charsWritten, default(ReadOnlySpan), invariantCulture); stringBuilder.Append(span.Slice(0, charsWritten)); } Array.Clear(array, 0, num2); return stringBuilder.ToString(); } private static bool Duplicate(string?[] names, int count, string key) { for (int i = 0; i < count; i++) { if (names[i] == key) { return true; } } return false; } private static bool Empty(object? value) { //IL_014e: Unknown result type (might be due to invalid IL or missing references) //IL_0153: Unknown result type (might be due to invalid IL or missing references) //IL_0155: Unknown result type (might be due to invalid IL or missing references) //IL_0157: Unknown result type (might be due to invalid IL or missing references) if (value != null && (!(value is string text) || (text.Length != 0 && !(text == "unknown"))) && (!(value is bool) || (bool)value) && (!(value is byte) || (byte)value != 0) && (!(value is sbyte) || (sbyte)value != 0) && (!(value is short) || (short)value != 0) && (!(value is ushort) || (ushort)value != 0) && (!(value is int) || (int)value != 0) && (!(value is uint) || (uint)value != 0) && (!(value is long num) || num != 0L) && (!(value is ulong num2) || num2 != 0L) && (!(value is float num3) || num3 != 0f) && (!(value is double num4) || num4 != 0.0) && (!(value is decimal num5) || !(num5 == 0m))) { if (value is ZDOID val) { return val == ZDOID.None; } return false; } return true; } private static void Plain(StringBuilder builder, string? value) { if (value != null) { foreach (char c in value) { builder.Append(char.IsControl(c) ? ' ' : c); } } } private static void AppendField(StringBuilder builder, string key, object? value, Span buffer) { //IL_00ac: Unknown result type (might be due to invalid IL or missing references) //IL_00b1: Unknown result type (might be due to invalid IL or missing references) //IL_00c1: Unknown result type (might be due to invalid IL or missing references) //IL_00c6: Unknown result type (might be due to invalid IL or missing references) if (value == null) { return; } int length = builder.Length; try { builder.Append(' '); builder.Append(key); builder.Append('='); if (value is string value2) { Quoted(builder, value2); return; } if (value is bool flag) { builder.Append(flag ? "true" : "false"); return; } string text = (key.EndsWith("_ms", StringComparison.Ordinal) ? "F2" : ((key.EndsWith("_m", StringComparison.Ordinal) || key.EndsWith("_s", StringComparison.Ordinal)) ? "F1" : "0.###")); int charsWritten; if (!(value is Vector3 val)) { if (!(value is ZDOID val2)) { if (!(value is float num)) { if (!(value is double num2)) { if (!(value is decimal num3)) { if (!(value is int num4)) { if (!(value is long num5)) { if (!(value is uint num6)) { if (!(value is ulong num7)) { if (!(value is short num8)) { if (!(value is ushort num9)) { if (!(value is byte b)) { if (!(value is sbyte b2)) { if (value is Enum obj) { Dictionary dictionary = _enums ?? (_enums = new Dictionary()); if (!dictionary.TryGetValue(obj, out var value3)) { dictionary.Add(obj, value3 = obj.ToString()); } Quoted(builder, value3); } else { Quoted(builder, value.ToString() ?? ""); } return; } Span destination = buffer; IFormatProvider invariantCulture = CultureInfo.InvariantCulture; b2.TryFormat(destination, out charsWritten, default(ReadOnlySpan), invariantCulture); } else { Span destination2 = buffer; IFormatProvider invariantCulture = CultureInfo.InvariantCulture; b.TryFormat(destination2, out charsWritten, default(ReadOnlySpan), invariantCulture); } } else { Span destination3 = buffer; IFormatProvider invariantCulture = CultureInfo.InvariantCulture; num9.TryFormat(destination3, out charsWritten, default(ReadOnlySpan), invariantCulture); } } else { Span destination4 = buffer; IFormatProvider invariantCulture = CultureInfo.InvariantCulture; num8.TryFormat(destination4, out charsWritten, default(ReadOnlySpan), invariantCulture); } } else { Span destination5 = buffer; IFormatProvider invariantCulture = CultureInfo.InvariantCulture; num7.TryFormat(destination5, out charsWritten, default(ReadOnlySpan), invariantCulture); } } else { Span destination6 = buffer; IFormatProvider invariantCulture = CultureInfo.InvariantCulture; num6.TryFormat(destination6, out charsWritten, default(ReadOnlySpan), invariantCulture); } } else { Span destination7 = buffer; IFormatProvider invariantCulture = CultureInfo.InvariantCulture; num5.TryFormat(destination7, out charsWritten, default(ReadOnlySpan), invariantCulture); } } else { Span destination8 = buffer; IFormatProvider invariantCulture = CultureInfo.InvariantCulture; num4.TryFormat(destination8, out charsWritten, default(ReadOnlySpan), invariantCulture); } } else { num3.TryFormat(buffer, out charsWritten, text.AsSpan(), CultureInfo.InvariantCulture); } } else { num2.TryFormat(buffer, out charsWritten, text.AsSpan(), CultureInfo.InvariantCulture); } } else { num.TryFormat(buffer, out charsWritten, text.AsSpan(), CultureInfo.InvariantCulture); } } else { long userID = ((ZDOID)(ref val2)).UserID; Span destination9 = buffer; IFormatProvider invariantCulture = CultureInfo.InvariantCulture; userID.TryFormat(destination9, out charsWritten, default(ReadOnlySpan), invariantCulture); builder.Append(buffer.Slice(0, charsWritten)); builder.Append(':'); uint iD = ((ZDOID)(ref val2)).ID; Span destination10 = buffer; invariantCulture = CultureInfo.InvariantCulture; iD.TryFormat(destination10, out charsWritten, default(ReadOnlySpan), invariantCulture); } builder.Append(buffer.Slice(0, charsWritten)); } else { val.x.TryFormat(buffer, out charsWritten, "F1".AsSpan(), CultureInfo.InvariantCulture); builder.Append(buffer.Slice(0, charsWritten)); builder.Append(','); val.y.TryFormat(buffer, out charsWritten, "F1".AsSpan(), CultureInfo.InvariantCulture); builder.Append(buffer.Slice(0, charsWritten)); builder.Append(','); val.z.TryFormat(buffer, out charsWritten, "F1".AsSpan(), CultureInfo.InvariantCulture); builder.Append(buffer.Slice(0, charsWritten)); } } catch { builder.Length = length; } } private static void Quoted(StringBuilder builder, string value) { bool flag = value.Length == 0; string text = value; foreach (char c in text) { if (char.IsWhiteSpace(c) || c == '"' || c == '=' || c == '\\' || char.IsControl(c)) { flag = true; break; } } if (!flag) { builder.Append(value); return; } builder.Append('"'); text = value; foreach (char c2 in text) { switch (c2) { case '\\': builder.Append("\\\\"); continue; case '"': builder.Append("\\\""); continue; case '\n': builder.Append("\\n"); continue; case '\r': builder.Append("\\r"); continue; case '\t': builder.Append("\\t"); continue; } if (char.IsControl(c2)) { builder.Append("\\u"); builder.Append("0123456789abcdef"[((int)c2 >> 12) & 0xF]); builder.Append("0123456789abcdef"[((int)c2 >> 8) & 0xF]); builder.Append("0123456789abcdef"[((int)c2 >> 4) & 0xF]); builder.Append("0123456789abcdef"[c2 & 0xF]); } else { builder.Append(c2); } } builder.Append('"'); } public static string Value(object? value) { object obj; if (value != null) { if (value is bool) { if (!(bool)value) { return "false"; } return "true"; } if (value is IFormattable formattable) { return formattable.ToString(null, CultureInfo.InvariantCulture); } obj = value.ToString(); if (obj == null) { return "unknown"; } } else { obj = "unknown"; } return (string)obj; } } public abstract class FeatureDiagnostics { private Func _enabled = () => false; private ManualLogSource? _logger; private string _name = ""; protected readonly DiagnosticBudget _budget = new DiagnosticBudget(); protected bool DiagnosticsEnabled { get { if (_enabled() && DiagnosticLog.ServerActivity.Allowed) { if (_logger != null) { return DiagnosticLog.DebugAvailable(_logger, _name); } return true; } return false; } } public bool VerboseEnabled { get { if (DiagnosticsEnabled) { return DiagnosticLog.VerboseConfigured; } return false; } } public bool VerboseAfterNormalEnabled { get { if (VerboseEnabled) { if (_logger != null) { return DiagnosticLog.DebugAvailable(_logger, _name, verbose: true, 2); } return true; } return false; } } public bool OptionalEnabled => DiagnosticsEnabled; protected void ConfigureDiagnostics(Func enabled, ManualLogSource? logger = null, string name = "") { _enabled = enabled; _logger = logger; _name = name; } public bool SummaryReady(float now) { if (DiagnosticsEnabled) { return _budget.Available(now, "summary", 1); } return false; } protected bool SummaryDue(float now) { if (DiagnosticsEnabled) { return _budget.Reserve(now, "summary", 1, countOmitted: false); } return false; } protected bool RecordDue(float now, string stream, int limit) { if (DiagnosticsEnabled) { return _budget.Reserve(now, stream, limit); } return false; } } public readonly struct LogField { public string Key { get; } public object? Value { get; } public bool Always { get; } public LogField(string key, object? value, bool always = false) { Key = key; Value = value; Always = always; } public static implicit operator LogField((string Key, object? Value) field) { return new LogField(field.Key, field.Value); } } public readonly struct LogFields { public struct Enumerator { private readonly LogFields _owner; private Dictionary.Enumerator _dictionary; private int _index; private int _skip; private int _remaining; public LogField Current { get; private set; } internal Enumerator(LogFields owner) { _owner = owner; _dictionary = owner._dictionary?.GetEnumerator() ?? default(Dictionary.Enumerator); _index = -1; _skip = owner._skip; _remaining = ((owner._limit == 0) ? int.MaxValue : owner._limit); Current = default(LogField); } public bool MoveNext() { while (_skip > 0) { if (!Next()) { return false; } _skip--; } if (_remaining <= 0 || !Next()) { return false; } _remaining--; return true; } private bool Next() { if (_owner._dictionary != null) { if (!_dictionary.MoveNext()) { return false; } Current = new LogField(_dictionary.Current.Key, _dictionary.Current.Value); return true; } _index++; if (_owner._array != null && _index < _owner._array.Length) { Current = _owner._array[_index]; return true; } if (_owner._list != null && _index < _owner._list.Count) { Current = _owner._list[_index]; return true; } if (_owner._fields != null && _index < _owner._fields.Length) { Current = _owner._fields[_index]; return true; } return false; } public void Dispose() { _dictionary.Dispose(); } } private readonly (string Key, object? Value)[]? _array; private readonly List<(string Key, object? Value)>? _list; private readonly Dictionary? _dictionary; private readonly LogField[]? _fields; private readonly int _skip; private readonly int _limit; private LogFields((string, object?)[] value) { _array = value; _list = null; _dictionary = null; _fields = null; _skip = (_limit = 0); } private LogFields(List<(string, object?)> value) { _array = null; _list = value; _dictionary = null; _fields = null; _skip = (_limit = 0); } private LogFields(Dictionary value) { _array = null; _list = null; _dictionary = value; _fields = null; _skip = (_limit = 0); } private LogFields(LogField[] value) { _array = null; _list = null; _dictionary = null; _fields = value; _skip = (_limit = 0); } private LogFields(LogFields owner, int skip, int limit) { _array = owner._array; _list = owner._list; _dictionary = owner._dictionary; _fields = owner._fields; _skip = skip; _limit = limit; } public LogFields Take(int count) { return new LogFields(this, _skip, count); } public LogFields Skip(int count) { return new LogFields(this, _skip + count, _limit); } public static implicit operator LogFields((string Key, object? Value)[]? value) { if (value != null) { return new LogFields(value); } return default(LogFields); } public static implicit operator LogFields(List<(string Key, object? Value)>? value) { if (value != null) { return new LogFields(value); } return default(LogFields); } public static implicit operator LogFields(Dictionary? value) { if (value != null) { return new LogFields(value); } return default(LogFields); } public static implicit operator LogFields(LogField[]? value) { if (value != null) { return new LogFields(value); } return default(LogFields); } public Enumerator GetEnumerator() { return new Enumerator(this); } } public readonly struct LogTopic { public string Name { get; } public LogTopic(string name) { if (!Valid(name)) { throw new ArgumentException("A log topic must match [a-z][a-z0-9_]*.", "name"); } Name = name; } internal static bool Valid(string? name) { if (string.IsNullOrEmpty(name) || name[0] < 'a' || name[0] > 'z') { return false; } for (int i = 1; i < name.Length; i++) { if ((name[i] < 'a' || name[i] > 'z') && (name[i] < '0' || name[i] > '9') && name[i] != '_') { return false; } } return true; } public override string ToString() { return Name ?? "lifecycle"; } } public static class CoreLogTopics { public static readonly LogTopic Lifecycle = new LogTopic("lifecycle"); public static readonly LogTopic Config = new LogTopic("config"); public static readonly LogTopic Scope = new LogTopic("scope"); public static readonly LogTopic Timing = new LogTopic("timing"); } internal sealed class ProcessingTiming { private sealed class Measurement : IDisposable { private readonly ProcessingTiming _owner; private readonly float _now; private readonly Func _scope; private readonly long _started = Stopwatch.GetTimestamp(); private bool _done; public Measurement(ProcessingTiming owner, float now, Func scope) { _owner = owner; _now = now; _scope = scope; } public void Dispose() { if (!_done) { _done = true; double duration = (double)(Stopwatch.GetTimestamp() - _started) * 1000.0 / (double)Stopwatch.Frequency; _owner.Complete(_now, _scope(), duration); } } } private readonly ManualLogSource _log; private readonly string _name; private readonly DebugLoggingPolicy _policy; private float _next; private int _passes; private double _total; private double _maximum; public ProcessingTiming(ManualLogSource log, string name, DebugLoggingPolicy policy) { _log = log; _name = name; _policy = policy; } public IDisposable Measure(float now, Func scope) { return new Measurement(this, now, scope); } private void Complete(float now, int scope, double duration) { if (!_policy.Enabled) { return; } _passes++; _total += duration; _maximum = Math.Max(_maximum, duration); if (!(now < _next)) { _next = now + 60f; if (scope > 0 && DiagnosticLog.DebugAvailable(_log, _name)) { DiagnosticLog.Write(_log, _name, CoreLogTopics.Timing, string.Format("{0} passes in the last minute, avg {1} ms, max {2} ms.", _passes, (_total / (double)_passes).ToString("F2", CultureInfo.InvariantCulture), _maximum.ToString("F2", CultureInfo.InvariantCulture)), new(string, object)[1] { ("scope", scope) }, (LogLevel)32); } _passes = 0; _total = (_maximum = 0.0); } } } public sealed class SummaryCadence { private float _poll = float.NegativeInfinity; private float _emitted = float.NegativeInfinity; private string? _key; public bool Changed { get; private set; } public bool PollReady(float now) { if (now >= _poll) { return !(now - _poll < 60f); } return true; } public bool CanPoll(float now) { if (now >= _poll && now - _poll < 60f) { return false; } _poll = now; return true; } public bool ShouldEmit(float now, string key) { if (key == _key && now >= _emitted && now - _emitted < 300f) { return false; } Changed = key != _key; _key = key; _emitted = now; return true; } public void Reset() { _key = null; } } } namespace HeimKit.Configuration { public static class ConfigurationLayout { private static readonly HashSet SharedSections = new HashSet(StringComparer.Ordinal) { "Compatibility", "Diagnostics", "PlayerActivity" }; public static void Apply(string path) { string text = File.ReadAllText(path); MatchCollection matchCollection = Regex.Matches(text, "^\\[([^\\r\\n]+)\\]\\r?$", RegexOptions.Multiline); if (matchCollection.Count != 0) { List<(bool, string)> list = new List<(bool, string)>(); for (int i = 0; i < matchCollection.Count; i++) { int index = matchCollection[i].Index; int num = ((i + 1 < matchCollection.Count) ? matchCollection[i + 1].Index : text.Length); list.Add((SharedSections.Contains(matchCollection[i].Groups[1].Value), text.Substring(index, num - index))); } string text2 = string.Concat(text.Substring(0, matchCollection[0].Index), string.Concat(from section in list orderby !section.Shared select section.Text)); if (!string.Equals(text, text2, StringComparison.Ordinal)) { File.WriteAllText(path, text2, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false)); } } } } public static class ConfigurationLoader { public static T Load(string configDirectory, ManualLogSource logger, Func bindSettings) { //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_0043: Expected O, but got Unknown string path = Path.Combine(configDirectory, "heimkit.cfg"); bool flag = File.Exists(path); try { ConfigFile config = new ConfigFile(path, false) { SaveOnConfigSet = false }; T result = bindSettings(config); config.Save(); ConfigurationLayout.Apply(path); config.SaveOnConfigSet = true; config.SettingChanged += delegate { if (!config.SaveOnConfigSet) { return; } try { ConfigurationLayout.Apply(path); } catch (Exception ex2) { ManualLogSource logger3 = logger; LogTopic config3 = CoreLogTopics.Config; Exception error2 = ex2; DiagnosticLog.Write(logger3, "HeimKit", config3, "Could not organize saved configuration sections.", default(LogFields), (LogLevel)2, verbose: false, error2); } }; DiagnosticLog.Write(logger, "HeimKit", flag ? ("Loaded configuration: " + path + ".") : ("Created default configuration: " + path + "."), (LogLevel)16); return result; } catch (Exception ex) { ManualLogSource logger2 = logger; LogTopic config2 = CoreLogTopics.Config; string message = "Could not load or create configuration at " + path + "."; Exception error = ex; DiagnosticLog.Write(logger2, "HeimKit", config2, message, default(LogFields), (LogLevel)2, verbose: false, error); throw; } } } public sealed class DebugLoggingPolicy { private readonly ConfigEntry _global; private readonly ConfigEntry? _feature; public bool Suppressed { get; } public bool ConfiguredEnabled { get { if (!_global.Value) { ConfigEntry? feature = _feature; if (feature == null || !feature.Value) { return false; } } return !Suppressed; } } public bool Enabled { get { if (ConfiguredEnabled) { return DiagnosticLog.ServerActivity.Allowed; } return false; } } public void ReportStartup(ManualLogSource logger, string name, bool featureEnabled) { if (!_global.Value) { ConfigEntry? feature = _feature; if ((feature == null || !feature.Value) && !Suppressed) { return; } } if (ConfiguredEnabled) { DebugLoggingDelivery.Report(logger, name); } object obj; if (!Suppressed) { if (_global.Value) { ConfigEntry? feature2 = _feature; if (feature2 != null && feature2.Value) { obj = "global_and_feature"; goto IL_0093; } } ConfigEntry? feature3 = _feature; obj = ((feature3 != null && feature3.Value) ? "feature" : "global"); } else { obj = "hidden_override"; } goto IL_0093; IL_0093: string text = (string)obj; if (DiagnosticLog.DebugAvailable(logger, name)) { LogTopic config = CoreLogTopics.Config; string message = (Suppressed ? "Debug logging suppressed by DisableDebugLogging." : ((text == "feature") ? "Debug logging enabled by feature DebugMode." : ((text == "global") ? "Debug logging enabled by global DebugMode." : "Debug logging enabled by global and feature DebugMode."))); LogField[] obj2 = new LogField[8] { (Key: "source", Value: text), DiagnosticLog.FieldAlways("global_debug_mode", _global.Value), DiagnosticLog.FieldAlways("feature_debug_mode", _feature?.Value ?? false), DiagnosticLog.FieldAlways("disable_debug_logging", Suppressed), DiagnosticLog.FieldAlways("configured_debug_enabled", ConfiguredEnabled), DiagnosticLog.FieldAlways("feature_enabled", featureEnabled), default(LogField), default(LogField) }; ConfigEntry? feature4 = _feature; obj2[6] = (Key: "config_section", Value: (feature4 != null) ? ((ConfigEntryBase)feature4).Definition.Section : null); obj2[7] = (Key: "log_schema", Value: 2); DiagnosticLog.Write(logger, name, config, message, obj2, (LogLevel)32); } } public DebugLoggingPolicy(ConfigEntry global, bool suppressed, ConfigEntry? feature = null) { _global = global; _feature = feature; Suppressed = suppressed; } } public static class DebugLoggingResolver { private sealed class OverrideState { public bool Suppressed; public bool Invalid; public bool Warned; } public const string Key = "DisableDebugLogging"; private static readonly ConditionalWeakTable> Cache = new ConditionalWeakTable>(); public static DebugLoggingPolicy Resolve(ConfigFile config, string section, ConfigEntry global, ManualLogSource? logger = null, ConfigEntry? feature = null) { Dictionary orCreateValue = Cache.GetOrCreateValue(config); lock (orCreateValue) { if (!orCreateValue.TryGetValue(section, out var value)) { value = new OverrideState(); try { string text = Read(config, section); if (text != null) { if (bool.TryParse(text, out var result)) { value.Suppressed = result; } else { value.Suppressed = true; value.Invalid = true; } } } catch (IOException) { value.Suppressed = true; value.Invalid = true; } catch (UnauthorizedAccessException) { value.Suppressed = true; value.Invalid = true; } orCreateValue.Add(section, value); } if (value.Invalid && !value.Warned && logger != null) { value.Warned = true; DiagnosticLog.Write(logger, "HeimKit", "Invalid or unreadable feature debug override; feature diagnostics suppressed until corrected and restarted", (LogLevel)4); } return new DebugLoggingPolicy(global, value.Suppressed, feature); } } private static string? Read(ConfigFile config, string section) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Expected O, but got Unknown ConfigDefinition val = new ConfigDefinition(section, "DisableDebugLogging"); if (config.ContainsKey(val)) { return config[val].GetSerializedValue(); } if (!File.Exists(config.ConfigFilePath)) { return null; } string text = ""; string result = null; foreach (string item in File.ReadLines(config.ConfigFilePath)) { string text2 = item.Trim(); if (text2.StartsWith("#")) { continue; } if (text2.StartsWith("[") && text2.EndsWith("]")) { text = text2.Substring(1, text2.Length - 2); continue; } int num = text2.IndexOf('='); if (num >= 0 && text == section && text2.Substring(0, num).Trim() == "DisableDebugLogging") { result = text2.Substring(num + 1).Trim(); } } return result; } } public enum DebugVerbosity { Normal, Verbose } public static class DiagnosticsSettings { private static ConfigEntry? _verbosity; public static DebugVerbosity Verbosity => _verbosity?.Value ?? DebugVerbosity.Normal; public static ConfigEntry Bind(ConfigFile config) { //IL_007b: Unknown result type (might be due to invalid IL or missing references) //IL_0085: Expected O, but got Unknown _verbosity = config.Bind("Diagnostics", "DebugVerbosity", DebugVerbosity.Normal, "Normal shows concise diagnostics; Verbose adds detailed evidence when effective feature debugging is enabled. Restart after edits."); ConfigEntry result = config.Bind("Diagnostics", "DebugMode", false, "Enable diagnostics for all features unless their hidden feature override suppresses them. When false, feature DebugMode settings can enable individual diagnostics. Restart after edits."); string[] array = new string[4] { "LogStatus", "StatusIntervalSeconds", "LogRefillDetails", "LogRefillRequests" }; foreach (string text in array) { config.Bind("Diagnostics", text, "", (ConfigDescription)null); config.Remove(new ConfigDefinition("Diagnostics", text)); } return result; } } public sealed class GameVersionCompatibility { public const string AuditedVersion = "1.0.20"; private const string Section = "Compatibility"; private const string Key = "SupportedValheimVersion"; private static readonly ConditionalWeakTable Policies = new ConditionalWeakTable(); public string RequiredVersion { get; } private GameVersionCompatibility(ConfigFile config, ManualLogSource logger) { RequiredVersion = "1.0.20"; string text; try { text = Read(config); } catch (Exception ex) when (ex is IOException || ex is UnauthorizedAccessException) { Warn(logger, "Could not read Compatibility.SupportedValheimVersion; using built-in Valheim version 1.0.20."); return; } if (text == null) { return; } if (text.Length > 32 || !Version.TryParse(text, out Version result) || result.Build < 0 || result.Revision >= 0 || !string.Equals(result.ToString(), text, StringComparison.Ordinal)) { Warn(logger, "Invalid Compatibility.SupportedValheimVersion; enter one exact major.minor.patch version. Using built-in Valheim version 1.0.20."); return; } RequiredVersion = text; if (RequiredVersion != "1.0.20") { Warn(logger, "Manual Valheim version requirement is " + RequiredVersion + "; built-in audited version is 1.0.20. This override does not validate gameplay compatibility; runtime API checks remain active."); } } public static GameVersionCompatibility Resolve(ConfigFile config, ManualLogSource logger) { return Policies.GetValue(config, (ConfigFile current) => new GameVersionCompatibility(current, logger)); } public bool Supports(string gameVersion) { return string.Equals(gameVersion, RequiredVersion, StringComparison.Ordinal); } private static void Warn(ManualLogSource logger, string message) { DiagnosticLog.Write(logger, "HeimKit", message, (LogLevel)4); } private static string? Read(ConfigFile config) { //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Expected O, but got Unknown ConfigDefinition val = new ConfigDefinition("Compatibility", "SupportedValheimVersion"); if (config.ContainsKey(val)) { return config[val].GetSerializedValue().Trim(); } if (!File.Exists(config.ConfigFilePath)) { return null; } string text = ""; string result = null; foreach (string item in File.ReadLines(config.ConfigFilePath)) { string text2 = item.Trim(); if (text2.StartsWith("#")) { continue; } if (text2.StartsWith("[") && text2.EndsWith("]")) { text = text2.Substring(1, text2.Length - 2); continue; } int num = text2.IndexOf('='); if (num >= 0 && text == "Compatibility" && text2.Substring(0, num).Trim() == "SupportedValheimVersion") { result = text2.Substring(num + 1).Trim(); } } return result; } } public sealed class PlayerActivitySettings { public ConfigEntry DebugMode { get; } public DebugLoggingPolicy DebugLogging { get; } public ConfigEntry IdleTimeoutSeconds { get; } public ConfigEntry JoinGraceSeconds { get; } public ConfigEntry MovementThresholdMeters { get; } public ConfigEntry LookThresholdDegrees { get; } public ConfigEntry SampleIntervalSeconds { get; } public PlayerActivitySettings(ConfigFile config, ManualLogSource? logger = null) { //IL_006a: Unknown result type (might be due to invalid IL or missing references) //IL_0074: Expected O, but got Unknown //IL_00a3: Unknown result type (might be due to invalid IL or missing references) //IL_00ad: Expected O, but got Unknown //IL_00dc: Unknown result type (might be due to invalid IL or missing references) //IL_00e6: Expected O, but got Unknown //IL_0115: Unknown result type (might be due to invalid IL or missing references) //IL_011f: Expected O, but got Unknown //IL_014e: Unknown result type (might be due to invalid IL or missing references) //IL_0158: Expected O, but got Unknown DebugMode = config.Bind("PlayerActivity", "DebugMode", false, "Enable shared player activity diagnostics even when global and AFK feature DebugMode settings are off. Requires an active AFK tracking consumer; does not enable tracking or change AFK notices. Hidden suppression takes precedence. Restart after edits."); DebugLogging = DebugLoggingResolver.Resolve(config, "PlayerActivity", DiagnosticsSettings.Bind(config), logger, DebugMode); IdleTimeoutSeconds = config.Bind("PlayerActivity", "IdleTimeoutSeconds", 300f, new ConfigDescription("How long a player must go without activity the server can detect before HeimKit considers them idle. Default: 300 seconds (5 minutes). Lower values mark players idle sooner; higher values wait longer. The join/recovery grace must also have ended. Restart after edits.", (AcceptableValueBase)(object)new AcceptableValueRange(30f, 3600f), Array.Empty())); JoinGraceSeconds = config.Bind("PlayerActivity", "JoinGraceSeconds", 60f, new ConfigDescription("Minimum time a player is kept active after joining or recovering from loading, death or unreliable player information. Default: 60 seconds (1 minute). Both this grace period and the idle timeout must have passed before the player can be considered idle; the two times are not added together. Restart after edits.", (AcceptableValueBase)(object)new AcceptableValueRange(0f, 600f), Array.Empty())); MovementThresholdMeters = config.Bind("PlayerActivity", "MovementThresholdMeters", 0.5f, new ConfigDescription("How far a player position must change from the last activity position to count as movement. Default: 0.5 meters. Small position changes can build up to this threshold. Lower values detect smaller movements; higher values ignore more small movements. Being carried or moved by the world also counts. Restart after edits.", (AcceptableValueBase)(object)new AcceptableValueRange(0.1f, 5f), Array.Empty())); LookThresholdDegrees = config.Bind("PlayerActivity", "LookThresholdDegrees", 10f, new ConfigDescription("How much a player character must turn for the server to count it as activity. Default: 10 degrees. Lower values detect smaller turns; higher values require larger turns. This checks character direction reported to the server, so moving only the camera may not count. Restart after edits.", (AcceptableValueBase)(object)new AcceptableValueRange(1f, 90f), Array.Empty())); SampleIntervalSeconds = config.Bind("PlayerActivity", "SampleIntervalSeconds", 1f, new ConfigDescription("How often HeimKit checks player state for activity, in seconds. Default: 1 second. Lower values check more often and use more server processing; higher values check less often and may delay detecting changes. Checks run whenever an enabled feature needs idle detection, including during the day. Restart after edits.", (AcceptableValueBase)(object)new AcceptableValueRange(0.2f, 5f), Array.Empty())); } public PlayerActivityOptions Options() { return new PlayerActivityOptions(IdleTimeoutSeconds.Value, JoinGraceSeconds.Value, MovementThresholdMeters.Value, LookThresholdDegrees.Value, SampleIntervalSeconds.Value); } } }