Decompiled source of GTFO Sentry Skins v1.2.13

BepInEx/plugins/SentrySkinSlayerSquad-GTFO_Sentry_Skins/SentrySkinCompat.dll

Decompiled 5 days ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text;
using System.Text.RegularExpressions;
using BepInEx;
using BepInEx.Logging;
using BepInEx.Unity.IL2CPP;
using Gear;
using GtfoSentrySkins.SentrySkinCompat.Interop;
using GtfoSentrySkins.SentrySkinCompat.Pure;
using HarmonyLib;
using Il2CppInterop.Runtime.Injection;
using Il2CppInterop.Runtime.InteropTypes.Arrays;
using Microsoft.CodeAnalysis;
using Skins;
using Skins.Data;
using Skins.Manifest;
using Skins.Textures;
using Skins.Utils;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")]
[assembly: AssemblyCompany("GtfoSentrySkins")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyDescription("Compatibility hook that routes the four deployed GTFO sentries (null PlayfabItemInstanceId) through the Skins 0.12.0 skin target path.")]
[assembly: AssemblyFileVersion("1.2.13.0")]
[assembly: AssemblyInformationalVersion("1.2.13")]
[assembly: AssemblyProduct("GTFO Sentry Skin Compat")]
[assembly: AssemblyTitle("SentrySkinCompat")]
[assembly: AssemblyVersion("1.2.13.0")]
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;
		}
	}
}
namespace GtfoSentrySkins.SentrySkinCompat
{
	[BepInPlugin("gtfosentryskins.sentry-skin-compat", "Sentry Skin Compat", "1.2.13")]
	[BepInDependency("io.takina.gtfo.Skins", "0.12.0")]
	public sealed class Plugin : BasePlugin
	{
		public const string Guid = "gtfosentryskins.sentry-skin-compat";

		public const string SkinsGuid = "io.takina.gtfo.Skins";

		public const string SkinsMinimumVersion = "0.12.0";

		public const string Name = "Sentry Skin Compat";

		public const string Version = "1.2.13";

		internal static ManualLogSource LogSource = null;

		internal static SentryLeaseReadiness Readiness { get; private set; } = new SentryLeaseReadiness(surfaceOk: false);

		internal static bool LeaseReady
		{
			get
			{
				if (Readiness.SurfaceOk)
				{
					return EnsureRunnerHost();
				}
				return false;
			}
		}

		internal static bool CanQueueFlush => EnsureRunnerHost();

		internal static Harmony HarmonyInstance { get; } = new Harmony("gtfosentryskins.sentry-skin-compat");

		internal static bool EnsureRunnerHost()
		{
			return Readiness.TryEnsure(() => FrameLeaseRunner.IsReady, FrameLeaseRunner.Ensure, () => FrameLeaseRunner.LastError);
		}

		public override void Load()
		{
			LogSource = ((BasePlugin)this).Log;
			((BasePlugin)this).Log.LogInfo((object)"[SentrySkinCompat] Sentry Skin Compat 1.2.13 loading (Skins io.takina.gtfo.Skins 0.12.0 pinned).");
			((BasePlugin)this).Log.LogInfo((object)"[SentrySkinCompat] Root cause: Skins GearPatches.cs:31-35 returns on null PlayfabItemInstanceId, skipping AddComponent<ManagedGroupTarget>() (GearPatches.cs:69) for deployed sentries.");
			((BasePlugin)this).Log.LogInfo((object)"[SentrySkinCompat] Apply path: SkinManager.ApplyGroupToRawTarget (Skins 0.12.0 public API) - Skins.dll is not modified.");
			((BasePlugin)this).Log.LogInfo((object)"[SentrySkinCompat] Scope: only the four bundled sentry skin groups (gtfosentryskins.sentry-sgb3 / gtfosentryskins.sentry-meduza / gtfosentryskins.sentry-b5lfr / gtfosentryskins.sentry-rsg). Any other selection fails closed; Turret_Base_1 and material '1' are shared across all four turrets, so this is deliberately not a wildcard bridge.");
			((BasePlugin)this).Log.LogInfo((object)"[SentrySkinCompat] Owner scope: one token per MeshRenderer (Turret_Base_1 and Turret_Verticle_1 both carry material '1'). Skins defers texture writes by owner identity, so a shared owner left the visible body on the vanilla atlas (black).");
			try
			{
				Assembly assembly = typeof(Plugin).Assembly;
				HarmonyInstance.PatchAll(assembly);
				bool flag = TextureLibraryBridge.TryInitialize(delegate(string message)
				{
					((BasePlugin)this).Log.LogError((object)message);
				});
				Readiness = new SentryLeaseReadiness(flag && SkinsLeaseAccessors.IsAvailable);
				if (Readiness.SurfaceOk && EnsureRunnerHost())
				{
					((BasePlugin)this).Log.LogInfo((object)("[SentrySkinCompat] Harmony PatchAll invoked for " + assembly.GetName().Name + " (GearPartHolder.OnAllPartsSpawned postfix priority -200 after io.takina.gtfo.Skins, plus GearPartHolder.OnDestroy ledger + lease cleanup; texture lease runner started)."));
					return;
				}
				((BasePlugin)this).Log.LogError((object)("[SentrySkinCompat] Texture lease surface incomplete (" + (flag ? SkinsLeaseAccessors.FailureReason : TextureLibraryBridge.FailureReason) + "; " + Readiness.Describe() + "); Harmony hooks stay installed but every apply is refused (fail-closed)."));
			}
			catch (Exception ex)
			{
				Readiness = new SentryLeaseReadiness(surfaceOk: false);
				Readiness.MarkRunnerFailed(ex.GetType().Name + ": " + ex.Message);
				((BasePlugin)this).Log.LogError((object)("[SentrySkinCompat] Harmony PatchAll failed: " + ex));
			}
		}
	}
}
namespace GtfoSentrySkins.SentrySkinCompat.Pure
{
	public sealed class ReceiptBudget
	{
		private int _issued;

		public int Max { get; }

		public int Issued => _issued;

		public ReceiptBudget(int maxReceipts)
		{
			Max = ((maxReceipts >= 0) ? maxReceipts : 0);
		}

		public bool TryTake(out int index)
		{
			if (_issued >= Max)
			{
				index = -1;
				return false;
			}
			index = _issued;
			_issued++;
			return true;
		}
	}
	public enum SentryRendererGate
	{
		Applicable,
		NoMeshFilter,
		NullSharedMesh,
		NullMaterial,
		Unreadable
	}
	public static class SentryApplyGate
	{
		public static SentryRendererGate Check(bool hasMeshFilter, bool hasSharedMesh, bool hasMaterial)
		{
			if (!hasMeshFilter)
			{
				return SentryRendererGate.NoMeshFilter;
			}
			if (!hasSharedMesh)
			{
				return SentryRendererGate.NullSharedMesh;
			}
			if (!hasMaterial)
			{
				return SentryRendererGate.NullMaterial;
			}
			return SentryRendererGate.Applicable;
		}

		public static bool IsApplicable(SentryRendererGate gate)
		{
			return gate == SentryRendererGate.Applicable;
		}

		public static string Describe(SentryRendererGate gate)
		{
			return gate switch
			{
				SentryRendererGate.NoMeshFilter => "no MeshFilter", 
				SentryRendererGate.NullSharedMesh => "null sharedMesh", 
				SentryRendererGate.NullMaterial => "null material", 
				SentryRendererGate.Unreadable => "unreadable renderer", 
				_ => "applicable", 
			};
		}
	}
	public sealed class SentryApplyLedger
	{
		private struct Entry
		{
			public string GroupGuid;

			public double AppliedAtSeconds;
		}

		public const int Capacity = 128;

		public const double DefaultMaxAgeSeconds = 600.0;

		private readonly Dictionary<int, Entry> _entries = new Dictionary<int, Entry>();

		private readonly Queue<int> _order = new Queue<int>();

		public int Count => _entries.Count;

		public bool IsApplied(int instanceId, string groupGuid, double nowSeconds, double maxAgeSeconds)
		{
			if (groupGuid == null)
			{
				return false;
			}
			if (!_entries.TryGetValue(instanceId, out var value))
			{
				return false;
			}
			if (!string.Equals(value.GroupGuid, groupGuid, StringComparison.OrdinalIgnoreCase))
			{
				return false;
			}
			if (maxAgeSeconds > 0.0 && nowSeconds - value.AppliedAtSeconds > maxAgeSeconds)
			{
				_entries.Remove(instanceId);
				return false;
			}
			return true;
		}

		public bool IsApplied(int instanceId, string groupGuid)
		{
			return IsApplied(instanceId, groupGuid, 0.0, 0.0);
		}

		public bool MarkApplied(int instanceId, string groupGuid, double nowSeconds)
		{
			if (groupGuid == null)
			{
				return false;
			}
			if (IsApplied(instanceId, groupGuid, 0.0, 0.0))
			{
				return false;
			}
			if (!_entries.ContainsKey(instanceId))
			{
				_order.Enqueue(instanceId);
			}
			_entries[instanceId] = new Entry
			{
				GroupGuid = groupGuid,
				AppliedAtSeconds = nowSeconds
			};
			while (_entries.Count > 128 && _order.Count > 0)
			{
				int key = _order.Dequeue();
				_entries.Remove(key);
			}
			return true;
		}

		public bool MarkApplied(int instanceId, string groupGuid)
		{
			return MarkApplied(instanceId, groupGuid, 0.0);
		}

		public bool Forget(int instanceId)
		{
			if (!_entries.Remove(instanceId))
			{
				return false;
			}
			RebuildQueue();
			return true;
		}

		private void RebuildQueue()
		{
			if (_order.Count == 0)
			{
				return;
			}
			int[] array = _order.ToArray();
			_order.Clear();
			HashSet<int> hashSet = new HashSet<int>();
			int[] array2 = array;
			foreach (int num in array2)
			{
				if (_entries.ContainsKey(num) && hashSet.Add(num))
				{
					_order.Enqueue(num);
				}
			}
		}

		public int Prune(double nowSeconds, double maxAgeSeconds)
		{
			if (maxAgeSeconds <= 0.0 || _entries.Count == 0)
			{
				return 0;
			}
			List<int> list = null;
			foreach (KeyValuePair<int, Entry> entry in _entries)
			{
				if (nowSeconds - entry.Value.AppliedAtSeconds > maxAgeSeconds)
				{
					(list ?? (list = new List<int>())).Add(entry.Key);
				}
			}
			if (list == null)
			{
				return 0;
			}
			foreach (int item in list)
			{
				_entries.Remove(item);
			}
			PruneDeadQueueEntries();
			return list.Count;
		}

		public void Clear()
		{
			_entries.Clear();
			_order.Clear();
		}

		private void PruneDeadQueueEntries()
		{
			while (_order.Count > 0 && !_entries.ContainsKey(_order.Peek()))
			{
				_order.Dequeue();
			}
		}
	}
	public enum SentryDecision
	{
		Apply,
		SkipNotSentry,
		SkipAlreadyApplied,
		SkipSelectionMissing,
		SkipSelectionMismatch,
		SkipGroupUnavailable,
		SkipNoRenderers,
		SkipNoMeshTarget,
		SkipMeshTargetUnresolved
	}
	public readonly struct SentryProbe
	{
		public int RendererCount { get; }

		public int MeshTargetCount { get; }

		public int ResolvedMeshTargetCount { get; }

		public int SatisfiedTargetCount { get; }

		public bool LedgerSaysApplied { get; }

		public SentryProbe(int rendererCount, int meshTargetCount, int resolvedMeshTargetCount, int satisfiedTargetCount, bool ledgerSaysApplied)
		{
			RendererCount = rendererCount;
			MeshTargetCount = meshTargetCount;
			ResolvedMeshTargetCount = resolvedMeshTargetCount;
			SatisfiedTargetCount = satisfiedTargetCount;
			LedgerSaysApplied = ledgerSaysApplied;
		}
	}
	public enum SentryApplyOutcome
	{
		Proven,
		ProvenAlreadyTarget,
		Unproven
	}
	public sealed class SentryDecisionResult
	{
		public SentryDecision Decision { get; }

		public SentryBinding? Binding { get; }

		public bool PlayfabItemInstanceIdNull { get; }

		public string Detail { get; }

		public bool ShouldApply => Decision == SentryDecision.Apply;

		public SentryDecisionResult(SentryDecision decision, SentryBinding? binding, bool playfabItemInstanceIdNull, string detail)
		{
			Decision = decision;
			Binding = binding;
			PlayfabItemInstanceIdNull = playfabItemInstanceIdNull;
			Detail = detail ?? string.Empty;
		}

		public override string ToString()
		{
			return Decision.ToString() + " (" + Detail + ")";
		}
	}
	public static class SentryApplyPolicy
	{
		public static SentryDecisionResult Decide(string? holderName, string? selectedGroupGuid, bool groupRegistered, SentryProbe probe, bool playfabItemInstanceIdNull)
		{
			if (!SentryMatrix.TryResolve(holderName, out SentryBinding binding) || binding == null)
			{
				return new SentryDecisionResult(SentryDecision.SkipNotSentry, null, playfabItemInstanceIdNull, "not one of the four sentry models");
			}
			if (string.IsNullOrWhiteSpace(selectedGroupGuid))
			{
				return new SentryDecisionResult(SentryDecision.SkipSelectionMissing, binding, playfabItemInstanceIdNull, "no skin selection for gear " + binding.GearPersistentId);
			}
			string text = SentrySeams.ExpectedGroupGuid(binding);
			if (!string.Equals(selectedGroupGuid, text, StringComparison.OrdinalIgnoreCase))
			{
				return new SentryDecisionResult(SentryDecision.SkipSelectionMismatch, binding, playfabItemInstanceIdNull, "selected '" + selectedGroupGuid + "' <> sentry group '" + text + "'");
			}
			if (!groupRegistered)
			{
				return new SentryDecisionResult(SentryDecision.SkipGroupUnavailable, binding, playfabItemInstanceIdNull, "group '" + selectedGroupGuid + "' is not registered with Skins");
			}
			if (probe.RendererCount <= 0)
			{
				return new SentryDecisionResult(SentryDecision.SkipNoRenderers, binding, playfabItemInstanceIdNull, "no MeshRenderer under holder");
			}
			if (probe.MeshTargetCount <= 0)
			{
				return new SentryDecisionResult(SentryDecision.SkipNoMeshTarget, binding, playfabItemInstanceIdNull, "group '" + binding.GroupGuid + "' has no mesh target for these renderer names");
			}
			if (probe.ResolvedMeshTargetCount <= 0)
			{
				return new SentryDecisionResult(SentryDecision.SkipMeshTargetUnresolved, binding, playfabItemInstanceIdNull, "mesh targets exist but none resolved to a Mesh (bundle not loaded)");
			}
			if (probe.LedgerSaysApplied && probe.SatisfiedTargetCount >= probe.ResolvedMeshTargetCount && probe.SatisfiedTargetCount > 0)
			{
				return new SentryDecisionResult(SentryDecision.SkipAlreadyApplied, binding, playfabItemInstanceIdNull, "ledger + mesh state prove group " + binding.GroupGuid + " is already applied");
			}
			return new SentryDecisionResult(SentryDecision.Apply, binding, playfabItemInstanceIdNull, "null-PSII fallback");
		}

