Please disclose if any significant portion of your mod was created using AI tools by adding the 'AI Generated' category. Failing to do so may result in the mod being removed from Thunderstore.
Decompiled source of Y4NGZUpgrades v1.2.2
Y4NGZUpgrades.dll
Decompiled 2 days ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Buffers.Binary; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Linq.Expressions; using System.Numerics; using System.Reflection; using System.Reflection.Emit; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Security; using System.Security.Cryptography; using System.Security.Permissions; using System.Text; using System.Text.RegularExpressions; using BepInEx; using BepInEx.Bootstrap; using BepInEx.Configuration; using BepInEx.Logging; using Dawn; using GameNetcodeStuff; using HarmonyLib; using LethalCompanyInputUtils.Api; using Microsoft.CodeAnalysis; using TMPro; using Unity.Collections; using Unity.Netcode; using UnityEngine; using UnityEngine.AI; using UnityEngine.Animations; using UnityEngine.Audio; using UnityEngine.EventSystems; using UnityEngine.Events; using UnityEngine.Experimental.Animations; using UnityEngine.Experimental.Rendering; using UnityEngine.InputSystem; using UnityEngine.InputSystem.Controls; using UnityEngine.InputSystem.UI; using UnityEngine.InputSystem.Utilities; using UnityEngine.Networking; using UnityEngine.Playables; using UnityEngine.Rendering; using UnityEngine.Rendering.HighDefinition; using UnityEngine.SceneManagement; using UnityEngine.TextCore; using UnityEngine.UI; using Y4NGZInteractions.InteractionAnimationApi; using Y4NGZUpgrades; using Y4NGZUpgrades.Config; using Y4NGZUpgrades.Effects; using Y4NGZUpgrades.Gui; using Y4NGZUpgrades.HUD; using Y4NGZUpgrades.Interactive; using Y4NGZUpgrades.Interactive.Feedback; using Y4NGZUpgrades.Interactive.Hud; using Y4NGZUpgrades.Interactive.Patches; using Y4NGZUpgrades.Patches; using Y4NGZUpgrades.TokenCoins; using Y4NGZUpgrades.UITheme; using Y4NGZUpgrades.Upgrades; using cakeslice; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: IgnoresAccessChecksTo("AmazingAssets.TerrainToMesh")] [assembly: IgnoresAccessChecksTo("Assembly-CSharp-firstpass")] [assembly: IgnoresAccessChecksTo("Assembly-CSharp")] [assembly: IgnoresAccessChecksTo("ClientNetworkTransform")] [assembly: IgnoresAccessChecksTo("com.olegknyazev.softmask")] [assembly: IgnoresAccessChecksTo("DissonanceVoip")] [assembly: IgnoresAccessChecksTo("DunGen")] [assembly: IgnoresAccessChecksTo("DunGen.Integration.ASPP")] [assembly: IgnoresAccessChecksTo("DunGen.Integration.UnityNav")] [assembly: IgnoresAccessChecksTo("EasyTextEffects")] [assembly: IgnoresAccessChecksTo("Facepunch Transport for Netcode for GameObjects")] [assembly: IgnoresAccessChecksTo("Facepunch.Steamworks.Win64")] [assembly: IgnoresAccessChecksTo("Unity.AI.Navigation")] [assembly: IgnoresAccessChecksTo("Unity.Animation.Rigging")] [assembly: IgnoresAccessChecksTo("Unity.Animation.Rigging.DocCodeExamples")] [assembly: IgnoresAccessChecksTo("Unity.Burst")] [assembly: IgnoresAccessChecksTo("Unity.Burst.Unsafe")] [assembly: IgnoresAccessChecksTo("Unity.Collections")] [assembly: IgnoresAccessChecksTo("Unity.Collections.LowLevel.ILSupport")] [assembly: IgnoresAccessChecksTo("Unity.InputSystem")] [assembly: IgnoresAccessChecksTo("Unity.InputSystem.ForUI")] [assembly: IgnoresAccessChecksTo("Unity.Jobs")] [assembly: IgnoresAccessChecksTo("Unity.Mathematics")] [assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.Common")] [assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.MetricTypes")] [assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.NetStats")] [assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.NetStatsMonitor.Component")] [assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.NetStatsMonitor.Configuration")] [assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.NetStatsMonitor.Implementation")] [assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.NetStatsReporting")] [assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.NetworkProfiler.Runtime")] [assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.NetworkSolutionInterface")] [assembly: IgnoresAccessChecksTo("Unity.Netcode.Components")] [assembly: IgnoresAccessChecksTo("Unity.Netcode.Runtime")] [assembly: IgnoresAccessChecksTo("Unity.Networking.Transport")] [assembly: IgnoresAccessChecksTo("Unity.ProBuilder.Csg")] [assembly: IgnoresAccessChecksTo("Unity.ProBuilder")] [assembly: IgnoresAccessChecksTo("Unity.ProBuilder.KdTree")] [assembly: IgnoresAccessChecksTo("Unity.ProBuilder.Poly2Tri")] [assembly: IgnoresAccessChecksTo("Unity.ProBuilder.Stl")] [assembly: IgnoresAccessChecksTo("Unity.Profiling.Core")] [assembly: IgnoresAccessChecksTo("Unity.RenderPipelines.Core.Runtime")] [assembly: IgnoresAccessChecksTo("Unity.RenderPipelines.Core.ShaderLibrary")] [assembly: IgnoresAccessChecksTo("Unity.RenderPipelines.HighDefinition.Config.Runtime")] [assembly: IgnoresAccessChecksTo("Unity.RenderPipelines.HighDefinition.Runtime")] [assembly: IgnoresAccessChecksTo("Unity.RenderPipelines.ShaderGraph.ShaderGraphLibrary")] [assembly: IgnoresAccessChecksTo("Unity.Services.Authentication")] [assembly: IgnoresAccessChecksTo("Unity.Services.Core.Analytics")] [assembly: IgnoresAccessChecksTo("Unity.Services.Core.Components")] [assembly: IgnoresAccessChecksTo("Unity.Services.Core.Configuration")] [assembly: IgnoresAccessChecksTo("Unity.Services.Core.Device")] [assembly: IgnoresAccessChecksTo("Unity.Services.Core")] [assembly: IgnoresAccessChecksTo("Unity.Services.Core.Environments")] [assembly: IgnoresAccessChecksTo("Unity.Services.Core.Environments.Internal")] [assembly: IgnoresAccessChecksTo("Unity.Services.Core.Internal")] [assembly: IgnoresAccessChecksTo("Unity.Services.Core.Networking")] [assembly: IgnoresAccessChecksTo("Unity.Services.Core.Registration")] [assembly: IgnoresAccessChecksTo("Unity.Services.Core.Scheduler")] [assembly: IgnoresAccessChecksTo("Unity.Services.Core.Telemetry")] [assembly: IgnoresAccessChecksTo("Unity.Services.Core.Threading")] [assembly: IgnoresAccessChecksTo("Unity.Services.QoS")] [assembly: IgnoresAccessChecksTo("Unity.Services.Relay")] [assembly: IgnoresAccessChecksTo("Unity.TextMeshPro")] [assembly: IgnoresAccessChecksTo("Unity.Timeline")] [assembly: IgnoresAccessChecksTo("Unity.VisualEffectGraph.Runtime")] [assembly: IgnoresAccessChecksTo("Unity.XR.CoreUtils")] [assembly: IgnoresAccessChecksTo("Unity.XR.Management")] [assembly: IgnoresAccessChecksTo("Unity.XR.OpenXR")] [assembly: IgnoresAccessChecksTo("Unity.XR.OpenXR.Features.ConformanceAutomation")] [assembly: IgnoresAccessChecksTo("Unity.XR.OpenXR.Features.MetaQuestSupport")] [assembly: IgnoresAccessChecksTo("Unity.XR.OpenXR.Features.MockRuntime")] [assembly: IgnoresAccessChecksTo("Unity.XR.OpenXR.Features.OculusQuestSupport")] [assembly: IgnoresAccessChecksTo("Unity.XR.OpenXR.Features.RuntimeDebugger")] [assembly: IgnoresAccessChecksTo("UnityEngine.ARModule")] [assembly: IgnoresAccessChecksTo("UnityEngine.NVIDIAModule")] [assembly: IgnoresAccessChecksTo("UnityEngine.SpatialTracking")] [assembly: IgnoresAccessChecksTo("UnityEngine.UI")] [assembly: IgnoresAccessChecksTo("UnityEngine.XR.LegacyInputHelpers")] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: AssemblyCompany("Y4NGZUpgrades")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyDescription("Native Y4NGZ progression and upgrade framework spine")] [assembly: AssemblyFileVersion("1.2.2.0")] [assembly: AssemblyInformationalVersion("1.2.2+16362a473c0672ee4ffe083b5265fe6a4f5d1a34")] [assembly: AssemblyProduct("Y4NGZUpgrades")] [assembly: AssemblyTitle("Y4NGZUpgrades")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.2.2.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class NullableAttribute : Attribute { public readonly byte[] NullableFlags; public NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class NullableContextAttribute : Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace cakeslice { public sealed class LinkedSet<T> : IEnumerable<T>, IEnumerable { private readonly LinkedList<T> _list = new LinkedList<T>(); private readonly Dictionary<T, LinkedListNode<T>> _dictionary = new Dictionary<T, LinkedListNode<T>>(); public int Count => _list.Count; public bool Add(T item) { if (_dictionary.ContainsKey(item)) { return false; } LinkedListNode<T> value = _list.AddLast(item); _dictionary.Add(item, value); return true; } public bool Remove(T item) { if (!_dictionary.TryGetValue(item, out var value)) { return false; } _dictionary.Remove(item); _list.Remove(value); return true; } public bool Contains(T item) { return _dictionary.ContainsKey(item); } public LinkedList<T>.Enumerator GetEnumerator() { return _list.GetEnumerator(); } IEnumerator<T> IEnumerable<T>.GetEnumerator() { return _list.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable<T>)this).GetEnumerator(); } } [RequireComponent(typeof(Renderer))] public sealed class Outline : MonoBehaviour { private MeshFilter _meshFilter; private SkinnedMeshRenderer _skinnedMeshRenderer; private SpriteRenderer _spriteRenderer; private int _materialCount = -1; public int color; public float opacity = 1f; public Renderer Renderer { get; private set; } internal int SubmeshCount { get { if ((Object)(object)Renderer == (Object)null) { return 0; } if (_materialCount < 0) { _materialCount = Renderer.sharedMaterials.Length; } Mesh val = null; if ((Object)(object)_meshFilter != (Object)null) { val = _meshFilter.sharedMesh; } else if ((Object)(object)_skinnedMeshRenderer != (Object)null) { val = _skinnedMeshRenderer.sharedMesh; } if ((Object)(object)val != (Object)null) { return Mathf.Min(_materialCount, val.subMeshCount); } if (!((Object)(object)_spriteRenderer != (Object)null) || _materialCount <= 0) { return 0; } return 1; } } private void Awake() { Renderer = ((Component)this).GetComponent<Renderer>(); _meshFilter = ((Component)this).GetComponent<MeshFilter>(); _skinnedMeshRenderer = ((Component)this).GetComponent<SkinnedMeshRenderer>(); _spriteRenderer = ((Component)this).GetComponent<SpriteRenderer>(); } private void OnEnable() { OutlineEffect instance = OutlineEffect.Instance; if ((Object)(object)instance != (Object)null) { instance.AddOutline(this); } } private void OnDisable() { OutlineEffect instance = OutlineEffect.Instance; if ((Object)(object)instance != (Object)null) { instance.RemoveOutline(this); } } } [DisallowMultipleComponent] [RequireComponent(typeof(Camera))] public sealed class OutlineEffect : MonoBehaviour { public sealed class Y4NGZHDRPOutlinePass : CustomPass { internal OutlineEffect Owner; public override void Execute(CustomPassContext ctx) { //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_003b: Unknown result type (might be due to invalid IL or missing references) OutlineEffect owner = Owner; if (!((Object)(object)owner == (Object)null) && ctx.cmd != null && ctx.hdCamera != null && !((Object)(object)ctx.hdCamera.camera != (Object)(object)owner._camera)) { owner.Render(ctx); } } } private const string DepthArrayKeyword = "Y4NGZ_HALO_DEPTH_ARRAY"; private const int OccupancyPass = 0; private const int HaloPass = 1; private static readonly int MaskParamsId = Shader.PropertyToID("_Y4NGZHaloMaskParams"); private static readonly int DepthParamsId = Shader.PropertyToID("_Y4NGZHaloDepthParams"); private static readonly int SceneDepthId = Shader.PropertyToID("_Y4NGZHaloSceneDepth"); private static readonly int SceneDepthArrayId = Shader.PropertyToID("_Y4NGZHaloSceneDepthX"); private static readonly int RadiiId = Shader.PropertyToID("_Y4NGZHaloRadii"); private static readonly int AlphasId = Shader.PropertyToID("_Y4NGZHaloAlphas"); private static readonly int MaskId = Shader.PropertyToID("_Y4NGZHaloMask"); private static readonly int OccupancyId = Shader.PropertyToID("_Y4NGZHaloOccupancy"); private static readonly int SceneId = Shader.PropertyToID("_Y4NGZHaloScene"); private static readonly int[] ColorIds = new int[3] { Shader.PropertyToID("_Y4NGZHaloColor0"), Shader.PropertyToID("_Y4NGZHaloColor1"), Shader.PropertyToID("_Y4NGZHaloColor2") }; private readonly LinkedSet<Outline> _outlines = new LinkedSet<Outline>(); private Camera _camera; private Material _maskMaterial; private Material _haloMaterial; private bool _depthArrayKeyword; private RenderTexture _maskTexture; private RenderTexture _occupancyTexture; private RenderTexture _sceneTexture; private GameObject _volumeObject; private CustomPassVolume _volume; private Y4NGZHDRPOutlinePass _pass; private bool _passWarningLogged; public static OutlineEffect Instance { get; private set; } private void Awake() { if ((Object)(object)Instance != (Object)null && (Object)(object)Instance != (Object)(object)this) { Object.Destroy((Object)(object)Instance); } Instance = this; _camera = ((Component)this).GetComponent<Camera>(); } private void OnEnable() { Outline[] array = Object.FindObjectsOfType<Outline>(); for (int i = 0; i < array.Length; i++) { if ((Object)(object)array[i] != (Object)null && ((Behaviour)array[i]).isActiveAndEnabled) { _outlines.Add(array[i]); } } UpdateVolumeState(); } private void OnDisable() { if ((Object)(object)_volume != (Object)null) { ((Behaviour)_volume).enabled = false; } } private void OnDestroy() { if ((Object)(object)Instance == (Object)(object)this) { Instance = null; } if ((Object)(object)_volumeObject != (Object)null) { Object.Destroy((Object)(object)_volumeObject); } _volumeObject = null; _volume = null; _pass = null; ReleaseTexture(ref _maskTexture); ReleaseTexture(ref _occupancyTexture); ReleaseTexture(ref _sceneTexture); if ((Object)(object)_maskMaterial != (Object)null) { Object.Destroy((Object)(object)_maskMaterial); } if ((Object)(object)_haloMaterial != (Object)null) { Object.Destroy((Object)(object)_haloMaterial); } _maskMaterial = null; _haloMaterial = null; } public void AddOutline(Outline outline) { if (!((Object)(object)outline == (Object)null)) { _outlines.Add(outline); UpdateVolumeState(); } } public void RemoveOutline(Outline outline) { if (outline != null) { _outlines.Remove(outline); UpdateVolumeState(); } } private void UpdateVolumeState() { bool flag = ((Behaviour)this).isActiveAndEnabled && _outlines.Count > 0 && EnsureMaterials() && EnsureVolume(); if ((Object)(object)_volume != (Object)null && ((Behaviour)_volume).enabled != flag) { ((Behaviour)_volume).enabled = flag; } } private bool EnsureMaterials() { //IL_003b: Unknown result type (might be due to invalid IL or missing references) //IL_0040: Unknown result type (might be due to invalid IL or missing references) //IL_004b: Unknown result type (might be due to invalid IL or missing references) //IL_0058: Expected O, but got Unknown //IL_0082: Unknown result type (might be due to invalid IL or missing references) //IL_0087: Unknown result type (might be due to invalid IL or missing references) //IL_0092: Unknown result type (might be due to invalid IL or missing references) //IL_009f: Expected O, but got Unknown //IL_00be: Unknown result type (might be due to invalid IL or missing references) //IL_00df: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)_maskMaterial != (Object)null && (Object)(object)_haloMaterial != (Object)null) { return true; } if (!OutlineRuntimeAssets.TryGetShaders(out var maskShader, out var haloShader)) { return false; } if ((Object)(object)_maskMaterial == (Object)null) { _maskMaterial = new Material(maskShader) { name = "Y4NGZ Outline Halo Mask", hideFlags = (HideFlags)61 }; _maskMaterial.DisableKeyword("Y4NGZ_HALO_DEPTH_ARRAY"); _depthArrayKeyword = false; } if ((Object)(object)_haloMaterial == (Object)null) { _haloMaterial = new Material(haloShader) { name = "Y4NGZ Outline Halo", hideFlags = (HideFlags)61 }; _haloMaterial.SetVector(AlphasId, new Vector4(0.45f, 0.18f, 0.4f, 0f)); for (int i = 0; i < 3; i++) { _haloMaterial.SetVector(ColorIds[i], SrgbVector(OutlineHaloStyle.SlotColor(i))); } ReleaseTexture(ref _maskTexture); ReleaseTexture(ref _occupancyTexture); ReleaseTexture(ref _sceneTexture); } return true; } private bool EnsureVolume() { //IL_003c: Unknown result type (might be due to invalid IL or missing references) //IL_0041: Unknown result type (might be due to invalid IL or missing references) //IL_004e: Expected O, but got Unknown //IL_00ac: Unknown result type (might be due to invalid IL or missing references) //IL_0143: Unknown result type (might be due to invalid IL or missing references) //IL_014f: Unknown result type (might be due to invalid IL or missing references) //IL_015b: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)_volume != (Object)null && _pass != null) { return true; } if ((Object)(object)_camera == (Object)null) { return false; } if ((Object)(object)_volumeObject == (Object)null) { _volumeObject = new GameObject("Y4NGZ_OutlineCustomPassVolume") { hideFlags = (HideFlags)61 }; Object.DontDestroyOnLoad((Object)(object)_volumeObject); } _volume = _volumeObject.GetComponent<CustomPassVolume>(); if ((Object)(object)_volume == (Object)null) { _volume = _volumeObject.AddComponent<CustomPassVolume>(); } _volume.isGlobal = true; _volume.priority = 1000f; _volume.injectionPoint = (CustomPassInjectionPoint)3; _volume.targetCamera = _camera; _volume.customPasses.Clear(); _pass = _volume.AddPassOfType(typeof(Y4NGZHDRPOutlinePass)) as Y4NGZHDRPOutlinePass; if (_pass == null) { if (!_passWarningLogged) { _passWarningLogged = true; ManualLogSource log = Y4NGZUpgrades.Plugin.Log; if (log != null) { log.LogWarning((object)"OutlineEffect: failed to register the HDRP custom pass; outlines are invisible."); } } return false; } ((CustomPass)_pass).name = "Y4NGZ Outline Halo"; ((CustomPass)_pass).enabled = true; ((CustomPass)_pass).targetColorBuffer = (TargetBuffer)0; ((CustomPass)_pass).targetDepthBuffer = (TargetBuffer)0; ((CustomPass)_pass).clearFlags = (ClearFlag)0; _pass.Owner = this; ManualLogSource log2 = Y4NGZUpgrades.Plugin.Log; if (log2 != null) { log2.LogInfo((object)("OutlineEffect: HDRP custom pass registered on '" + ((Object)_camera).name + "'.")); } return true; } private void Render(CustomPassContext ctx) { //IL_002b: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_0066: Unknown result type (might be due to invalid IL or missing references) //IL_0078: Unknown result type (might be due to invalid IL or missing references) //IL_0092: Unknown result type (might be due to invalid IL or missing references) //IL_009c: Unknown result type (might be due to invalid IL or missing references) //IL_00ac: Unknown result type (might be due to invalid IL or missing references) //IL_00ba: Unknown result type (might be due to invalid IL or missing references) //IL_00cc: Unknown result type (might be due to invalid IL or missing references) //IL_00d7: Unknown result type (might be due to invalid IL or missing references) //IL_00e7: Unknown result type (might be due to invalid IL or missing references) //IL_00ed: Invalid comparison between Unknown and I4 //IL_010c: Unknown result type (might be due to invalid IL or missing references) //IL_0123: Unknown result type (might be due to invalid IL or missing references) //IL_0170: Unknown result type (might be due to invalid IL or missing references) //IL_017c: Unknown result type (might be due to invalid IL or missing references) //IL_0192: Unknown result type (might be due to invalid IL or missing references) //IL_01a3: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)_maskMaterial == (Object)null || (Object)(object)_haloMaterial == (Object)null || (Object)(object)_camera == (Object)null) { return; } RTHandle cameraColorBuffer = ctx.cameraColorBuffer; RTHandle cameraDepthBuffer = ctx.cameraDepthBuffer; if (cameraColorBuffer == null || (Object)(object)cameraColorBuffer.rt == (Object)null || cameraDepthBuffer == null || (Object)(object)cameraDepthBuffer.rt == (Object)null || !HasDrawableOutline()) { return; } int num = Mathf.Max(1, ctx.hdCamera.actualWidth); int num2 = Mathf.Max(1, ctx.hdCamera.actualHeight); EnsureTextures(num, num2, cameraColorBuffer.rt.graphicsFormat); CommandBuffer cmd = ctx.cmd; cmd.SetRenderTarget(RenderTargetIdentifier.op_Implicit((Texture)(object)_maskTexture)); cmd.ClearRenderTarget(true, true, Color.clear); cmd.SetViewProjectionMatrices(_camera.worldToCameraMatrix, _camera.projectionMatrix); bool flag = (int)((Texture)cameraDepthBuffer.rt).dimension == 5; SetDepthArrayKeyword(flag); cmd.SetGlobalTexture(flag ? SceneDepthArrayId : SceneDepthId, RTHandle.op_Implicit(cameraDepthBuffer)); cmd.SetGlobalVector(DepthParamsId, EyeDepthParams(_camera)); foreach (Outline outline in _outlines) { DrawMask(cmd, outline); } cmd.SetRenderTarget(RenderTargetIdentifier.op_Implicit((Texture)(object)_occupancyTexture)); cmd.DrawProcedural(Matrix4x4.identity, _haloMaterial, 0, (MeshTopology)0, 3); cmd.CopyTexture(RTHandle.op_Implicit(cameraColorBuffer), 0, 0, 0, 0, num, num2, RenderTargetIdentifier.op_Implicit((Texture)(object)_sceneTexture), 0, 0, 0, 0); HDUtils.DrawFullScreen(cmd, _haloMaterial, cameraColorBuffer, (MaterialPropertyBlock)null, 1); } private bool HasDrawableOutline() { foreach (Outline outline in _outlines) { if (IsDrawable(outline)) { return true; } } return false; } private static bool IsDrawable(Outline outline) { if ((Object)(object)outline != (Object)null && ((Behaviour)outline).enabled && (Object)(object)outline.Renderer != (Object)null) { return outline.Renderer.enabled; } return false; } private void DrawMask(CommandBuffer cmd, Outline outline) { //IL_003f: Unknown result type (might be due to invalid IL or missing references) if (!IsDrawable(outline)) { return; } int submeshCount = outline.SubmeshCount; if (submeshCount > 0) { cmd.SetGlobalVector(MaskParamsId, new Vector4((float)(outline.color + 1) * 0.25f, Mathf.Clamp01(outline.opacity), 0f, 0f)); for (int i = 0; i < submeshCount; i++) { cmd.DrawRenderer(outline.Renderer, _maskMaterial, i, 0); } } } private void SetDepthArrayKeyword(bool enabled) { if (_depthArrayKeyword != enabled) { _depthArrayKeyword = enabled; if (enabled) { _maskMaterial.EnableKeyword("Y4NGZ_HALO_DEPTH_ARRAY"); } else { _maskMaterial.DisableKeyword("Y4NGZ_HALO_DEPTH_ARRAY"); } } } private static Vector4 EyeDepthParams(Camera camera) { //IL_0045: Unknown result type (might be due to invalid IL or missing references) float nearClipPlane = camera.nearClipPlane; float farClipPlane = camera.farClipPlane; float num; float num2; if (SystemInfo.usesReversedZBuffer) { num = -1f + farClipPlane / nearClipPlane; num2 = 1f; } else { num = 1f - farClipPlane / nearClipPlane; num2 = farClipPlane / nearClipPlane; } return new Vector4(num / farClipPlane, num2 / farClipPlane, 0.02f, 0.05f); } private void EnsureTextures(int width, int height, GraphicsFormat sceneFormat) { //IL_0062: Unknown result type (might be due to invalid IL or missing references) //IL_0071: Expected O, but got Unknown //IL_0089: Unknown result type (might be due to invalid IL or missing references) //IL_0098: Expected O, but got Unknown //IL_00ec: Unknown result type (might be due to invalid IL or missing references) //IL_013d: Unknown result type (might be due to invalid IL or missing references) //IL_013e: Unknown result type (might be due to invalid IL or missing references) //IL_014d: Expected O, but got Unknown //IL_0126: Unknown result type (might be due to invalid IL or missing references) //IL_012b: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)_maskTexture == (Object)null || ((Texture)_maskTexture).width != width || ((Texture)_maskTexture).height != height || (Object)(object)_occupancyTexture == (Object)null) { ReleaseTexture(ref _maskTexture); ReleaseTexture(ref _occupancyTexture); int num = 8; _maskTexture = CreateTexture(new RenderTexture(width, height, 16, (RenderTextureFormat)0, (RenderTextureReadWrite)1), "Y4NGZ Outline Halo Mask"); _occupancyTexture = CreateTexture(new RenderTexture((width + num - 1) / num, (height + num - 1) / num, 0, (RenderTextureFormat)16, (RenderTextureReadWrite)1), "Y4NGZ Outline Halo Occupancy"); _haloMaterial.SetTexture(MaskId, (Texture)(object)_maskTexture); _haloMaterial.SetTexture(OccupancyId, (Texture)(object)_occupancyTexture); OutlineHaloStyle.BandRadii(height, out var near, out var far); _haloMaterial.SetVector(RadiiId, new Vector4((float)near, (float)far, 0f, 0f)); } if ((Object)(object)_sceneTexture == (Object)null || ((Texture)_sceneTexture).width != width || ((Texture)_sceneTexture).height != height || _sceneTexture.graphicsFormat != sceneFormat) { ReleaseTexture(ref _sceneTexture); _sceneTexture = CreateTexture(new RenderTexture(width, height, 0, sceneFormat), "Y4NGZ Outline Halo Scene"); _haloMaterial.SetTexture(SceneId, (Texture)(object)_sceneTexture); } } private static RenderTexture CreateTexture(RenderTexture texture, string name) { ((Object)texture).name = name; ((Object)texture).hideFlags = (HideFlags)61; ((Texture)texture).filterMode = (FilterMode)0; ((Texture)texture).wrapMode = (TextureWrapMode)1; texture.Create(); return texture; } private static void ReleaseTexture(ref RenderTexture texture) { if ((Object)(object)texture != (Object)null) { texture.Release(); Object.Destroy((Object)(object)texture); } texture = null; } private static Vector4 SrgbVector(byte[] rgb) { //IL_0023: Unknown result type (might be due to invalid IL or missing references) return new Vector4((float)(int)rgb[0] / 255f, (float)(int)rgb[1] / 255f, (float)(int)rgb[2] / 255f, 1f); } } } namespace Y4NGZUpgrades { internal static class ArmoryBridge { private const string AmmoApiTypeName = "Y4NGZUpgrades.Weapons.ArmoryAmmoReserveApi"; private const string PresentationApiTypeName = "Y4NGZUpgrades.Weapons.ArmoryPresentationApi"; private const string HostingApiTypeName = "Y4NGZUpgrades.Weapons.WeaponHostingApi"; private const string AmmoPickupTypeName = "Y4NGZUpgrades.Weapons.AmmoPickupItem"; private static readonly string[] NoIds = new string[0]; private static readonly Type[] OneString = new Type[1] { typeof(string) }; private static readonly Lazy<MethodInfo> AmmoFamilyIds = Method("Y4NGZUpgrades.Weapons.ArmoryAmmoReserveApi", "GetAmmoFamilyIds", Type.EmptyTypes); private static readonly Lazy<MethodInfo> AmmoFamilyLabel = Method("Y4NGZUpgrades.Weapons.ArmoryAmmoReserveApi", "GetAmmoFamilyLabel", OneString); private static readonly Lazy<MethodInfo> AmmoFamilyReserve = Method("Y4NGZUpgrades.Weapons.ArmoryAmmoReserveApi", "GetAmmoFamilyReserve", OneString); private static readonly Lazy<Type> AmmoPickupType = new Lazy<Type>(() => FindType("Y4NGZUpgrades.Weapons.AmmoPickupItem")); private static readonly Lazy<MethodInfo> StopPresentation = Method("Y4NGZUpgrades.Weapons.ArmoryPresentationApi", "StopPresentationForHeldItemStow", new Type[1] { typeof(PlayerControllerB) }); private static readonly Lazy<Func<bool>> IncomingFirearmResistance = new Lazy<Func<bool>>(delegate { MethodInfo methodInfo = FindType("Y4NGZUpgrades.Weapons.WeaponHostingApi")?.GetMethod("IsIncomingFirearmResistanceAvailable", BindingFlags.Static | BindingFlags.Public, null, Type.EmptyTypes, null); return (!(methodInfo?.ReturnType == typeof(bool))) ? null : ((Func<bool>)Delegate.CreateDelegate(typeof(Func<bool>), methodInfo)); }); internal static bool IsArmoryPresent => OptionalPluginCapabilities.BetterArmory; internal static bool SupportsIncomingFirearmResistance { get { try { return IncomingFirearmResistance.Value?.Invoke() ?? false; } catch (Exception ex) { Warn("IsIncomingFirearmResistanceAvailable", ex); return false; } } } internal static string[] GetAmmoFamilyIds() { return Strings(AmmoFamilyIds, "GetAmmoFamilyIds"); } internal static string GetAmmoFamilyLabel(string familyId) { return (Invoke(AmmoFamilyLabel, "GetAmmoFamilyLabel", familyId) as string) ?? familyId; } internal static int GetAmmoFamilyReserve(string familyId) { object obj = Invoke(AmmoFamilyReserve, "GetAmmoFamilyReserve", familyId); if (obj is int) { return (int)obj; } return 0; } internal static bool IsAmmoPickup(GrabbableObject item) { Type value = AmmoPickupType.Value; if (value != null) { return (Object)(object)((Component)item).GetComponent(value) != (Object)null; } return false; } internal static void StopPresentationForHeldItemStow(PlayerControllerB player) { MethodInfo methodInfo = Resolve(StopPresentation, "StopPresentationForHeldItemStow"); if (methodInfo == null || (Object)(object)player == (Object)null) { return; } try { methodInfo.Invoke(null, new object[1] { player }); } catch (Exception ex) { Warn("StopPresentationForHeldItemStow", ex); } } private static Lazy<MethodInfo> Method(string typeName, string methodName, Type[] parameters) { return new Lazy<MethodInfo>(delegate { Type type = FindType(typeName); if (type == null) { return (MethodInfo)null; } MethodInfo method = type.GetMethod(methodName, BindingFlags.Static | BindingFlags.Public, null, parameters, null); if (method == null) { ManualLogSource log = Plugin.Log; if (log != null) { log.LogWarning((object)("[ArmoryBridge] " + typeName + "." + methodName + " was not found. That bridge is disabled for this session.")); } } return method; }); } private static MethodInfo Resolve(Lazy<MethodInfo> lazy, string member) { try { return lazy.Value; } catch (Exception ex) { Warn(member, ex); return null; } } private static object Invoke(Lazy<MethodInfo> lazy, string member, string argument) { MethodInfo methodInfo = Resolve(lazy, member); if (methodInfo == null) { return null; } try { return methodInfo.Invoke(null, new object[1] { argument }); } catch (Exception ex) { Warn(methodInfo.Name, ex); return null; } } private static string[] Strings(Lazy<MethodInfo> lazy, string member) { MethodInfo methodInfo = Resolve(lazy, member); if (methodInfo == null) { return NoIds; } try { return (methodInfo.Invoke(null, null) as string[]) ?? NoIds; } catch (Exception ex) { Warn(methodInfo.Name, ex); return NoIds; } } private static void Warn(string member, Exception ex) { if (LogGate.Once("Y4NGZUpgrades.ArmoryBridge.call:" + member, LogScope.Session)) { ManualLogSource log = Plugin.Log; if (log != null) { log.LogWarning((object)("[ArmoryBridge] " + member + " failed safely: " + ex.Message)); } } } internal static Type FindType(string fullName) { if (!IsArmoryPresent) { return null; } Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies(); foreach (Assembly assembly in assemblies) { try { Type type = assembly.GetType(fullName, throwOnError: false); if (type != null) { return type; } } catch { } } if (LogGate.Once("Y4NGZUpgrades.ArmoryBridge.type:" + fullName, LogScope.Session)) { ManualLogSource log = Plugin.Log; if (log != null) { log.LogWarning((object)("[ArmoryBridge] Better Armory is installed but '" + fullName + "' was not found. That bridge is disabled for this session.")); } } return null; } } internal static class ArmoryItemProbe { private const string WeaponNamespacePrefix = "Y4NGZUpgrades.Weapons."; internal static bool IsArmoryWeapon(GrabbableObject item) { if ((Object)(object)item == (Object)null) { return false; } Component[] components = ((Component)item).GetComponents<Component>(); foreach (Component val in components) { if (!((Object)(object)val == (Object)null)) { string fullName = ((object)val).GetType().FullName; if (fullName != null && fullName.StartsWith("Y4NGZUpgrades.Weapons.", StringComparison.Ordinal)) { return true; } } } return false; } } internal sealed class CctvStatisticsEventGuard { private readonly HashSet<string> _acceptedDeviceKeys = new HashSet<string>(StringComparer.Ordinal); private readonly HashSet<string> _acceptedAlarmKeys = new HashSet<string>(StringComparer.Ordinal); internal bool TryAcceptDevice(string logicalDeviceKey) { if (!string.IsNullOrWhiteSpace(logicalDeviceKey)) { return _acceptedDeviceKeys.Add(logicalDeviceKey); } return false; } internal bool TryAcceptAlarm(string episodeKey) { if (!string.IsNullOrWhiteSpace(episodeKey)) { return _acceptedAlarmKeys.Add(episodeKey); } return false; } internal static bool IsNewCameraDisable(bool wasDisabled, bool providerAccepted, bool isDisabled) { return !wasDisabled && providerAccepted && isDisabled; } internal static bool IsTrustedDelivery(ulong senderClientId, ulong serverClientId, ulong recipientClientId, ulong localClientId, ulong eventId) { if (senderClientId == serverClientId && recipientClientId == localClientId) { return eventId != 0; } return false; } internal void Reset() { _acceptedDeviceKeys.Clear(); _acceptedAlarmKeys.Clear(); } } internal static class CctvLateJoinLifecycle { internal static bool ShouldInitializePersonalRound(bool latchActive, bool isSaveKeyResolved, bool isLocalPlayerReady, bool isMapReady, bool shipHasLanded, bool inShipPhase, bool shipIsLeaving) { if (!latchActive && isSaveKeyResolved && isLocalPlayerReady && isMapReady && shipHasLanded && !inShipPhase) { return !shipIsLeaving; } return false; } } internal sealed class CctvStatisticsEpochGuard { private ulong _activeEpoch; private ulong _minimumEpoch; private ulong _levelToken; private bool _ready; internal ulong ActiveEpoch => _activeEpoch; internal ulong LevelToken => _levelToken; internal bool IsReady => _ready; internal void BeginRound(ulong levelToken) { if (_activeEpoch != 0L && _activeEpoch < ulong.MaxValue) { _minimumEpoch = _activeEpoch + 1; } _activeEpoch = 0uL; _levelToken = levelToken; _ready = false; } internal bool TryAcceptHostEpoch(ulong epoch, ulong levelToken) { if (epoch == 0L || levelToken == 0L || levelToken != _levelToken || epoch < _minimumEpoch || (_ready && epoch != _activeEpoch)) { return false; } _activeEpoch = epoch; _ready = true; return true; } internal bool IsCurrent(ulong epoch, ulong levelToken) { if (_ready && epoch != 0L && epoch == _activeEpoch && levelToken != 0L) { return levelToken == _levelToken; } return false; } internal void ResetSession() { _activeEpoch = 0uL; _minimumEpoch = 0uL; _levelToken = 0uL; _ready = false; } } public static class ClutchXpPolicy { public static bool IsEligible(bool localEnteredFacility, bool localExtractedAlive, int otherFacilityEntrants, int deadOtherFacilityEntrants) { if (localEnteredFacility && localExtractedAlive && otherFacilityEntrants > 0) { return deadOtherFacilityEntrants == otherFacilityEntrants; } return false; } } internal static class CompanyQuotaTokenIntegration { [HarmonyPatch(typeof(StartOfRound), "Awake")] private static class StartOfRoundAwakePatch { private static void Postfix() { EnsureRegistered(); } } [HarmonyPatch(typeof(GameNetworkManager), "Disconnect")] private static class DisconnectPatch { private static void Prefix() { Shutdown(); } } [CompilerGenerated] private static class <>O { public static HandleNamedMessageDelegate <0>__OnGrantMessage; } private const string CompanyApiTypeName = "Y4NGZCompany.Core.QuotaProgressionApi"; private const string GrantMessageName = "Y4NGZUpgrades.CompanyQuotaTokenGrant.v1"; private const string CompanyProtocolVersionMember = "TokenGrantProtocolVersion"; private const int MaxActionIdCharacters = 120; private const int LegacyCompanyProtocolVersion = 1; private static readonly NamedMessageLatch Latch = new NamedMessageLatch(); private static object _companyHandler; private static MethodInfo _companyUnregister; internal static bool IsCompanyProviderRegistered => _companyHandler != null; internal static void EnsureRegistered() { RegisterNetworkHandler(); RegisterCompanyHandler(); } internal static void Shutdown() { UnregisterCompanyHandler(); Latch.Disarm(); } private static void RegisterCompanyHandler() { if (_companyHandler != null) { return; } Type type = FindType("Y4NGZCompany.Core.QuotaProgressionApi"); if (type == null) { if (OptionalPluginCapabilities.MonitorTakeover) { WarnRegisterShape("Y4NGZCompany.Core.QuotaProgressionApi was not found"); } } else { if (!IsCompanyProtocolCompatible(type)) { return; } MethodInfo method = type.GetMethod("RegisterTokenGrantHandler", BindingFlags.Static | BindingFlags.Public); _companyUnregister = type.GetMethod("UnregisterTokenGrantHandler", BindingFlags.Static | BindingFlags.Public); ParameterInfo[] array = method?.GetParameters(); if (array == null || array.Length != 1) { WarnRegisterShape("QuotaProgressionApi.RegisterTokenGrantHandler is missing or does not take exactly one parameter"); return; } Type parameterType = array[0].ParameterType; MethodInfo method2 = parameterType.GetMethod("Invoke"); ParameterInfo[] array2 = method2?.GetParameters(); if (method2 == null || method2.ReturnType != typeof(bool) || array2 == null || array2.Length != 1) { WarnRegisterShape("the RegisterTokenGrantHandler parameter type '" + parameterType.FullName + "' is not a delegate taking one request and returning bool"); } else { if (!HasRequiredRequestFields(array2[0].ParameterType)) { return; } try { ParameterExpression parameterExpression = Expression.Parameter(array2[0].ParameterType, "request"); MethodInfo method3 = typeof(CompanyQuotaTokenIntegration).GetMethod("HandleCompanyRequest", BindingFlags.Static | BindingFlags.NonPublic); _companyHandler = Expression.Lambda(parameterType, Expression.Call(method3, Expression.Convert(parameterExpression, typeof(object))), parameterExpression).Compile(); method.Invoke(null, new object[1] { _companyHandler }); ManualLogSource log = Plugin.Log; if (log != null) { log.LogInfo((object)"[QuotaTokens] Registered Company quota token provider."); } } catch (Exception ex) { _companyHandler = null; _companyUnregister = null; ManualLogSource log2 = Plugin.Log; if (log2 != null) { log2.LogWarning((object)("[QuotaTokens] Company provider registration failed: " + ex.Message)); } } } } } private static void WarnRegisterShape(string problem) { if (LogGate.Once("Y4NGZUpgrades.QuotaTokens.registerShape", LogScope.Session)) { ManualLogSource log = Plugin.Log; if (log != null) { log.LogWarning((object)("[Y4NGZUpgrades.QuotaTokens] " + OptionalPluginCapabilities.PluginLabel("com.y4ngz.company.monitortakeover", "Monitor Takeover") + " is loaded but " + problem + "; quota token rewards are off this session; update Y4NGZUpgrades and Y4NGZCompany together.")); } } } private static void UnregisterCompanyHandler() { if (_companyHandler == null) { return; } try { _companyUnregister?.Invoke(null, new object[1] { _companyHandler }); } catch (Exception ex) { ManualLogSource log = Plugin.Log; if (log != null) { log.LogWarning((object)("[QuotaTokens] Company provider unregister failed: " + ex.Message)); } } _companyHandler = null; _companyUnregister = null; } private static bool IsCompanyProtocolCompatible(Type apiType) { FieldInfo field = apiType.GetField("TokenGrantProtocolVersion", BindingFlags.Static | BindingFlags.Public | BindingFlags.FlattenHierarchy); int num; if (field == null) { num = 1; } else { if (!(field.GetValue(null) is int num2)) { ManualLogSource log = Plugin.Log; if (log != null) { log.LogWarning((object)("[QuotaTokens] Not registering: Company TokenGrantProtocolVersion is not an int " + $"(Upgrades protocol {1}). Update Y4NGZUpgrades and Y4NGZCompany together.")); } return false; } num = num2; } if (num == 1) { return true; } ManualLogSource log2 = Plugin.Log; if (log2 != null) { log2.LogWarning((object)("[QuotaTokens] Not registering: token-grant protocol mismatch " + $"(Y4NGZUpgrades {1}, Y4NGZCompany {num}). " + "Quota token rewards are disabled until both mods are updated together.")); } return false; } private static bool HasRequiredRequestFields(Type requestType) { string empty = string.Empty; empty = AppendMissing(empty, requestType, "CompletedQuota", typeof(int)); empty = AppendMissing(empty, requestType, "TokensPerPlayer", typeof(int)); empty = AppendMissing(empty, requestType, "ActionId", typeof(string)); if (empty.Length == 0) { return true; } ManualLogSource log = Plugin.Log; if (log != null) { log.LogWarning((object)("[QuotaTokens] Not registering: Company request type '" + requestType.FullName + "' is missing expected field(s): " + empty + ". Quota token rewards are disabled until both mods are updated together.")); } return false; } private static string AppendMissing(string missing, Type requestType, string name, Type expected) { FieldInfo field = requestType.GetField(name, BindingFlags.Instance | BindingFlags.Public); if (field != null && field.FieldType == expected) { return missing; } string text = ((field == null) ? name : (name + " (expected " + expected.Name + ", found " + field.FieldType.Name + ")")); if (missing.Length != 0) { return missing + ", " + text; } return text; } private static bool HandleCompanyRequest(object request) { NetworkManager singleton = NetworkManager.Singleton; if (request == null || (Object)(object)singleton == (Object)null || !singleton.IsServer) { return false; } try { Type type = request.GetType(); if (!TryReadIntField(type, request, "CompletedQuota", out var value) || !TryReadIntField(type, request, "TokensPerPlayer", out var value2) || !TryReadStringField(type, request, "ActionId", out var value3)) { return false; } bool isReplay = ReadOptionalBoolField(type, request, "IsReplay"); if (value < 1 || value2 < 1 || string.IsNullOrWhiteSpace(value3)) { return false; } return TryGrantConnectedPlayers(new ExternalTokenGrantRequest(value2, "Y4NGZCompany", $"quota:{value}", value3), isReplay); } catch (Exception ex) { ManualLogSource log = Plugin.Log; if (log != null) { log.LogWarning((object)("[QuotaTokens] Company grant failed: " + ex.Message)); } return false; } } internal static bool TryGrantConnectedPlayers(ExternalTokenGrantRequest request) { return TryGrantConnectedPlayers(request, isReplay: false); } internal unsafe static bool TryGrantConnectedPlayers(ExternalTokenGrantRequest request, bool isReplay) { //IL_00f3: Unknown result type (might be due to invalid IL or missing references) //IL_00f9: Unknown result type (might be due to invalid IL or missing references) //IL_010b: Unknown result type (might be due to invalid IL or missing references) //IL_0111: Unknown result type (might be due to invalid IL or missing references) //IL_011b: Unknown result type (might be due to invalid IL or missing references) //IL_0120: Unknown result type (might be due to invalid IL or missing references) //IL_0126: Unknown result type (might be due to invalid IL or missing references) //IL_012c: Unknown result type (might be due to invalid IL or missing references) //IL_015e: Unknown result type (might be due to invalid IL or missing references) NetworkManager singleton = NetworkManager.Singleton; if ((Object)(object)singleton == (Object)null || !singleton.IsServer || request.AmountPerPlayer < 1) { return false; } string text = (string.IsNullOrWhiteSpace(request.Source) ? "external" : request.Source.Trim()); string text2 = (string.IsNullOrWhiteSpace(request.ActionId) ? string.Empty : request.ActionId.Trim()); string text3 = text + ":" + text2; int completedQuota = ParseQuota(request.MilestoneId); if (text2.Length == 0) { return false; } try { if (text3.Length > 120) { ManualLogSource log = Plugin.Log; if (log != null) { log.LogWarning((object)("[QuotaTokens] Rejected " + text + " grant with oversized action ID.")); } return false; } bool result = ApplyLocalGrant(completedQuota, request.AmountPerPlayer, text3, isReplay); CustomMessagingManager customMessagingManager = singleton.CustomMessagingManager; if (customMessagingManager == null) { return result; } FastBufferWriter val = default(FastBufferWriter); ((FastBufferWriter)(ref val))..ctor(256, (Allocator)2, -1); try { ((FastBufferWriter)(ref val)).WriteValueSafe<int>(ref completedQuota, default(ForPrimitives)); ((FastBufferWriter)(ref val)).WriteValueSafe<int>(ref request.AmountPerPlayer, default(ForPrimitives)); FixedString128Bytes val2 = new FixedString128Bytes(text3); ((FastBufferWriter)(ref val)).WriteValueSafe<FixedString128Bytes>(ref val2, default(ForFixedStrings)); foreach (ulong connectedClientsId in singleton.ConnectedClientsIds) { if (connectedClientsId != singleton.LocalClientId) { customMessagingManager.SendNamedMessage("Y4NGZUpgrades.CompanyQuotaTokenGrant.v1", connectedClientsId, val, (NetworkDelivery)4); } } } finally { ((IDisposable)(*(FastBufferWriter*)(&val))/*cast due to .constrained prefix*/).Dispose(); } return true; } catch (Exception ex) { ManualLogSource log2 = Plugin.Log; if (log2 != null) { log2.LogWarning((object)("[QuotaTokens] " + text + " grant failed: " + ex.Message)); } return false; } } private static bool ApplyLocalGrant(int completedQuota, int tokensPerPlayer, string actionId, bool isReplay = false) { if (!ProgressionManager.TryApplyExternalTokenGrant(actionId, tokensPerPlayer, out var alreadyApplied)) { return false; } if (alreadyApplied) { ManualLogSource log = Plugin.Log; if (log != null) { log.LogDebug((object)string.Format("[QuotaTokens] Quota {0} grant already in this save's ledger ({1}); ignoring{2}.", completedQuota, actionId, isReplay ? " replay" : string.Empty)); } return true; } ManualLogSource log2 = Plugin.Log; if (log2 != null) { log2.LogInfo((object)string.Format("[QuotaTokens] Quota {0} grant accepted{1}: +{2} tokens ({3}).", completedQuota, isReplay ? " (replay)" : string.Empty, tokensPerPlayer, actionId)); } return true; } private static void RegisterNetworkHandler() { //IL_0041: Unknown result type (might be due to invalid IL or missing references) //IL_0046: Unknown result type (might be due to invalid IL or missing references) //IL_004c: Expected O, but got Unknown NetworkManager singleton = NetworkManager.Singleton; CustomMessagingManager val = ((singleton != null) ? singleton.CustomMessagingManager : null); if (val == null || !Latch.TryArm(val, singleton.ShutdownInProgress)) { return; } try { object obj = <>O.<0>__OnGrantMessage; if (obj == null) { HandleNamedMessageDelegate val2 = OnGrantMessage; <>O.<0>__OnGrantMessage = val2; obj = (object)val2; } val.RegisterNamedMessageHandler("Y4NGZUpgrades.CompanyQuotaTokenGrant.v1", (HandleNamedMessageDelegate)obj); } catch (Exception ex) { Latch.Disarm(); ManualLogSource log = Plugin.Log; if (log != null) { log.LogWarning((object)("[QuotaTokens] Network handler registration failed: " + ex.Message)); } } } private unsafe static void OnGrantMessage(ulong senderClientId, FastBufferReader reader) { //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Unknown result type (might be due to invalid IL or missing references) //IL_003c: Unknown result type (might be due to invalid IL or missing references) //IL_0042: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)NetworkManager.Singleton == (Object)null || senderClientId != 0L) { return; } try { int num = default(int); ((FastBufferReader)(ref reader)).ReadValueSafe<int>(ref num, default(ForPrimitives)); int num2 = default(int); ((FastBufferReader)(ref reader)).ReadValueSafe<int>(ref num2, default(ForPrimitives)); FixedString128Bytes val = default(FixedString128Bytes); ((FastBufferReader)(ref reader)).ReadValueSafe<FixedString128Bytes>(ref val, default(ForFixedStrings)); if (num >= 1 && num2 >= 1 && !((FixedString128Bytes)(ref val)).IsEmpty) { ApplyLocalGrant(num, num2, ((object)(*(FixedString128Bytes*)(&val))/*cast due to .constrained prefix*/).ToString()); } } catch (Exception ex) { ManualLogSource log = Plugin.Log; if (log != null) { log.LogWarning((object)("[QuotaTokens] Malformed grant from server: " + ex.Message)); } } } private static Type FindType(string fullName) { Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies(); foreach (Assembly assembly in assemblies) { try { Type type = assembly.GetType(fullName, throwOnError: false); if (type != null) { return type; } } catch { } } return null; } private static bool TryReadIntField(Type type, object instance, string name, out int value) { value = 0; if (type.GetField(name, BindingFlags.Instance | BindingFlags.Public)?.GetValue(instance) is int num) { value = num; return true; } LogRequestShapeError(type, name, "int"); return false; } private static bool TryReadStringField(Type type, object instance, string name, out string value) { value = string.Empty; FieldInfo field = type.GetField(name, BindingFlags.Instance | BindingFlags.Public); if (field != null && field.FieldType == typeof(string)) { value = (field.GetValue(instance) as string) ?? string.Empty; return true; } LogRequestShapeError(type, name, "string"); return false; } private static bool ReadOptionalBoolField(Type type, object instance, string name) { object obj = type.GetField(name, BindingFlags.Instance | BindingFlags.Public)?.GetValue(instance); bool flag = default(bool); int num; if (obj is bool) { flag = (bool)obj; num = 1; } else { num = 0; } return (byte)((uint)num & (flag ? 1u : 0u)) != 0; } private static void LogRequestShapeError(Type type, string name, string expected) { if (LogGate.Once("Y4NGZUpgrades.QuotaTokens.requestShape", LogScope.Session)) { ManualLogSource log = Plugin.Log; if (log != null) { log.LogError((object)("[QuotaTokens] Company request type '" + type.FullName + "' has no readable " + expected + " field '" + name + "'. " + $"Quota token grants are being dropped; Y4NGZUpgrades expects token-grant protocol {1}. " + "Update Y4NGZUpgrades and Y4NGZCompany together.")); } } } private static int ParseQuota(string milestoneId) { if (string.IsNullOrWhiteSpace(milestoneId)) { return 0; } int num = milestoneId.LastIndexOf(':'); if (!int.TryParse((num >= 0) ? milestoneId.Substring(num + 1) : milestoneId, out var result)) { return 0; } return Math.Max(0, result); } } internal sealed class CompanyReportWriterLink { internal enum RowWriter { Upgrades, Contracted, ContractedPending } private enum Mode { Unresolved, Absent, Bound, FullCap } internal const string PresenterTypeName = "Y4NGZCompany.Contracts._Shared.PerformanceReportXpPresenter, Y4NGZCompany"; internal const int SupportedProtocolVersion = 1; private const string FullCapLoss = "the XP lines on the round-end report arrive about a second and a half later."; private readonly Func<bool> _contractedLoaded; private readonly Func<Type> _findPresenter; private readonly Func<string> _label; private readonly Action<string> _warn; private readonly Action<string> _debug; private Mode _mode; private Func<bool> _isWritePending; private Func<bool> _isReportApplied; private bool _probeFailureWarned; private bool _appliedFailureWarned; internal CompanyReportWriterLink(Func<bool> contractedLoaded, Func<Type> findPresenter, Func<string> label, Action<string> warn, Action<string> debug) { _contractedLoaded = contractedLoaded; _findPresenter = findPresenter; _label = label; _warn = warn; _debug = debug; } internal bool KeepWaiting(ref int framesRemaining) { switch (Resolve()) { case Mode.Bound: if (framesRemaining-- > 0) { return IsPending(); } return false; case Mode.FullCap: return framesRemaining-- > 0; default: return false; } } internal bool IsPending() { if (Resolve() != Mode.Bound) { return false; } try { return _isWritePending(); } catch (Exception ex) { if (!_probeFailureWarned) { _probeFailureWarned = true; _warn("[Progression] " + _label() + " failed to report whether its performance-report writer is pending; the XP lines on the round-end report may be written before it finishes."); _debug("[Progression] Report-writer probe exception: " + ex); } return false; } } internal RowWriter DecideRowWriter(bool hasNoteOwner) { Mode mode = Resolve(); if (mode == Mode.Absent || !hasNoteOwner) { return RowWriter.Upgrades; } if (mode != Mode.Bound) { return RowWriter.Contracted; } if (IsPending()) { return RowWriter.ContractedPending; } if (_isReportApplied == null) { return RowWriter.Contracted; } try { return _isReportApplied() ? RowWriter.Contracted : RowWriter.Upgrades; } catch (Exception ex) { if (!_appliedFailureWarned) { _appliedFailureWarned = true; _warn("[Y4NGZUpgrades.Progression] " + _label() + " failed to report whether its performance report is applied; the crewmates' XP lines on the round-end report are left to it."); _debug("[Y4NGZUpgrades.Progression] Report-applied member exception: " + ex); } return RowWriter.Contracted; } } private Mode Resolve() { if (_mode != Mode.Unresolved) { return _mode; } if (!_contractedLoaded()) { return _mode = Mode.Absent; } bool protocolMismatch = false; string text; try { text = Bind(_findPresenter(), out protocolMismatch); } catch (Exception ex) { text = "binding threw " + ex; } if (text == null) { return _mode = Mode.Bound; } _mode = Mode.FullCap; if (protocolMismatch) { _warn("[Progression] " + _label() + " performance-report protocol is " + text + ", Y4NGZUpgrades supports " + string.Format("{0}; {1}", 1, "the XP lines on the round-end report arrive about a second and a half later.")); return _mode; } _warn("[Progression] " + _label() + " does not offer the performance-report writer state Y4NGZUpgrades waits on; the XP lines on the round-end report arrive about a second and a half later."); _debug("[Progression] Report-writer bind: " + text + "."); return _mode; } private string Bind(Type presenter, out bool protocolMismatch) { protocolMismatch = false; if (presenter == null) { return "PerformanceReportXpPresenter not found"; } FieldInfo field = presenter.GetField("ProtocolVersion", BindingFlags.Static | BindingFlags.Public); if (field == null) { return "PerformanceReportXpPresenter.ProtocolVersion not found"; } if (!field.IsLiteral || !(field.GetRawConstantValue() is int num)) { protocolMismatch = true; return "not an int constant"; } if (num != 1) { protocolMismatch = true; return num.ToString(CultureInfo.InvariantCulture); } MethodInfo method = presenter.GetMethod("IsReportWritePending", BindingFlags.Static | BindingFlags.Public, null, Type.EmptyTypes, null); if (method == null || method.ReturnType != typeof(bool)) { return "PerformanceReportXpPresenter.IsReportWritePending is missing or not public static bool()"; } _isWritePending = (Func<bool>)Delegate.CreateDelegate(typeof(Func<bool>), method); MethodInfo method2 = presenter.GetMethod("IsReportApplied", BindingFlags.Static | BindingFlags.Public, null, Type.EmptyTypes, null); _isReportApplied = ((method2 != null && method2.ReturnType == typeof(bool)) ? ((Func<bool>)Delegate.CreateDelegate(typeof(Func<bool>), method2)) : null); return null; } } internal static class CompanyReportXpBridge { private const string SinkTypeName = "Y4NGZCompany.Contracts._Shared.PerformanceReportXpAmounts, Y4NGZCompany"; private const int SupportedProtocolVersion = 1; private static bool _noteOwnerResolved; private static MethodInfo _recordSources; private static MethodInfo _applyNotes; private static bool _resolved; private static MethodInfo _recordAmount; internal static bool HasNoteOwner { get { ResolveNoteOwner(); if (_recordSources != null) { return _applyNotes != null; } return false; } } internal static bool CanShare { get { if (!OptionalPluginCapabilities.BetterExp && HasNoteOwner) { return Resolve() != null; } return false; } } private static void WarnShapeChanged(string seam, string problem) { if (OptionalPluginCapabilities.Contracted) { ManualLogSource log = Plugin.Log; if (log != null) { log.LogWarning((object)("[Y4NGZUpgrades.Progression] Y4NGZCompany's " + seam + " is unusable: " + problem + "; contract XP stays on the Upgrades note; check the Y4NGZCompany (Contracted) version.")); } } } private static void ResolveNoteOwner() { if (_noteOwnerResolved) { return; } _noteOwnerResolved = true; string text = null; try { Type type = Type.GetType("Y4NGZCompany.Contracts._Shared.PerformanceReportXpLedger, Y4NGZCompany", throwOnError: false); object obj = type?.GetField("ProtocolVersion")?.GetRawConstantValue(); if (type == null) { text = "PerformanceReportXpLedger was not found"; } else if (!(obj is int num)) { text = "PerformanceReportXpLedger.ProtocolVersion is missing or not an int constant"; } else if (num != 1) { text = $"PerformanceReportXpLedger speaks protocol {num}, this plugin expects {1}"; } else { _recordSources = type.GetMethod("RecordSources", new Type[5] { typeof(int), typeof(string[]), typeof(string[]), typeof(int[]), typeof(int) }); _applyNotes = Type.GetType("Y4NGZCompany.Contracts._Shared.PerformanceReportXpPresenter, Y4NGZCompany", throwOnError: false)?.GetMethod("TryApplyNotes", new Type[2] { typeof(object), typeof(int) }); if (_recordSources == null) { text = "PerformanceReportXpLedger.RecordSources(int, string[], string[], int[], int) was not found"; } else if (_applyNotes == null) { text = "PerformanceReportXpPresenter.TryApplyNotes(object, int) was not found"; } } } catch (Exception ex) { _recordSources = null; _applyNotes = null; text = "resolving threw " + ex.GetType().Name + ": " + ex.Message; ManualLogSource log = Plugin.Log; if (log != null) { log.LogDebug((object)("[Y4NGZUpgrades.Progression] Report XP note owner resolve exception: " + ex)); } } if (text != null) { WarnShapeChanged("report XP note owner", text); } } internal static void RecordSources(int playerIndex, IReadOnlyList<ProgressionReportSource> sources, int total) { if (OptionalPluginCapabilities.BetterExp || !HasNoteOwner || sources == null) { return; } try { string[] array = new string[sources.Count]; string[] array2 = ProgressionReportNotePlan.DescribeSources(sources); int[] array3 = new int[sources.Count]; for (int i = 0; i < sources.Count; i++) { array[i] = sources[i].Key; array3[i] = sources[i].Amount; } _recordSources.Invoke(null, new object[5] { playerIndex, array, array2, array3, total }); } catch (Exception ex) { ManualLogSource log = Plugin.Log; if (log != null) { log.LogWarning((object)("[Progression] Could not record Company XP notes: " + ex.Message)); } } } internal static bool TryApplyNotes(object hud, int playerIndex) { if (!HasNoteOwner) { return false; } try { object obj = _applyNotes.Invoke(null, new object[2] { hud, playerIndex }); bool flag = default(bool); int num; if (obj is bool) { flag = (bool)obj; num = 1; } else { num = 0; } return (byte)((uint)num & (flag ? 1u : 0u)) != 0; } catch (Exception ex) { ManualLogSource log = Plugin.Log; if (log != null) { log.LogWarning((object)("[Progression] Company XP notes unavailable; using standalone layout: " + ex.Message)); } return false; } } internal static void RecordShare(ProgressionReportShare share) { if (share == null || !CanShare) { return; } ProgressionSettings progressionConfig = Plugin.ProgressionConfig; if (progressionConfig != null && progressionConfig.DebugLogging?.Value == true) { string text = XpSourceLabel.FirstOverBudget(share.SourceLabels); if (text != null) { ManualLogSource log = Plugin.Log; if (log != null) { log.LogWarning((object)$"[Progression] Crew share label '{text}' from slot {share.Slot} is {text.Length} characters; the report budget is {19} (#1614)."); } } } try { share.RecordInto(delegate(int slot, string[] keys, string[] labels, int[] amounts, int total) { object obj = _recordSources.Invoke(null, new object[5] { slot, keys, labels, amounts, total }); bool flag = default(bool); int num; if (obj is bool) { flag = (bool)obj; num = 1; } else { num = 0; } return (byte)((uint)num & (flag ? 1u : 0u)) != 0; }, delegate(int slot, string key, int amount) { _recordAmount.Invoke(null, new object[3] { slot, key, amount }); }); } catch (Exception ex) { ManualLogSource log2 = Plugin.Log; if (log2 != null) { log2.LogWarning((object)("[Progression] Could not record a crewmate's report XP: " + ex.Message)); } } } internal static int Record(int playerIndex, IReadOnlyList<KeyValuePair<string, int>> lines, out int crewWideRecorded) { crewWideRecorded = 0; if (playerIndex < 0 || lines == null || lines.Count == 0) { return 0; } MethodInfo methodInfo = Resolve(); if (methodInfo == null) { return 0; } int num = 0; try { for (int i = 0; i < lines.Count; i++) { string key = lines[i].Key; int value = lines[i].Value; if (!string.IsNullOrWhiteSpace(key) && value > 0) { methodInfo.Invoke(null, new object[3] { playerIndex, key, value }); num += value; if (ProgressionReportLineKeys.IsCrewWideKey(key)) { crewWideRecorded += value; } } } } catch (Exception ex) { if (LogGate.Once("Y4NGZUpgrades.Progression.reportXpHandOver", LogScope.Session)) { ManualLogSource log = Plugin.Log; if (log != null) { log.LogWarning((object)("[Progression] Could not hand report XP amounts to Y4NGZCompany: " + ex.GetType().Name + ": " + ex.Message)); } } } return num; } private static MethodInfo Resolve() { if (_resolved) { return _recordAmount; } _resolved = true; try { Type type = Type.GetType("Y4NGZCompany.Contracts._Shared.PerformanceReportXpAmounts, Y4NGZCompany", throwOnError: false); if (type == null) { WarnShapeChanged("report XP sink", "PerformanceReportXpAmounts was not found"); return null; } FieldInfo field = type.GetField("ProtocolVersion", BindingFlags.Static | BindingFlags.Public); object obj = ((field != null && field.IsLiteral) ? field.GetRawConstantValue() : field?.GetValue(null)); if (!(obj is int num) || num != 1) { ManualLogSource log = Plugin.Log; if (log != null) { log.LogWarning((object)("[Progression] Y4NGZCompany's report XP sink speaks protocol " + string.Format("{0}, this plugin expects {1}; ", (obj is int num2) ? num2.ToString() : "<none>", 1) + "contract XP stays on the Upgrades note.")); } return null; } _recordAmount = type.GetMethod("RecordAmount", BindingFlags.Static | BindingFlags.Public, null, new Type[3] { typeof(int), typeof(string), typeof(int) }, null); if (_recordAmount == null) { WarnShapeChanged("report XP sink", "PerformanceReportXpAmounts.RecordAmount(int, string, int) was not found"); } } catch (Exception ex) { _recordAmount = null; WarnShapeChanged("report XP sink", "resolving threw " + ex.GetType().Name + ": " + ex.Message); ManualLogSource log2 = Plugin.Log; if (log2 != null) { log2.LogDebug((object)("[Y4NGZUpgrades.Progression] Report XP sink resolve exception: " + ex)); } } return _recordAmount; } } internal static class ContractActCatalog { internal enum ActScaling { Headline, Step } internal readonly struct Row { internal readonly string Kind; internal readonly ActScaling Scaling; internal readonly int FlatDefaultXp; internal Row(string kind, ActScaling scaling, int flatDefaultXp) { Kind = kind; Scaling = scaling; FlatDefaultXp = flatDefaultXp; } } private static readonly Row[] Rows = new Row[12] { new Row("BlackoutAuditRestored", ActScaling.Headline, 35), new Row("WhistleblowerNeutralized", ActScaling.Headline, 35), new Row("ShadowRaidDrillCompleted", ActScaling.Headline, 15), new Row("PestControlCompleted", ActScaling.Headline, 25), new Row("WasteDisposalCompleted", ActScaling.Headline, 25), new Row("LguDataRecovered", ActScaling.Headline, LguFlatDefault("LguDataRecovered")), new Row("LguNestDestroyed", ActScaling.Headline, LguFlatDefault("LguNestDestroyed")), new Row("LguScavengerRecovered", ActScaling.Headline, LguFlatDefault("LguScavengerRecovered")), new Row("LguDemonIdentified", ActScaling.Headline, LguFlatDefault("LguDemonIdentified")), new Row("LguDeviceDefused", ActScaling.Headline, LguFlatDefault("LguDeviceDefused")), new Row("SurveyDronePlaced", ActScaling.Step, 12), new Row("ContainmentBreachWaveSurvived", ActScaling.Step, 10) }; internal static IReadOnlyList<Row> All => Rows; internal static bool TryGet(string kind, out Row row) { if (!string.IsNullOrEmpty(kind)) { Row[] rows = Rows; for (int i = 0; i < rows.Length; i++) { Row row2 = rows[i]; if (string.Equals(kind, row2.Kind, StringComparison.Ordinal)) { row = row2; return true; } } } row = default(Row); return false; } internal static int FlatDefaultXp(string kind) { if (!TryGet(kind, out var row)) { return 0; } return row.FlatDefaultXp; } internal static bool CountsAsParticipation(string eventKind, bool crewWide) { if (!crewWide && !string.IsNullOrWhiteSpace(eventKind) && !string.Equals(eventKind, "ContractCompleted", StringComparison.Ordinal) && !string.Equals(eventKind, "ContractFailed", StringComparison.Ordinal) && !SideObjectiveXpPolicy.IsSideObjectiveKind(eventKind)) { return !ContractRewardXpPolicy.IsKind(eventKind); } return false; } private static int LguFlatDefault(string kind) { if (!LguContractXpCatalog.TryGet(kind, out var award)) { return 0; } return award.BaseXp; } } internal static class ContractEventAttribution { internal const string CrewFanOutMarker = ".crew."; private const string CrewSegment = ".crew"; internal static bool IsIndividuallyAttributed(string eventId, ulong creditedClientId) { if (string.IsNullOrEmpty(eventId)) { return false; } if (!eventId.EndsWith("." + creditedClientId, StringComparison.Ordinal)) { return false; } return eventId.IndexOf(".crew.", StringComparison.Ordinal) < 0; } internal static bool IsCrewFanOut(string eventId) { if (!string.IsNullOrEmpty(eventId)) { return eventId.IndexOf(".crew.", StringComparison.Ordinal) >= 0; } return false; } internal static string WithoutPlayerTail(string eventId) { if (string.IsNullOrEmpty(eventId)) { return eventId; } int num = eventId.Length; while (num > 0 && eventId[num - 1] >= '0' && eventId[num - 1] <= '9') { num--; } if (num == eventId.Length || num < 2 || eventId[num - 1] != '.') { return eventId; } string text = eventId.Substring(0, num - 1); if (text.EndsWith(".crew", StringComparison.Ordinal)) { text = text.Substring(0, text.Length - ".crew".Length); } if (text.Length <= 0) { return eventId; } return text; } } internal sealed class ContractProgressionEventLink { private static readonly MethodInfo DispatchMethod = typeof(ContractProgressionEventLink).GetMethod("Dispatch", BindingFlags.Instance | BindingFlags.NonPublic); private readonly Action<object> _handler; private readonly Func<string> _label; private readonly Action<string> _warn; private readonly Action<string> _debug; private bool _attempted; private bool _subscribed; private Delegate _listener; private MethodInfo _removeMethod; private bool _handlerFailureWarned; internal ContractProgressionEventLink(Action<object> handler, Func<string> label, Action<string> warn, Action<string> debug) { _handler = handler; _label = label; _warn = warn; _debug = debug; } internal bool Subscribe(bool contractedLoaded, Func<Type> findEventsType) { if (_attempted) { return _subscribed; } _attempted = true; if (!contractedLoaded) { return false; } try { Type type = findEventsType(); EventInfo? obj = type?.GetEvent("Published", BindingFlags.Static | BindingFlags.Public); MethodInfo methodInfo = obj?.GetAddMethod(); MethodInfo methodInfo2 = obj?.GetRemoveMethod(); Type type2 = obj?.EventHandlerType; MethodInfo methodInfo3 = type2?.GetMethod("Invoke"); ParameterInfo[] array = methodInfo3?.GetParameters(); if (methodInfo == null || methodInfo2 == null || !typeof(Delegate).IsAssignableFrom(type2) || methodInfo3 == null || methodInfo3.ReturnType != typeof(void) || array.Length != 1 || !IsReferenceType(array[0].ParameterType)) { return Unavailable((type == null) ? "ContractProgressionEvents not found" : "no public static event Published whose handler returns void and takes one reference-type argument"); } ParameterExpression parameterExpression = Expression.Parameter(array[0].ParameterType, "progressionEvent"); Delegate obj2 = Expression.Lambda(type2, Expression.Call(Expression.Constant(this), DispatchMethod, Expression.Convert(parameterExpression, typeof(object))), parameterExpression).Compile(); methodInfo.Invoke(null, new object[1] { obj2 }); _listener = obj2; _removeMethod = methodInfo2; return _subscribed = true; } catch (Exception ex) { return Unavailable("subscribing threw " + ex); } } internal void Unsubscribe() { Delegate listener = _listener; if ((object)listener != null) { _listener = null; _removeMethod.Invoke(null, new object[1] { listener }); } } private void Dispatch(object progressionEvent) { try { _handler(progressionEvent); } catch (Exception ex) { if (!_handlerFailureWarned) { _handlerFailureWarned = true; _warn("[Progression] A contract progression event from " + _label() + " could not be turned into XP; contract XP for such events may be missing."); _debug("[Progression] Contract progression handler exception: " + ex); } } } private bool Unavailable(string detail) { _warn("[Progression] " + _label() + " does not offer the contract progression event Y4NGZUpgrades listens to; contract XP from Contracted is off."); _debug("[Progression] Contract progression subscribe: " + detail + "."); return false; } private static bool IsReferenceType(Type type) { if (!type.IsValueType && !type.IsByRef) { return !type.IsPointer; } return false; } } internal static class ContractRewardXpPolicy { internal const string Kind = "ContractRewardXp"; internal const int MaxAmount = 2000; internal static bool IsKind(string kind) { return string.Equals(kind, "ContractRewardXp", StringComparison.Ordinal); } internal static string AwardKey(string eventId) { return ContractEventAttribution.WithoutPlayerTail(eventId); } internal static int Amount(int count) { if (count > 0) { return Math.Min(count, 2000); } return 0; } } internal sealed class CumulativeCountTracker { private readonly Dictionary<int, int> _deltaByTotal = new Dictionary<int, int>(); private int _highWater; internal int Observe(int cumulativeTotal) { if (cumulativeTotal <= 0) { return 1; } if (cumulativeTotal > _highWater) { int num = cumulativeTotal - _highWater; _highWater = cumulativeTotal; _deltaByTotal[cumulativeTotal] = num; return num; } if (!_deltaByTotal.TryGetValue(cumulativeTotal, out var value)) { return 0; } return value; } } internal static class DawnLibCompat { internal const string ItemNamespace = "y4ngz_upgrades"; [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)] internal static void FixMixerGroups(GameObject prefab) { DawnLib.FixMixerGroups(prefab); } [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)] internal static void RegisterNetworkPrefab(GameObject prefab) { DawnLib.RegisterNetworkPrefab(prefab); } [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)] internal static void RegisterScrapItem(string itemKey, Item item, int weight) { NamespacedKey<DawnItemInfo> obj = NamespacedKey<DawnItemInfo>.From("y4ngz_upgrades", itemKey); int clamped = Math.Max(0, weight); DawnLib.DefineItem(obj, item, (Action<ItemInfoBuilder>)delegate(ItemInfoBuilder builder) { builder.DefineScrap((Action<ScrapBuilder>)delegate(ScrapBuilder scrap) { scrap.SetWeights((Action<WeightTableBuilder<DawnMoonInfo, SpawnWeightContext>>)delegate(WeightTableBuilder<DawnMoonInfo, SpawnWeightContext> w) { w.SetGlobalWeight(clamped); }); }); }); } } internal sealed class DeliveryAttributionLedger { internal const ulong UnattributedHandler = ulong.MaxValue; private readonly Dictionary<ulong, ulong> _lastHandlerByKey = new Dictionary<ulong, ulong>(); private readonly HashSet<ulong> _preexistingInsideKeys = new HashSet<ulong>(); private readonly HashSet<ulong> _foundKeys = new HashSet<ulong>(); internal int PreexistingInsideCount => _preexistingInsideKeys.Count; internal void Reset() { _lastHandlerByKey.Clear(); _preexistingInsideKeys.Clear(); _foundKeys.Clear(); } internal bool TryClaimFoundXp(ulong key) { if (!_preexistingInsideKeys.Contains(key)) { return _foundKeys.Add(key); } return false; } internal void MarkPreexistingInside(ulong key) { _preexistingInsideKeys.Add(key); } internal void RecordBoundaryCrossing(ulong key, ulong handlerClientId, bool nowInside) { if (nowInside) { _lastHandlerByKey[key] = handlerClientId; } else { _lastHandlerByKey.Remove(key); } } internal static bool SuppressOutwardTransition(bool nowInside, bool handlerKnown, bool handlerIsDead, bool handlerIsInsideShip) { if (!nowInside && handlerKnown) { return handlerIsDead || handlerIsInsideShip; } return false; } internal static bool ShouldPayBodyRetrieval(bool lastHandlerIsPayee, bool bodyIsInShip, bool bodyDeactivated, bool ownerResolved, bool payeeOwnsBody) { if (lastHandlerIsPayee && bodyIsInShip && !bodyDeactivated && ownerResolved) { return !payeeOwnsBody; } return false; } internal bool TryGetDeliveryHandler(ulong key, out ulong handlerClientId) { return _lastHandlerByKey.TryGetValue(key, out handlerClientId); } internal bool ShouldPayDelivery(ulong key, bool insideAtRoundEnd, ulong localClientId) { if (insideAtRoundEnd && !_preexistingInsideKeys.Contains(key) && _lastHandlerByKey.TryGetValue(key, out var value) && value != ulong.MaxValue) { return value == localClientId; } return false; } } internal static class EffectiveConfigInventory { private readonly struct InventoryRow { internal string FileName { get; } internal ConfigEntryBase Entry { get; } internal InventoryRow(string fileName, ConfigEntryBase entry) { FileName = fileName; Entry = entry; } } internal static string ReportPath => Path.Combine(Paths.ConfigPath, "Y4NGZUpgrades", "effective-config.tsv"); internal static void Write(IEnumerable<ConfigFile> configs) { if (configs == null) { return; } try { List<InventoryRow> list = new List<InventoryRow>(); foreach (ConfigFile config in configs) { if (config == null) { continue; } string fileName = Path.GetFileName(config.ConfigFilePath); foreach (KeyValuePair<ConfigDefinition, ConfigEntryBase> item in config) { list.Add(new InventoryRow(fileName, item.Value)); } } list.Sort(delegate(InventoryRow left, InventoryRow right) { int num2 = string.Compare(left.FileName, right.FileName, StringComparison.OrdinalIgnoreCase); if (num2 != 0) { return num2; } int num3 = string.Compare(left.Entry.Definition.Section, right.Entry.Definition.Section, StringComparison.OrdinalIgnoreCase); return (num3 == 0) ? string.Compare(left.Entry.Definition.Key, right.Entry.Definition.Key, StringComparison.OrdinalIgnoreCase) : num3; }); StringBuilder stringBuilder = new StringBuilder(); stringBuilder.AppendLine("file\tsection\tkey\ttype\tdefault\teffective\tdescription"); for (int num = 0; num < list.Count; num++) { InventoryRow inventoryRow = list[num]; ConfigEntryBase entry = inventoryRow.Entry; StringBuilder stringBuilder2 = stringBuilder.Append(Escape(inventoryRow.FileName)).Append('\t').Append(Escape(entry.Definition.Section)) .Append('\t') .Append(Escape(entry.Definition.Key)) .Append('\t') .Append(Escape(entry.SettingType?.FullName)) .Append('\t') .Append(Escape(Format(entry.DefaultValue))) .Append('\t') .Append(Escape(Format(entry.BoxedValue))) .Append('\t'); ConfigDescription description = entry.Description; stringBuilder2.Append(Escape((description != null) ? description.Description : null)).AppendLine(); } Directory.CreateDirectory(Path.GetDirectoryName(ReportPath)); File.WriteAllText(ReportPath, stringBuilder.ToString()); ManualLogSource log = Plugin.Log; if (log != null) { log.LogInfo((object)$"Effective config inventory written to '{ReportPath}' ({list.Count} definitions)."); } } catch (Exception ex) { ManualLogSource log2 = Plugin.Log; if (log2 != null) { log2.LogWarning((object)("Failed writing effective config inventory: " + ex.Message)); } } } private static string Format(object value) { if (value == null) { return string.Empty; } if (!(value is IFormattable formattable)) { return value.ToString(); } return formattable.ToString(null, CultureInfo.InvariantCulture); } private static string Escape(string value) { return (value ?? string.Empty).Replace("\t", "\\t").Replace("\r", "\\r").Replace("\n", "\\n"); } } internal static class EmployeeStatistics { private sealed class RoundState { internal readonly EmployeeStatisticsData Data = new EmployeeStatisticsData(); internal readonly Dictionary<ulong, ulong> LastItemHolderByKey = new Dictionary<ulong, ulong>(); internal readonly Dictionary<ulong, float> LastEnemyHitByLocalPlayer = new Dictionary<ulong, float>(); internal readonly HashSet<ulong> KilledEnemies = new HashSet<ulong>(); internal readonly HashSet<string> UniqueEventKeys = new HashSet<string>(StringComparer.Ordinal); internal readonly CctvStatisticsEventGuard CctvEvents = new CctvStatisticsEventGuard(); internal Vector3 LastPlayerPosition; internal bool PlayerPositionValid; internal float StepDistance; internal object PayloadCart; internal Vector3 LastPayloadPosition; internal bool PayloadPositionValid; internal readonly CumulativeCountTracker PestCaptureCounts = new CumulativeCountTracker(); } private const string CompanyAssemblyName = "Y4NGZCompany"; private const string CctvAssemblyName = "LethalCCTV"; internal const float StepMeters = 0.76f; private const float MinimumTrackedMovement = 0.02f; private const float MaximumTrackedMovement = 8f; private static readonly string SaveDir = Path.Combine(Paths.ConfigPath, "Y4NGZEmployeeFile"); private static EmployeeStatisticsData _lifetime; private static EmployeeStatisticsData _lastRound; private static RoundState _round = new RoundState(); private static readonly RoundLatch _latch = new RoundLatch(); private static string _key; private static int _lastTimesFulfilledQuota = -1; private static bool _cctvReflectionResolved; private static PropertyInfo _cctvFocusedProperty; private static bool _payloadReflectionResolved; private static PropertyInfo _localPayloadCartProperty; private static PropertyInfo _payloadAttachedToLocalProperty; internal static EmployeeStatisticsData CurrentSnapshot { get { EnsureLoaded(); EmployeeStatisticsData employeeStatisticsData = _lifetime?.Clone() ?? new EmployeeStatisticsData(); if (_latch.Active && !_latch.Finalized) { employeeStatisticsData.Add(_round.Data); } return employeeStatisticsData; } } internal static EmployeeStatisticsData CurrentRoundSnapshot { get { if (!_latch.Active || _latch.Finalized) { return null; } return _round.Data.Clone(); } } internal static void SwitchToCurrentSave() { if (!SaveKey.TryGetCurrent(out var key)) { _key = null; _lifetime = new EmployeeStatisticsData(); ResetRuntimeState(); } else if (_lifetime == null || !string.Equals(_key, key, StringComparison.OrdinalIgnoreCase)) { _key = key; _lifetime = Load(key); _lastRound = null; _round = new RoundState(); _latch.Abandon(); _lastTimesFulfilledQuota = CurrentQuotaCount(); ResetPositionTracking(); } } internal static void BeginRound() { SwitchToCurrentSave(); _round = new RoundState(); _latch.Begin(); _lastRound = null; _lastTimesFulfilledQuota = CurrentQuotaCount(); ResetPositionTracking(); CctvEmployeeStatisticsNetwork.ResetRound(); } internal static void AbandonUnfinalizedRound() { if (!_latch.Finalized && _latch.Active) { _latch.Abandon(); _round = new RoundState(); ResetPositionTracking(); } } internal static bool DeleteForKey(string key) { bool result = false; try { string path = GetPath(key); if (File.Exists(path)) { File.Delete(path); result = true; } } catch (Exception ex) { ManualLogSource log = Plugin.Log; if (log != null) { log.LogWarning((object)("[EmployeeFile] Failed resetting statistics: " + ex.Message)); } } if (string.Equals(_key, key, StringComparison.OrdinalIgnoreCase)) { _key = null; _lifetime = new EmployeeStatisticsData(); } ResetRuntimeState(); return result; } internal static void RecordItemGrabbed(GrabbableObject item) { if (_latch.Active && !_latch.Finalized && !((Object)(object)item == (Object)null)) { PlayerControllerB playerHeldBy = item.playerHeldBy; if ((Object)(object)playerHeldBy != (Object)null) { _round.LastItemHolderByKey[NetworkKey((Component)(object)item)] = playerHeldBy.actualClientId; } } } internal static void RecordEnemyHit(EnemyAI enemy, PlayerControllerB playerWhoHit) { if (_latch.Active && !_latch.Finalized && !((Object)(object)enemy == (Object)null) && IsLocalPlayer(playerWhoHit)) { _round.LastEnemyHitByLocalPlayer[NetworkKey((Component)(object)enemy)] = Time.time; } } internal static void RecordEnemyKilled(EnemyAI enemy) { if (_latch.Active && !_latch.Finalized && !((Object)(object)enemy == (Object)null)) { ulong num = NetworkKey((Component)(object)enemy); if (_round.KilledEnemies.Add(num) && _round.LastEnemyHitByLocalPlayer.TryGetValue(num, out var value) && !(Time.time - value > Mathf.Max(1f, Plugin.ProgressionConfig.KillAttributionWindowSeconds.Value))) { _round.Data.monstersKilled = AddOne(_round.Data.monstersKilled); } } } internal static void RecordDeath() { AddRoundOrLifetime(delegate(EmployeeStatisticsData data) { data.timesDied = AddOne(data.timesDied); }); } internal static void RecordSurveyBeaconPlaced(string eventId) { if (TryAddRoundKey("survey." + (eventId ?? string.Empty))) { _round.Data.surveyBeaconsPlaced = AddOne(_round.Data.surveyBeaconsPlaced); } } internal static void RecordItemIncinerated(int playerId, ulong itemNetworkObjectId) { PlayerControllerB val = LocalPlayer(); if (!((Object)(object)val == (Object)null) && (int)val.playerClientId == playerId && TryAddRoundKey("incinerator.item." + itemNetworkObjectId)) { _round.Data.itemsIncinerated = AddOne(_round.Data.itemsIncinerated); } } internal static void RecordWhistleblowerDamage(EnemyAI enemy, PlayerControllerB playerWhoHit, int damage) { if (!((Object)(object)enemy == (Object)null) && damage > 0 && IsLocalPlayer(playerWhoHit) && _latch.Active && !_latch.Finalized) { _round.Data.whistleblowerDamageDealt = AddClamped(_round.Data.whistleblowerDamageDealt, damage); } } internal static void ObservePestsTrapped(string eventId, ulong creditedClientId, int capturedTotal) { if (_latch.Active && !_latch.Finalized) { int num = _round.PestCaptureCounts.Observe(capturedTotal); PlayerControllerB val = LocalPlayer(); if (num > 0 && !((Object)(object)val == (Object)null) && val.actualClientId == creditedClientId && TryAddRoundKey("pest.trapped." + (eventId ?? string.Empty))) { _round.Data.pestsTrapped = AddClamped(_round.Data.pestsTrapped, num); } } } internal static void RecordContainmentWaveSurvived(string eventId) { if (TryAddRoundKey("containment.wave." + (eventId ?? string.Empty))) { _round.Data.containmentWavesSurvived = AddOne(_round.Data.containmentWavesSurvived); } } internal static void RecordDrillPlaced(string eventId) { if (TryAddRoundKey("shadowraid.drill." + (eventId ?? string.Empty))) { _round.Data.drillsPlaced = AddOne(_round.Data.drillsPlaced); } } internal static void RecordBreakerRestored(int restoredCount, ulong actorClientId) { PlayerControllerB val = LocalPlayer(); if (!((Object)(object)val == (Object)null) && val.actualClientId == actorClientId && TryAddRoundKey("blackout.breaker.count." + Mathf.Max(1, restoredCount))) { _round.Data.breakersRestored = AddOne(_round.Data.breakersRestored); } } internal static void RecordSingleBreakerRestored(string eventId) { if (TryAddRoundKey("blackout.breaker.single." + (eventId ?? string.Empty))) { _round.Data.breakersRestored = AddOne(_round.Data.breakersRestored); } } internal static void RecordDeviceHacked(Object target) { RecordDeviceHacked((target != (Object)null) ? (((object)target).GetType().FullName + "." + target.GetInstanceID()) : ("unknown." + Time.frameCount)); } internal static void RecordDeviceHacked(string targetKey) { if (TryAddRoundKey("hack." + (targetKey ?? string.Empty))) { _round.Data.devicesHacked = AddOne(_round.Data.devicesHacked); } } internal static void RecordCctvDeviceHacked(string logicalDeviceKey) { if (_latch.Active && !_latch.Finalized && !string.IsNullOrWhiteSpace(logicalDeviceKey) && _round.CctvEvents.TryAcceptDevice(logicalDeviceKey) && TryAddRoundKey("cctv.hack." + logicalDeviceKey)) { _round.Data.cctvDevicesHacked = AddOne(_round.Data.cctvDevicesHacked); _round.Data.devicesHacked = AddOne(_round.Data.devicesHacked); } } internal static void RecordCctvAlarmSetOff(string episodeKey) { if (_latch.Active && !_latch.Finalized && !string.IsNullOrWhiteSpace(episodeKey) && _round.CctvEvents.TryAcceptAlarm(episodeKey) && TryAddRoundKey("cctv.alarm." + episodeKey)) { _round.Data.cctvAlarmsSetOff = AddOne(_round.Data.cctvAlarmsSetOff); } } internal static bool TryInitializeLateJoinRound(PlayerControllerB localPlayer) { StartOfRound instance = StartOfRound.Instance; string key; bool isSaveKeyResolved = SaveKey.TryGetCurrent(out key); bool isLocalPlayerReady = (Object)(object)localPlayer != (Object)null && IsLocalPlayer(localPlayer); bool isMapReady = (Object)(object)instance != (Object)null && (Object)(object)instance.currentLevel != (Object)null; if (!CctvLateJoinLifecycle.ShouldInitializePersonalRound(_latch.Active, isSaveKeyResolved, isLocalPlayerReady, isMapReady, (Object)(object)instance != (Object)null && instance.shipHasLanded, (Object)(object)instance != (Object)null && instance.inShipPhase, (Object)(object)instance != (Object)null && instance.shipIsLeaving)) { return false; } SwitchToCurrentSave(); if (_latch.Active) { return false; } _round = new RoundState(); _latch.Begin(); _lastRound = null; _lastTimesFulfilledQuota = CurrentQuotaCount(); ResetPositionTracking(); return true; } internal static void UpdateRuntime(PlayerControllerB localPlayer, float deltaTime) { if (_lifetime == null) { SwitchToCurrentSave(); } TryInitializeLateJoinRound(localPlayer); CctvEmployeeStatisticsNetwork.EnsureRegistered(); UpdateQuotaCompletion(); if (_latch.Active && !_latch.Finalized && IsLocalPlayer(localPlayer)) { CctvEmployeeStatisticsNetwork.EnsureEpochForActiveRound(); float num = Mathf.Clamp(deltaTime, 0f, 0.25f); UpdateSteps(localPlayer); if (IsCctvFocused()) { _round.Data.timeSpentOnCctvSeconds += num; } UpdatePayloadDistance(); } } internal static EmployeeStatisticsData FinalizeRound(int scrapCollected) { EnsureLoaded(); if (!_latch.TryBeginFinalize(out var recoveredMissedStart)) { return _lastRound?.Clone() ?? new EmployeeStatisticsData(); } if (recoveredMissedStart) { ManualLogSource log = Plugin.Log; if (log != null) { log.LogWarning((object)("[EmployeeStatistics] FinalizeRound ran without a round start " + $"(sequence={_latch.Sequence}, scrapCollected={scrapCollected}). " + "Nothing was recorded this round â€â€ÂÂÂ\u009d the RoundLifecycle.RoundStarted hook did not fire for this peer.")); } } _round.Data.scrapValueDelivered = ComputeLocalDeliveredScrapValue(); _lastRound = _round.Data.Clone(); if (_lifetime == null) { _lifetime = new EmployeeStatisticsData(); } _lifetime.Add(_lastRound); _latch.CompleteFinalize(); Save(); return _lastRound.Clone(); } internal static string FormatDuration(float seconds) { int num = Mathf.Max(0, Mathf.FloorToInt(seconds)); int num2 = num / 3600; int num3 = num % 3600 / 60; int num4 = num % 60; if (num2 <= 0) { return $"{num3:00}:{num4:00}"; } return $"{num2}:{num3:00}:{num4:00}"; } private static void EnsureLoaded() { if (_lifetime == null) { SwitchToCurrentSave(); } } private static EmployeeStatisticsData Load(string key) { try { string path = GetPath(key); if (File.Exists(path)) { return JsonUtility.FromJson<EmployeeStatisticsData>(File.ReadAllText(path)) ?? new EmployeeStatisticsData(); } } catch (Exception ex) { ManualLogSource log = Plugin.Log; if (log != null) { log.LogWarning((object)("[EmployeeFile] Failed reading statistics: " + ex.Message)); } } return new EmployeeStatisticsData(); } private static void Save() { if (_lifetime == null || string.IsNullOrWhiteSpace(_key)) { return; } try { Directory.CreateDirectory(SaveDir); File.WriteAllText(GetPath(_key), JsonUtility.ToJson((object)_lifetime, true)); } catch (Exception ex) { ManualLogSource log = Plugin.Log; if (log != null) { log.LogWarning((object)("[EmployeeFile] Failed writing statistics: " + ex.Message)); } } } private static string GetPath(string key) { char[] invalidFileNameChars = Path.GetInvalidFileNameChars(); char[] array = (key ?? "employee").ToCharArray(); for (int i = 0; i < array.Length; i++) { if (Array.IndexOf(invalidFileNameChars, array[i]) >= 0) { array[i] = '_'; } } return Path.Combine(SaveDir, new string(array) + ".json"); } private static void UpdateSteps(PlayerControllerB player) { //IL_002b: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Unknown result type (might be due to invalid IL or missing references) //IL_0059: Unknown result type (might be due to invalid IL or missing references) //IL_005e: Unknown result type (might be due to invalid IL or missing references) //IL_006a: Unknown result type (might be due to invalid IL or missing references) //IL_006b: Unknown result type (might be due to invalid IL or missing references) //IL_0042: Unknown result type (might be due to invalid IL or missing references) //IL_0043: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)player == (Object)null || !player.isPlayerControlled || player.isPlayerDead) { _round.PlayerPositionValid = false; return; } Vector3 position = ((Component)player).transform.position; if (!_round.PlayerPositionValid) { _round.LastPlayerPosition = position; _round.PlayerPositionValid = true; return; } float num = Vector3.Distance(_round.LastPlayerPosition, position); _round.LastPlayerPosition = position; if (!(num < 0.02f) && !(num > 8f)) { _round.StepDistance += num; _round.Data.stepsTaken = Mathf.Clamp(Mathf.FloorToInt(_round.StepDistance / 0.76f), 0, int.MaxValue); } } private static void UpdatePayloadDistance() { //IL_003b: Unknown result type (might be due to invalid IL or missing references) //IL_0040: Unknown result type (might be due to invalid IL or missing references) //IL_006a: Unknown result type (might be due to invalid IL or missing references) //IL_006b: Unknown result type (might be due to invalid IL or missing references) //IL_0081: Unknown result type (might be due to invalid IL or missing references) //IL_0086: Unknown result type (might be due to invalid IL or missing references) //IL_0092: Unknown result type (might be due to invalid IL or missing references) //IL_0093: Unknown result type (might be due to invalid IL or missing references) object localPayloadCart = GetLocalPayloadCart(); Component val = (Component)((localPayloadCart is Component) ? localPayloadCart : null); if ((Object)(object)val == (Object)null || !IsPayloadAttachedToLocal(localPayloadCart)) { _round.PayloadCart = null; _round.PayloadPositionValid = false; return; } Vector3 position = val.transform.position; if (_round.PayloadCart != localPayloadCart || !_round.PayloadPositionValid) { _round.PayloadCart = localPayloadCart; _round.LastPayloadPosition = position; _round.PayloadPositionValid = true; return; } float num = Vector3.Distance(_round.LastPayloadPosition, position); _round.LastPayloadPosition = position; if (!(num < 0.005f) && !(num > 8f)) { _round.Data.payloadDistancePushedMeters = Mathf.Clamp(_round.Data.payloadDistancePushedMeters + num, 0f, 1E+09f); } } private static bool IsCctvFocused() { if (!_cctvReflectionResolved) { _cctvReflectionResolved = true; _cctvFocusedProperty = ResolveCompanyType("Y4NGZCompany.ShipSystems.Surveillance.MonitorFocus")?.GetProperty("IsFocused", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); if (_cctvFocusedProperty == null) { ProgressionPatches.WarnOptionalMissing("EmployeeStatistics", "MonitorFocus.IsFocused", "com.y4ngz.company.lethalcctv", "LethalCCTV", "the time-on-CCTV statistic stays at 0"); } } try { bool flag = default(bool); int num; if (_cctvFocusedProperty != null) { object value = _cctvFocusedProperty.GetValue(null); if (value is bool) { flag = (bool)value; num = 1; } else { num = 0; } } else { num = 0; } return (byte)((uint)num & (flag ? 1u : 0u)) != 0; } catch (Exception ex) { ProgressionPatches.WarnOptionalThrew("EmployeeStatistics", "Reading MonitorFocus.IsFocused", ex, "com.y4ngz.company.lethalcctv", "LethalCCTV", "the time-on-CCTV statistic stops counting"); return false; } } private static object GetLocalPayloadCart() { ResolvePayloadReflection(); try { return _localPayload