		public static bool ShouldPersistLedger(SentryApplyOutcome outcome)
		{
			if (outcome != SentryApplyOutcome.Proven)
			{
				return outcome == SentryApplyOutcome.ProvenAlreadyTarget;
			}
			return true;
		}

		public static SentryApplyOutcome ClassifyOutcome(int resolvedMeshTargetCount, int provenAfterApply, int changedAfterApply)
		{
			if (provenAfterApply <= 0)
			{
				return SentryApplyOutcome.Unproven;
			}
			if (changedAfterApply <= 0 && provenAfterApply >= resolvedMeshTargetCount)
			{
				return SentryApplyOutcome.ProvenAlreadyTarget;
			}
			return SentryApplyOutcome.Proven;
		}

		public static SkipReceiptClass ClassifySkip(SentryDecision decision)
		{
			switch (decision)
			{
			case SentryDecision.Apply:
			case SentryDecision.SkipNotSentry:
			case SentryDecision.SkipAlreadyApplied:
				return SkipReceiptClass.None;
			case SentryDecision.SkipNoMeshTarget:
			case SentryDecision.SkipMeshTargetUnresolved:
				return SkipReceiptClass.StableState;
			default:
				return SkipReceiptClass.Diagnostic;
			}
		}

		public static bool ConsumesDiagnosticSkipBudget(SentryDecision decision)
		{
			return ClassifySkip(decision) == SkipReceiptClass.Diagnostic;
		}
	}
	public sealed class SentryDecodeLedger
	{
		private readonly int[] _decodes;

		private int _cursor;

		public int Slots { get; }

		public int Cursor
		{
			get
			{
				if (Slots != 0)
				{
					return _cursor % Slots;
				}
				return 0;
			}
		}

		public int TotalDecodes
		{
			get
			{
				int num = 0;
				for (int i = 0; i < _decodes.Length; i++)
				{
					num += _decodes[i];
				}
				return num;
			}
		}

		public bool AllSlotsExhausted
		{
			get
			{
				for (int i = 0; i < _decodes.Length; i++)
				{
					if (_decodes[i] < 8)
					{
						return false;
					}
				}
				return true;
			}
		}

		public SentryDecodeLedger(int slots)
		{
			Slots = ((slots >= 0) ? slots : 0);
			_decodes = new int[Slots];
		}

		public int Decodes(int slot)
		{
			if (slot < 0 || slot >= Slots)
			{
				return 0;
			}
			return _decodes[slot];
		}

		public bool CanDecode(int slot)
		{
			if (slot < 0 || slot >= Slots)
			{
				return false;
			}
			return _decodes[slot] < 8;
		}

		public void RecordDecode(int slot)
		{
			if (slot >= 0 && slot < Slots)
			{
				_decodes[slot]++;
			}
		}

		public int Order(int index)
		{
			if (Slots <= 0)
			{
				return 0;
			}
			return ((Cursor + index) % Slots + Slots) % Slots;
		}

		public void AdvanceCursor(int served)
		{
			if (Slots > 0 && served > 0)
			{
				_cursor = (_cursor + served) % Slots;
			}
		}

		public void Reset()
		{
			Array.Clear(_decodes, 0, _decodes.Length);
			_cursor = 0;
		}
	}
	public enum SentryEvictionOutcome
	{
		NotAttempted,
		Deferred,
		EvictionFailed,
		EvictedThenLive,
		EvictedThenDead
	}
	public enum SentryPinRecovery
	{
		Reacquired,
		EnsuredFallback,
		Lost
	}
	public static class SentryEvictionPolicy
	{
		public static bool TryReserveRetry(bool decodeSlotAvailable, out SentryEvictionOutcome outcome)
		{
			if (!decodeSlotAvailable)
			{
				outcome = SentryEvictionOutcome.Deferred;
				return false;
			}
			outcome = SentryEvictionOutcome.NotAttempted;
			return true;
		}

		public static SentryEvictionOutcome Complete(bool evictProved, bool retryAlive)
		{
			if (!evictProved)
			{
				return SentryEvictionOutcome.EvictionFailed;
			}
			if (!retryAlive)
			{
				return SentryEvictionOutcome.EvictedThenDead;
			}
			return SentryEvictionOutcome.EvictedThenLive;
		}

		public static bool CountsAsEviction(SentryEvictionOutcome outcome)
		{
			if (outcome != SentryEvictionOutcome.EvictedThenLive)
			{
				return outcome == SentryEvictionOutcome.EvictedThenDead;
			}
			return true;
		}

		public static bool IsGiveUp(SentryEvictionOutcome outcome)
		{
			return outcome == SentryEvictionOutcome.EvictedThenDead;
		}

		public static bool IsTrouble(SentryEvictionOutcome outcome)
		{
			if (outcome != SentryEvictionOutcome.Deferred)
			{
				return outcome == SentryEvictionOutcome.EvictionFailed;
			}
			return true;
		}

		public static string Describe(SentryEvictionOutcome outcome)
		{
			return outcome switch
			{
				SentryEvictionOutcome.Deferred => "evict-deferred/no-decode-slot", 
				SentryEvictionOutcome.EvictionFailed => "evict-failed/key-still-cached", 
				SentryEvictionOutcome.EvictedThenLive => "evicted/recovered", 
				SentryEvictionOutcome.EvictedThenDead => "evicted/still-dead", 
				_ => "not-attempted", 
			};
		}

		public static SentryPinRecovery PinDecision(bool reacquired, bool ensureOk)
		{
			if (reacquired)
			{
				return SentryPinRecovery.Reacquired;
			}
			if (!ensureOk)
			{
				return SentryPinRecovery.Lost;
			}
			return SentryPinRecovery.EnsuredFallback;
		}

		public static bool PinNeedsWarn(SentryPinRecovery pin)
		{
			return pin != SentryPinRecovery.Reacquired;
		}

		public static string DescribePin(SentryPinRecovery pin)
		{
			return pin switch
			{
				SentryPinRecovery.Reacquired => "reacquired", 
				SentryPinRecovery.EnsuredFallback => "fallback-ensured", 
				_ => "lost", 
			};
		}
	}
	public sealed class SentryRecoveryTally
	{
		private const int OutcomeCount = 5;

		private const int PinCount = 3;

		private readonly object _gate = new object();

		private readonly int[] _evictions = new int[5];

		private readonly int[] _pins = new int[3];

		public int Evicted
		{
			get
			{
				lock (_gate)
				{
					return _evictions[3] + _evictions[4];
				}
			}
		}

		public int Deferred
		{
			get
			{
				lock (_gate)
				{
					return _evictions[1];
				}
			}
		}

		public int Failed
		{
			get
			{
				lock (_gate)
				{
					return _evictions[2];
				}
			}
		}

		public void RecordEviction(SentryEvictionOutcome outcome)
		{
			if (outcome <= SentryEvictionOutcome.NotAttempted || outcome >= (SentryEvictionOutcome)5)
			{
				return;
			}
			lock (_gate)
			{
				_evictions[(int)outcome]++;
			}
		}

		public void RecordPin(SentryPinRecovery pin)
		{
			if (pin < SentryPinRecovery.Reacquired || pin >= (SentryPinRecovery)3)
			{
				return;
			}
			lock (_gate)
			{
				_pins[(int)pin]++;
			}
		}

		public int Count(SentryEvictionOutcome outcome)
		{
			if (outcome <= SentryEvictionOutcome.NotAttempted || outcome >= (SentryEvictionOutcome)5)
			{
				return 0;
			}
			lock (_gate)
			{
				return _evictions[(int)outcome];
			}
		}

		public int Count(SentryPinRecovery pin)
		{
			if (pin < SentryPinRecovery.Reacquired || pin >= (SentryPinRecovery)3)
			{
				return 0;
			}
			lock (_gate)
			{
				return _pins[(int)pin];
			}
		}

		public string Describe()
		{
			lock (_gate)
			{
				return "evicted=" + (_evictions[3] + _evictions[4]) + " evictFailed=" + _evictions[2] + " evictDeferred=" + _evictions[1] + " pinBack=" + _pins[0] + " pinEnsure=" + _pins[1] + " pinLost=" + _pins[2];
			}
		}

		public void Clear()
		{
			lock (_gate)
			{
				for (int i = 0; i < 5; i++)
				{
					_evictions[i] = 0;
				}
				for (int j = 0; j < 3; j++)
				{
					_pins[j] = 0;
				}
			}
		}
	}
	public enum SentryFlushVerdict
	{
		Complete,
		Waiting,
		TimedOut
	}
	public enum SentryFlushRetire
	{
		Written,
		AlreadyWritten,
		MaterialGone,
		TimedOut,
		Exception,
		Rejected
	}
	public static class SentryFlushPolicy
	{
		public const int MaxEntries = 32;

		public const double RetryIntervalSeconds = 0.1;

		public const double MaxRetryIntervalSeconds = 1.0;

		public const double GiveUpSeconds = 20.0;

		public const int MaxDecodeAttempts = 8;

		public const int MaxDecodesPerFrame = 2;

		public static double RetryDelaySeconds(int attempt)
		{
			if (attempt <= 1)
			{
				return 0.1;
			}
			double num = 0.1;
			for (int i = 1; i < attempt; i++)
			{
				num *= 2.0;
				if (num >= 1.0)
				{
					return 1.0;
				}
			}
			return num;
		}

		public static bool ShouldRequestDecode(int decodesSpent, bool cacheHit)
		{
			if (cacheHit)
			{
				return false;
			}
			if (decodesSpent >= 0)
			{
				return decodesSpent < 8;
			}
			return false;
		}

		public static bool IsSlotFilled(bool written, bool holdsLiveTexture)
		{
			return written && holdsLiveTexture;
		}

		public static bool WriteProved(bool readbackAlive, int readbackId, int writtenId)
		{
			if (!readbackAlive || writtenId == 0)
			{
				return false;
			}
			return readbackId == writtenId;
		}

		public static SentryFlushVerdict Decide(int pendingSlots, double now, double deadline)
		{
			if (pendingSlots <= 0)
			{
				return SentryFlushVerdict.Complete;
			}
			if (!(now >= deadline))
			{
				return SentryFlushVerdict.Waiting;
			}
			return SentryFlushVerdict.TimedOut;
		}

		public static SentryFlushRetire CompleteReason(int writtenByUs)
		{
			if (writtenByUs <= 0)
			{
				return SentryFlushRetire.AlreadyWritten;
			}
			return SentryFlushRetire.Written;
		}

		public static bool IsFailure(SentryFlushRetire reason)
		{
			if (reason != SentryFlushRetire.TimedOut && reason != SentryFlushRetire.Exception)
			{
				return reason == SentryFlushRetire.Rejected;
			}
			return true;
		}
	}
	public sealed class SentryFlushTally
	{
		private const int ReasonCount = 6;

		private readonly object _gate = new object();

		private readonly int[] _counts = new int[6];

		public int Total
		{
			get
			{
				lock (_gate)
				{
					int num = 0;
					for (int i = 0; i < 6; i++)
					{
						num += _counts[i];
					}
					return num;
				}
			}
		}

		public int Failures => Count(SentryFlushRetire.TimedOut) + Count(SentryFlushRetire.Exception) + Count(SentryFlushRetire.Rejected);

		public void Record(SentryFlushRetire reason)
		{
			if (reason < SentryFlushRetire.Written || reason >= (SentryFlushRetire)6)
			{
				return;
			}
			lock (_gate)
			{
				_counts[(int)reason]++;
			}
		}

		public int Count(SentryFlushRetire reason)
		{
			if (reason < SentryFlushRetire.Written || reason >= (SentryFlushRetire)6)
			{
				return 0;
			}
			lock (_gate)
			{
				return _counts[(int)reason];
			}
		}

		public string Describe()
		{
			lock (_gate)
			{
				return "written=" + _counts[0] + " alreadyWritten=" + _counts[1] + " materialGone=" + _counts[2] + " timedOut=" + _counts[3] + " exception=" + _counts[4] + " rejected=" + _counts[5];
			}
		}

		public void Clear()
		{
			lock (_gate)
			{
				for (int i = 0; i < 6; i++)
				{
					_counts[i] = 0;
				}
			}
		}
	}
	public enum SentryOfferResult
	{
		Reused,
		Repointed,
		Added,
		RejectedNoMaterial,
		RejectedNoSlot,
		RejectedFull
	}
	public interface ISentryQueuePayload
	{
		int HolderId { get; }

		object Token { get; }

		string RendererName { get; set; }

		string GroupGuid { get; set; }

		string GroupFolder { get; set; }

		int SlotCount { get; }

		double Deadline { get; set; }

		double NextTry { get; set; }

		int Ticks { get; set; }

		int Supersedes { get; set; }

		bool Retired { get; set; }
	}
	public readonly struct SentryQueueRequest
	{
		public int HolderId { get; }

		public object Token { get; }

		public int MaterialId { get; }

		public int SlotCount { get; }

		public string RendererName { get; }

		public string GroupGuid { get; }

		public string GroupFolder { get; }

		public double Now { get; }

		public double DeadlineSeconds { get; }

		public SentryQueueRequest(int holderId, object token, int materialId, int slotCount, string? rendererName, string? groupGuid, string? groupFolder, double now, double deadlineSeconds)
		{
			HolderId = holderId;
			Token = token;
			MaterialId = materialId;
			SlotCount = slotCount;
			RendererName = rendererName ?? string.Empty;
			GroupGuid = groupGuid ?? string.Empty;
			GroupFolder = groupFolder ?? string.Empty;
			Now = now;
			DeadlineSeconds = deadlineSeconds;
		}
	}
	public sealed class SentryFlushTable
	{
		private readonly Func<ISentryQueuePayload, int> _materialIdOf;

		private readonly List<ISentryQueuePayload> _entries;

		public int Capacity { get; }

		public int Count => _entries.Count;

		public SentryFlushTable(Func<ISentryQueuePayload, int> materialIdOf, int capacity = 32)
		{
			_materialIdOf = materialIdOf ?? throw new ArgumentNullException("materialIdOf");
			Capacity = ((capacity >= 0) ? capacity : 0);
			_entries = new List<ISentryQueuePayload>(Capacity);
		}

		public IReadOnlyList<ISentryQueuePayload> Snapshot()
		{
			return new List<ISentryQueuePayload>(_entries);
		}

		public ISentryQueuePayload? Find(int holderId, object token)
		{
			if (token == null)
			{
				return null;
			}
			for (int i = 0; i < _entries.Count; i++)
			{
				ISentryQueuePayload sentryQueuePayload = _entries[i];
				if (sentryQueuePayload.HolderId == holderId && sentryQueuePayload.Token == token)
				{
					return sentryQueuePayload;
				}
			}
			return null;
		}

		public bool TokenStillHeld(int holderId, object token)
		{
			return Find(holderId, token) != null;
		}

		public SentryOfferResult Offer(in SentryQueueRequest request, Action<ISentryQueuePayload>? repoint, out ISentryQueuePayload? entry, out int droppedDuplicates)
		{
			entry = null;
			droppedDuplicates = 0;
			if (request.Token == null)
			{
				return SentryOfferResult.RejectedNoMaterial;
			}
			ISentryQueuePayload sentryQueuePayload = null;
			ISentryQueuePayload sentryQueuePayload2 = null;
			List<ISentryQueuePayload> list = null;
			for (int i = 0; i < _entries.Count; i++)
			{
				ISentryQueuePayload sentryQueuePayload3 = _entries[i];
				if (sentryQueuePayload3.HolderId == request.HolderId && sentryQueuePayload3.Token == request.Token)
				{
					if (sentryQueuePayload2 == null)
					{
						sentryQueuePayload2 = sentryQueuePayload3;
					}
					else
					{
						(list ?? (list = new List<ISentryQueuePayload>(1))).Add(sentryQueuePayload3);
					}
					if (sentryQueuePayload == null && request.MaterialId != 0 && _materialIdOf(sentryQueuePayload3) == request.MaterialId)
					{
						sentryQueuePayload = sentryQueuePayload3;
					}
				}
			}
			if (sentryQueuePayload != null)
			{
				droppedDuplicates += DropExtras(list, sentryQueuePayload2, sentryQueuePayload);
				entry = sentryQueuePayload;
				return SentryOfferResult.Reused;
			}
			if (sentryQueuePayload2 != null)
			{
				if (request.MaterialId == 0)
				{
					return SentryOfferResult.RejectedNoMaterial;
				}
				if (request.SlotCount <= 0)
				{
					return SentryOfferResult.RejectedNoSlot;
				}
				droppedDuplicates += DropExtras(list, null, sentryQueuePayload2);
				repoint?.Invoke(sentryQueuePayload2);
				sentryQueuePayload2.RendererName = request.RendererName;
				sentryQueuePayload2.GroupGuid = request.GroupGuid;
				sentryQueuePayload2.GroupFolder = request.GroupFolder;
				sentryQueuePayload2.Ticks = 0;
				sentryQueuePayload2.NextTry = 0.0;
				sentryQueuePayload2.Supersedes++;
				entry = sentryQueuePayload2;
				return SentryOfferResult.Repointed;
			}
			if (_entries.Count >= Capacity)
			{
				return SentryOfferResult.RejectedFull;
			}
			return SentryOfferResult.Added;
		}

		public bool TryAdd(ISentryQueuePayload payload, in SentryQueueRequest request)
		{
			if (payload == null || request.Token == null || request.MaterialId == 0 || request.SlotCount <= 0)
			{
				return false;
			}
			if (payload.HolderId != request.HolderId || payload.Token != request.Token)
			{
				return false;
			}
			if (_entries.Count >= Capacity || Find(request.HolderId, request.Token) != null)
			{
				return false;
			}
			payload.RendererName = request.RendererName;
			payload.GroupGuid = request.GroupGuid;
			payload.GroupFolder = request.GroupFolder;
			payload.Ticks = 0;
			payload.NextTry = 0.0;
			payload.Supersedes = 0;
			payload.Retired = false;
			payload.Deadline = request.Now + request.DeadlineSeconds;
			_entries.Add(payload);
			return true;
		}

		public bool Remove(ISentryQueuePayload? payload)
		{
			if (payload == null)
			{
				return false;
			}
			if (!_entries.Remove(payload))
			{
				return false;
			}
			payload.Retired = true;
			return true;
		}

		public int RemoveAll(int holderId)
		{
			int num = 0;
			for (int num2 = _entries.Count - 1; num2 >= 0; num2--)
			{
				if (_entries[num2].HolderId == holderId)
				{
					_entries[num2].Retired = true;
					_entries.RemoveAt(num2);
					num++;
				}
			}
			return num;
		}

		public void Clear()
		{
			for (int i = 0; i < _entries.Count; i++)
			{
				_entries[i].Retired = true;
			}
			_entries.Clear();
		}

		private int DropExtras(List<ISentryQueuePayload>? extras, ISentryQueuePayload? first, ISentryQueuePayload keep)
		{
			int num = 0;
			if (extras != null)
			{
				for (int i = 0; i < extras.Count; i++)
				{
					if (extras[i] != keep && _entries.Remove(extras[i]))
					{
						num++;
					}
				}
			}
			if (first != null && first != keep && _entries.Remove(first))
			{
				num++;
			}
			return num;
		}
	}
	public sealed class SentryFrameBudget
	{
		private readonly int _max;

		private int _taken;

		public int Max => _max;

		public int Taken => _taken;

		public int Remaining => _max - _taken;

		public SentryFrameBudget(int maxPerFrame)
		{
			_max = ((maxPerFrame >= 0) ? maxPerFrame : 0);
		}

		public void Reset()
		{
			_taken = 0;
		}

		public bool TryTake(out int index)
		{
			if (_taken >= _max)
			{
				index = -1;
				return false;
			}
			index = _taken;
			_taken++;
			return true;
		}
	}
	public static class SentryTickRotation
	{
		public static int NextStart(int previousStart, int count)
		{
			return Advance(previousStart, count, 1);
		}

		public static int Advance(int previousStart, int count, int step)
		{
			if (count <= 1)
			{
				return 0;
			}
			if (step < 1)
			{
				step = 1;
			}
			int num = (previousStart + step) % count;
			if (num >= 0)
			{
				return num;
			}
			return 0;
		}

		public static int[] Order(int start, int count)
		{
			if (count <= 0)
			{
				return Array.Empty<int>();
			}
			int[] array = new int[count];
			int num = start % count;
			if (num < 0)
			{
				num = 0;
			}
			for (int i = 0; i < count; i++)
			{
				array[i] = (num + i) % count;
			}
			return array;
		}
	}
	public static class SentryGroupMap
	{
		public const int MaxGuidLength = 96;

		public const int MinGuidLength = 8;

		public static bool TryResolveExpectedGuid(string? rawHolderName, IReadOnlyDictionary<string, string>? overrides, out SentryBinding? binding, out string groupGuid, out string reason)
		{
			groupGuid = string.Empty;
			if (!SentryMatrix.TryResolve(rawHolderName, out binding) || binding == null)
			{
				reason = "not-a-sentry";
				return false;
			}
			if (overrides == null || overrides.Count == 0)
			{
				reason = "no-overrides-configured";
				return false;
			}
			if (!TryGetOverride(overrides, binding.DisplayName, out string value))
			{
				reason = "no-override-for-" + Slug(binding.DisplayName);
				return false;
			}
			string text = (value ?? string.Empty).Trim();
			if (!IsUsableGuid(text, out string reason2))
			{
				reason = "invalid-guid:" + reason2;
				return false;
			}
			if (string.Equals(text, binding.GroupGuid, StringComparison.OrdinalIgnoreCase))
			{
				reason = "override-equals-shared-guid:" + binding.GroupGuid;
				return false;
			}
			if (TryFindDuplicate(overrides, binding.DisplayName, text, out string duplicateOf))
			{
				reason = "duplicate-guid-shared-with-" + Slug(duplicateOf);
				return false;
			}
			groupGuid = text;
			reason = "profile-local-override";
			return true;
		}

		public static bool IsUsableGuid(string? value, out string reason)
		{
			if (string.IsNullOrWhiteSpace(value))
			{
				reason = "blank";
				return false;
			}
			string text = value.Trim();
			if (text.Length < 8 || text.Length > 96)
			{
				reason = "length(" + text.Length + ")";
				return false;
			}
			for (int i = 0; i < text.Length; i++)
			{
				char c = text[i];
				if ((c < 'a' || c > 'z') && (c < 'A' || c > 'Z') && (c < '0' || c > '9') && c != '.' && c != '_' && c != '-')
				{
					reason = "illegal-char(" + c + ")";
					return false;
				}
			}
			if (text == "." || text == ".." || text.Contains(".."))
			{
				reason = "path-traversal";
				return false;
			}
			reason = "ok";
			return true;
		}

		public static string UnconfiguredSentinel(SentryBinding binding)
		{
			return "<unconfigured-sentry-gear-" + binding.GearPersistentId + ">";
		}

		private static bool TryGetOverride(IReadOnlyDictionary<string, string> overrides, string displayName, out string? value)
		{
			foreach (KeyValuePair<string, string> @override in overrides)
			{
				if (string.Equals(@override.Key?.Trim(), displayName, StringComparison.OrdinalIgnoreCase))
				{
					value = @override.Value;
					return true;
				}
			}
			value = null;
			return false;
		}

		private static bool TryFindDuplicate(IReadOnlyDictionary<string, string> overrides, string selfName, string guid, out string duplicateOf)
		{
			foreach (KeyValuePair<string, string> @override in overrides)
			{
				if (@override.Key != null && !string.Equals(@override.Key.Trim(), selfName, StringComparison.OrdinalIgnoreCase) && string.Equals((@override.Value ?? string.Empty).Trim(), guid, StringComparison.OrdinalIgnoreCase))
				{
					duplicateOf = @override.Key.Trim();
					return true;
				}
			}
			duplicateOf = string.Empty;
			return false;
		}

		private static string Slug(string value)
		{
			return value.Replace(' ', '-').ToLowerInvariant();
		}
	}
	public static class SentryLeasePolicy
	{
		public static bool ShouldLease(SentryApplyOutcome outcome, int proven)
		{
			if (proven <= 0)
			{
				return false;
			}
			if ((uint)outcome <= 1u)
			{
				return true;
			}
			return false;
		}

		public static bool MustReleaseBeforeRegister(bool shouldLease, string leasedGroup, string selectedGroup)
		{
			if (string.IsNullOrEmpty(leasedGroup))
			{
				return false;
			}
			if (!shouldLease)
			{
				return true;
			}
			return !string.Equals(leasedGroup, selectedGroup, StringComparison.Ordinal);
		}
	}
	public sealed class SentryLeaseReadiness
	{
		public const int MaxEnsureAttempts = 16;

		public const int MaxRunnerRecoveries = 8;

		private bool _surfaceOk;

		private bool _runnerOk;

		private int _ensureAttempts;

		private int _recoveries;

		private string _lastError = string.Empty;

		public bool SurfaceOk => _surfaceOk;

		public bool RunnerOk => _runnerOk;

		public int EnsureAttempts => _ensureAttempts;

		public int Recoveries => _recoveries;

		public string LastError => _lastError;

		public bool CanApply
		{
			get
			{
				if (_surfaceOk)
				{
					return _runnerOk;
				}
				return false;
			}
		}

		public bool CanQueueFlush => _runnerOk;

		public SentryLeaseReadiness(bool surfaceOk)
		{
			_surfaceOk = surfaceOk;
		}

		public bool Reconcile(bool runnerAliveNow)
		{
			if (runnerAliveNow)
			{
				_runnerOk = true;
				_lastError = string.Empty;
				return true;
			}
			if (!_runnerOk)
			{
				return false;
			}
			_runnerOk = false;
			if (_recoveries < 8)
			{
				_recoveries++;
				_ensureAttempts = 0;
				_lastError = "the runtime host disappeared after it had started (recovery " + _recoveries + "/" + 8 + ")";
			}
			else
			{
				_ensureAttempts = 16;
				_lastError = "the runtime host keeps disappearing (recovery cap " + 8 + " reached)";
			}
			return false;
		}

		public bool TryEnsure(Func<bool> runnerAliveNow, Func<bool> create, Func<string> lastError)
		{
			if (runnerAliveNow != null && runnerAliveNow())
			{
				Reconcile(runnerAliveNow: true);
				return true;
			}
			Reconcile(runnerAliveNow: false);
			if (!TryBeginEnsure())
			{
				return false;
			}
			bool flag;
			try
			{
				flag = create?.Invoke() ?? false;
			}
			catch (Exception ex)
			{
				MarkRunnerFailed(ex.GetType().Name + ": " + ex.Message);
				return false;
			}
			if (flag)
			{
				MarkRunnerReady();
				return true;
			}
			MarkRunnerFailed((lastError != null) ? lastError() : string.Empty);
			return false;
		}

		public bool TryBeginEnsure()
		{
			if (_runnerOk)
			{
				return false;
			}
			if (_ensureAttempts >= 16)
			{
				return false;
			}
			_ensureAttempts++;
			return true;
		}

		public void MarkRunnerReady()
		{
			_runnerOk = true;
			_lastError = string.Empty;
		}

		public void MarkRunnerFailed(string reason)
		{
			_runnerOk = false;
			_lastError = reason ?? string.Empty;
		}

		public string Describe()
		{
			return "surface=" + _surfaceOk + " runner=" + _runnerOk + " ensureAttempts=" + _ensureAttempts + " recoveries=" + _recoveries + ((_lastError.Length == 0) ? string.Empty : (" lastError='" + _lastError + "'"));
		}
	}
	public sealed class SentryLeaseTable
	{
		private sealed class HolderEntry
		{
			public string GroupGuid = string.Empty;

			public List<string> Keys = new List<string>(16);
		}

		public const int MaxHolders = 64;

		public const int MaxKeysPerHolder = 16;

		private readonly object _gate = new object();

		private readonly Dictionary<int, HolderEntry> _holders = new Dictionary<int, HolderEntry>();

		public int HolderCount
		{
			get
			{
				lock (_gate)
				{
					return _holders.Count;
				}
			}
		}

		public int KeyCount
		{
			get
			{
				lock (_gate)
				{
					int num = 0;
					foreach (HolderEntry value in _holders.Values)
					{
						num += value.Keys.Count;
					}
					return num;
				}
			}
		}

		public LeaseRegisterResult Register(int holderId, string groupGuid, string cacheKey)
		{
			IReadOnlyList<string> readOnlyList = KeysOf(holderId);
			List<string> list = new List<string>(readOnlyList.Count + 1);
			list.AddRange(readOnlyList);
			if (!string.IsNullOrEmpty(cacheKey) && !list.Contains(cacheKey))
			{
				list.Add(cacheKey);
			}
			return ReplaceKeys(holderId, groupGuid, list);
		}

		public LeaseRegisterResult ResetTo(int holderId, string groupGuid, string cacheKey)
		{
			return ReplaceKeys(holderId, groupGuid, (cacheKey == null) ? ((IReadOnlyList<string>)Array.Empty<string>()) : ((IReadOnlyList<string>)new string[1] { cacheKey }), exact: true);
		}

		public LeaseRegisterResult ReplaceKeys(int holderId, string groupGuid, IReadOnlyList<string> cacheKeys, bool exact = false)
		{
			lock (_gate)
			{
				List<string> list = new List<string>();
				bool added = false;
				if (!_holders.TryGetValue(holderId, out HolderEntry value))
				{
					if (_holders.Count >= 64)
					{
						int? num = null;
						foreach (int key in _holders.Keys)
						{
							num = (num.HasValue ? Math.Min(num.Value, key) : key);
						}
						if (num.HasValue && _holders.TryGetValue(num.Value, out HolderEntry value2))
						{
							list.AddRange(value2.Keys);
							_holders.Remove(num.Value);
						}
					}
					value = new HolderEntry();
					_holders[holderId] = value;
				}
				List<string> list2 = new List<string>(16);
				if (cacheKeys != null)
				{
					for (int i = 0; i < cacheKeys.Count; i++)
					{
						if (list2.Count >= 16)
						{
							break;
						}
						string text = cacheKeys[i];
						if (!string.IsNullOrEmpty(text) && !list2.Contains(text))
						{
							list2.Add(text);
						}
					}
				}
				foreach (string key2 in value.Keys)
				{
					if (!list2.Contains(key2))
					{
						list.Add(key2);
					}
				}
				if (exact || !string.Equals(value.GroupGuid, groupGuid, StringComparison.Ordinal))
				{
					foreach (string key3 in value.Keys)
					{
						if (!list.Contains(key3))
						{
							list.Add(key3);
						}
					}
					value.GroupGuid = groupGuid;
				}
				foreach (string item in list2)
				{
					if (!value.Keys.Contains(item))
					{
						value.Keys.Add(item);
						added = true;
					}
				}
				foreach (string item2 in list)
				{
					value.Keys.Remove(item2);
				}
				return new LeaseRegisterResult(new List<string>(value.Keys), list, added);
			}
		}

		public IReadOnlyList<string> Forget(int holderId)
		{
			lock (_gate)
			{
				if (_holders.TryGetValue(holderId, out HolderEntry value))
				{
					_holders.Remove(holderId);
					return new List<string>(value.Keys);
				}
				return Array.Empty<string>();
			}
		}

		public IReadOnlyList<string> Prune(Func<int, bool> isAlive)
		{
			lock (_gate)
			{
				List<int> list = new List<int>();
				foreach (int key in _holders.Keys)
				{
					if (!isAlive(key))
					{
						list.Add(key);
					}
				}
				List<string> list2 = new List<string>();
				foreach (int item in list)
				{
					if (_holders.TryGetValue(item, out HolderEntry value))
					{
						list2.AddRange(value.Keys);
						_holders.Remove(item);
					}
				}
				return list2;
			}
		}

		public IReadOnlyList<string> KeysOf(int holderId)
		{
			lock (_gate)
			{
				IReadOnlyList<string> result;
				if (!_holders.TryGetValue(holderId, out HolderEntry value))
				{
					IReadOnlyList<string> readOnlyList = Array.Empty<string>();
					result = readOnlyList;
				}
				else
				{
					IReadOnlyList<string> readOnlyList = new List<string>(value.Keys);
					result = readOnlyList;
				}
				return result;
			}
		}

		public string GroupOf(int holderId)
		{
			lock (_gate)
			{
				HolderEntry value;
				return _holders.TryGetValue(holderId, out value) ? value.GroupGuid : string.Empty;
			}
		}

		public void Clear()
		{
			lock (_gate)
			{
				_holders.Clear();
			}
		}
	}
	public readonly struct LeaseRegisterResult
	{
		public IReadOnlyList<string> Held { get; }

		public IReadOnlyList<string> Release { get; }

		public bool Added { get; }

		public LeaseRegisterResult(IReadOnlyList<string> held, IReadOnlyList<string> release, bool added)
		{
			Held = held;
			Release = release;
			Added = added;
		}
	}
	public sealed class SentryMaterialBindingLedger
	{
		public readonly struct Entry
		{
			public int MaterialId { get; }

			public string GroupGuid { get; }

			public Entry(int materialId, string groupGuid)
			{
				MaterialId = materialId;
				GroupGuid = groupGuid;
			}
		}

		public const int Capacity = 256;

		private readonly Dictionary<int, Entry> _entries = new Dictionary<int, Entry>();

		private readonly Queue<int> _order = new Queue<int>();

		public int Count => _entries.Count;

		public bool NeedsRebind(int rendererId, int materialId, string? groupGuid)
		{
			if (rendererId == 0 || materialId == 0)
			{
				return true;
			}
			if (!_entries.TryGetValue(rendererId, out var value))
			{
				return true;
			}
			if (value.MaterialId != materialId)
			{
				return true;
			}
			return !string.Equals(value.GroupGuid, groupGuid ?? string.Empty, StringComparison.Ordinal);
		}

		public bool Record(int rendererId, int materialId, string? groupGuid)
		{
			if (rendererId == 0)
			{
				return false;
			}
			bool num = _entries.ContainsKey(rendererId);
			_entries[rendererId] = new Entry(materialId, groupGuid ?? string.Empty);
			if (!num)
			{
				_order.Enqueue(rendererId);
				Trim();
			}
			return num;
		}

		public bool TryGet(int rendererId, out int materialId, out string groupGuid)
		{
			materialId = 0;
			groupGuid = string.Empty;
			if (!_entries.TryGetValue(rendererId, out var value))
			{
				return false;
			}
			materialId = value.MaterialId;
			groupGuid = value.GroupGuid;
			return true;
		}

		public bool Forget(int rendererId)
		{
			return _entries.Remove(rendererId);
		}

		public void Clear()
		{
			_entries.Clear();
			_order.Clear();
		}

		private void Trim()
		{
			while (_entries.Count > 256 && _order.Count > 0)
			{
				int key = _order.Dequeue();
				if (_entries.ContainsKey(key))
				{
					_entries.Remove(key);
				}
			}
		}
	}
	public static class SentryMaterialName
	{
		private static readonly Regex CleanPattern = new Regex("\\s*(?:\\(Clone\\)|\\(Instance\\)|Instance).*$", RegexOptions.Compiled);

		public static string Clean(string? name)
		{
			if (string.IsNullOrEmpty(name))
			{
				return string.Empty;
			}
			string text = CleanPattern.Replace(name, string.Empty);
			if (text.Length != 0)
			{
				return text;
			}
			return string.Empty;
		}

		public static bool MatchesTarget(string? materialName, string? targetName)
		{
			string text = Clean(materialName);
			string b = Clean(targetName);
			if (text.Length != 0)
			{
				return string.Equals(text, b, StringComparison.Ordinal);
			}
			return false;
		}
	}
	public sealed class SentryBinding
	{
		public string DisplayName { get; }

		public uint GearPersistentId { get; }

		public string GroupGuid { get; }

		public SentryBinding(string displayName, uint gearPersistentId, string groupGuid)
		{
			DisplayName = displayName ?? throw new ArgumentNullException("displayName");
			GearPersistentId = gearPersistentId;
			GroupGuid = groupGuid ?? throw new ArgumentNullException("groupGuid");
		}

		public override string ToString()
		{
			return DisplayName + " (gear " + GearPersistentId + " -> " + GroupGuid + ")";
		}
	}
	public static class SentryMatrix
	{
		public const string HolderPrefix = "GearPartHolder_";

		private static readonly SentryBinding[] BindingTable = new SentryBinding[4]
		{
			new SentryBinding("Mechatronic SGB3", 24u, "gtfosentryskins.sentry-sgb3"),
			new SentryBinding("RAD Labs Meduza", 6u, "gtfosentryskins.sentry-meduza"),
			new SentryBinding("Mechatronic B5 LFR", 25u, "gtfosentryskins.sentry-b5lfr"),
			new SentryBinding("Autotek 51 RSG", 23u, "gtfosentryskins.sentry-rsg")
		};

		public static IReadOnlyList<SentryBinding> Bindings => BindingTable;

		public static string NormalizeHolderName(string? rawHolderName)
		{
			if (string.IsNullOrEmpty(rawHolderName))
			{
				return string.Empty;
			}
			string text = rawHolderName.Trim();
			if (text.StartsWith("GearPartHolder_", StringComparison.OrdinalIgnoreCase))
			{
				text = text.Substring("GearPartHolder_".Length);
			}
			text = text.Trim();
			bool flag;
			do
			{
				flag = false;
				if (text.EndsWith("(Clone)", StringComparison.OrdinalIgnoreCase))
				{
					text = text.Substring(0, text.Length - "(Clone)".Length).Trim();
					flag = true;
					continue;
				}
				int num = text.LastIndexOf('(');
				if (num > 0 && text.EndsWith(")", StringComparison.Ordinal) && IsPositiveInteger(text.Substring(num + 1, text.Length - num - 2).Trim()))
				{
					text = text.Substring(0, num).Trim();
					flag = true;
				}
			}
			while (flag);
			return text;
		}

		private static bool IsPositiveInteger(string value)
		{
			if (value.Length == 0 || value.Length > 4)
			{
				return false;
			}
			for (int i = 0; i < value.Length; i++)
			{
				if (value[i] < '0' || value[i] > '9')
				{
					return false;
				}
			}
			return true;
		}

		public static bool TryResolve(string? rawHolderName, out SentryBinding? binding)
		{
			string text = NormalizeHolderName(rawHolderName);
			if (text.Length == 0)
			{
				binding = null;
				return false;
			}
			for (int i = 0; i < BindingTable.Length; i++)
			{
				if (string.Equals(BindingTable[i].DisplayName, text, StringComparison.OrdinalIgnoreCase))
				{
					binding = BindingTable[i];
					return true;
				}
			}
			binding = null;
			return false;
		}

		public static bool TryGetByGearId(uint gearPersistentId, out SentryBinding? binding)
		{
			for (int i = 0; i < BindingTable.Length; i++)
			{
				if (BindingTable[i].GearPersistentId == gearPersistentId)
				{
					binding = BindingTable[i];
					return true;
				}
			}
			binding = null;
			return false;
		}
	}
	public readonly struct LoadCandidate
	{
		public bool IsStatic { get; }

		public bool IsPublic { get; }

		public string? Name { get; }

		public bool ReturnsTexture { get; }

		public string?[]? ParameterTypes { get; }

		public int Ordinal { get; }

		public string Signature
		{
			get
			{
				string text = (Name ?? "<null>") + "(";
				if (ParameterTypes == null)
				{
					return text + "<null>)";
				}
				for (int i = 0; i < ParameterTypes.Length; i++)
				{
					if (i > 0)
					{
						text += ", ";
					}
					text += ParameterTypes[i] ?? "<null>";
				}
				return text + ")";
			}
		}

		public LoadCandidate(bool isStatic, bool isPublic, string? name, bool returnsTexture, string?[]? parameterTypes, int ordinal)
		{
			IsStatic = isStatic;
			IsPublic = isPublic;
			Name = name;
			ReturnsTexture = returnsTexture;
			ParameterTypes = parameterTypes;
			Ordinal = ordinal;
		}
	}
	public readonly struct LoadSelection
	{
		public int Index { get; }

		public int Rank { get; }

		public int UsableCandidates { get; }

		public bool OptionsParameterMissing { get; }

		public bool Bound => Index >= 0;

		public LoadSelection(int index, int rank, int usableCandidates, bool optionsParameterMissing)
		{
			Index = index;
			Rank = rank;
			UsableCandidates = usableCandidates;
			OptionsParameterMissing = optionsParameterMissing;
		}
	}
	public static class SentryMemberBinding
	{
		public const int NotUsable = 0;

		public const string PathParameter = "System.String";

		public const string ManagedParameter = "System.Boolean";

		public static int RankLoadOverload(bool isStatic, bool isPublic, string? name, bool returnsTexture, string?[]? parameterTypes, string? optionsParameter)
		{
			if (!isStatic || !isPublic)
			{
				return 0;
			}
			if (!string.Equals(name, "Load", StringComparison.Ordinal))
			{
				return 0;
			}
			if (!returnsTexture || parameterTypes == null)
			{
				return 0;
			}
			int num = parameterTypes.Length;
			if (num < 1 || num > 3)
			{
				return 0;
			}
			if (!string.Equals(parameterTypes[0], "System.String", StringComparison.Ordinal))
			{
				return 0;
			}
			if (num >= 2 && (string.IsNullOrEmpty(optionsParameter) || !string.Equals(parameterTypes[1], optionsParameter, StringComparison.Ordinal)))
			{
				return 0;
			}
			if (num == 3 && !string.Equals(parameterTypes[2], "System.Boolean", StringComparison.Ordinal))
			{
				return 0;
			}
			return num;
		}

		public static int BestRank(int currentBest, int candidate)
		{
			if (candidate <= 0)
			{
				return currentBest;
			}
			if (candidate <= currentBest)
			{
				return currentBest;
			}
			return candidate;
		}

		public static bool ShouldBind(int rank)
		{
			return rank > 0;
		}

		public static LoadSelection SelectLoad(string? optionsParameter, IReadOnlyList<LoadCandidate>? candidates)
		{
			bool optionsParameterMissing = string.IsNullOrEmpty(optionsParameter);
			if (candidates == null || candidates.Count == 0)
			{
				return new LoadSelection(-1, 0, 0, optionsParameterMissing);
			}
			int num = 0;
			int num2 = 0;
			int num3 = -1;
			string strB = null;
			for (int i = 0; i < candidates.Count; i++)
			{
				LoadCandidate loadCandidate = candidates[i];
				int num4 = RankLoadOverload(loadCandidate.IsStatic, loadCandidate.IsPublic, loadCandidate.Name, loadCandidate.ReturnsTexture, loadCandidate.ParameterTypes, optionsParameter);
				if (ShouldBind(num4))
				{
					num2++;
					string signature = loadCandidate.Signature;
					if (num3 < 0 || num4 > num || (num4 == num && string.CompareOrdinal(signature, strB) < 0))
					{
						num = num4;
						num3 = i;
						strB = signature;
					}
				}
			}
			return new LoadSelection(num3, (num3 >= 0) ? num : 0, num2, optionsParameterMissing);
		}

		public static string DescribeCandidates(IReadOnlyList<LoadCandidate>? candidates)
		{
			if (candidates == null || candidates.Count == 0)
			{
				return "<none>";
			}
			List<string> list = new List<string>(candidates.Count);
			for (int i = 0; i < candidates.Count; i++)
			{
				LoadCandidate loadCandidate = candidates[i];
				if (string.Equals(loadCandidate.Name, "Load", StringComparison.Ordinal))
				{
					list.Add((loadCandidate.IsPublic ? "public " : "non-public ") + (loadCandidate.IsStatic ? "static " : "instance ") + (loadCandidate.ReturnsTexture ? "Texture2D " : "<not Texture2D> ") + loadCandidate.Signature);
				}
			}
			if (list.Count != 0)
			{
				return string.Join("; ", list);
			}
			return "<no method named Load>";
		}

		public static string DescribeLoadFailure(string? optionsParameter, LoadSelection selection, IReadOnlyList<LoadCandidate>? candidates)
		{
			string text = "no public static Load(string[, TextureOptions[, bool]]) returning Texture2D";
			if (selection.UsableCandidates > 0)
			{
				text = "no overload could be selected among " + selection.UsableCandidates + " usable candidate(s)";
			}
			text = text + "; optionsType=" + (string.IsNullOrEmpty(optionsParameter) ? "<unresolved>" : optionsParameter);
			if (selection.OptionsParameterMissing)
			{
				text += " (the referenced Skins.Textures.TextureOptions type reported no FullName, so no overload can be matched; the bind stays closed instead of guessing)";
			}
			return text + "; candidates=[" + DescribeCandidates(candidates) + "]";
		}

		public static string DescribeFailure(string? member, int usableCandidates, string? reason)
		{
			string text = "[SentrySkinCompat] " + (string.IsNullOrEmpty(member) ? "<member>" : member) + " could not be bound";
			if (!string.IsNullOrEmpty(reason))
			{
				text = text + " (" + reason + ")";
			}
			return text + "; usable candidate overloads=" + usableCandidates + ". That member stays null, the other members keep their own binding, and every path that needs it refuses to run instead of guessing.";
		}
	}
	public sealed class SentryOwnerTable
	{
		public const int MaxHolders = 64;

		public const int MaxOwnersPerHolder = 64;

		private readonly object _gate = new object();

		private readonly Dictionary<int, Dictionary<int, object>> _holders = new Dictionary<int, Dictionary<int, object>>();

		public int HolderCount
		{
			get
			{
				lock (_gate)
				{
					return _holders.Count;
				}
			}
		}

		public int OwnerCount
		{
			get
			{
				lock (_gate)
				{
					int num = 0;
					foreach (Dictionary<int, object> value in _holders.Values)
					{
						num += value.Count;
					}
					return num;
				}
			}
		}

		public object? OwnerFor(int holderId, int rendererId)
		{
			if (rendererId == 0)
			{
				return null;
			}
			lock (_gate)
			{
				if (_holders.TryGetValue(holderId, out Dictionary<int, object> value))
				{
					if (value.TryGetValue(rendererId, out var value2))
					{
						return value2;
					}
					if (value.Count >= 64)
					{
						return null;
					}
				}
				else
				{
					if (_holders.Count >= 64)
					{
						return null;
					}
					value = new Dictionary<int, object>();
					_holders[holderId] = value;
				}
				return value[rendererId] = new object();
			}
		}

		public object? Peek(int holderId, int rendererId)
		{
			lock (_gate)
			{
				Dictionary<int, object> value;
				object value2;
				return (_holders.TryGetValue(holderId, out value) && value.TryGetValue(rendererId, out value2)) ? value2 : null;
			}
		}

		public IReadOnlyList<object> Forget(int holderId)
		{
			lock (_gate)
			{
				if (!_holders.TryGetValue(holderId, out Dictionary<int, object> value))
				{
					return Array.Empty<object>();
				}
				_holders.Remove(holderId);
				List<object> list = new List<object>(value.Count);
				foreach (object value2 in value.Values)
				{
					list.Add(value2);
				}
				return list;
			}
		}

		public bool ForgetToken(int holderId, object token)
		{
			if (token == null)
			{
				return false;
			}
			lock (_gate)
			{
				if (!_holders.TryGetValue(holderId, out Dictionary<int, object> value))
				{
					return false;
				}
				int num = -1;
				foreach (KeyValuePair<int, object> item in value)
				{
					if (item.Value == token)
					{
						num = item.Key;
						break;
					}
				}
				if (num < 0)
				{
					return false;
				}
				value.Remove(num);
				if (value.Count == 0)
				{
					_holders.Remove(holderId);
				}
				return true;
			}
		}

		public IReadOnlyList<object> TokensOf(int holderId)
		{
			lock (_gate)
			{
				if (!_holders.TryGetValue(holderId, out Dictionary<int, object> value))
				{
					return Array.Empty<object>();
				}
				List<object> list = new List<object>(value.Count);
				foreach (object value2 in value.Values)
				{
					list.Add(value2);
				}
				return list;
			}
		}

		public void Clear()
		{
			lock (_gate)
			{
				_holders.Clear();
			}
		}
	}
	public sealed class SentryPinLedger
	{
		private readonly int _maxGroups;

		private readonly HashSet<string> _pinned = new HashSet<string>(StringComparer.Ordinal);

		private readonly Dictionary<string, List<string>> _keys = new Dictionary<string, List<string>>(StringComparer.Ordinal);

		private int _pendingAcquired;

		private string? _pendingGroup;

		public int MaxGroups => _maxGroups;

		public int PinnedCount => _pinned.Count;

		public int PendingAcquired => _pendingAcquired;

		public string? PendingGroup => _pendingGroup;

		public SentryPinLedger(int maxGroups)
		{
			_maxGroups = ((maxGroups < 1) ? 1 : maxGroups);
		}

		public bool IsPinned(string? guid)
		{
			if (!string.IsNullOrEmpty(guid))
			{
				return _pinned.Contains(guid);
			}
			return false;
		}

		public bool CanPin(string? guid)
		{
			if (string.IsNullOrEmpty(guid))
			{
				return false;
			}
			if (!_pinned.Contains(guid))
			{
				return _pinned.Count < _maxGroups;
			}
			return true;
		}

		public bool Begin(string? guid)
		{
			if (!CanPin(guid) || IsPinned(guid))
			{
				return false;
			}
			_pendingGroup = guid;
			_pendingAcquired = 0;
			return true;
		}

		public void RecordAcquired()
		{
			if (_pendingGroup != null)
			{
				_pendingAcquired++;
			}
		}

		public void RecordKey(string? key)
		{
			if (_pendingGroup != null && !string.IsNullOrEmpty(key))
			{
				if (!_keys.TryGetValue(_pendingGroup, out List<string> value))
				{
					value = new List<string>(4);
					_keys[_pendingGroup] = value;
				}
				if (!value.Contains(key))
				{
					value.Add(key);
				}
			}
		}

		public IReadOnlyList<string> KeysOf(string? guid)
		{
			if (string.IsNullOrEmpty(guid) || !_keys.TryGetValue(guid, out List<string> value))
			{
				return Array.Empty<string>();
			}
			return value;
		}

		public bool Forget(string? guid)
		{
			if (string.IsNullOrEmpty(guid))
			{
				return false;
			}
			_keys.Remove(guid);
			return _pinned.Remove(guid);
		}

		public bool Reverify(string? guid, Func<string, bool> isResident)
		{
			if (!IsPinned(guid))
			{
				return false;
			}
			if (isResident == null)
			{
				return true;
			}
			IReadOnlyList<string> readOnlyList = KeysOf(guid);
			for (int i = 0; i < readOnlyList.Count; i++)
			{
				bool flag;
				try
				{
					flag = isResident(readOnlyList[i]);
				}
				catch
				{
					flag = false;
				}
				if (!flag)
				{
					Forget(guid);
					return false;
				}
			}
			return true;
		}

		public bool Commit()
		{
			string pendingGroup = _pendingGroup;
			int pendingAcquired = _pendingAcquired;
			_pendingGroup = null;
			_pendingAcquired = 0;
			if (pendingGroup == null || pendingAcquired <= 0)
			{
				return false;
			}
			return _pinned.Add(pendingGroup);
		}

		public void Abort()
		{
			_pendingGroup = null;
			_pendingAcquired = 0;
		}

		public void Clear()
		{
			_pinned.Clear();
			_keys.Clear();
			Abort();
		}
	}
	public delegate bool SelectionLookup(uint gearPersistentId, out string? groupGuid, out string source);
	public static class SentrySeams
	{
		public static SelectionLookup? SelectionOverride { get; set; }

		public static Func<SentryBinding, string>? ExpectedGuidOverride { get; set; }

		public static string ExpectedGroupGuid(SentryBinding binding)
		{
			if (binding == null)
			{
				throw new ArgumentNullException("binding");
			}
			if (ExpectedGuidOverride == null)
			{
				return binding.GroupGuid;
			}
			string text = ExpectedGuidOverride(binding);
			if (!string.IsNullOrWhiteSpace(text))
			{
				return text.Trim();
			}
			return string.Empty;
		}

		public static void Reset()
		{
			SelectionOverride = null;
			ExpectedGuidOverride = null;
		}
	}
	public static class SentrySettleProof
	{
		public const string RendererGone = "renderer-gone";

		public const string RendererMaterialGone = "renderer-material-gone";

		public const string CapturedMaterialGone = "captured-material-gone";

		public const string Same = "same";

		public static string Describe(bool rendererAlive, int rendererMaterialId, int capturedMaterialId)
		{
			if (!rendererAlive)
			{
				return "renderer-gone";
			}
			if (rendererMaterialId == 0)
			{
				return "renderer-material-gone";
			}
			if (capturedMaterialId == 0)
			{
				return "captured-material-gone";
			}
			if (rendererMaterialId == capturedMaterialId)
			{
				return "same";
			}
			return "reassigned(" + capturedMaterialId + "->" + rendererMaterialId + ")";
		}

		public static bool IsVisible(bool rendererAlive, int rendererMaterialId, int capturedMaterialId)
		{
			if (rendererAlive && rendererMaterialId != 0)
			{
				return rendererMaterialId == capturedMaterialId;
			}
			return false;
		}
	}
	public readonly struct SentrySpawnObservation
	{
		public string HolderName { get; }

		public int InstanceId { get; }

		public uint GearPersistentId { get; }

		public string GroupGuid { get; }

		public int RendererCount { get; }

		public int MeshTargetCount { get; }

		public int ResolvedMeshTargetCount { get; }

		public int SatisfiedTargetCount { get; }

		public bool PlayfabItemInstanceIdNull { get; }

		public string? SelectedGroupGuid { get; }

		public string SelectionSource { get; }

		public bool GroupRegistered { get; }

		public bool LedgerSaysApplied { get; }

		public SentrySpawnObservation(string? holderName, int instanceId, uint gearPersistentId, string? groupGuid, int rendererCount, int meshTargetCount, int resolvedMeshTargetCount, int satisfiedTargetCount, bool playfabItemInstanceIdNull, string? selectedGroupGuid, string? selectionSource, bool groupRegistered, bool ledgerSaysApplied)
		{
			HolderName = holderName ?? string.Empty;
			InstanceId = instanceId;
			GearPersistentId = gearPersistentId;
			GroupGuid = groupGuid ?? string.Empty;
			RendererCount = rendererCount;
			MeshTargetCount = meshTargetCount;
			ResolvedMeshTargetCount = resolvedMeshTargetCount;
			SatisfiedTargetCount = satisfiedTargetCount;
			PlayfabItemInstanceIdNull = playfabItemInstanceIdNull;
			SelectedGroupGuid = selectedGroupGuid;
			SelectionSource = selectionSource ?? string.Empty;
			GroupRegistered = groupRegistered;
			LedgerSaysApplied = ledgerSaysApplied;
		}
	}
	public static class SentrySpawnReceipt
	{
		public const string Prefix = "[SentrySkinCompat] SPAWN#";

		public const int MaxReceipts = 64;

		public static bool IsNonApply(SentryDecision decision)
		{
			return decision != SentryDecision.Apply;
		}

		public static string Format(int index, in SentrySpawnObservation observation, SentryDecisionResult decision, string? bridge)
		{
			StringBuilder stringBuilder = new StringBuilder(384);
			stringBuilder.Append("[SentrySkinCompat] SPAWN#").Append(index).Append(" gear=")
				.Append(observation.GearPersistentId)
				.Append(" group=")
				.Append(observation.GroupGuid)
				.Append(" holder='")
				.Append(observation.HolderName)
				.Append('\'')
				.Append(" instance=")
				.Append(observation.InstanceId)
				.Append(" renderers=")
				.Append(observation.RendererCount)
				.Append(" meshTargets=")
				.Append(observation.MeshTargetCount)
				.Append(" resolvedTargets=")
				.Append(observation.ResolvedMeshTargetCount)
				.Append(" satisfiedBefore=")
				.Append(observation.SatisfiedTargetCount)
				.Append(" playfab=")
				.Append(observation.PlayfabItemInstanceIdNull ? "null" : "id")
				.Append(" selected=")
				.Append(string.IsNullOrEmpty(observation.SelectedGroupGuid) ? "<none>" : observation.SelectedGroupGuid)
				.Append(" selection=")
				.Append((observation.SelectionSource.Length == 0) ? "<none>" : observation.SelectionSource)
				.Append(" registered=")
				.Append(observation.GroupRegistered)
				.Append(" ledgerApplied=")
				.Append(observation.LedgerSaysApplied)
				.Append(" decision=")
				.Append(decision?.Decision ?? SentryDecision.SkipNotSentry)
				.Append(" bridge=")
				.Append(string.IsNullOrEmpty(bridge) ? "n/a" : bridge)
				.Append(" detail='")
				.Append(decision?.Detail ?? string.Empty)
				.Append('\'');
			return stringBuilder.ToString();
		}

		public static string Exhausted(int maxReceipts)
		{
			return "[SentrySkinCompat] SPAWN#budget exhausted after " + ((maxReceipts >= 0) ? maxReceipts : 0) + " receipt(s): further sentry spawns are decided exactly as before but are no longer logged. Absence of a SPAWN line after this one is NOT evidence that a holder was never spawned.";
		}
	}
	public enum SentryBindAction
	{
		Ok,
		WriteFromCache,
		QueueDecode,
		NoSlot
	}
	public static class SentryTextureBinding
	{
		public const int MaxReportedFailures = 6;

		public static SentryBindAction Decide(bool hasProperty, bool expectedCached, bool currentAlive, int currentId, int expectedId, bool materialChanged = false)
		{
			if (!hasProperty)
			{
				return SentryBindAction.NoSlot;
			}
			if (!expectedCached)
			{
				return SentryBindAction.QueueDecode;
			}
			if (!currentAlive)
			{
				return SentryBindAction.WriteFromCache;
			}
			if (currentId != expectedId)
			{
				return SentryBindAction.WriteFromCache;
			}
			if (!materialChanged)
			{
				return SentryBindAction.Ok;
			}
			return SentryBindAction.WriteFromCache;
		}

		public static bool IsWrite(SentryBindAction action)
		{
			return action == SentryBindAction.WriteFromCache;
		}
	}
	public sealed class SentryBindTally
	{
		private readonly List<string> _failures = new List<string>(4);

		private readonly List<string> _unprovable = new List<string>(2);

		public int Ok { get; private set; }

		public int Rewritten { get; private set; }

		public int Queued { get; private set; }

		public int Dead { get; private set; }

		public int Unprovable { get; private set; }

		public int NoSlot { get; private set; }

		public int Slots => Ok + Rewritten + Queued + Dead + NoSlot + Unprovable;

		public IReadOnlyList<string> Failures => _failures;

		public int FailureCount => _failures.Count;

		public int UnprovableCount => _unprovable.Count;

		public bool Complete
		{
			get
			{
				if (Queued == 0)
				{
					return Dead == 0;
				}
				return false;
			}
		}

		public void Record(SentryBindAction action)
		{
			switch (action)
			{
			case SentryBindAction.Ok:
				Ok++;
				break;
			case SentryBindAction.WriteFromCache:
				Rewritten++;
				break;
			case SentryBindAction.QueueDecode:
				Queued++;
				break;
			case SentryBindAction.NoSlot:
				NoSlot++;
				break;
			}
		}

		public void RecordFailure(string slot, string reason)
		{
			Dead++;
			AddFailure(slot, reason);
		}

		public void RecordUnprovable(string slot, string reason)
		{
			Unprovable++;
			if (_unprovable.Count < 6)
			{
				_unprovable.Add("slot=" + (slot ?? "?") + " reason=" + (reason ?? "?"));
			}
		}

		public void AddFailure(string slot, string reason)
		{
			if (_failures.Count < 6)
			{
				_failures.Add("slot=" + (slot ?? "?") + " reason=" + (reason ?? "?"));
			}
		}

		public void Add(SentryBindTally other)
		{
			if (other == null)
			{
				return;
			}
			Ok += other.Ok;
			Rewritten += other.Rewritten;
			Queued += other.Queued;
			Dead += other.Dead;
			NoSlot += other.NoSlot;
			Unprovable += other.Unprovable;
			for (int i = 0; i < other._failures.Count; i++)
			{
				if (_failures.Count >= 6)
				{
					break;
				}
				_failures.Add(other._failures[i]);
			}
			for (int j = 0; j < other._unprovable.Count; j++)
			{
				if (_unprovable.Count >= 6)
				{
					break;
				}
				_unprovable.Add(other._unprovable[j]);
			}
		}

		public string Describe()
		{
			return "ok=" + Ok + " rewrite=" + Rewritten + " queued=" + Queued + " dead=" + Dead + " noslot=" + NoSlot + " unprov=" + Unprovable;
		}

		public string DescribeFailures()
		{
			if (_failures.Count == 0)
			{
				return string.Empty;
			}
			StringBuilder stringBuilder = new StringBuilder();
			for (int i = 0; i < _failures.Count; i++)
			{
				if (i > 0)
				{
					stringBuilder.Append(';');
				}
				stringBuilder.Append(_failures[i]);
			}
			return stringBuilder.ToString();
		}

		public string DescribeUnprovable()
		{
			if (_unprovable.Count == 0)
			{
				return string.Empty;
			}
			StringBuilder stringBuilder = new StringBuilder();
			for (int i = 0; i < _unprovable.Count; i++)
			{
				if (i > 0)
				{
					stringBuilder.Append(';');
				}
				stringBuilder.Append(_unprovable[i]);
			}
			return stringBuilder.ToString();
		}
	}
	public enum SentryRecoveryAction
	{
		UseDecoded,
		UseCacheEntry,
		EvictAndDecode,
		GiveUp
	}
	public enum SentryKeySource
	{
		Raw,
		Rooted,
		Mismatch
	}
	public static class SentryTextureRecovery
	{
		public const int MaxEvictionsPerSlot = 1;

		public static SentryRecoveryAction Decide(bool decodedAlive, bool cacheEntryPresent, bool cacheEntryAlive, int evictionsSpent)
		{
			if (decodedAlive)
			{
				return SentryRecoveryAction.UseDecoded;
			}
			if (cacheEntryAlive)
			{
				return SentryRecoveryAction.UseCacheEntry;
			}
			if (!WouldGiveUp(cacheEntryAlive, evictionsSpent))
			{
				return SentryRecoveryAction.EvictAndDecode;
			}
			return SentryRecoveryAction.GiveUp;
		}

		public static bool WouldGiveUp(bool cacheEntryAlive, int evictionsSpent)
		{
			if (!cacheEntryAlive)
			{
				return evictionsSpent >= 1;
			}
			return false;
		}

		public static string Describe(bool decodedAlive, bool cacheEntryPresent, bool cacheEntryAlive, int evictionsSpent)
		{
			if (decodedAlive)
			{
				return "decoded-alive";
			}
			if (cacheEntryAlive)
			{
				return "cache-entry-alive/decode-wrapper-dead";
			}
			if (!cacheEntryPresent)
			{
				if (evictionsSpent <= 0)
				{
					return "decode-dead/no-cache-entry";
				}
				return "decode-dead/no-cache-entry/after-evict";
			}
			if (evictionsSpent <= 0)
			{
				return "cache-entry-dead";
			}
			return "cache-entry-dead/after-evict";
		}

		public static bool IsFailure(SentryRecoveryAction action)
		{
			return action == SentryRecoveryAction.GiveUp;
		}

		public static bool IsEviction(SentryRecoveryAction action)
		{
			return action == SentryRecoveryAction.EvictAndDecode;
		}

		public static bool KeysAgree(string? requestedKey, string? recomputedKey)
		{
			if (!string.IsNullOrEmpty(requestedKey) && !string.IsNullOrEmpty(recomputedKey))
			{
				return string.Equals(requestedKey, recomputedKey, StringComparison.Ordinal);
			}
			return false;
		}

		public static string? DescribeKeyMismatch(string? requestedKey, string? recomputedKey)
		{
			if (string.IsNullOrEmpty(requestedKey) || string.IsNullOrEmpty(recomputedKey))
			{
				return null;
			}
			if (KeysAgree(requestedKey, recomputedKey))
			{
				return null;
			}
			return "requested=" + requestedKey + " recomputed=" + recomputedKey;
		}

		public static SentryKeySource ChooseKeySource(string? requestedKey, string? rawKey, bool rootedUsable)
		{
			if (string.IsNullOrEmpty(requestedKey))
			{
				return SentryKeySource.Raw;
			}
			if (KeysAgree(requestedKey, rawKey))
			{
				return SentryKeySource.Raw;
			}
			if (!rootedUsable)
			{
				return SentryKeySource.Mismatch;
			}
			return SentryKeySource.Rooted;
		}

		public static bool RootedPathUsable(bool pathExists, string? requestedKey, string? rootedKey)
		{
			if (!pathExists)
			{
				return false;
			}
			if (!string.IsNullOrEmpty(requestedKey))
			{
				return KeysAgree(requestedKey, rootedKey);
			}
			return true;
		}

		public static string DescribeKeySource(SentryKeySource source)
		{
			return source switch
			{
				SentryKeySource.Rooted => "rooted", 
				SentryKeySource.Mismatch => "mismatch", 
				_ => "raw", 
			};
		}

		public static bool ShouldRefuseDecode(bool cacheEntryPresent, bool cacheEntryAlive, int evictionsSpent)
		{
			if (cacheEntryPresent)
			{
				return WouldGiveUp(cacheEntryAlive, evictionsSpent);
			}
			return false;
		}
	}
	public sealed class SentryKeySourceTally
	{
		private int _raw;

		private int _rooted;

		private int _mismatch;

		public int Raw => _raw;

		public int Rooted => _rooted;

		public int Mismatch => _mismatch;

		public int Total => _raw + _rooted + _mismatch;

		public void Record(SentryKeySource source)
		{
			switch (source)
			{
			case SentryKeySource.Rooted:
				_rooted++;
				break;
			case SentryKeySource.Mismatch:
				_mismatch++;
				break;
			default:
				_raw++;
				break;
			}
		}

		public string Describe()
		{
			if (Total == 0)
			{
				return "none";
			}
			string text = ((_raw > 0) ? "raw" : string.Empty);
			if (_rooted > 0)
			{
				text = text + ((text.Length == 0) ? string.Empty : ",") + "rooted";
			}
			if (_mismatch > 0)
			{
				text = text + ((text.Length == 0) ? string.Empty : ",") + "mismatch";
			}
			return text;
		}
	}
	public enum ReflectionReadStatus
	{
		Ok,
		DeclaringTypeUnavailable,
		MemberNotFound,
		ValueNull,
		Threw
	}
	public static class SkinsConfigReflection
	{
		public const BindingFlags StaticMemberFlags = BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;

		public const BindingFlags StaticFieldFlags = BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic;

		public const BindingFlags InstanceMemberFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;

		public const BindingFlags PublicOnlyStaticFlags = BindingFlags.Static | BindingFlags.Public;

		public const BindingFlags PublicOnlyInstanceFlags = BindingFlags.Instance | BindingFlags.Public;

		public static ReflectionReadStatus TryReadStaticProperty(Type? declaringType, string propertyName, out object? value, out string detail)
		{
			value = null;
			if (declaringType == null)
			{
				detail = "declaring type unavailable";
				return ReflectionReadStatus.DeclaringTypeUnavailable;
			}
			PropertyInfo property = declaringType.GetProperty(propertyName, BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
			if (property == null)
			{
				detail = "property '" + propertyName + "' not found on " + declaringType.FullName + " with " + (BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
				return ReflectionReadStatus.MemberNotFound;
			}
			MethodInfo getMethod = property.GetGetMethod(nonPublic: true);
			if (getMethod == null)
			{
				detail = "property '" + propertyName + "' on " + declaringType.FullName + " has no getter";
				return ReflectionReadStatus.MemberNotFound;
			}
			try
			{
				object obj = getMethod.Invoke(null, null);
				if (obj == null)
				{
					detail = declaringType.FullName + "." + propertyName + " returned null";
					return ReflectionReadStatus.ValueNull;
				}
				value = obj;
				detail = "ok";
				return ReflectionReadStatus.Ok;
			}
			catch (Exception ex)
			{
				detail = declaringType.FullName + "." + propertyName + " threw " + (ex.InnerException?.GetType().Name ?? ex.GetType().Name) + ": " + (ex.InnerException?.Message ?? ex.Message);
				return ReflectionReadStatus.Threw;
			}
		}

		public static ReflectionReadStatus TryReadStaticField(Type? declaringType, string fieldName, out object? value, out string detail)
		{
			value = null;
			if (declaringType == null)
			{
				detail = "declaring type unavailable";
				return ReflectionReadStatus.DeclaringTypeUnavailable;
			}
			FieldInfo field = declaringType.GetField(fieldName, BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
			if (field == null)
			{
				detail = "field '" + fieldName + "' not found on " + declaringType.FullName + " with " + (BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
				return ReflectionReadStatus.MemberNotFound;
			}
			try
			{
				object value2 = field.GetValue(null);
				if (value2 == null)
				{
					detail = declaringType.FullName + "." + fieldName + " is null";
					return ReflectionReadStatus.ValueNull;
				}
				value = value2;
				detail = "ok";
				return ReflectionReadStatus.Ok;
			}
			catch (Exception ex)
			{
				detail = declaringType.FullName + "." + fieldName + " threw " + (ex.InnerException?.GetType().Name ?? ex.GetType().Name) + ": " + (ex.InnerException?.Message ?? ex.Message);
				return ReflectionReadStatus.Threw;
			}
		}

		public static ReflectionReadStatus TryReadInstanceProperty(object? instance, Type? declaringType, string propertyName, out object? value, out string detail)
		{
			value = null;
			if (declaringType == null)
			{
				detail = "declaring type unavailable";
				return ReflectionReadStatus.DeclaringTypeUnavailable;
			}
			if (instance == null)
			{
				detail = "instance is null";
				return ReflectionReadStatus.ValueNull;
			}
			PropertyInfo property = declaringType.GetProperty(propertyName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
			if (property == null)
			{
				detail = "property '" + propertyName + "' not found on " + declaringType.FullName + " with " + (BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
				return ReflectionReadStatus.MemberNotFound;
			}
			MethodInfo getMethod = property.GetGetMethod(nonPublic: true);
			if (getMethod == null)
			{
				detail = "property '" + propertyName + "' on " + declaringType.FullName + " has no getter";
				return ReflectionReadStatus.MemberNotFound;
			}
			try
			{
				object obj = getMethod.Invoke(instance, null);
				if (obj == null)
				{
					detail = declaringType.FullName + "." + propertyName + " returned null";
					return ReflectionReadStatus.ValueNull;
				}
				value = obj;
				detail = "ok";
				return ReflectionReadStatus.Ok;
			}
			catch (Exception ex)
			{
				detail = declaringType.FullName + "." + propertyName + " threw " + (ex.InnerException?.GetType().Name ?? ex.GetType().Name) + ": " + (ex.InnerException?.Message ?? ex.Message);
				return ReflectionReadStatus.Threw;
			}
		}
	}
	public enum SkipReceiptClass
	{
		None,
		StableState,
		Diagnostic
	}
	public sealed class StableStateSkipLedger
	{
		public const int Capacity = 64;

		private readonly HashSet<long> _seen = new HashSet<long>();

		private readonly Queue<long> _order = new Queue<long>();

		public int Count => _seen.Count;

		public static long Key(int instanceId, SentryDecision decision)
		{
			return Key(instanceId, (int)decision);
		}

		public static long Key(int instanceId, int kind)
		{
			return ((long)instanceId << 8) | (byte)(kind & 0xFF);
		}

		public bool ShouldLog(int instanceId, SentryDecision decision)
		{
			return ShouldLog(Key(instanceId, decision));
		}

		public bool ShouldLog(int instanceId, int kind)
		{
			return ShouldLog(Key(instanceId, kind));
		}

		public bool HasLogged(int instanceId, SentryDecision decision)
		{
			return _seen.Contains(Key(instanceId, decision));
		}

		public bool HasLogged(int instanceId, int kind)
		{
			return _seen.Contains(Key(instanceId, kind));
		}

		private bool ShouldLog(long key)
		{
			if (!_seen.Add(key))
			{
				return false;
			}
			_order.Enqueue(key);
			while (_seen.Count > 64 && _order.Count > 0)
			{
				_seen.Remove(_order.Dequeue());
			}
			return true;
		}

		public void Clear()
		{
			_seen.Clear();
			_order.Clear();
		}
	}
}
namespace GtfoSentrySkins.SentrySkinCompat.Patches
{
	[HarmonyPatch(typeof(GearPartHolder), "OnAllPartsSpawned")]
	[HarmonyAfter(new string[] { "io.takina.gtfo.Skins" })]
	internal static class GearPartHolderOnAllPartsSpawnedPatch
	{
		[HarmonyPrepare]
		private static bool Prepare()
		{
			bool result = AccessTools.Method(typeof(GearPartHolder), "OnAllPartsSpawned", (Type[])null, (Type[])null) != null;
			Plugin.LogSource.LogInfo((object)("[SentrySkinCompat] Prepare: Gear.GearPartHolder.OnAllPartsSpawned found=" + result + " (interop: BepInEx/interop/Modules-ASM.dll)."));
			return result;
		}

		[HarmonyPostfix]
		[HarmonyPriority(-200)]
		private static void Postfix(GearPartHolder __instance)
		{
			try
			{
				SentrySkinApplier.TryApply(__instance);
			}
			catch (Exception ex)
			{
				SentrySkinApplier.ReportInternalError(ex);
			}
		}
	}
	[HarmonyPatch(typeof(GearPartHolder), "OnDestroy")]
	internal static class GearPartHolderOnDestroyPatch
	{
		[HarmonyPrepare]
		private static bool Prepare()
		{
			MethodInfo methodInfo = AccessTools.Method(typeof(GearPartHolder), "OnDestroy", (Type[])null, (Type[])null);
			bool flag = methodInfo != null && methodInfo.DeclaringType == typeof(GearPartHolder);
			ManualLogSource logSource = Plugin.LogSource;
			if (logSource != null)
			{
				logSource.LogInfo((object)("[SentrySkinCompat] Prepare: Gear.GearPartHolder.OnDestroy found=" + (methodInfo != null) + " declaredType=" + (methodInfo?.DeclaringType?.FullName ?? "<none>") + " declaredOnGearPartHolder=" + flag + " (ledger lifecycle cleanup " + (flag ? "enabled" : "disabled") + ")."));
			}
			return flag;
		}

		[HarmonyPostfix]
		private static void Postfix(GearPartHolder __instance)
		{
			try
			{
				SentrySkinApplier.ForgetHolder(__instance);
			}
			catch (Exception ex)
			{
				SentrySkinApplier.ReportInternalError(ex);
			}
		}
	}
}
namespace GtfoSentrySkins.SentrySkinCompat.Interop
{
	internal sealed class FrameLeaseRunner : MonoBehaviour
	{
		private static FrameLeaseRunner? _instance;

		private static bool _registered;

		private static readonly SentryLeaseTable Table = new SentryLeaseTable();

		private readonly Dictionary<int, GearPartHolder> _owners = new Dictionary<int, GearPartHolder>();

		private bool _pruneScheduled;

		public static SentryLeaseTable Lease => Table;

		public static bool IsReady => (Object)(object)_instance != (Object)null;

		public static string LastError { get; private set; } = string.Empty;

		public static int LeasedHolders => Table.HolderCount;

		public static bool Ensure()
		{
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Expected O, but got Unknown
			if ((Object)(object)_instance != (Object)null)
			{
				return true;
			}
			GameObject val = null;
			try
			{
				if (!_registered)
				{
					ClassInjector.RegisterTypeInIl2Cpp<FrameLeaseRunner>();
					_registered = true;
				}
				val = new GameObject("GtfoSentrySkins.FrameLease");
				Object.DontDestroyOnLoad((Object)(object)val);
				((Object)val).hideFlags = (HideFlags)61;
				_instance = val.AddComponent<FrameLeaseRunner>() ?? throw new InvalidOperationException("AddComponent<FrameLeaseRunner>() returned null");
				val = null;
				LastError = string.Empty;
			}
			catch (Exception ex)
			{
				_instance = null;
				LastError = ex.GetType().Name + ": " + ex.Message;
				DestroyHost(val);
				ManualLogSource logSource = Plugin.LogSource;
				if (logSource != null)
				{
					logSource.LogError((object)("[SentrySkinCompat] FrameLease runner could not be created: " + ex));
				}
				return false;
			}
			ManualLogSource logSource2 = Plugin.LogSource;
			if (logSource2 != null)
			{
				logSource2.LogInfo((object)("[SentrySkinCompat] FrameLease runner created (owner-wide re-lease, bounded table " + 64 + " holders x " + 16 + " keys)."));
			}
			return true;
		}

		private static void DestroyHost(GameObject? host)
		{
			if (host == null)
			{
				return;
			}
			try
			{
				Object.Destroy((Object)(object)host);
			}
			catch (Exception ex)
			{
				try
				{
					Object.DestroyImmediate((Object)(object)host);
				}
				catch (Exception ex2)
				{
					ManualLogSource logSource = Plugin.LogSource;
					if (logSource != null)
					{
						logSource.LogWarning((object)("[SentrySkinCompat] an unused FrameLease host leaked (" + ex.Message + " / " + ex2.Message + ")."));
					}
				}
			}
		}

		public static LeaseRegisterResult Apply(int holderId, GearPartHolder holder, string groupGuid, IReadOnlyList<string> cacheKeys)
		{
			if ((Object)(object)holder == (Object)null)
			{
				return new LeaseRegisterResult(Array.Empty<string>(), Array.Empty<string>(), added: false);
			}
			if ((Object)(object)_instance == (Object)null && !Plugin.EnsureRunnerHost())
			{
				return new LeaseRegisterResult(Array.Empty<string>(), Array.Empty<string>(), added: false);
			}
			if ((Object)(object)_instance == (Object)null)
			{
				return new LeaseRegisterResult(Array.Empty<string>(), Array.Empty<string>(), added: false);
			}
			LeaseRegisterResult result = Table.ReplaceKeys(holderId, groupGuid, cacheKeys);
			if (result.Added)
			{
				_instance._owners[holderId] = holder;
				if (!TextureLibraryBridge.AcquireAll(result.Held, holder))
				{
					Table.Forget(holderId);
					_instance._owners.Remove(holderId);
					return new LeaseRegisterResult(Array.Empty<string>(), result.Held, added: false);
				}
			}
			if (result.Release.Count > 0)
			{
				_instance.ReleaseKeys(holderId, holder, result.Release);
			}
			return result;
		}

		public static IReadOnlyList<string> Drop(int holderId)
		{
			IReadOnlyList<string> result = Table.Forget(holderId);
			if ((Object)(object)_instance == (Object)null)
			{
				return result;
			}
			if (_instance._owners.TryGetValue(holderId, out GearPartHolder value))
			{
				_instance._owners.Remove(holderId);
				_instance.ReleaseOwnerSafely(value);
			}
			return result;
		}

		private void ReleaseKeys(int holderId, GearPartHolder holder, IReadOnlyList<string> keys)
		{
			ReleaseOwnerSafely(holder);
			if (!_owners.ContainsKey(holderId))
			{
				_owners[holderId] = holder;
			}
			ManualLogSource logSource = Plugin.LogSource;
			if (logSource != null)
			{
				logSource.LogInfo((object)("[SentrySkinCompat] FrameLease released " + keys.Count + " key(s) for holder instance " + holderId + ": " + Join(keys)));
			}
		}

		private void ReleaseOwnerSafely(GearPartHolder holder)
		{
			try
			{
				TextureLibraryBridge.ReleaseOwner(holder);
			}
			catch (Exception ex)
			{
				ManualLogSource logSource = Plugin.LogSource;
				if (logSource != null)
				{
					logSource.LogError((object)("[SentrySkinCompat] FrameLease ReleaseOwner failed: " + ex.Message));
				}
			}
		}

		public void Update()
		{
			try
			{
				SentryFlushQueue.Tick();
			}
			catch (Exception ex)
			{
				SentrySkinApplier.ReportInternalError(ex);
			}
			if (Table.HolderCount == 0)
			{
				return;
			}
			foreach (KeyValuePair<int, GearPartHolder> item in new List<KeyValuePair<int, GearPartHolder>>(_owners))
			{
				if (item.Value == null)
				{
					Drop(item.Key);
				}
				else if (!TextureLibraryBridge.AcquireAll(Table.KeysOf(item.Key), item.Value))
				{
					Drop(item.Key);
				}
			}
			if (_pruneScheduled || _owners.Count <= 0)
			{
				return;
			}
			_pruneScheduled = true;
			IReadOnlyList<string> readOnlyList = Table.Prune((int id) => _owners.ContainsKey(id) && _owners[id] != null);
			if (readOnlyList.Count > 0)
			{
				ManualLogSource logSource = Plugin.LogSource;
				if (logSource != null)
				{
					logSource.LogInfo((object)("[SentrySkinCompat] FrameLease pruned " + readOnlyList.Count + " dead key(s)."));
				}
			}
		}

		private static string Join(IReadOnlyList<string> keys)
		{
			StringBuilder stringBuilder = new StringBuilder();
			for (int i = 0; i < keys.Count && i < 8; i++)
			{
				if (i > 0)
				{
					stringBuilder.Append(" | ");
				}
				string text = keys[i];
				stringBuilder.Append(text[..((text.Length > 48) ? 48 : text.Length)]);
			}
			return stringBuilder.ToString();
		}
	}
	internal static class SentryFlushQueue
	{
		private sealed class SlotWork
		{
			public string Slot = string.Empty;

			public Texture2DProperty Property;

			public string? CacheKey;

			public string? LoadPath;

			public bool Written;

			public bool WrittenByUs;

			public int Evictions;
		}

		private sealed class Entry : ISentryQueuePayload
		{
			public Material Material;

			public MeshRenderer? Renderer;

			public readonly List<SlotWork> Slots = new List<SlotWork>(8);

			public SentryDecodeLedger Ledger = new SentryDecodeLedger(0);

			public readonly SentryKeySourceTally KeySources = new SentryKeySourceTally();

			public int HolderId { get; }

			public object Token { get; }

			public string RendererName { get; set; } = string.Empty;

			public string GroupGuid { get; set; } = string.Empty;

			public string GroupFolder { get; set; } = string.Empty;

			public int SlotCount => Slots.Count;

			public double Deadline { get; set; }

			public double NextTry { get; set; }

			public int Ticks { get; set; }

			public int Supersedes { get; set; }

			public bool Retired { get; set; }

			public Entry(int holderId, object token)
			{
				HolderId = holderId;
				Token = token;
			}
		}

		private static readonly object Gate = new object();

		private static readonly SentryFlushTable Table = new SentryFlushTable((ISentryQueuePayload payload) => MaterialIdOf(((Entry)payload).Material));

		private static readonly SentryFlushTally Tally = new SentryFlushTally();

		private static readonly SentryRecoveryTally Recovery = new SentryRecoveryTally();

		private static readonly HashSet<string> LoggedPinRecovery = new HashSet<string>(StringComparer.Ordinal);

		private static readonly HashSet<string> LoggedEvictTrouble = new HashSet<string>(StringComparer.Ordinal);

		private static readonly HashSet<string> LoggedKeyAdopt = new HashSet<string>(StringComparer.Ordinal);

		private static readonly SentryFrameBudget DecodeBudget = new SentryFrameBudget(2);

		private static int _rotation;

		private static bool _duplicateOwnerLogged;

		private static bool _ownerKeptLogged;

		private static bool _rejectedLogged;

		private static bool _supersededLogged;

		public static int PendingCount
		{
			get
			{
				lock (Gate)
				{
					return Table.Count;
				}
			}
		}

		public static SentryFlushTally Counters => Tally;

		public static SentryRecoveryTally RecoveryCounters => Recovery;

		public static bool Enqueue(int holderId, object token, Material? material, string groupGuid, string? rendererName, MeshRenderer? renderer, Dictionary<string, Texture2DProperty>? properties, string? groupDirectory, double now)
		{
			string text = null;
			if (!Plugin.CanQueueFlush)
			{
				text = "the FrameLease runner is not running (or could not be re-created), so nothing would tick this write";
			}
			else if (token == null || material == null || properties == null || properties.Count == 0)
			{
				text = "no material or no texture property to write";
			}
			else
			{
				SentryQueueRequest request = new SentryQueueRequest(holderId, token, MaterialIdOf(material), CountUsableSlots(properties), rendererName, groupGuid, groupDirectory, now, 20.0);
				lock (Gate)
				{
					int previousMaterialId = 0;
					ISentryQueuePayload entry;
					int droppedDuplicates;
					SentryOfferResult sentryOfferResult = Table.Offer(in request, delegate(ISentryQueuePayload payload)
					{
						previousMaterialId = MaterialIdOf(((Entry)payload).Material);
						RepointPayload((Entry)payload, material, renderer, properties, groupDirectory);
					}, out entry, out droppedDuplicates);
					if (droppedDuplicates > 0)
					{
						ReportDuplicateOwnerOnce(holderId, rendererName, droppedDuplicates);
					}
					switch (sentryOfferResult)
					{
					case SentryOfferResult.Reused:
						return true;
					case SentryOfferResult.Repointed:
						ReportSupersededOnce(holderId, rendererName, groupGuid, previousMaterialId, request.MaterialId, ((Entry)entry).Supersedes);
						return true;
					case SentryOfferResult.Added:
					{
						Entry entry2 = new Entry(holderId, token)
						{
							Material = material,
							Renderer = renderer
						};
						AddSlots(entry2, properties, groupDirectory);
						entry2.Ledger = new SentryDecodeLedger(entry2.Slots.Count);
						if (Table.TryAdd(entry2, in request))
						{
							return true;
						}
						text = "flush table full (" + Table.Capacity + " owners)";
						break;
					}
					case SentryOfferResult.RejectedNoMaterial:
						text = "the material instance is not readable (null or destroyed)";
						break;
					case SentryOfferResult.RejectedNoSlot:
						text = "no usable slot in the material target";
						break;
					default:
						text = "flush table full (" + Table.Capacity + " owners)";
						break;
					}
				}
			}
			RecordRejection(holderId, groupGuid, text ?? "unknown");
			return false;
		}

		private static int CountUsableSlots(Dictionary<string, Texture2DProperty> properties)
		{
			int num = 0;
			foreach (KeyValuePair<string, Texture2DProperty> property in properties)
			{
				if (property.Value != null)
				{
					num++;
				}
			}
			return num;
		}

		private static void AddSlots(Entry entry, Dictionary<string, Texture2DProperty> properties, string? groupDirectory)
		{
			foreach (KeyValuePair<string, Texture2DProperty> property in properties)
			{
				if (property.Value != null)
				{
					entry.Slots.Add(new SlotWork
					{
						Slot = property.Key,
						Property = property.Value,
						CacheKey = property.Value.CacheKeyForLease(groupDirectory ?? string.Empty),
						LoadPath = property.Value.LoadPathForFlush()
					});
				}
			}
		}

		private static void RepointPayload(Entry entry, Material material, MeshRenderer? renderer, Dictionary<string, Texture2DProperty> properties, string? groupDirectory)
		{
			entry.Material = material;
			entry.Renderer = renderer;
			int num = CountUsableSlots(properties);
			if (entry.Slots.Count != num)
			{
				entry.Slots.Clear();
				AddSlots(entry, properties, groupDirectory);
				entry.Ledger = new SentryDecodeLedger(entry.Slots.Count);
				return;
			}
			for (int i = 0; i < entry.Slots.Count; i++)
			{
				entry.Slots[i].Written = false;
				entry.Slots[i].WrittenByUs = false;
			}
		}

		public static bool IsHeld(int holderId, object token)
		{
			lock (Gate)
			{
				return Table.Find(holderId, token) != null;
			}
		}

		public static bool TokenStillHeld(int holderId, object token)
		{
			lock (Gate)
			{
				return Table.TokenStillHeld(holderId, token);
			}
		}

		public static void Tick()
		{
			List<Entry> list;
			lock (Gate)
			{
				if (Table.Count == 0)
				{
					return;
				}
				IReadOnlyList<ISentryQueuePayload> readOnlyList = Table.Snapshot();
				list = new List<Entry>(readOnlyList.Count);
				for (int i = 0; i < readOnlyList.Count; i++)
				{
					list.Add((Entry)readOnlyList[i]);
				}
			}
			DecodeBudget.Reset();
			int count = list.Count;
			int num = _rotation % count;
			int[] array = SentryTickRotation.Order(num, count);
			double now = NowSeconds();
			int num2 = 0;
			for (int j = 0; j < array.Length; j++)
			{
				Entry entry = list[array[j]];
				try
				{
					if (TickEntry(entry, now))
					{
						num2++;
					}
				}
				catch (Exception ex)
				{
					SentrySkinApplier.ReportInternalError(ex);
					Retire(entry, SentryFlushRetire.Exception, ex.GetType().Name + ": " + ex.Message);
				}
			}
			_rotation = ((num2 > 0) ? SentryTickRotation.Advance(num, count, num2) : num);
		}

		private static bool TickEntry(Entry entry, double now)
		{
			//IL_026f: Unknown result type (might be due to invalid IL or missing references)
			if (now < entry.NextTry)
			{
				return false;
			}
			int index = entry.Ticks++;
			entry.NextTry = now + SentryFlushPolicy.RetryDelaySeconds(entry.Ticks);
			if (entry.Material == null || (Object)(object)entry.Material == (Object)null)
			{
				Retire(entry, SentryFlushRetire.MaterialGone, "material gone");
				return false;
			}
			int num = 0;
			int num2 = 0;
			int num3 = 0;
			int decodesThisTick = 0;
			int count = entry.Slots.Count;
			List<string> list = null;
			for (int i = 0; i < count; i++)
			{
				int index2 = entry.Ledger.Order(i);
				SlotWork slotWork = entry.Slots[index2];
				bool holdsLiveTexture = HasTexture(entry.Material, slotWork.Slot);
				if (SentryFlushPolicy.IsSlotFilled(slotWork.Written, holdsLiveTexture))
				{
					num2++;
					if (slotWork.WrittenByUs)
					{
						num3++;
					}
					continue;
				}
				if (!SafeHasProperty(entry.Material, slotWork.Slot))
				{
					slotWork.Written = true;
					num2++;
					continue;
				}
				Texture2D val = SentryTextureAccess.TryGetAlive(slotWork.CacheKey);
				if (SentryFlushPolicy.ShouldRequestDecode(entry.Ledger.Decodes(index2), val != null))
				{
					bool cacheEntryPresent = (Object)(object)SentryTextureAccess.TryGetCached(slotWork.CacheKey) != (Object)null;
					bool cacheEntryAlive = val != null;
					if (SentryTextureRecovery.ShouldRefuseDecode(cacheEntryPresent, cacheEntryAlive, slotWork.Evictions))
					{
						SentryTextureAccess.ReportGiveUpOnce(slotWork.LoadPath ?? string.Empty, SentryTextureRecovery.Describe(decodedAlive: false, cacheEntryPresent, cacheEntryAlive, slotWork.Evictions), slotWork.CacheKey);
					}
					else if (DecodeBudget.TryTake(out index))
					{
						entry.Ledger.RecordDecode(index2);
						index = decodesThisTick;
						decodesThisTick = index + 1;
						val = SentryTextureAccess.Resolve(slotWork.LoadPath, slotWork.Property.Options.GetValueOrDefault(), slotWork.CacheKey, entry.GroupFolder, slotWork.Evictions, TakeRetrySlot, out SentryEvictionOutcome eviction, out SentryKeySource keySource, out string effectiveKey);
						entry.KeySources.Record(keySource);
						AdoptEffectiveKey(entry, slotWork, keySource, effectiveKey);
						HandleEviction(entry, slotWork, eviction);
					}
				}
				if (SentryTextureBinder.IsAlive((Object?)(object)val) && WriteSlot(entry.Material, slotWork.Slot, val))
				{
					slotWork.Written = true;
					slotWork.WrittenByUs = true;
					num2++;
					num3++;
					continue;
				}
				try
				{
					slotWork.Property.Apply(entry.Material, slotWork.Slot, entry.Token);
				}
				catch
				{
				}
				num++;
				(list ?? (list = new List<string>(4))).Add(slotWork.Slot);
				bool TakeRetrySlot()
				{
					if (!DecodeBudget.TryTake(out var index3))
					{
						return false;
					}
					entry.Ledger.RecordDecode(index2);
					index3 = decodesThisTick;
					decodesThisTick = index3 + 1;
					return true;
				}
			}
			entry.Ledger.AdvanceCursor(decodesThisTick);
			string detail = num2 + "/" + count + " slot(s) filled, " + num3 + " written by the compat plugin, " + entry.Ticks + " tick(s), " + entry.Ledger.TotalDecodes + " decode(s), keySource=" + entry.KeySources.Describe() + ", " + Recovery.Describe() + ((list == null) ? string.Empty : (", unfilled=[" + string.Join(",", list) + "]"));
			switch (SentryFlushPolicy.Decide(num, now, entry.Deadline))
			{
			case SentryFlushVerdict.Complete:
				Retire(entry, SentryFlushPolicy.CompleteReason(num3), detail);
				return decodesThisTick > 0;
			case SentryFlushVerdict.TimedOut:
				Retire(entry, SentryFlushRetire.TimedOut, detail);
				return decodesThisTick > 0;
			default:
				return decodesThisTick > 0;
			}
		}

		private static void AdoptEffectiveKey(Entry entry, SlotWork work, SentryKeySource source, string? effectiveKey)
		{
			if (!string.IsNullOrEmpty(effectiveKey) && !string.Equals(effectiveKey, work.CacheKey, StringComparison.Ordinal))
			{
				string cacheKey = work.CacheKey;
				work.CacheKey = effectiveKey;
				LogKeyAdoptOnce(entry, work, cacheKey, source);
			}
		}

		private static void LogKeyAdoptOnce(Entry entry, SlotWork work, string? previousKey, SentryKeySource source)
		{
			string item = "keysource|" + entry.GroupGuid + "|" + entry.RendererName + "|" + work.Slot;
			lock (LoggedKeyAdopt)
			{
				if (!LoggedKeyAdopt.Add(item))
				{
					return;
				}
			}
			ManualLogSource logSource = Plugin.LogSource;
			if (logSource != null)
			{
				logSource.LogWarning((object)("[SentrySkinCompat] texture key source=" + SentryTextureRecovery.DescribeKeySource(source) + " for group '" + entry.GroupGuid + "' renderer='" + entry.RendererName + "' slot=" + work.Slot + ": probing/pinning key " + (previousKey ?? "<unresolved>") + " became " + (work.CacheKey ?? "<unresolved>") + " (the key the decode registered), so the texture in use and the pinned key cannot separate and the next idle sweep keeps it (D7-8). Logged once per group+renderer+slot."));
			}
		}

		private static void HandleEviction(Entry entry, SlotWork work, SentryEvictionOutcome eviction)
		{
			if (eviction == SentryEvictionOutcome.NotAttempted)
			{
				return;
			}
			Recovery.RecordEviction(eviction);
			if (!SentryEvictionPolicy.CountsAsEviction(eviction))
			{
				if (SentryEvictionPolicy.IsTrouble(eviction))
				{
					LogEvictionTroubleOnce(entry, work, eviction);
				}
				return;
			}
			work.Evictions++;
			bool num = SentryGroupPins.Reacquire(entry.GroupGuid, work.CacheKey);
			bool ensureOk = num || SentryGroupPins.EnsureByGuid(entry.Grou