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 Anomalies v2.0.0
EyeMonster.dll
Decompiled a day ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Text; using System.Text.RegularExpressions; using System.Threading; using BepInEx; using BepInEx.Configuration; using BepInEx.Logging; using Dawn; using EyeMonster.AI; using EyeMonster.NetcodePatcher; using EyeMonster.Utils; using GameNetcodeStuff; using Microsoft.CodeAnalysis; using Unity.Netcode; using Unity.Netcode.Components; using UnityEngine; using UnityEngine.AI; using UnityEngine.Audio; using UnityEngine.Networking; using UnityEngine.Rendering; using UnityEngine.SceneManagement; using Y4NGZMonsters.Shared; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: AssemblyCompany("EyeMonster")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0+3460ec64f0cec4948e51ddb3f02a4b0e414f105e")] [assembly: AssemblyProduct("EyeMonster")] [assembly: AssemblyTitle("EyeMonster")] [assembly: AssemblyVersion("1.0.0.0")] [module: RefSafetyRules(11)] [module: NetcodePatchedAssembly] 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 EyeMonster { internal readonly struct EyeCornerSettings { public float HalfWidth { get; } public float BakeRadius { get; } public float FadeStartDistance { get; } public float FadeEndDistance { get; } public float PushTimeConstantSeconds { get; } public float MaxPushSpeed { get; } public float MaxPushSpeedUnknownFarSide { get; } public float MinSlideFraction { get; } public float MinDesiredSpeed { get; } public float OppositeWallDot { get; } public float SameWallDot { get; } public static EyeCornerSettings Eye { get; } = new EyeCornerSettings(1.75f, 0.35f, 4f, 2f, 0.4f, 1f, 0.4f, 0.1f, 0.05f, -0.7f, 0.9f); public EyeCornerSettings(float halfWidth, float bakeRadius, float fadeStartDistance, float fadeEndDistance, float pushTimeConstantSeconds, float maxPushSpeed, float maxPushSpeedUnknownFarSide, float minSlideFraction, float minDesiredSpeed, float oppositeWallDot, float sameWallDot) { HalfWidth = halfWidth; BakeRadius = bakeRadius; FadeStartDistance = fadeStartDistance; FadeEndDistance = fadeEndDistance; PushTimeConstantSeconds = pushTimeConstantSeconds; MaxPushSpeed = maxPushSpeed; MaxPushSpeedUnknownFarSide = maxPushSpeedUnknownFarSide; MinSlideFraction = minSlideFraction; MinDesiredSpeed = minDesiredSpeed; OppositeWallDot = oppositeWallDot; SameWallDot = sameWallDot; } } internal struct EyeEdgePlane { public bool Valid; public float PointX; public float PointZ; public float NormalX; public float NormalZ; public readonly float DistanceAt(float x, float z) { return (x - PointX) * NormalX + (z - PointZ) * NormalZ; } } internal struct EyeCornerMemory { private const float MinNormalLength = 0.0001f; public EyeEdgePlane Near; public EyeEdgePlane Far; public void Clear() { Near = default(EyeEdgePlane); Far = default(EyeEdgePlane); } public bool Observe(float edgeX, float edgeZ, float normalX, float normalZ, in EyeCornerSettings settings) { float num = MathF.Sqrt(normalX * normalX + normalZ * normalZ); if (!float.IsFinite(edgeX) || !float.IsFinite(edgeZ) || !float.IsFinite(num) || !(num >= 0.0001f)) { Clear(); return false; } float num2 = normalX / num; float num3 = normalZ / num; if (Near.Valid) { float num4 = Near.NormalX * num2 + Near.NormalZ * num3; if (num4 < settings.OppositeWallDot) { Far = Near; } else if (num4 < settings.SameWallDot) { Far = default(EyeEdgePlane); } } Near = new EyeEdgePlane { Valid = true, PointX = edgeX, PointZ = edgeZ, NormalX = num2, NormalZ = num3 }; return true; } } internal struct EyeCornerCorrection { public bool Active; public bool OverrideVelocity; public float VelocityX; public float VelocityZ; public float MoveX; public float MoveZ; } internal static class EyeCornerClearance { private const float MinSpeed = 0.0001f; public static void OrientEdgeNormal(float posX, float posZ, float edgeX, float edgeZ, ref float normalX, ref float normalZ) { if ((posX - edgeX) * normalX + (posZ - edgeZ) * normalZ < 0f) { normalX = 0f - normalX; normalZ = 0f - normalZ; } } public static float DestinationFade(float destinationDistance, in EyeCornerSettings settings) { if (!float.IsFinite(destinationDistance) || !(destinationDistance > settings.FadeEndDistance)) { return 0f; } if (destinationDistance >= settings.FadeStartDistance) { return 1f; } return (destinationDistance - settings.FadeEndDistance) / (settings.FadeStartDistance - settings.FadeEndDistance); } public static float WantedShift(float edgeDistance, float farRoom, float destinationDistance, in EyeCornerSettings settings) { if (!float.IsFinite(edgeDistance) || !float.IsFinite(destinationDistance)) { return 0f; } float num = MathF.Max(0f, edgeDistance); float num2 = MathF.Max(0f, settings.HalfWidth - settings.BakeRadius - num); if (farRoom >= 0f) { num2 = MathF.Min(num2, MathF.Max(0f, (farRoom - num) * 0.5f)); } return num2 * DestinationFade(destinationDistance, in settings); } public static EyeCornerCorrection Step(in EyeCornerMemory memory, in EyeCornerSettings settings, float posX, float posZ, float velX, float velZ, float desiredVelX, float desiredVelZ, float destinationDistance, float dt) { EyeCornerCorrection result = default(EyeCornerCorrection); float num = MathF.Sqrt(desiredVelX * desiredVelX + desiredVelZ * desiredVelZ); if (!memory.Near.Valid || !float.IsFinite(dt) || !(dt > 0f) || !float.IsFinite(posX) || !float.IsFinite(posZ) || !float.IsFinite(velX) || !float.IsFinite(velZ) || !float.IsFinite(desiredVelX) || !float.IsFinite(desiredVelZ) || !float.IsFinite(num) || !float.IsFinite(destinationDistance) || num < settings.MinDesiredSpeed) { return result; } float normalX = memory.Near.NormalX; float normalZ = memory.Near.NormalZ; float edgeDistance = MathF.Max(0f, memory.Near.DistanceAt(posX, posZ)); float num2 = -1f; if (memory.Far.Valid) { float num3 = memory.Far.DistanceAt(posX, posZ); if (num3 >= 0f) { num2 = num3; } } bool flag = num2 >= 0f; float num4 = WantedShift(edgeDistance, num2, destinationDistance, in settings); if (!(num4 > 0f)) { return result; } float num5 = velX * normalX + velZ * normalZ; float num6 = MathF.Sqrt(velX * velX + velZ * velZ); if (num5 < 0f && num6 > 0.0001f) { float num7 = velX - num5 * normalX; float num8 = velZ - num5 * normalZ; float num9 = MathF.Sqrt(num7 * num7 + num8 * num8); if (!(num9 >= settings.MinSlideFraction * num6) || !(num9 > 0f)) { return result; } float num10 = desiredVelX * normalX + desiredVelZ * normalZ; float num11 = desiredVelX - num10 * normalX; float num12 = desiredVelZ - num10 * normalZ; float num13 = ((num7 * num11 + num8 * num12 > 0f) ? (num / num9) : 1f); result.OverrideVelocity = true; result.VelocityX = num7 * num13; result.VelocityZ = num8 * num13; result.MoveX = (0f - num5) * normalX * dt; result.MoveZ = (0f - num5) * normalZ * dt; } float num14 = MathF.Min(MathF.Min(num4 / settings.PushTimeConstantSeconds, flag ? settings.MaxPushSpeed : settings.MaxPushSpeedUnknownFarSide) * dt, num4); result.MoveX += normalX * num14; result.MoveZ += normalZ * num14; result.Active = true; return result; } } internal enum EyeReaction { None, Frustrated, Blinded } internal enum EyeStareSample : byte { Gone, Away, Staring, StaringClose } internal enum EyeReactionEventKind { WarnStarted, WarnEnded, StareAttack, Blinded, RecoilFinished } internal readonly struct EyeReactionEvent { public EyeReactionEventKind Kind { get; } public int PlayerId { get; } public EyeReactionEvent(EyeReactionEventKind kind, int playerId) { Kind = kind; PlayerId = playerId; } } internal readonly struct EyeReactionThresholds { public float WarnSeconds { get; } public float AttackSeconds { get; } public float BlindSeconds { get; } public EyeReactionThresholds(float warnSeconds, float attackSeconds, float blindSeconds) { WarnSeconds = Math.Max(0f, warnSeconds); AttackSeconds = Math.Max(WarnSeconds, attackSeconds); BlindSeconds = Math.Max(0f, blindSeconds); } } internal sealed class EyeReactionBrain { public const int NoPlayer = -1; private readonly List<EyeReactionEvent> _events = new List<EyeReactionEvent>(4); private float[] _stare = Array.Empty<float>(); private float[] _closeStare = Array.Empty<float>(); public EyeReaction Reaction { get; private set; } public int WarnedPlayerId { get; private set; } = -1; public int RecoilTargetId { get; private set; } = -1; public float RecoilElapsed { get; private set; } public float BlindMeter { get; private set; } public bool BeamObserved { get; private set; } public IReadOnlyList<EyeReactionEvent> Events => _events; public float StareMeter(int playerId) { if (playerId < 0 || playerId >= _stare.Length) { return 0f; } return _stare[playerId]; } public float CloseStareMeter(int playerId) { if (playerId < 0 || playerId >= _closeStare.Length) { return 0f; } return _closeStare[playerId]; } public void Tick(float dt, bool reactionsAllowed, EyeStareSample[] stareSamples, int beamHolderId, EyeReactionThresholds thresholds) { _events.Clear(); if (!(dt > 0f)) { dt = 0f; } if (Reaction == EyeReaction.Blinded) { RecoilElapsed += dt; if (RecoilElapsed >= 1.2f) { int recoilTargetId = RecoilTargetId; Reaction = EyeReaction.None; RecoilTargetId = -1; RecoilElapsed = 0f; _events.Add(new EyeReactionEvent(EyeReactionEventKind.RecoilFinished, recoilTargetId)); } return; } if (!reactionsAllowed) { Array.Clear(_stare, 0, _stare.Length); Array.Clear(_closeStare, 0, _closeStare.Length); BreakBeam(); return; } int num = ((stareSamples != null) ? stareSamples.Length : 0); if (_stare.Length < num) { Array.Resize(ref _stare, num); Array.Resize(ref _closeStare, num); } if (beamHolderId >= 0) { BlindMeter = (BeamObserved ? (BlindMeter + dt) : 0f); BeamObserved = true; if (BlindMeter >= thresholds.BlindSeconds) { ClearMeters(); Reaction = EyeReaction.Blinded; RecoilElapsed = 0f; RecoilTargetId = beamHolderId; _events.Add(new EyeReactionEvent(EyeReactionEventKind.Blinded, beamHolderId)); return; } } else { BreakBeam(); } int num2 = -1; float num3 = 0f; float num4 = dt * 0.5f; for (int i = 0; i < _stare.Length; i++) { EyeStareSample eyeStareSample = ((i < num) ? stareSamples[i] : EyeStareSample.Gone); float num5 = _stare[i]; float num6 = _closeStare[i]; switch (eyeStareSample) { case EyeStareSample.StaringClose: num5 = Math.Min(thresholds.AttackSeconds, num5 + dt); num6 += dt; break; case EyeStareSample.Staring: num5 = Math.Min(thresholds.AttackSeconds, num5 + dt); num6 = Math.Max(0f, num6 - num4); break; case EyeStareSample.Away: num5 = Math.Max(0f, num5 - num4); num6 = Math.Max(0f, num6 - num4); break; default: num5 = 0f; num6 = 0f; break; } _stare[i] = num5; _closeStare[i] = num6; if (num6 >= thresholds.AttackSeconds && num6 > num3) { num2 = i; num3 = num6; } } if (num2 != -1) { ClearMeters(); Reaction = EyeReaction.None; _events.Add(new EyeReactionEvent(EyeReactionEventKind.StareAttack, num2)); return; } if (WarnedPlayerId != -1 && StareMeter(WarnedPlayerId) <= 0f) { int warnedPlayerId = WarnedPlayerId; WarnedPlayerId = -1; _events.Add(new EyeReactionEvent(EyeReactionEventKind.WarnEnded, warnedPlayerId)); } if (WarnedPlayerId == -1) { int num7 = -1; float num8 = 0f; for (int j = 0; j < _stare.Length; j++) { float num9 = _stare[j]; if (num9 >= thresholds.WarnSeconds && num9 > num8) { num7 = j; num8 = num9; } } if (num7 != -1) { WarnedPlayerId = num7; _events.Add(new EyeReactionEvent(EyeReactionEventKind.WarnStarted, num7)); } } Reaction = ((WarnedPlayerId != -1) ? EyeReaction.Frustrated : EyeReaction.None); } public bool Hit(int attackerId) { if (Reaction == EyeReaction.Blinded) { if (attackerId >= 0) { RecoilTargetId = attackerId; } return true; } Reset(); return false; } public void ForgetPlayer(int playerId) { if (playerId >= 0 && playerId < _stare.Length) { _stare[playerId] = 0f; _closeStare[playerId] = 0f; } if (playerId != -1 && WarnedPlayerId == playerId) { WarnedPlayerId = -1; if (Reaction == EyeReaction.Frustrated) { Reaction = EyeReaction.None; } } } public void BreakBeam() { BlindMeter = 0f; BeamObserved = false; } public void Reset() { ClearMeters(); Reaction = EyeReaction.None; RecoilTargetId = -1; RecoilElapsed = 0f; } private void ClearMeters() { Array.Clear(_stare, 0, _stare.Length); Array.Clear(_closeStare, 0, _closeStare.Length); WarnedPlayerId = -1; BreakBeam(); } } internal enum EyeFarStareOutcome { None, Attack, Leave } internal static class EyeFarStareRoll { public static EyeFarStareOutcome Decide(EyeStareSample sampleAtWarn, Func<float> roll01, float leaveChance) { if (sampleAtWarn != EyeStareSample.Staring) { return EyeFarStareOutcome.None; } float num = roll01(); if (!(num > 0f)) { num = 0f; } if (num >= 1f) { num = MathF.PI * 113f / 355f; } float num2 = ((leaveChance > 0f) ? Math.Min(1f, leaveChance) : 0f); if (!(num < num2)) { return EyeFarStareOutcome.Attack; } return EyeFarStareOutcome.Leave; } } internal sealed class EyePlayerDeadlines { private float[] _until = Array.Empty<float>(); private bool[] _set = Array.Empty<bool>(); public void Set(int playerId, float until) { if (playerId >= 0) { if (playerId >= _until.Length) { Array.Resize(ref _until, playerId + 1); Array.Resize(ref _set, playerId + 1); } _until[playerId] = until; _set[playerId] = true; } } public bool IsActive(int playerId, float now) { if (playerId >= 0 && playerId < _set.Length && _set[playerId]) { return now < _until[playerId]; } return false; } public void Forget(int playerId) { if (playerId >= 0 && playerId < _set.Length) { _set[playerId] = false; _until[playerId] = 0f; } } public void Clear() { Array.Clear(_until, 0, _until.Length); Array.Clear(_set, 0, _set.Length); } } internal sealed class EyeStareIgnore { private readonly EyePlayerDeadlines _ignoredUntil = new EyePlayerDeadlines(); public void Ignore(int playerId, float now, float seconds) { _ignoredUntil.Set(playerId, now + ((seconds > 0f) ? seconds : 0f)); } public bool IsIgnored(int playerId, float now) { return _ignoredUntil.IsActive(playerId, now); } public EyeStareSample Filter(int playerId, EyeStareSample sample, float now) { if (sample != EyeStareSample.Staring || !IsIgnored(playerId, now)) { return sample; } return EyeStareSample.Away; } public void Forget(int playerId) { _ignoredUntil.Forget(playerId); } public void Clear() { _ignoredUntil.Clear(); } } internal sealed class EyePersonalSpace { private readonly EyePlayerDeadlines _cooldownUntil = new EyePlayerDeadlines(); public int Pick(EyeStareSample[] samples, float[] distances, float range, float now) { if (!(range > 0f) || samples == null || distances == null) { return -1; } int num = Math.Min(samples.Length, distances.Length); int num2 = -1; float num3 = 0f; for (int i = 0; i < num; i++) { float num4 = distances[i]; if (samples[i] == EyeStareSample.Away && num4 <= range && !OnCooldown(i, now) && (num2 == -1 || num4 < num3)) { num2 = i; num3 = num4; } } return num2; } public void MarkTriggered(int playerId, float now) { _cooldownUntil.Set(playerId, now + 4f); } public bool OnCooldown(int playerId, float now) { return _cooldownUntil.IsActive(playerId, now); } public void Forget(int playerId) { _cooldownUntil.Forget(playerId); } public void Clear() { _cooldownUntil.Clear(); } } internal readonly struct EyeRetreatCandidate { public bool Reachable { get; } public float MoveDistance { get; } public float DistanceFromThreat { get; } public EyeRetreatCandidate(bool reachable, float moveDistance, float distanceFromThreat) { Reachable = reachable; MoveDistance = moveDistance; DistanceFromThreat = distanceFromThreat; } } internal static class EyeRetreatPlanner { public static void FanYaws(float awayYawDegrees, float spreadDegrees, float[] yawsDegrees, int count) { if (yawsDegrees == null) { return; } count = Math.Min(count, yawsDegrees.Length); if (count <= 0) { return; } if (!float.IsFinite(awayYawDegrees)) { awayYawDegrees = 0f; } float num = ((spreadDegrees > 0f) ? Math.Min(360f, spreadDegrees) : 0f); float num2 = ((count > 1) ? (num / (float)(count - 1)) : 0f); bool flag = (count & 1) == 1; for (int i = 0; i < count; i++) { int num3 = (flag ? (i - 1) : i); float num4 = 0f; if (num3 >= 0) { float num5 = (float)(num3 / 2) + (flag ? 1f : 0.5f); num4 = ((num3 % 2 == 0) ? num5 : (0f - num5)) * num2; } yawsDegrees[i] = WrapDegrees(awayYawDegrees + num4); } } public static int Pick(EyeRetreatCandidate[] candidates, int count, float minMoveDistance) { if (candidates == null) { return -1; } count = Math.Min(count, candidates.Length); if (!(minMoveDistance > 0f)) { minMoveDistance = 0f; } int result = -1; float num = float.NegativeInfinity; for (int i = 0; i < count; i++) { EyeRetreatCandidate eyeRetreatCandidate = candidates[i]; if (eyeRetreatCandidate.Reachable && eyeRetreatCandidate.MoveDistance >= minMoveDistance && eyeRetreatCandidate.DistanceFromThreat > num) { result = i; num = eyeRetreatCandidate.DistanceFromThreat; } } return result; } public static int PickLeaveNode(float[] distancesFromThreat, bool[] usable, int count) { if (distancesFromThreat == null || usable == null) { return -1; } count = Math.Min(count, Math.Min(distancesFromThreat.Length, usable.Length)); int result = -1; float num = float.NegativeInfinity; for (int i = 0; i < count; i++) { if (usable[i] && distancesFromThreat[i] > num) { result = i; num = distancesFromThreat[i]; } } return result; } private static float WrapDegrees(float degrees) { float num = degrees % 360f; if (num < 0f) { num += 360f; } if (!(num >= 360f)) { return num; } return 0f; } } internal enum EyeRetreatOutcome { Continue, Leave, Blocked } internal sealed class EyeRetreatTracker { private float _anchorX; private float _anchorZ; private float _windowElapsed; public float Elapsed { get; private set; } public float NoSightElapsed { get; private set; } public void Begin(float x, float z) { _anchorX = x; _anchorZ = z; _windowElapsed = 0f; Elapsed = 0f; NoSightElapsed = 0f; } public EyeRetreatOutcome Tick(float dt, float x, float z, bool targetAlive, float targetDistance, bool hasLineOfSight, float leaveDistance, float maxSeconds, bool navigationReady) { if (!(dt > 0f)) { dt = 0f; } Elapsed += dt; NoSightElapsed = (hasLineOfSight ? 0f : (NoSightElapsed + dt)); if (navigationReady) { _windowElapsed += dt; } else { _anchorX = x; _anchorZ = z; _windowElapsed = 0f; } if (!targetAlive || targetDistance > leaveDistance) { return EyeRetreatOutcome.Leave; } if (NoSightElapsed >= 1.5f) { return EyeRetreatOutcome.Leave; } if (!(Elapsed < maxSeconds)) { return EyeRetreatOutcome.Leave; } if (navigationReady && _windowElapsed >= 1.5f) { float num = x - _anchorX; float num2 = z - _anchorZ; float num3 = 0.3f; if (num * num + num2 * num2 < num3 * num3) { return EyeRetreatOutcome.Blocked; } _anchorX = x; _anchorZ = z; _windowElapsed = 0f; } return EyeRetreatOutcome.Continue; } } internal sealed class EyeLookAtSolver { public const float WeightEpsilon = 0.001f; private const float RadiansToDegrees = 180f / MathF.PI; private const float DegreesToRadians = MathF.PI / 180f; public float YawDegrees { get; private set; } public float PitchDegrees { get; private set; } public float Weight { get; private set; } public bool IsTracking { get; private set; } public void Tick(bool hasTarget, float right, float up, float forward, bool allowed, float dt) { if (!(dt > 0f)) { dt = 0f; } IsTracking = hasTarget && allowed && forward > 0f; float num = 0f; float num2 = 0f; float num3 = 0f; if (IsTracking) { BearingDegrees(right, up, forward, out var yawDegrees, out var pitchDegrees); num = Clamp(yawDegrees, 45f); num2 = Clamp(pitchDegrees, 25f); num3 = 1f; } float num4 = 1f - MathF.Exp(-8f * dt); YawDegrees += (num - YawDegrees) * num4; PitchDegrees += (num2 - PitchDegrees) * num4; Weight += (num3 - Weight) * num4; if (!IsTracking && Weight < 0.001f) { Weight = 0f; YawDegrees = 0f; PitchDegrees = 0f; } } public static void BearingDegrees(float right, float up, float forward, out float yawDegrees, out float pitchDegrees) { float x = MathF.Sqrt(right * right + forward * forward); yawDegrees = MathF.Atan2(right, forward) * (180f / MathF.PI); pitchDegrees = MathF.Atan2(up, x) * (180f / MathF.PI); } public void GetDirection(out float right, out float up, out float forward) { float x = YawDegrees * (MathF.PI / 180f); float x2 = PitchDegrees * (MathF.PI / 180f); float num = MathF.Cos(x2); right = num * MathF.Sin(x); up = MathF.Sin(x2); forward = num * MathF.Cos(x); } public void Reset() { YawDegrees = 0f; PitchDegrees = 0f; Weight = 0f; IsTracking = false; } private static float Clamp(float value, float limit) { return Math.Max(0f - limit, Math.Min(limit, value)); } } internal readonly struct EyeLookBasis { public readonly float ForwardX; public readonly float ForwardY; public readonly float ForwardZ; public readonly float UpX; public readonly float UpY; public readonly float UpZ; public readonly float RightX; public readonly float RightY; public readonly float RightZ; private EyeLookBasis(float fx, float fy, float fz, float ux, float uy, float uz, float rx, float ry, float rz) { ForwardX = fx; ForwardY = fy; ForwardZ = fz; UpX = ux; UpY = uy; UpZ = uz; RightX = rx; RightY = ry; RightZ = rz; } public static EyeLookBasis FromRestRotation(float qx, float qy, float qz, float qw) { float num = MathF.Sqrt(qx * qx + qy * qy + qz * qz + qw * qw); if (!(num > 1E-06f)) { qx = 0f; qy = 0f; qz = 0f; qw = 1f; } else { qx /= num; qy /= num; qz /= num; qw /= num; } return new EyeLookBasis(2f * (qx * qz + qw * qy), 2f * (qy * qz - qw * qx), 1f - 2f * (qx * qx + qy * qy), 2f * (qx * qy - qw * qz), 1f - 2f * (qx * qx + qz * qz), 2f * (qy * qz + qw * qx), 1f - 2f * (qy * qy + qz * qz), 2f * (qx * qy + qw * qz), 2f * (qx * qz - qw * qy)); } public void Project(float x, float y, float z, out float right, out float up, out float forward) { right = x * RightX + y * RightY + z * RightZ; up = x * UpX + y * UpY + z * UpZ; forward = x * ForwardX + y * ForwardY + z * ForwardZ; } } internal static class EyeLocomotion { private const float TwoPi = MathF.PI * 2f; public static float RunPlaybackSpeed(float measuredSpeed, float referenceSpeed, float scale) { if (!(referenceSpeed > 0f) || !(scale > 0f)) { return 1f; } float val = measuredSpeed / referenceSpeed * scale; return Math.Max(0.5f, Math.Min(1.8f, val)); } public static float SmoothSpeed(float previous, float instant, float deltaTime) { if (!(deltaTime > 0f)) { return previous; } return previous + (instant - previous) * (1f - MathF.Exp((0f - deltaTime) / 0.3f)); } public static float StepJitterWeight(float current, bool moving, float deltaTime) { if (!(deltaTime > 0f)) { return current; } float num = deltaTime / 0.15f; float val = (moving ? (current + num) : (current - num)); return Math.Max(0f, Math.Min(1f, val)); } public static void JitterOffset(float time, float phaseSeed, float amplitude, out float x, out float y, out float z) { x = amplitude * (0.65f * MathF.Sin(57.17699f * time + phaseSeed) + 0.35f * MathF.Sin(71f * time + 1.7f * phaseSeed)); z = amplitude * (0.65f * MathF.Sin(64.71681f * time + 2.3f * phaseSeed) + 0.35f * MathF.Sin(52.778755f * time + 0.6f * phaseSeed)); y = 0.5f * amplitude * MathF.Sin(60.9469f * time + 3.1f * phaseSeed); } } internal struct EyeGaitState { public float Direction; public float RunShare; public bool Seeded; public bool Resting; } internal static class EyeGait { public static void Step(ref EyeGaitState state, float localRight, float localForward, float deltaTime) { if (!(deltaTime > 0f) || !float.IsFinite(deltaTime)) { return; } float num = MathF.Sqrt(localRight * localRight + localForward * localForward); if (!float.IsFinite(num) || num < 0.05f) { state.Resting = true; return; } float num2 = MathF.Atan2(localRight, localForward); float num3 = 1.35f; float num4 = 2.9f - num3; float num5 = Math.Max(0f, Math.Min(1f, (num - num3) / num4)); if (!state.Seeded || state.Resting) { state.Direction = WrapAngle(num2); state.RunShare = num5; state.Seeded = true; state.Resting = false; } else { float num6 = 1f - MathF.Exp((0f - deltaTime) / 0.2f); float num7 = WrapAngle(num2 - state.Direction); state.Direction = WrapAngle(state.Direction + num7 * num6); state.RunShare += (num5 - state.RunShare) * num6; } } public static void Blend(in EyeGaitState state, out float moveForward, out float moveStrafe, out float referenceSpeed) { float num = 0.46551722f; float num2 = MathF.Sin(state.Direction); float num3 = MathF.Cos(state.Direction); float num4 = ((num3 > 0f) ? (num3 * num) : num3); float num5 = Math.Max(0f, Math.Min(1f, (num3 - num) / (1f - num))); float num6 = state.RunShare * num5; moveStrafe = num2 * (1f - num6); moveForward = num4 + (1f - num4) * num6; referenceSpeed = 1.35f + 1.5500001f * num6; } private static float WrapAngle(float angle) { while (angle > MathF.PI) { angle -= MathF.PI * 2f; } while (angle <= -MathF.PI) { angle += MathF.PI * 2f; } return angle; } } internal static class EyeGroundConform { private const float RadiansToDegrees = 180f / MathF.PI; public static void Solve(bool hasFront, float frontY, bool hasBack, float backY, bool hasLeft, float leftY, bool hasRight, float rightY, bool hasCentre, float centreY, float rootY, out float pitchDegrees, out float rollDegrees, out float lift) { pitchDegrees = PairAngle(hasFront, frontY, hasBack, backY, 0.6f); rollDegrees = PairAngle(hasLeft, leftY, hasRight, rightY, 0.6f); float num = MathF.Sqrt(pitchDegrees * pitchDegrees + rollDegrees * rollDegrees); if (num > 12f) { float num2 = 12f / num; pitchDegrees *= num2; rollDegrees *= num2; } lift = (hasCentre ? Math.Max(-0.3f, Math.Min(0.3f, centreY - rootY)) : 0f); } private static float PairAngle(bool hasA, float a, bool hasB, float b, float halfSpan) { if (!hasA || !hasB) { return 0f; } float num = a - b; if (MathF.Abs(num) > 0.45f) { return 0f; } return MathF.Atan2(num, 2f * halfSpan) * (180f / MathF.PI); } } internal enum EyeSoundFamily { Mad, LightScare, Attack, Move, Aggro, Death } internal static class EyeSoundFamilies { public const int Count = 6; public const int MaxFilesPerFamily = 16; public static string Stem(EyeSoundFamily family) { return family switch { EyeSoundFamily.Mad => "eye_mad", EyeSoundFamily.LightScare => "eye_lightscare", EyeSoundFamily.Attack => "eye_attack", EyeSoundFamily.Move => "eye_move", EyeSoundFamily.Aggro => "eye_aggro", EyeSoundFamily.Death => "eye_death", _ => throw new ArgumentOutOfRangeException("family"), }; } public static string FileName(EyeSoundFamily family, int number) { return Stem(family) + "_" + number.ToString("00", CultureInfo.InvariantCulture) + ".wav"; } } internal sealed class EyeCueGate { private readonly float[] _minGap = new float[6]; private readonly float[] _last = new float[6]; private readonly bool[] _played = new bool[6]; public EyeCueGate(float minGapSeconds, float moveMinGapSeconds) { for (int i = 0; i < _minGap.Length; i++) { _minGap[i] = minGapSeconds; } _minGap[3] = moveMinGapSeconds; } public bool TryAcquire(EyeSoundFamily family, float now) { if (_played[(int)family] && now - _last[(int)family] < _minGap[(int)family]) { return false; } _played[(int)family] = true; _last[(int)family] = now; return true; } public void Reset() { Array.Clear(_last, 0, _last.Length); Array.Clear(_played, 0, _played.Length); } } internal static class EyeCuePick { public static int Pick(int count, int previous, float random01) { if (count <= 0) { return -1; } if (count == 1) { return 0; } if (!(random01 > 0f)) { random01 = 0f; } if (random01 >= 1f) { random01 = MathF.PI * 113f / 355f; } int num; int num2; if (previous >= 0) { num = ((previous < count) ? 1 : 0); if (num != 0) { num2 = count - 1; goto IL_003e; } } else { num = 0; } num2 = count; goto IL_003e; IL_003e: int num3 = num2; int num4 = Math.Min((int)(random01 * (float)num3), num3 - 1); if (num != 0 && num4 >= previous) { num4++; } return num4; } } internal static class EyeAnimatorIntents { public static bool WatchIdle(bool watching, EyeReaction reaction, bool dead) { if (watching && reaction == EyeReaction.None) { return !dead; } return false; } public static bool Frustrated(EyeReaction reaction, bool dead) { if (reaction == EyeReaction.Frustrated) { return !dead; } return false; } public static bool Settles(bool wasWatchIdle, bool wasFrustrated, bool watchIdle, bool frustrated, bool escalated, bool dead) { if (!dead && !escalated) { if (!wasFrustrated || frustrated) { if (wasWatchIdle && !watchIdle) { return !frustrated; } return false; } return true; } return false; } } internal sealed class EyeSplatPool { private readonly float[] _spawnedAt; private readonly bool[] _used; private int _next; public float LifetimeSeconds { get; } public EyeSplatPool(int capacity, float lifetimeSeconds) { if (capacity <= 0) { throw new ArgumentOutOfRangeException("capacity"); } if (!(lifetimeSeconds > 0f)) { throw new ArgumentOutOfRangeException("lifetimeSeconds"); } _spawnedAt = new float[capacity]; _used = new bool[capacity]; LifetimeSeconds = lifetimeSeconds; } public int Acquire(float now) { int next = _next; _next = (_next + 1) % _spawnedAt.Length; _spawnedAt[next] = now; _used[next] = true; return next; } public bool IsAlive(int slot, float now) { if (_used[slot]) { return now - _spawnedAt[slot] < LifetimeSeconds; } return false; } public float Alpha(int slot, float now) { if (!IsAlive(slot, now)) { return 0f; } return FadeAlpha(now - _spawnedAt[slot], LifetimeSeconds); } public int AliveCount(float now) { int num = 0; for (int i = 0; i < _spawnedAt.Length; i++) { if (IsAlive(i, now)) { num++; } } return num; } public static float FadeAlpha(float ageSeconds, float lifetimeSeconds) { if (!(ageSeconds > 0f)) { return 1f; } if (ageSeconds >= lifetimeSeconds) { return 0f; } float num = ageSeconds / lifetimeSeconds; return 1f - num * num * (3f - 2f * num); } } internal static class EyeLightScareFlinch { private const float LidSeconds = 0.52f; public const float DurationSeconds = 0.52f; public static bool IsActive(float t) { if (t >= 0f) { return t < 0.52f; } return false; } public static float LidClosure(float t) { if (t < 0f || t >= 0.52f) { return 0f; } if (t <= 0.12f) { return 1f; } float num = (t - 0.12f) / 0.4f; return 1f - num * num * (3f - 2f * num); } public static float PupilScale(float t) { if (t < 0f || t > 0.3f) { return 1f; } return 1f + 0.14999998f * (float)Math.Sin(Math.PI * (double)t / 0.30000001192092896); } } internal static class EyeMonsterLooseAudio { private const float LoadTimeoutSeconds = 5f; private static readonly AudioClip[] NoClips = Array.Empty<AudioClip>(); private static readonly AudioClip[][] Pools = new AudioClip[6][]; private static bool _loaded; public static void Load(string pluginDirectory) { if (!_loaded) { _loaded = true; string directory = Path.Combine(pluginDirectory, "assets", "EyeMonster", "sfx"); for (int i = 0; i < Pools.Length; i++) { Pools[i] = LoadFamily(directory, (EyeSoundFamily)i); } ManualLogSource log = Plugin.Log; if (log != null) { log.LogInfo((object)($"[EyeMonster] Loose sound families: eye_mad {Pool(EyeSoundFamily.Mad).Length}, " + $"eye_lightscare {Pool(EyeSoundFamily.LightScare).Length}, " + $"eye_attack {Pool(EyeSoundFamily.Attack).Length}, " + $"eye_move {Pool(EyeSoundFamily.Move).Length}, " + $"eye_aggro {Pool(EyeSoundFamily.Aggro).Length}, " + $"eye_death {Pool(EyeSoundFamily.Death).Length}.")); } } } public static AudioClip[] Pool(EyeSoundFamily family) { if (family < EyeSoundFamily.Mad || (int)family >= Pools.Length) { return NoClips; } return Pools[(int)family] ?? NoClips; } private static AudioClip[] LoadFamily(string directory, EyeSoundFamily family) { List<AudioClip> list = null; for (int i = 1; i <= 16; i++) { string text = EyeSoundFamilies.FileName(family, i); string path = Path.Combine(directory, text); if (!File.Exists(path)) { if (i == 1) { string text2 = family switch { EyeSoundFamily.Move => "using the bundled eyemonster_step clips", EyeSoundFamily.Aggro => "using the bundled eyemonster_vocal clips", _ => "it stays silent", }; ManualLogSource log = Plugin.Log; if (log != null) { log.LogWarning((object)("[EyeMonster] Sound family '" + EyeSoundFamilies.Stem(family) + "' has no file in assets/EyeMonster/sfx (expected " + text + "); " + text2 + ".")); } } break; } AudioClip val = LoadClip(path); if ((Object)(object)val != (Object)null) { if (list == null) { list = new List<AudioClip>(); } list.Add(val); } } if (list == null) { return NoClips; } return list.ToArray(); } private static AudioClip LoadClip(string path) { //IL_0082: Unknown result type (might be due to invalid IL or missing references) //IL_0088: Invalid comparison between Unknown and I4 try { UnityWebRequest audioClip = UnityWebRequestMultimedia.GetAudioClip("file:///" + path.Replace('\\', '/'), (AudioType)20); try { UnityWebRequestAsyncOperation val = audioClip.SendWebRequest(); Stopwatch stopwatch = Stopwatch.StartNew(); while (!((AsyncOperation)val).isDone) { if (stopwatch.Elapsed.TotalSeconds > 5.0) { audioClip.Abort(); ManualLogSource log = Plugin.Log; if (log != null) { log.LogWarning((object)("[EyeMonster] Timed out loading loose audio " + path + ".")); } return null; } Thread.Sleep(1); } if ((int)audioClip.result != 1) { ManualLogSource log2 = Plugin.Log; if (log2 != null) { log2.LogWarning((object)("[EyeMonster] Failed to load loose audio " + path + ": " + audioClip.error)); } return null; } AudioClip content = DownloadHandlerAudioClip.GetContent(audioClip); if ((Object)(object)content == (Object)null) { ManualLogSource log3 = Plugin.Log; if (log3 != null) { log3.LogWarning((object)("[EyeMonster] Failed to decode loose audio " + path + ": no AudioClip was returned.")); } return null; } ((Object)content).name = Path.GetFileNameWithoutExtension(path); return content; } finally { ((IDisposable)audioClip)?.Dispose(); } } catch (Exception ex) { ManualLogSource log4 = Plugin.Log; if (log4 != null) { log4.LogWarning((object)("[EyeMonster] Loose audio " + path + " failed: " + ex.Message)); } return null; } } } public sealed class EyeMonsterConfig { public ConfigEntry<bool> Enabled { get; } public ConfigEntry<float> SpawnWeightMultiplier { get; } public ConfigEntry<string> MoonWeightOverrides { get; } public ConfigEntry<int> MaxCount { get; } public ConfigEntry<float> PowerLevel { get; } public ConfigEntry<int> Health { get; } public ConfigEntry<float> NoticeRange { get; } public ConfigEntry<float> GazeAngle { get; } public ConfigEntry<float> FlashlightRange { get; } public ConfigEntry<float> StareRange { get; } public ConfigEntry<float> StareWarnSeconds { get; } public ConfigEntry<float> StareAttackSeconds { get; } public ConfigEntry<float> StareAttackRange { get; } public ConfigEntry<float> BlindSeconds { get; } public ConfigEntry<bool> HelmetLightCounts { get; } public ConfigEntry<float> ChaseLeashDistance { get; } public ConfigEntry<float> FarStareLeaveChance { get; } public ConfigEntry<float> RetreatSpeed { get; } public ConfigEntry<float> RetreatMaxSeconds { get; } public ConfigEntry<float> LeaveIgnoreSeconds { get; } public ConfigEntry<float> PersonalSpaceRange { get; } public ConfigEntry<float> PersonalSpaceDistance { get; } public ConfigEntry<float> RoamSpeed { get; } public ConfigEntry<float> ChaseSpeed { get; } public ConfigEntry<float> MovePlaybackScale { get; } public ConfigEntry<bool> CornerClearance { get; } public ConfigEntry<int> AttackDamage { get; } public ConfigEntry<float> AttackCooldown { get; } public ConfigEntry<float> LookAtRange { get; } public ConfigEntry<bool> SlimeTrail { get; } public ConfigEntry<bool> DebugLogs { get; } public EyeMonsterConfig(ConfigFile config) { //IL_0085: Unknown result type (might be due to invalid IL or missing references) //IL_008f: Expected O, but got Unknown //IL_00d2: Unknown result type (might be due to invalid IL or missing references) //IL_00dc: Expected O, but got Unknown //IL_010b: Unknown result type (might be due to invalid IL or missing references) //IL_0115: Expected O, but got Unknown //IL_0139: Unknown result type (might be due to invalid IL or missing references) //IL_0143: Expected O, but got Unknown //IL_0172: Unknown result type (might be due to invalid IL or missing references) //IL_017c: Expected O, but got Unknown //IL_01ab: Unknown result type (might be due to invalid IL or missing references) //IL_01b5: Expected O, but got Unknown //IL_01e4: Unknown result type (might be due to invalid IL or missing references) //IL_01ee: Expected O, but got Unknown //IL_021d: Unknown result type (might be due to invalid IL or missing references) //IL_0227: Expected O, but got Unknown //IL_0256: Unknown result type (might be due to invalid IL or missing references) //IL_0260: Expected O, but got Unknown //IL_028f: Unknown result type (might be due to invalid IL or missing references) //IL_0299: Expected O, but got Unknown //IL_02c8: Unknown result type (might be due to invalid IL or missing references) //IL_02d2: Expected O, but got Unknown //IL_0301: Unknown result type (might be due to invalid IL or missing references) //IL_030b: Expected O, but got Unknown //IL_0356: Unknown result type (might be due to invalid IL or missing references) //IL_0360: Expected O, but got Unknown //IL_038f: Unknown result type (might be due to invalid IL or missing references) //IL_0399: Expected O, but got Unknown //IL_03c8: Unknown result type (might be due to invalid IL or missing references) //IL_03d2: Expected O, but got Unknown //IL_0401: Unknown result type (might be due to invalid IL or missing references) //IL_040b: Expected O, but got Unknown //IL_043a: Unknown result type (might be due to invalid IL or missing references) //IL_0444: Expected O, but got Unknown //IL_0473: Unknown result type (might be due to invalid IL or missing references) //IL_047d: Expected O, but got Unknown //IL_04ac: Unknown result type (might be due to invalid IL or missing references) //IL_04b6: Expected O, but got Unknown //IL_04e5: Unknown result type (might be due to invalid IL or missing references) //IL_04ef: Expected O, but got Unknown //IL_051e: Unknown result type (might be due to invalid IL or missing references) //IL_0528: Expected O, but got Unknown //IL_0557: Unknown result type (might be due to invalid IL or missing references) //IL_0561: Expected O, but got Unknown //IL_05a5: Unknown result type (might be due to invalid IL or missing references) //IL_05af: Expected O, but got Unknown //IL_05de: Unknown result type (might be due to invalid IL or missing references) //IL_05e8: Expected O, but got Unknown //IL_0617: Unknown result type (might be due to invalid IL or missing references) //IL_0621: Expected O, but got Unknown using (ConfigPersistence.BeginBinding(config, Plugin.Log, "Eye Monster")) { EyeMonsterConfigMigration.TryMigrate(config, Plugin.Log); ConfigSectionNameMigration.TryMigrate(config, Plugin.Log, "Eye Monster"); EyeMonsterConfigMigration.RetireRemovedEntries(config, Plugin.Log); Enabled = config.Bind<bool>("General", "Enabled", true, "Enable the Eye Monster encounter. Host-only: the host's value decides whether it spawns; every install still registers the creature so clients stay in sync."); SpawnWeightMultiplier = config.Bind<float>("Spawning", "SpawnWeightMultiplier", 1f, new ConfigDescription("Multiplier applied to Eye Monster's contextual moon/interior spawn policy. 0 disables natural spawns.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 5f), Array.Empty<object>())); MoonWeightOverrides = config.Bind<string>("Spawning", "MoonWeightOverrides", string.Empty, "Optional comma-separated base moon weights, e.g. Experimentation:8,Offense:15 or namespace:moon=12. Use 0 to disable a moon; unlisted moons keep authored defaults."); MaxCount = config.Bind<int>("Spawning", "MaxCount", 2, new ConfigDescription("Maximum number of living Eye Monsters at once.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 4), Array.Empty<object>())); PowerLevel = config.Bind<float>("Spawning", "PowerLevel", 2f, new ConfigDescription("Indoor enemy power budget cost for each Eye Monster.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.1f, 20f), Array.Empty<object>())); Health = config.Bind<int>("Core Stats", "Health", 5, new ConfigDescription("Hits the Eye Monster can take before dying.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 100), Array.Empty<object>())); NoticeRange = config.Bind<float>("Detection", "NoticeRange", 12f, new ConfigDescription("Distance at which an Eye Monster facing a player notices them, stops and watches them. Watching alone never makes it attack.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(2f, 80f), Array.Empty<object>())); GazeAngle = config.Bind<float>("Detection", "GazeAngle", 28f, new ConfigDescription("How directly a player has to look at the eye for it to count as staring: the half-angle, in degrees, around the centre of the player's view.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(5f, 90f), Array.Empty<object>())); FlashlightRange = config.Bind<float>("Detection", "FlashlightRange", 15f, new ConfigDescription("Maximum distance at which a flashlight beam shone straight into the eye can blind it.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(2f, 80f), Array.Empty<object>())); StareRange = config.Bind<float>("Detection", "StareRange", 12f, new ConfigDescription("Maximum distance from the eye at which a player's stare counts.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(2f, 40f), Array.Empty<object>())); StareWarnSeconds = config.Bind<float>("Detection", "StareWarnSeconds", 2.5f, new ConfigDescription("Seconds of staring at the eye before it reacts. Outside a retreat, if that player is still staring from beyond StareAttackRange when the warning starts, it decides right away to chase or back away (FarStareLeaveChance). Otherwise it is irritated: it stays put, its eye narrows and keeps following that player. Looking away lets the stare wear off at half speed.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.1f, 30f), Array.Empty<object>())); StareAttackSeconds = config.Bind<float>("Detection", "StareAttackSeconds", 5f, new ConfigDescription("Seconds of staring at the eye from within StareAttackRange before the Eye Monster chases that player. A farther stare (beyond StareAttackRange, up to StareRange) builds the warning after StareWarnSeconds and then rolls FarStareLeaveChance once: it either chases that player or backs away and leaves. A value below StareWarnSeconds acts as StareWarnSeconds.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.2f, 60f), Array.Empty<object>())); StareAttackRange = config.Bind<float>("Detection", "StareAttackRange", 4f, new ConfigDescription("A stare from within this many meters fills the close meter that makes it chase after StareAttackSeconds. A farther stare (up to StareRange) builds the warning and then rolls FarStareLeaveChance: it either chases that player or backs away and leaves. 0 turns off only the close-stare meter; far stares still roll. With FarStareLeaveChance at 1 the roll always picks backing away, but an Eye with no room to back away, or stuck while backing away, still chases.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 40f), Array.Empty<object>())); BlindSeconds = config.Bind<float>("Detection", "BlindSeconds", 0.75f, new ConfigDescription("Seconds a light has to shine straight into the eye without a break before the Eye Monster is blinded. When it recovers it chases whoever held the light.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.05f, 10f), Array.Empty<object>())); HelmetLightCounts = config.Bind<bool>("Detection", "HelmetLightCounts", true, "Whether a helmet light shining into the eye counts as a flashlight beam."); ChaseLeashDistance = config.Bind<float>("Detection", "ChaseLeashDistance", 10f, new ConfigDescription("A chase ends, and it goes back to watching, once its target has been out of sight or farther than this many meters for 3.5 seconds.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(2f, 80f), Array.Empty<object>())); FarStareLeaveChance = config.Bind<float>("Behaviour", "FarStareLeaveChance", 0.5f, new ConfigDescription("When a stare from beyond StareAttackRange (but within StareRange) irritates it outside a retreat, the chance that it backs away from that player and leaves instead of chasing them. Rolled once per warning; a close stare never rolls and always ends in a chase. A warning that starts while it is already backing away does not interrupt the retreat or roll again. At 1 the roll always picks backing away, but an Eye with no room to back away, or stuck while backing away, still chases. Host-only: the host's value applies.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 1f), Array.Empty<object>())); RetreatSpeed = config.Bind<float>("Behaviour", "RetreatSpeed", 1.4f, new ConfigDescription("Movement speed while it backs away from a player, still facing them. Host-only: the host's value applies.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.1f, 10f), Array.Empty<object>())); RetreatMaxSeconds = config.Bind<float>("Behaviour", "RetreatMaxSeconds", 8f, new ConfigDescription("Longest it keeps backing away before it turns and leaves. It leaves sooner once the player is out of sight for 1.5 seconds or more than 2 m beyond StareRange. Host-only: the host's value applies.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 60f), Array.Empty<object>())); LeaveIgnoreSeconds = config.Bind<float>("Behaviour", "LeaveIgnoreSeconds", 20f, new ConfigDescription("Once it has backed away and starts leaving, how many seconds it ignores that player's stares from beyond StareAttackRange (no warning, no new roll). The window starts when the retreat ends and includes the walk away. A close stare still makes it chase. 0 turns this off. Host-only: the host's value applies.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 120f), Array.Empty<object>())); PersonalSpaceRange = config.Bind<float>("Behaviour", "PersonalSpaceRange", 3f, new ConfigDescription("While it roams or watches (except while leaving or while a warning is on), a living player who is not staring at it and comes within this many meters makes it back off, facing them. It never attacks for this, and each player can set it off once every 4 seconds. 0 turns this off. Host-only: the host's value applies.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 10f), Array.Empty<object>())); PersonalSpaceDistance = config.Bind<float>("Behaviour", "PersonalSpaceDistance", 2.5f, new ConfigDescription("How many meters it backs off when a player gets within PersonalSpaceRange. Host-only: the host's value applies.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.5f, 10f), Array.Empty<object>())); RoamSpeed = config.Bind<float>("Movement", "RoamSpeed", 2f, new ConfigDescription("Movement speed while roaming.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.1f, 10f), Array.Empty<object>())); ChaseSpeed = config.Bind<float>("Movement", "ChaseSpeed", 5f, new ConfigDescription("Movement speed while chasing a player who stared at it too long from close by, blinded it with a light or hit it.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.1f, 15f), Array.Empty<object>())); MovePlaybackScale = config.Bind<float>("Movement", "MovePlaybackScale", 1f, new ConfigDescription("Multiplier on the speed-matched RUN playback rate (1 = tentacles cycle at the clip's measured pace for the current move speed).", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.25f, 3f), Array.Empty<object>())); CornerClearance = config.Bind<bool>("Movement", "CornerClearance", true, "Keep its legs clear of walls while it roams or walks away: where the corridor has room it steers off the wall at corners and along walls, without changing where it goes. Off follows the game's path. Host-only: the host's value applies."); AttackDamage = config.Bind<int>("Combat", "AttackDamage", 35, new ConfigDescription("Damage dealt by a successful attack.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 200), Array.Empty<object>())); AttackCooldown = config.Bind<float>("Combat", "AttackCooldown", 1.5f, new ConfigDescription("Seconds between attack attempts.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.1f, 30f), Array.Empty<object>())); LookAtRange = config.Bind<float>("Audio and Presentation", "LookAtRange", 10f, new ConfigDescription("Distance within which the eye turns to look at the nearest player in sight. While a stare irritates it, it looks as far as StareRange. Cosmetic only and local to your game; 0 turns it off.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 40f), Array.Empty<object>())); SlimeTrail = config.Bind<bool>("Audio and Presentation", "SlimeTrail", true, "Leave slime behind: a mark every 0.78 m it moves and a small splat on each slithering step. Each player sees their own; off stops both."); DebugLogs = config.Bind<bool>("Diagnostics", "DebugLogs", false, "Log detailed Eye Monster targeting and setup diagnostics."); } } } internal static class EyeMonsterConfigMigration { private static readonly ConfigDefinition LegacySpawnWeight = new ConfigDefinition("Spawning", "SpawnWeight"); private static readonly Dictionary<ConfigDefinition, float> RetiredEntries = new Dictionary<ConfigDefinition, float> { { new ConfigDefinition("Movement", "FleeSpeed"), 7f }, { new ConfigDefinition("Abilities", "FleeDuration"), 6f } }; private static readonly LegacyMigrationSpec Spec = new LegacyMigrationSpec("Eye Monster", (IReadOnlyList<ConfigDefinition>)(object)new ConfigDefinition[6] { LegacySpawnWeight, new ConfigDefinition("Combat", "EnemyHP"), new ConfigDefinition("Detection", "AggroRange"), new ConfigDefinition("Detection", "PlayerGazeAngle"), new ConfigDefinition("Detection", "FlashlightDetectionRange"), new ConfigDefinition("Behavior", "FleeDuration") }, null, new Dictionary<ConfigDefinition, string> { { new ConfigDefinition("Movement", "InvestigateSpeed"), "2.6" }, { new ConfigDefinition("Combat", "AttackRange"), "2.5" }, { new ConfigDefinition("Detection", "NoticeViewAngle"), "52" }, { new ConfigDefinition("Behavior", "InvestigationStopDistance"), "4.5" }, { new ConfigDefinition("Behavior", "InvestigationDecisionDelay"), "0.8" }, { new ConfigDefinition("Detection", "FlashlightDetectionAngle"), "25" }, { new ConfigDefinition("Behavior", "LoseTargetSeconds"), "3.5" }, { new ConfigDefinition("Behavior", "FailedNoticeCooldown"), "4" }, { new ConfigDefinition("Movement", "FleeSpeed"), "7" }, { new ConfigDefinition("Abilities", "FleeDuration"), "6" }, { new ConfigDefinition("Behavior", "FleeDuration"), "6" } }, Build); internal static bool TryMigrate(ConfigFile config, ManualLogSource log) { return LegacyConfigMigrator.TryMigrate(config, log, Spec); } internal static void RetireRemovedEntries(ConfigFile config, ManualLogSource log) { foreach (KeyValuePair<ConfigDefinition, float> retiredEntry in RetiredEntries) { string value = config.Bind<string>(retiredEntry.Key, retiredEntry.Value.ToString(CultureInfo.InvariantCulture), (ConfigDescription)null).Value; config.Remove(retiredEntry.Key); if (!IsApproximately(value, retiredEntry.Value) && log != null) { log.LogWarning((object)("[Eye Monster] Removed retired setting " + retiredEntry.Key.Section + "." + retiredEntry.Key.Key + " = " + value + ". It has no replacement.")); } } } private static void Build(LegacyConfigValues values, MigratedConfigWriter output) { //IL_0081: Unknown result type (might be due to invalid IL or missing references) //IL_0087: Expected O, but got Unknown //IL_00a9: Unknown result type (might be due to invalid IL or missing references) //IL_00af: Expected O, but got Unknown //IL_00d1: Unknown result type (might be due to invalid IL or missing references) //IL_00d7: Expected O, but got Unknown //IL_00f9: Unknown result type (might be due to invalid IL or missing references) //IL_00ff: Expected O, but got Unknown output.Carry("General", "Enabled"); output.CarrySpawnWeightMultiplier(LegacySpawnWeight, 40f); output.Carry("Spawning", "MoonWeightOverrides"); output.Carry("Spawning", "MaxCount"); output.Carry("Spawning", "PowerLevel"); output.Carry("Core Stats", "Health", new ConfigDefinition("Combat", "EnemyHP")); output.Carry("Detection", "NoticeRange", new ConfigDefinition("Detection", "AggroRange")); output.Carry("Detection", "GazeAngle", new ConfigDefinition("Detection", "PlayerGazeAngle")); output.Carry("Detection", "FlashlightRange", new ConfigDefinition("Detection", "FlashlightDetectionRange")); output.Carry("Movement", "RoamSpeed"); output.Carry("Movement", "ChaseSpeed"); output.Carry("Combat", "AttackDamage"); output.Carry("Combat", "AttackCooldown"); output.Carry("Diagnostics", "DebugLogs"); } private static bool IsApproximately(string value, float expected) { if (float.TryParse(value, NumberStyles.Float, CultureInfo.InvariantCulture, out var result)) { return Math.Abs(result - expected) < 0.01f; } return false; } } internal sealed class EyeMonsterSpawnWeights : ContextualSpawnWeights { internal EyeMonsterSpawnWeights(Func<float> multiplier, Func<string> moonOverrides, Action<string> logWarning) : base(SpawnWeightTable.EyeMonster, "Eye Monster", multiplier, moonOverrides, logWarning) { } } internal static class EyeMonsterTuning { internal const float AttackRange = 2.5f; internal const float NoticeViewAngle = 52f; internal const float FlashlightDetectionAngle = 25f; internal const float LoseTargetSeconds = 3.5f; internal const float FailedNoticeCooldown = 4f; internal const float StareDecayPerSecond = 0.5f; internal const float BlindedRecoilSeconds = 1.2f; internal const float WatchForgetSeconds = 3f; internal const float WatchTimeoutSeconds = 12f; internal const float RetreatMinMoveDistance = 3f; internal const float RetreatSampleRadius = 6f; internal const int RetreatFanCount = 7; internal const float RetreatFanSpreadDegrees = 140f; internal const float RetreatLeaveMargin = 2f; internal const float RetreatNoSightLeaveSeconds = 1.5f; internal const float RetreatStuckWindowSeconds = 1.5f; internal const float RetreatStuckMinProgress = 0.3f; internal const float LeaveMinNodeDistance = 20f; internal const float LeaveMaxSeconds = 20f; internal const float PersonalSpaceCooldownSeconds = 4f; internal const float LookAtMaxYawDegrees = 45f; internal const float LookAtMaxPitchDegrees = 25f; internal const float LookAtSharpness = 8f; internal const float LookAtScanSeconds = 0.2f; internal const float LidOverrideFadeSeconds = 0.1f; internal const float EyeIrritationRiseSeconds = 0.35f; internal const float EyeIrritationFallSeconds = 0.5f; internal const float FrustratedEyelidClosure = 0.48f; internal const float AgentAngularSpeed = 180f; internal const float AgentAcceleration = 12f; internal const float AgentRadius = 0.42f; internal const float AgentHeight = 2.3f; internal const float CornerBodyHalfWidth = 1.75f; internal const float NavMeshBakeRadius = 0.35f; internal const float CornerFadeStartDistance = 4f; internal const float CornerFadeEndDistance = 2f; internal const float CornerPushTimeConstantSeconds = 0.4f; internal const float CornerMaxPushSpeed = 1f; internal const float CornerMaxPushSpeedUnknownFarSide = 0.4f; internal const float CornerMinSlideFraction = 0.1f; internal const float CornerMinDesiredSpeed = 0.05f; internal const float CornerOppositeWallDot = -0.7f; internal const float CornerSameWallDot = 0.9f; internal const float RunClipReferenceSpeed = 2.9f; internal const float WalkGaitReferenceSpeed = 1.35f; internal const float GaitWalkForwardBlend = 0.46551722f; internal const float GaitDampSeconds = 0.2f; internal const float GaitIdleSpeed = 0.05f; internal const float RunPlaybackMin = 0.5f; internal const float RunPlaybackMax = 1.8f; internal const float MeasuredSpeedSmoothingSeconds = 0.3f; internal const float JitterAmplitudeMeters = 0.01f; internal const float JitterFadeSeconds = 0.15f; internal const float GroundProbeForward = 0.6f; internal const float GroundProbeSide = 0.6f; internal const float GroundProbeStartHeight = 1f; internal const float GroundProbeLength = 2.5f; internal const float GroundMaxTiltDegrees = 12f; internal const float GroundMaxLift = 0.3f; internal const float GroundPairMaxStep = 0.45f; internal const float GroundLiftSpeed = 2f; internal const float GroundTiltSharpness = 6f; internal const float GroundProbeInterval = 0.05f; internal const float GroundContactSinkMeters = 0.03f; internal const float CueFamilyMinGapSeconds = 0.5f; internal const float MoveCueMinGapSeconds = 0.3f; internal const int SlimeSplatMax = 24; internal const float SlimeSplatLifetimeSeconds = 6f; internal const float SlimeSplatMinDiameter = 0.25f; internal const float SlimeSplatMaxDiameter = 0.4f; internal const float LightScareLidSnapSeconds = 0.12f; internal const float LightScareLidReopenSeconds = 0.4f; internal const float LightScarePupilPulseSeconds = 0.3f; internal const float LightScarePupilPulseScale = 1.15f; } [BepInPlugin("y4ngz.lethalcompany.eyemonster", "Y4NGZ Eye Monster", "2.0.0")] [BepInDependency(/*Could not decode attribute arguments.*/)] public class Plugin : BaseUnityPlugin { internal const string DawnNamespace = "y4ngz_monsters"; internal const string DawnEnemyKey = "eye_monster"; internal const string BestiaryText = "Eye Monster\n\nDanger level: high\n\nA wandering ocular creature that watches workers but leaves them alone. It only minds being stared at or lit up: hold its gaze too long and it grows agitated, then attacks; shine a light into its eye and it recoils, then charges whoever held the light. Look away and keep your light off it, and it loses interest.\n\n"; internal static ManualLogSource Log; internal static EyeMonsterConfig ModConfig; internal static AssetBundle ModAssets; internal static EnemyType EyeMonsterEnemy; private static bool _netcodeInitialized; private static bool _loggedScanNodeLayer; private static bool _loggedMissingAudioEyeBone; private void Awake() { Log = ((BaseUnityPlugin)this).Logger; try { InitializeNetcodeRPCs(); ModConfig = new EyeMonsterConfig(((BaseUnityPlugin)this).Config); string text = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "eyemonster.bundle"); ModAssets = AssetBundle.LoadFromFile(text); if ((Object)(object)ModAssets == (Object)null) { Log.LogError((object)("Failed to load asset bundle at: " + text)); return; } GameObject val = ModAssets.LoadAsset<GameObject>("EyeMonster"); if ((Object)(object)val == (Object)null) { Log.LogError((object)"Failed to load EyeMonster prefab from bundle."); return; } SetupPrefabComponents(val); EyeMonsterEnemy = CreateEnemyType(val); EyeMonsterAI component = val.GetComponent<EyeMonsterAI>(); if ((Object)(object)component == (Object)null) { Log.LogError((object)"EyeMonster prefab does not contain EyeMonsterAI."); return; } ((EnemyAI)component).enemyType = EyeMonsterEnemy; RegisterWithDawn(val); if (!ModConfig.Enabled.Value) { Log.LogInfo((object)"Y4NGZ Eye Monster: registered network prefab; spawning disabled by config."); } Log.LogInfo((object)"Y4NGZ Eye Monster v2.0.0 loaded."); } catch (Exception arg) { Log.LogError((object)string.Format("Failed to initialize {0}: {1}", "Y4NGZ Eye Monster", arg)); } } private static void RegisterWithDawn(GameObject prefab) { EyeMonsterSpawnWeights spawnWeights = new EyeMonsterSpawnWeights(() => (!ModConfig.Enabled.Value) ? 0f : ModConfig.SpawnWeightMultiplier.Value, () => ModConfig.MoonWeightOverrides.Value, delegate(string message) { Log.LogWarning((object)message); }); DawnLib.RegisterNetworkPrefab(prefab); DawnLib.DefineEnemy(NamespacedKey<DawnEnemyInfo>.From("y4ngz_monsters", "eye_monster"), EyeMonsterEnemy, (Action<EnemyInfoBuilder>)delegate(EnemyInfoBuilder builder) { ((BaseInfoBuilder<DawnEnemyInfo, EnemyType, EnemyInfoBuilder>)(object)builder.DefineInside((Action<EnemyLocationBuilder>)delegate(EnemyLocationBuilder location) { location.SetWeights((Action<WeightTableBuilder<DawnMoonInfo, SpawnWeightContext>>)delegate(WeightTableBuilder<DawnMoonInfo, SpawnWeightContext> table) { table.SetGlobalWeight((IWeighted)(object)spawnWeights); }); }).CreateBestiaryNode("Eye Monster\n\nDanger level: high\n\nA wandering ocular creature that watches workers but leaves them alone. It only minds being stared at or lit up: hold its gaze too long and it grows agitated, then attacks; shine a light into its eye and it recoils, then charges whoever held the light. Look away and keep your light off it, and it loses interest.\n\n").CreateNameKeyword("eye monster")).AddTags((IEnumerable<NamespacedKey>)(object)new NamespacedKey[4] { Tags.Hostile, Tags.Organic, Tags.Killable, Tags.Medium }); }); } private static void InitializeNetcodeRPCs() { if (_netcodeInitialized) { return; } _netcodeInitialized = true; Type[] types = Assembly.GetExecutingAssembly().GetTypes(); foreach (Type type in types) { MethodInfo[] methods; try { methods = type.GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); } catch { continue; } foreach (MethodInfo methodInfo in methods) { if (methodInfo.GetCustomAttributes(typeof(RuntimeInitializeOnLoadMethodAttribute), inherit: false).Length == 0) { continue; } try { methodInfo.Invoke(null, null); } catch (Exception ex) { ManualLogSource log = Log; if (log != null) { log.LogWarning((object)("[NetcodeInit] " + type.Name + "." + methodInfo.Name + " failed: " + ex.Message)); } } } } } private static void SetupPrefabComponents(GameObject prefab) { TrySetTag(prefab, "Enemy"); TrySetLayer(prefab, "Enemies"); CapBodySmoothness(prefab); EyeMonsterAI component = prefab.GetComponent<EyeMonsterAI>(); if ((Object)(object)component == (Object)null) { Log.LogError((object)"[EyeMon] EyeMonsterAI is missing from the bundled prefab."); return; } NetworkTransform[] componentsInChildren = prefab.GetComponentsInChildren<NetworkTransform>(true); NetworkTransform[] array = componentsInChildren; for (int i = 0; i < array.Length; i++) { Object.DestroyImmediate((Object)(object)array[i], true); } if (componentsInChildren.Length != 0) { Log.LogInfo((object)"[EyeMon] Removed ClientNetworkTransform from the prefab: EnemyAI already replicates position (serverPosition) and yaw, and two writers jitter clients."); } ((EnemyAI)component).updatePositionThreshold = 0.3f; NavMeshAgent val = prefab.GetComponent<NavMeshAgent>(); if ((Object)(object)val == (Object)null) { val = prefab.AddComponent<NavMeshAgent>(); } ConfigureAgent(val); ((EnemyAI)component).agent = val; Animator animator = ResolveAnimator(prefab, component); EnsureAnimationRelay(prefab, component, animator); EnsureEyeAnchor(prefab, component); EnsureScanNode(prefab); EnsureMapDot(prefab); EnsureCollision(prefab, component); EnsureExclusiveAudio(prefab, component); EnsureSlimeTrail(prefab, component); EnsureBehaviourStates(component); WireAudioClips(component); EyeMonsterLooseAudio.Load(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)); } private static void CapBodySmoothness(GameObject prefab) { HashSet<Material> hashSet = new HashSet<Material>(); int num = 0; Renderer[] componentsInChildren = prefab.GetComponentsInChildren<Renderer>(true); for (int i = 0; i < componentsInChildren.Length; i++) { Material[] sharedMaterials = componentsInChildren[i].sharedMaterials; foreach (Material val in sharedMaterials) { if (!((Object)(object)val == (Object)null) && hashSet.Add(val) && !((Object)(object)val.shader == (Object)null) && ((Object)val.shader).name.StartsWith("HDRP/Lit", StringComparison.Ordinal) && (!val.HasProperty("_SurfaceType") || val.GetFloat("_SurfaceType") == 0f) && !((Object)val).name.StartsWith("EyeMonsterSlime", StringComparison.Ordinal)) { if (val.HasProperty("_SmoothnessRemapMin")) { val.SetFloat("_SmoothnessRemapMin", 0f); } if (val.HasProperty("_SmoothnessRemapMax")) { val.SetFloat("_SmoothnessRemapMax", 0.35f); } if (val.HasProperty("_Smoothness")) { val.SetFloat("_Smoothness", 0.35f); } if (val.HasProperty("_EnableGeometricSpecularAA")) { val.SetFloat("_EnableGeometricSpecularAA", 1f); val.EnableKeyword("_ENABLE_GEOMETRIC_SPECULAR_AA"); } if (val.HasProperty("_SpecularAAScreenSpaceVariance")) { val.SetFloat("_SpecularAAScreenSpaceVariance", 0.1f); } if (val.HasProperty("_SpecularAAThreshold")) { val.SetFloat("_SpecularAAThreshold", 0.2f); } num++; } } } Log.LogInfo((object)$"EyeMonster: smoothness capped at 0.35 and specular AA on for {num} body material(s) (#287)."); } private static void ConfigureAgent(NavMeshAgent agent) { agent.speed = ModConfig.RoamSpeed.Value; agent.angularSpeed = 180f; agent.acceleration = 12f; agent.stoppingDistance = 0f; agent.radius = 0.42f; agent.height = 2.3f; agent.baseOffset = 0f; agent.autoRepath = true; agent.autoTraverseOffMeshLink = true; } private static Animator ResolveAnimator(GameObject prefab, EyeMonsterAI ai) { Transform val = prefab.transform.Find("VisualRoot"); Animator val2 = (((Object)(object)val != (Object)null) ? ((Component)val).GetComponent<Animator>() : prefab.GetComponent<Animator>()); if ((Object)(object)val2 == (Object)null) { val2 = prefab.GetComponentInChildren<Animator>(true); } ((EnemyAI)ai).creatureAnimator = val2; return val2; } private static void EnsureAnimationRelay(GameObject prefab, EyeMonsterAI ai, Animator animator) { if (!((Object)(object)animator == (Object)null) && !((Object)(object)((Component)animator).gameObject == (Object)(object)prefab)) { EyeMonsterAnimationRelay eyeMonsterAnimationRelay = ((Component)animator).GetComponent<EyeMonsterAnimationRelay>(); if ((Object)(object)eyeMonsterAnimationRelay == (Object)null) { eyeMonsterAnimationRelay = ((Component)animator).gameObject.AddComponent<EyeMonsterAnimationRelay>(); } eyeMonsterAnimationRelay.owner = ai; } } private static void EnsureEyeAnchor(GameObject prefab, EyeMonsterAI ai) { //IL_001a: Unknown result type (might be due to invalid IL or missing references) Transform val = FindOrCreateChild(prefab.transform, "Eye", new Vector3(0f, 1.45f, 0.45f)); TrySetLayer(((Component)val).gameObject, "Enemies"); ((EnemyAI)ai).eye = val; } internal static void EnsureScanNode(GameObject prefab) { //IL_0125: Unknown result type (might be due to invalid IL or missing references) //IL_0148: Unknown result type (might be due to invalid IL or missing references) //IL_022e: Unknown result type (might be due to invalid IL or missing references) //IL_0248: Unknown result type (might be due to invalid IL or missing references) ScanNodeProperties val = null; ScanNodeProperties[] componentsInChildren = prefab.GetComponentsInChildren<ScanNodeProperties>(true); foreach (ScanNodeProperties val2 in componentsInChildren) { bool flag = val2.creatureScanID >= 0; bool flag2 = (Object)(object)val != (Object)null && val.creatureScanID >= 0; bool flag3 = string.Equals(((Object)((Component)val2).gameObject).name, "ScanNode", StringComparison.Ordinal); bool flag4 = (Object)(object)val != (Object)null && string.Equals(((Object)((Component)val).gameObject).name, "ScanNode", StringComparison.Ordinal); if ((Object)(object)val == (Object)null || (flag && !flag2) || (flag == flag2 && flag3 && !flag4)) { val = val2; } } if (componentsInChildren.Length > 1) { ManualLogSource log = Log; if (log != null) { log.LogWarning((object)$"[EyeMon] Found {componentsInChildren.Length} scan nodes; retiring every duplicate."); } } for (int j = 0; j < componentsInChildren.Length; j++) { if ((Object)(object)componentsInChildren[j] != (Object)(object)val) { RetireExtraScanNode(componentsInChildren[j], val, prefab); } } Transform val3 = (((Object)(object)val != (Object)null) ? ((Component)val).transform : FindOrCreateChild(prefab.transform, "ScanNode", new Vector3(0f, 1.15f, 0f))); val3.localPosition = new Vector3(0f, 1.15f, 0f); ((Object)((Component)val3).gameObject).name = "ScanNode"; TrySetTag(((Component)val3).gameObject, "DoNotSet"); TrySetLayer(((Component)val3).gameObject, "ScanNode"); EnsureHierarchyActive(val3, prefab.transform); ((Component)val3).gameObject.SetActive(true); if (!_loggedScanNodeLayer) { _loggedScanNodeLayer = true; Log.LogInfo((object)($"[EyeMon] Scan node layer resolved to {((Component)val3).gameObject.layer} " + string.Format("(NameToLayer(\"ScanNode\")={0}, fallback 22); ", LayerMask.NameToLayer("ScanNode")) + $"active={((Component)val3).gameObject.activeInHierarchy}.")); } BoxCollider val4 = ((Component)val3).GetComponent<BoxCollider>(); if ((Object)(object)val4 == (Object)null) { val4 = ((Component)val3).gameObject.AddComponent<BoxCollider>(); } ((Collider)val4).enabled = true; ((Collider)val4).isTrigger = true; val4.center = Vector3.zero; val4.size = new Vector3(1.8f, 2.2f, 1.8f); val = val ?? ((Component)val3).gameObject.AddComponent<ScanNodeProperties>(); val.headerText = "Eye Monster"; val.subText = string.Empty; val.maxRange = 25; val.minRange = 1; val.nodeType = 1; val.requiresLineOfSight = true; } private static void RetireExtraScanNode(ScanNodeProperties extra, ScanNodeProperties preferred, GameObject root) { //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_003a: Unknown result type (might be due to invalid IL or missing references) //IL_0080: Unknown result type (might be due to invalid IL or missing references) //IL_0085: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)extra == (Object)null) { return; } Scene scene; if ((Object)(object)((Component)extra).gameObject == (Object)(object)root || ((Object)(object)preferred != (Object)null && (Object)(object)((Component)extra).gameObject == (Object)(object)((Component)preferred).gameObject)) { scene = root.scene; if (((Scene)(ref scene)).IsValid()) { Object.Destroy((Object)(object)extra); } else { Object.DestroyImmediate((Object)(object)extra, true); } return; } GameObject gameObject = ((Component)extra).gameObject; gameObject.SetActive(false); Collider[] components = gameObject.GetComponents<Collider>(); for (int i = 0; i < components.Length; i++) { components[i].enabled = false; } scene = root.scene; if (((Scene)(ref scene)).IsValid()) { Object.Destroy((Object)(object)gameObject); } else { Object.DestroyImmediate((Object)(object)gameObject, true); } } private static void EnsureMapDot(GameObject prefab) { //IL_001a: Unknown result type (might be due to invalid IL or missing references) Transform obj = FindOrCreateChild(prefab.transform, "MapDot", new Vector3(0f, 0.95f, 0f)); TrySetTag(((Component)obj).gameObject, "DoNotSet"); TrySetLayer(((Component)obj).gameObject, "MapRadar"); } private static void EnsureCollision(GameObject prefab, EyeMonsterAI ai) { //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_004f: Unknown result type (might be due to invalid IL or missing references) //IL_0064: Unknown result type (might be due to invalid IL or missing references) //IL_00c9: Unknown result type (might be due to invalid IL or missing references) //IL_00e3: Unknown result type (might be due to invalid IL or missing references) BoxCollider val = prefab.GetComponent<BoxCollider>(); if ((Object)(object)val == (Object)null) { val = prefab.AddComponent<BoxCollider>(); } ((Collider)val).enabled = true; ((Collider)val).isTrigger = false; val.center = new Vector3(0f, 1.15f, 0f); val.size = new Vector3(2.05f, 2.3f, 2.05f); Transform val2 = FindOrCreateChild(prefab.transform, "Collision", Vector3.zero); TrySetTag(((Component)val2).gameObject, "Enemy"); TrySetLayer(((Component)val2).gameObject, "Enemies"); BoxCollider val3 = ((Component)val2).GetComponent<BoxCollider>(); if ((Object)(object)val3 == (Object)null) { val3 = ((Component)val2).gameObject.AddComponent<BoxCollider>(); } ((Collider)val3).enabled = true; ((Collider)val3).isTrigger = true; val3.center = new Vector3(0f, 1.2f, 0f); val3.size = new Vector3(2.3f, 2.4f, 2.3f); Rigidbody val4 = ((Component)val2).GetComponent<Rigidbody>(); if ((Object)(object)val4 == (Object)null) { val4 = ((Component)val2).gameObject.AddComponent<Rigidbody>(); } val4.isKinematic = true; val4.useGravity = false; val4.detectCollisions = true; WireHitDetector(((Component)val2).gameObject, ai); } private static void WireHitDetector(GameObject host, EyeMonsterAI ai) { EnemyAICollisionDetect val = host.GetComponent<EnemyAICollisionDetect>(); if ((Object)(object)val == (Object)null) { val = host.AddComponent<EnemyAICollisionDetect>(); } val.mainScript = (EnemyAI)(object)ai; val.alwaysAllowHitting = true; val.canCollideWithEnemies = false; val.onlyCollideWhenGrounded = false; } private static void EnsureExclusiveAudio(GameObject prefab, EyeMonsterAI ai) { //IL_008b: Unknown result type (might be due to invalid IL or missing references) //IL_00be: Unknown result type (might be due to invalid IL or missing references) //IL_00b7: Unknown result type (might be due to invalid IL or missing references) //IL_00c9: Unknown result type (might be due to invalid IL or missing references) //IL_0160: Unknown result type (might be due to invalid IL or missing references) Transform val = prefab.transform.Find("VisualRoot"); Transform val2 = null; if ((Object)(object)val != (Object)null) { Transform[] componentsInChildren = ((Component)val).GetComponentsInChildren<Transform>(true); foreach (Transform val3 in componentsInChildren) { if (string.Equals(((Object)val3).name, "eye", StringComparison.Ordinal)) { val2 = val3; break; } } } Transform val4 = (((Object)(object)val2 != (Object)null) ? val2 : prefab.transform); Transform val5 = prefab.transform.Find("CreatureAudio"); if ((Object)(object)val5 == (Object)null) { val5 = FindOrCreateChild(val4, "CreatureAudio", Vector3.zero); } val5.SetParent(val4, false); val5.localPosition = (Vector3)(((Object)(object)val2 != (Object)null) ? Vector3.zero : new Vector3(0f, 1.1f, 0f)); val5.localRotation = Quaternion.identity; if ((Object)(object)val2 == (Object)null && !_loggedMissingAudioEyeBone) { _loggedMissingAudioEyeBone = true; Log.LogWarning((object)"[EyeMon] Optical bone 'eye' is missing under VisualRoot; keeping CreatureAudio at the root's +1.10 m fallback."); } TrySetLayer(((Component)val5).gameObject, "Enemies"); AudioSource val6 = ((Component)val5).GetComponent<AudioSource>(); if ((Object)(object)val6 == (Object)null) { val6 = ((Component)val5).gameObject.AddComponent<AudioSource>(); } ConfigureSpatialAudio(val6); ai.exclusiveAudioSource = val6; ((EnemyAI)ai).creatureSFX = val6; ((EnemyAI)ai).creatureVoice = val6; Transform val7 = FindOrCreateChild(prefab.transform, "CreatureFootsteps", new Vector3(0f, 0.15f, 0f)); TrySetLayer(((Component)val7).gameObject, "Enemies"); AudioSource val8 = ((Component)val7).GetComponent<AudioSource>(); if ((Object)(object)val8 == (Object)null) { val8 = ((Component)val7).gameObject.AddComponent<AudioSource>(); } ConfigureSpatialAudio(val8); ai.footstepAudioSource = val8; DisableLegacyAudio(prefab.transform.Find("CreatureSFX"), val6); DisableLegacyAudio(prefab.transform.Find("CreatureVoice"), val6); DisableLegacyAudio(prefab.transform.Find("LoopSource"), val6); } private static void DisableLegacyAudio(Transform legacyTransform, AudioSource retainedSource) { if (!((Object)(object)legacyTransform == (Object)null)) { AudioSource component = ((Component)legacyTransform).GetComponent<AudioSource>(); if (!((Object)(object)component == (Object)null) && !((Object)(object)component == (Object)(object)retainedSource)) { component.Stop(); component.playOnAwake = false; component.loop = false; component.clip = null; ((Behaviour)component).enabled = false; } } } private static void ConfigureSpatialAudio(AudioSource source) { source.playOnAwake = false; source.loop = false; source.spatialBlend = 1f; source.rolloffMode = (AudioRolloffMode)0; source.minDistance = 2f; source.maxDistance = 35f; source.spread = 0f; } private static void EnsureSlimeTrail(GameObject prefab, EyeMonsterAI ai) { EyeMonsterSlimeTrail eyeMonsterSlimeTrail = prefab.GetComponent<EyeMonsterSlimeTrail>(); if ((Object)(object)eyeMonsterSlimeTrail == (Object)null) { eyeMonsterSlimeTrail = prefab.AddComponent<EyeMonsterSlimeTrail>(); } eyeMonsterSlimeTrail.slimeMaterial = LoadMaterial("EyeMonsterSlime"); ai.slimeTrail = eyeMonsterSlimeTrail; if ((Object)(object)eyeMonsterSlimeTrail.slimeMaterial == (Object)null) { Log.LogWarning((object)"[EyeMon] EyeMonsterSlime material is missing from the bundle."); } } private static void EnsureBehaviourStates(EyeMonsterAI ai) { ((EnemyAI)ai).enemyBehaviourStates = (EnemyBehaviourState[])(object)new EnemyBehaviourState[6] { WalkingState("Roaming", walking: false), WalkingState("Watching", walking: false), WalkingState("Chasing", walking: true), WalkingState("Attacking", walking: false), WalkingState("Blinded", walking: false), WalkingState("Retreating", walking: false) }; ((EnemyAI)ai).currentBehaviourStateIndex = 0; ((EnemyAI)ai).previousBehaviourStateIndex = 0; ((EnemyAI)ai).currentBehaviourState = ((EnemyAI)ai).enemyBehaviourStates[0]; } private static EnemyBehaviourState WalkingState(string name, bool walking) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0013: 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_0026: Expected O, but got Unknown return new EnemyBehaviourState { name = name, IsAnimTrigger = false, parameterString = "isWalking", boolValue = walking }; } private static void WireAudioClips(EyeMonsterAI ai) { ai.idleClips = LoadAudioClips("eyemonster_idle_01", "eyemonster_idle_02"); ai.vocalClips = LoadAudioClips("eyemonster_vocal_01", "eyemonster_vocal_02"); ai.playerHitClips = LoadAudioClips("eyemonster_player_hit_01"); ai.runStepClips = LoadAudioClips("eyemonster_step_01", "eyemonster_step_02", "eyemonster_step_03"); } private static AudioClip[] LoadAudioClips(params string[] names) { AudioClip[] array = (AudioClip[])(object)new AudioClip[names.Length]; int num = 0; for (int i = 0; i < names.Length; i++) { AudioClip val = LoadAudioClip(names[i]); if ((Object)(object)val != (Object)null) { array[num++] = val; } } if (num == array.Length) { return array; } AudioClip[] array2 = (AudioClip[])(object)new AudioClip[num]; Array.Copy(array, array2, num); return array2; } private static AudioClip LoadAudioClip(string shortName) { AudioClip val = ModAssets.LoadAsset<AudioClip>(shortName) ?? ModAssets.LoadAsset<AudioClip>(shortName + ".wav"); if ((Object)(object)val != (Object)null) { return val; } string[] allAssetNames = ModAssets.GetAllAssetNames(); foreach (string text in allAssetNames) { if (text.EndsWith("/" + shortName + ".wav", StringComparison.OrdinalIgnoreCase)) { return ModAssets.LoadAsset<AudioClip>(text); } } Log.LogWarning((object)("[EyeMon] Audio clip missing from bundle: " + shortName)); return null; } private static Material LoadMaterial(string shortName) { Material val = ModAssets.LoadAsset<Material>(shortName) ?? ModAssets.LoadAsset<Material>(shortName + ".mat"); if ((Object)(object)val != (Object)null) { return val; } string[] allAssetNames = ModAssets.GetAllAssetNames(); foreach (string text in allAssetNames) { if (text.EndsWith("/" + shortName + ".mat", StringComparison.OrdinalIgnoreCase)) { return ModAssets.LoadAsset<Material>(text); } } return null; } private static Transform FindOrCreateChild(Transform parent, string name, Vector3 localPosition) { //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Unknown result type (might be due to invalid IL or missing references) Transform val = parent.Find(name); if ((Object)(object)val == (Object)null) { val = new GameObject(name).transform; val.SetParent(parent, false); } val.localPosition = localPosition; return val; } private static void TrySetTag(GameObject target, string tagName) { try { target.tag = tagName; } catch (UnityException) { Log.LogWarning((object)("[EyeMon] Tag '" + tagName + "' is unavailable for '" + ((Object)target).name + "'.")); } } internal static void TrySetLayer(GameObject target, string layerName) { if (!((Object)(object)target == (Object)null)) { int num = LayerMask.NameToLayer(layerName); if (num < 0) { num = ResolveLayerFallback(layerName); } if (num < 0 || num > 31) { Log.LogWarning((object)("[EyeMon] Layer '" + layerName + "' is unavailable for '" + ((Object)target).name + "'.")); } else { target.layer = num; } } } private static int ResolveLayerFallback(string layerName) { if (string.Equals(layerName, "ScanNode", StringComparison.OrdinalIgnoreCase)) { return 22; } if (string.Equals(layerName, "Enemies", StringComparison.OrdinalIgnoreCase)) { return 19; } return -1; } private static void EnsureHierarchyActive(Transform child, Transform stopAt) { Transform val = child; while ((Object)(object)val != (Object)null) { ((Component)val).gameObject.SetActive(true); if (!((Object)(object)val == (Object)(object)stopAt)) { val = val.parent; continue; } break; } } private static EnemyType CreateEnemyType(GameObject prefab) { //IL_00ce: Unknown result type (might be due to invalid IL or missing references) EnemyType obj = ScriptableObject.CreateInstance<EnemyType>(); obj.enemyName = "Eye Monster"; obj.enemyPrefab = prefab; obj.PowerLevel = ModConfig.PowerLevel.Value; obj.DiversityPowerLevel = 1; obj.MaxCount = ModConfig.MaxCount.Value; obj.canDie = true; obj.canBeStunned = true; obj.stunTimeMultiplier = 1f; obj.doorSpeedMultiplier = 1f; obj.stunGameDifficultyMultiplier = 1f; obj.destroyOnDeath = false; obj.isOutsideEnemy = false; obj.isDaytimeEnemy = false; obj.probabilityCurve = AnimationCurve.Constant(0f, 1f, 1f); obj.numberSpawnedFalloff = AnimationCurve.Linear(0f, 1f, 1f, 0.65f); obj.useNumberSpawnedFalloff = true; obj.SizeLimit = (NavSizeLimit)1; EyeMonsterAI component = prefab.GetComponent<EyeMonsterAI>(); AudioClip[] array = (((Object)(object)component != (Object)null) ? component.vocalClips : null); CreatureSfx.Apply(obj, (EnemyAI)(object)component, (array != null && array.Length != 0) ? array[0] : null, (array != null && array.Length != 0) ? array[^1] : null); return obj; } } public static class PluginInfo { public const string PLUGIN_GUID = "y4ngz.lethalcompany.eyemonster"; public const string PLUGIN_NAME = "Y4NGZ Eye Monster"; public const string PLUGIN_VERSION = "2.0.0"; } } namespace EyeMonster.Utils { public static class CreatureAudio { public static bool PlayExclusive(AudioSource source, AudioClip clip, bool interrupt) { if ((Object)(object)source == (Object)null || (Object)(object)clip == (Object)null) { return false; } if (source.isPlaying && !interrupt) { return false; } source.Stop(); source.loop = false; source.clip = clip; source.Play(); return true; } public static void Stop(AudioSource source) { if (!((Object)(object)source == (Object)null)) { source.Stop(); source.loop = false; source.clip = null; } } } } namespace EyeMonster.AI { public class EyeMonsterAI : EnemyAI { private enum AudioCue { Idle, Vocal, PlayerHit, Step, Mad, LightScare, Attack, Aggro, Death } private struct PendingHit { public int Id; public ulong VictimClientId; public int ClipIndex; public double ServerTime; public bool Active; } private static readonly EyeCornerSettings CornerSettings = EyeCornerSettings.Eye; private EyeCornerMemory _cornerMemory; public const int StateRoaming = 0; public const int StateWatching = 1; public const int StateChasing = 2; public const int StateAttacking = 3; public const int StateBlinded = 4; public const int StateRetreating = 5; [Header("Exclusive audio")] public AudioClip[] idleClips; public AudioClip[] vocalClips; public AudioClip[] playerHitClips; public AudioClip[] runStepClips; public AudioSource exclusiveAudioSource; [Header("Cosmetics")] public EyeMonsterSlimeTrail slimeTrail; private const float PassiveEyelidClosure = 0.24f; private const float FlashlightEyelidClosure = 0.72f; private const float PassiveEyelidSmoothTime = 0.42f; private const float RevealEyelidSmoothTime = 0.24f; private const float FlashlightEyelidSmoothTime = 0.16f; private const float DeathEyelidSmoothTime = 0.13f; private const float IdleAudioMinSeconds = 7.5f; private const float IdleAudioMaxSeconds = 14f; private const string StunnedParameter = "stunned"; private const float BiteForce = 12f; private const float MaxReactionStepSeconds = 0.5f; private const int NoPlayerSlot = -1; private static readonly int DoFrustratedTrigger = Animator.StringToHash("doFrustrated"); private static readonly int DoBlindedTrigger = Animator.StringToHash("doBlinded"); private static readonly int DoHitTrigger = Animator.StringToHash("doHit"); private static readonly int DoAttackTrigger = Animator.StringToHash("doAttack"); private static readonly int FrustratedStateHash = Animator.StringToHash("Frustrated"); private static readonly int IdleStateHash = Animator.StringToHash("Idle"); private static readonly int RunStateHash = Animator.StringToHash("Run"); private const string BlindedStatePath = "Base Layer.Blinded"; private static readonly int EyeIrritationParameter = Animator.StringToHash("EyeIrritation"); private static readonly int DoGlareTrigger = Animator.StringToHash("doGlare"); private static readonly int FrustratedStatePathHash = Animator.StringToHash("Base Layer.Frustrated"); private static readonly int WatchIdleParameter = Animator.StringToHash("WatchIdle"); private static readonly int FrustratedParameter = Animator.StringToHash("Frustrated"); private static readonly int SettleTrigger = Animator.StringToHash("Settle"); private static readonly int MoveForwardParameter = Animator.StringToHash("MoveForward"); private static readonly int MoveStrafeParameter = Animator.StringToHash("MoveStrafe"); private const float LookAtLogSeconds = 1f; private const float RunStepCueLogSeconds = 5f; private const float WatchWalkMinSpeed = 0.5f; private static readonly RaycastHit[] LineCheckHits = (RaycastHit[])(object)new RaycastHit[8]; private const float NoiseMinLoudness = 0.5f; private const float NoiseHearingRange = 20f; private const float NoiseMemorySeconds = 3f; private const float NoiseReseedCooldown = 4f; private const int NoiseMaxRepeatsInOneSpot = 10; private static readonly Vector3 UpperLidOpenPosition = new Vector3(0f, 0.53408f, 0.668f); private static readonly Vector3 LowerLidOpenPosition = new Vector3(0f, 0.53408f, 0.668f); private static readonly Vector3 UpperLidClosedPosition = new Vector3(0f, 0.53408f, 0.668f); private static readonly Vector3 LowerLidClosedPosition = new Vector3(0.44242f, 0.53408f, 0.668f); private static readonly Quaternion UpperLidOpenRotation = Quaternion.identity; private static readonly Quaternion LowerLidOpenRotation = Quaternion.identity; private static readonly Quaternion UpperLidClosedRotation = Quaternion.Euler(35.10085f, 0.00239f, 0.00126f); private static readonly Quaternion LowerLidClosedRotation = Quaternion.Euler(-37.8065f, 0.00281f, -0.00115f); private readonly Dictionary<ulong, float> _noticeCooldownUntil = new Dictionary<ulong, float>(); private readonly int[] _lastAudioIndices = CreateLastAudioIndices(); private readonly ServerOwnershipGuard _ownership = new ServerOwnershipGuard(); private readonly NoiseMemory _noiseMemory = new NoiseMemory(); private readonly EyeReactionBrain _brain = new EyeReactionBrain(); private readonly EyeLookAtSolver _lookSolver = new EyeLookAtSolver(); private readonly EyeCueGate _cueGate = new EyeCueGate(0.5f, 0.3f); private readonly NetworkVariable<int> _networkState = new NetworkVariable<int>(0, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); private readonly NetworkVariable<int> _networkReaction = new NetworkVariable<int>(0, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); private readonly NetworkVariable<double> _networkReactionStart = new NetworkVariable<double>(0.0, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); private readonly NetworkVariable<bool> _networkLit = new NetworkVariable<bool>(false, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); private float _loseTargetTimer; private float _attackCooldownTimer; private float _nextIdleAudioTime; private float _eyelidClosure = 0.24f; private float _eyelidClosureVelocity; private float _lidOverrideWeight = 1f; private float _remoteMovingUntil; private Vector3 _lastAnimationPosition; private bool _hasLastAnimationPosition; private bool _eyelidsInitialized; private Coroutine _attackCoroutine; private bool _gazeConfirmedForTarget; private bool _deathAnimationStarted; private float _nextNoiseReseedTime; private bool _wasStunned; private bool _audioRouted; private bool _attackSwingPending; private bool _deathPoseFrozen; private bool _corpseAnimatorStopped; private EyeStareSample[] _stareSamples = Array.Empty<EyeStareSample>(); private float _lastReactionTickTime; private float _watchStartedAt; private float _watchOutOfSightTime; private EyeReaction _publishedReaction; private EyeReaction _localReaction; private bool _reactionRpcReceived; private Animator _contractAnimator; private bool _hasEyeIrritationParameter; private bool _hasDoGlareParameter; private bool _hasDoFrustratedParameter; private bool _hasWatchIdleParameter; private bool _hasFrustratedParameter; private bool _hasSettleParameter; private bool _hasMoveForwardParameter; private bool _hasMoveStrafeParameter; private bool _eyeOnlyFrustration; private float _eyeIrritation; private bool _intentsSeeded; private bool _watchIdleIntent; private bool _frustratedIntent; private readonly int[] _runExitTriggers = new int[5]; private int _runExitTriggerCount; private PlayerControllerB _lookTarget; private float _nextLookScanTime; private float _nextLookLogTime; private Transform _lookFrame; private EyeLookBasis _lookBasis; private Quaternion _eyeRestLocalRotation; private static bool _lookRestReported; private Transform _eyeBone; private Transform _upperLid; private Transform _lowerLid; private float _measuredSpeed; private bool _moving; private Vector3 _measuredVelocity; private float _gaitReferenceSpeed = 2.9f; private EyeGaitState _gait; private EyeMonsterVisualGrounding _grounding; private float _nextRunStepLogTime; private bool _presentationTornDown; private int _pendingDeathCueIndex = -1; private Vector3 _eyeRestLocalScale = Vector3.one; private float _lightScareFlinchStart; private bool _lightScareFlinchActive; private static FieldInfo _targetYRotationField; private static bool _targetYRotationFieldResolved; [Header("Footstep audio")] public AudioSource footstepAudioSource; private const double HitConfirmationWindowSeconds = 3.0; private readonly PendingHit[] _pendingHits = new PendingHit[4]; private int _nextHitId; private const float RetreatSnapDistance = 2f; private const float RetreatArrivalTolerance = 0.3f; private const float BackOffMaxSeconds = 3f; private const int LeaveNodesPerPass = 4; private readonly EyeStareIgnore _stareIgnore = new EyeStareIgnore(); private readonly EyePersonalSpace _personalSpace = new EyePersonalSpace(); private readonly EyeRetreatTracker _retreatTracker = new EyeRetreatTracker(); private readonly float[] _retreatYaws = new float[7]; private readonly EyeRetreatCandidate[] _retreatCandidates = new EyeRetreatCandidate[7]; private readonly Vector3[] _retreatPoints = (Vector3[])(object)new Vector3[7]; private readonly Vector3[] _pathCorners = (Vector3[])(object)new Vector3[32]; private EyeStareSample[] _brainStareSamples = Array.Empty<EyeStareSample>(); private float[] _stareDistances = Array.Empty<float>(); private float[] _leaveNodeDistances = Array.Empty<float>(); private bool[] _leaveNodeUsable = Array.Empty<bool>(); private int _leaveNodeCount; private int _leaveNodesUntried; private ulong[] _slotOccupants = Array.Empty<ulong>(); private NavMeshPath _retreatPath; private bool _leaving; private bool _leaveSearching; private float _leaveStartedAt; private bool _backingOff; private float _backOffStartedAt; private bool _facingLocked; private bool _retreatLegFresh; private static readonly Func<float> FarStareRollSource = () => Random.value; private float RoamSpeed => Mathf.Max(0.1f, Plugin.ModConfig.RoamSpeed.Value); private float ChaseSpeed => Mathf.Max(0.1f, Plugin.ModConfig.ChaseSpeed.Value); private int AttackDamage => Mathf.Max(0, Plugin.ModConfig.AttackDamage.Value); private float AttackCooldown => Mathf.Max(0.1f, Plugin.ModConfig.AttackCooldown.Value); private float AttackRange => 2.5f; private float
SimonSays.dll
Decompiled a day ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security.Cryptography; 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 Microsoft.CodeAnalysis; using SimonSays.AI; using SimonSays.NetcodePatcher; using SimonSays.Utils; using Unity.Netcode; using UnityEngine; using UnityEngine.AI; using UnityEngine.Audio; using UnityEngine.Networking; using UnityEngine.Rendering; using UnityEngine.Rendering.HighDefinition; using UnityEngine.SceneManagement; using UnityEngine.UI; using Y4NGZMonsters.Shared; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: AssemblyCompany("SimonSays")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0+3460ec64f0cec4948e51ddb3f02a4b0e414f105e")] [assembly: AssemblyProduct("SimonSays")] [assembly: AssemblyTitle("SimonSays")] [assembly: AssemblyVersion("1.0.0.0")] [module: RefSafetyRules(11)] [module: NetcodePatchedAssembly] 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 SimonSays { [BepInPlugin("y4ngz.lethalcompany.simonsays", "Y4NGZ Simon Says", "2.0.0")] [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInDependency(/*Could not decode attribute arguments.*/)] public class Plugin : BaseUnityPlugin { internal const string DisplayName = "Simon Says"; internal const string DawnNamespace = "y4ngz_monsters"; internal const string DawnEnemyKey = "simon_says"; internal const string TerminalKeyword = "simon"; internal const string BestiaryText = "Simon Says\n\nDanger level: 100%\n\nSigurd's notes: It's a wheeled jester cart with a clockwork skull. It picks one crew member, puts a spotlight on them, and plays a game. Three commands. It cannot be killed, and when it is done it leaves in a cloud of smoke.\n\nThe rule is the whole trick: only obey a command it prefixes with \"Simon says\". Obey one it does not, and it kills you for it. Ignore one it does, and it kills you for that too. Listen for the words \"and\" (either order) versus \"then\" (that order).\n\n"; internal static ManualLogSource Log; private static bool _loggedScanNodeLayer; internal static SimonSaysConfig ModConfig; internal static AssetBundle ModAssets; internal static EnemyType SimonSaysEnemy; internal static AudioClip LetsPlayClip; internal static AudioClip SimonSaysWordClip; internal static AudioClip AndClip; internal static AudioClip ThenClip; internal static AudioClip CongratulationsClip; internal static AudioClip GoodbyeClip; private static readonly AudioClip[] _actionClips = (AudioClip[])(object)new AudioClip[4]; internal static AudioClip SpotlightStartClip; internal static GameObject VanishSmokePrefab; private const string SpotlightStartSfxFileName = "simon_says_spotlight.mp3"; private static bool _netcodeInitialized = false; private Harmony _harmony; internal static AudioClip ActionClip(ActionType action) { if (action < ActionType.Jump || (int)action >= _actionClips.Length) { return null; } return _actionClips[(int)action]; } private void Awake() { //IL_01f6: Unknown result type (might be due to invalid IL or missing references) //IL_0200: Expected O, but got Unknown Log = ((BaseUnityPlugin)this).Logger; try { InitializeNetcodeRPCs(); ModConfig = new SimonSaysConfig(((BaseUnityPlugin)this).Config); string directoryName = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); ((MonoBehaviour)this).StartCoroutine(LoadSpotlightStartClip(directoryName)); string text = Path.Combine(directoryName, "simonsays.bundle"); ModAssets = AssetBundle.LoadFromFile(text); if ((Object)(object)ModAssets == (Object)null) { Log.LogError((object)("Failed to load asset bundle at: " + text)); return; } GameObject val = LoadEnemyPrefab(); if ((Object)(object)val == (Object)null) { Log.LogError((object)"Failed to load SimonSays prefab from bundle. Available assets:"); string[] allAssetNames = ModAssets.GetAllAssetNames(); foreach (string text2 in allAssetNames) { Log.LogError((object)(" - " + text2)); } return; } Log.LogInfo((object)("Loaded prefab '" + ((Object)val).name + "' with " + $"{val.GetComponents<Component>().Length} root components.")); LoadAudioFromBundle(); LoadEffectsFromBundle(); AssignUniqueNetworkHash(val); RebindTexturesFromBundle(val); SetupPrefabComponents(val); SimonSaysEnemy = CreateEnemyType(val); SimonSaysAI component = val.GetComponent<SimonSaysAI>(); if ((Object)(object)component != (Object)null) { ((EnemyAI)component).enemyType = SimonSaysEnemy; } SimonSaysSpawnWeights spawnWeights = new SimonSaysSpawnWeights(() => (!ModConfig.Enabled.Value) ? 0f : ModConfig.SpawnWeightMultiplier.Value, () => ModConfig.MoonWeightOverrides.Value, delegate(string message) { Log.LogWarning((object)message); }); DawnLib.RegisterNetworkPrefab(val); DawnLib.DefineEnemy(NamespacedKey<DawnEnemyInfo>.From("y4ngz_monsters", "simon_says"), SimonSaysEnemy, (Action<EnemyInfoBuilder>)delegate(EnemyInfoBuilder builder) { ((BaseInfoBuilder<DawnEnemyInfo, EnemyType, EnemyInfoBuilder>)(object)builder.DefineInside((Action<EnemyLocationBuilder>)delegate(EnemyLocationBuilder location) { location.SetWeights((Action<WeightTableBuilder<DawnMoonInfo, SpawnWeightContext>>)delegate(WeightTableBuilder<DawnMoonInfo, SpawnWeightContext> table) { table.SetGlobalWeight((IWeighted)(object)spawnWeights); }); }).CreateBestiaryNode("Simon Says\n\nDanger level: 100%\n\nSigurd's notes: It's a wheeled jester cart with a clockwork skull. It picks one crew member, puts a spotlight on them, and plays a game. Three commands. It cannot be killed, and when it is done it leaves in a cloud of smoke.\n\nThe rule is the whole trick: only obey a command it prefixes with \"Simon says\". Obey one it does not, and it kills you for it. Ignore one it does, and it kills you for that too. Listen for the words \"and\" (either order) versus \"then\" (that order).\n\n").CreateNameKeyword("simon")).AddTags((IEnumerable<NamespacedKey>)(object)new NamespacedKey[3] { Tags.Hostile, Tags.Mechanical, Tags.Medium }); }); _harmony = new Harmony("y4ngz.lethalcompany.simonsays"); _harmony.PatchAll(typeof(Plugin).Assembly); if (!ModConfig.Enabled.Value) { Log.LogInfo((object)"Y4NGZ Simon Says: registered network prefab; spawning disabled by config."); } Log.LogInfo((object)"Y4NGZ Simon Says v2.0.0 loaded."); } catch (Exception arg) { Log.LogError((object)string.Format("Failed to initialize {0}: {1}", "Y4NGZ Simon Says", arg)); } } private static void InitializeNetcodeRPCs() { if (_netcodeInitialized) { return; } _netcodeInitialized = true; Type[] types = Assembly.GetExecutingAssembly().GetTypes(); foreach (Type type in types) { MethodInfo[] methods; try { methods = type.GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); } catch (Exception ex) { Log.LogWarning((object)("[NetcodeInit] skipped type " + type.FullName + ": " + ex.GetType().Name)); continue; } MethodInfo[] array = methods; foreach (MethodInfo methodInfo in array) { if (methodInfo.GetCustomAttributes(typeof(RuntimeInitializeOnLoadMethodAttribute), inherit: false).Length != 0) { try { methodInfo.Invoke(null, null); Log.LogInfo((object)("[NetcodeInit] invoked " + type.Name + "." + methodInfo.Name)); } catch (Exception arg) { Log.LogError((object)$"[NetcodeInit] {type.Name}.{methodInfo.Name} threw: {arg}"); } } } } } private static GameObject LoadEnemyPrefab() { string[] array = new string[4] { "Assets/Y4NGZ/SimonSays/SimonSays.prefab", "assets/y4ngz/simonsays/simonsays.prefab", "Assets/SimonSays/SimonSays.prefab", "assets/simonsays/simonsays.prefab" }; foreach (string text in array) { GameObject val = ModAssets.LoadAsset<GameObject>(text); if ((Object)(object)val != (Object)null && (Object)(object)val.GetComponent<SimonSaysAI>() != (Object)null) { Log.LogInfo((object)("Loaded SimonSays prefab by path '" + text + "'.")); return val; } } GameObject[] array2 = ModAssets.LoadAllAssets<GameObject>(); foreach (GameObject val2 in array2) { if ((Object)(object)val2 != (Object)null && (Object)(object)val2.GetComponent<SimonSaysAI>() != (Object)null) { Log.LogWarning((object)("SimonSays prefab not at any known path; recovered '" + ((Object)val2).name + "' by scanning the bundle for SimonSaysAI. Update knownPaths.")); return val2; } } return null; } private static void LoadAudioFromBundle() { LetsPlayClip = LoadClip("ss_lets_play"); SimonSaysWordClip = LoadClip("ss_simon_says"); AndClip = LoadClip("ss_and"); ThenClip = LoadClip("ss_then"); CongratulationsClip = LoadClip("ss_congratulations"); GoodbyeClip = LoadClip("ss_goodbye"); _actionClips[0] = LoadClip("ss_jump"); _actionClips[1] = LoadClip("ss_crouch"); _actionClips[2] = LoadClip("ss_dance"); _actionClips[3] = LoadClip("ss_turn_around"); WarnIfMissing(LetsPlayClip, "ss_lets_play"); WarnIfMissing(CongratulationsClip, "ss_congratulations"); WarnIfMissing(GoodbyeClip, "ss_goodbye"); if ((1u & (RequireCommandClip(SimonSaysWordClip, "ss_simon_says") ? 1u : 0u) & (RequireCommandClip(AndClip, "ss_and") ? 1u : 0u) & (RequireCommandClip(ThenClip, "ss_then") ? 1u : 0u) & (RequireCommandClip(_actionClips[0], "ss_jump") ? 1u : 0u) & (RequireCommandClip(_actionClips[1], "ss_crouch") ? 1u : 0u) & (RequireCommandClip(_actionClips[2], "ss_dance") ? 1u : 0u) & (RequireCommandClip(_actionClips[3], "ss_turn_around") ? 1u : 0u)) == 0) { Log.LogFatal((object)"[SimonSays] Command word bank is incomplete; SimonSays will not register because a partial spoken command must never be judged."); throw new InvalidDataException("[SimonSays] Command word bank is incomplete; SimonSays will not register because a partial spoken command must never be judged."); } } private static void WarnIfMissing(AudioClip clip, string name) { if ((Object)(object)clip == (Object)null) { Log.LogError((object)("SimonSays audio '" + name + "' not found in bundle.")); } } private static bool RequireCommandClip(AudioClip clip, string name) { if ((Object)(object)clip != (Object)null) { return true; } Log.LogFatal((object)("[SimonSays] Required command clip '" + name + "' not found in bundle.")); return false; } private static void LoadEffectsFromBundle() { VanishSmokePrefab = ModAssets.LoadAsset<GameObject>("SimonSaysVanishSmoke") ?? ModAssets.LoadAsset<GameObject>("Assets/Y4NGZ/SimonSays/Effects/SimonSaysVanishSmoke.prefab"); if ((Object)(object)VanishSmokePrefab == (Object)null) { Log.LogWarning((object)"SimonSaysVanishSmoke prefab not in bundle; the vanish will use the code-built smoke cloud instead."); } } private static void RebindTexturesFromBundle(GameObject prefab) { //IL_00f0: Unknown result type (might be due to invalid IL or missing references) //IL_0101: Unknown result type (might be due to invalid IL or missing references) try { Texture2D val = ModAssets.LoadAsset<Texture2D>("Meshy_AI_Clockwork_Jester_0505033555_texture"); Texture2D val2 = ModAssets.LoadAsset<Texture2D>("Meshy_AI_Clockwork_Jester_0505033555_texture_normal"); Texture2D val3 = ModAssets.LoadAsset<Texture2D>("Meshy_AI_Clockwork_Jester_0505033555_texture_metallic"); Texture2D val4 = ModAssets.LoadAsset<Texture2D>("Meshy_AI_Clockwork_Jester_0505033555_texture_emission"); if ((Object)(object)val == (Object)null) { Log.LogWarning((object)"Albedo texture missing from bundle."); } else { Log.LogInfo((object)$"Albedo loaded: {((Texture)val).width}x{((Texture)val).height}"); } int num = 0; int num2 = 0; int num3 = 0; Renderer[] componentsInChildren = prefab.GetComponentsInChildren<Renderer>(true); for (int i = 0; i < componentsInChildren.Length; i++) { Material[] sharedMaterials = componentsInChildren[i].sharedMaterials; foreach (Material val5 in sharedMaterials) { if ((Object)(object)val5 == (Object)null) { continue; } if ((Object)(object)val != (Object)null) { val5.SetTexture("_BaseColorMap", (Texture)(object)val); val5.SetTexture("_MainTex", (Texture)(object)val); val5.SetColor("_BaseColor", Color.white); val5.SetColor("_Color", Color.white); } if ((Object)(object)val2 != (Object)null) { val5.SetTexture("_NormalMap", (Texture)(object)val2); val5.SetTexture("_BumpMap", (Texture)(object)val2); val5.EnableKeyword("_NORMALMAP"); val5.EnableKeyword("_NORMALMAP_TANGENT_SPACE"); } if ((Object)(object)val3 != (Object)null) { val5.SetTexture("_MaskMap", (Texture)(object)val3); val5.SetTexture("_MetallicGlossMap", (Texture)(object)val3); val5.EnableKeyword("_MASKMAP"); if (val5.HasProperty("_SmoothnessRemapMin")) { val5.SetFloat("_SmoothnessRemapMin", 0f); } bool flag = false; if (val5.HasProperty("_SmoothnessRemapMax")) { val5.SetFloat("_SmoothnessRemapMax", 0.35f); flag = true; } if (val5.HasProperty("_Smoothness")) { val5.SetFloat("_Smoothness", 0.35f); flag = true; } if (flag) { num2++; } if (val5.HasProperty("_EnableGeometricSpecularAA")) { val5.SetFloat("_EnableGeometricSpecularAA", 1f); val5.EnableKeyword("_ENABLE_GEOMETRIC_SPECULAR_AA"); num3++; } if (val5.HasProperty("_SpecularAAScreenSpaceVariance")) { val5.SetFloat("_SpecularAAScreenSpaceVariance", 0.1f); } if (val5.HasProperty("_SpecularAAThreshold")) { val5.SetFloat("_SpecularAAThreshold", 0.2f); } } if ((Object)(object)val4 != (Object)null) { val5.SetTexture("_EmissiveColorMap", (Texture)(object)val4); val5.SetTexture("_EmissionMap", (Texture)(object)val4); val5.EnableKeyword("_EMISSIVE_COLOR_MAP"); } num++; } } Log.LogInfo((object)($"RebindTexturesFromBundle: applied to {num} material slot(s); " + $"smoothness capped at 0.35 on {num2}, specular AA on {num3}.")); } catch (Exception arg) { Log.LogError((object)$"RebindTexturesFromBundle: {arg}"); } } private static void AssignUniqueNetworkHash(GameObject prefab) { try { NetworkObject component = prefab.GetComponent<NetworkObject>(); if ((Object)(object)component == (Object)null) { Log.LogWarning((object)"Prefab missing NetworkObject — skipping hash override"); return; } uint num = BitConverter.ToUInt32(MD5.Create().ComputeHash(Encoding.UTF8.GetBytes("y4ngz.lethalcompany.simonsays.SimonSays")), 0); PropertyInfo property = typeof(NetworkObject).GetProperty("GlobalObjectIdHash", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); if (property != null && property.CanWrite) { property.SetValue(component, num); } else { FieldInfo field = typeof(NetworkObject).GetField("GlobalObjectIdHash", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); if (field != null) { field.SetValue(component, num); } else { Log.LogWarning((object)"Could not locate GlobalObjectIdHash via property or field — hash unchanged"); } } Log.LogInfo((object)$"SimonSays NetworkObject GlobalObjectIdHash = {num}"); } catch (Exception arg) { Log.LogError((object)$"AssignUniqueNetworkHash: {arg}"); } } private static AudioClip LoadClip(params string[] candidates) { foreach (string text in candidates) { AudioClip val = ModAssets.LoadAsset<AudioClip>(text); if ((Object)(object)val != (Object)null) { return val; } } return null; } private IEnumerator LoadSpotlightStartClip(string assemblyDir) { string path = Path.Combine(assemblyDir, "simon_says_spotlight.mp3"); if (!File.Exists(path)) { Log.LogWarning((object)("Spotlight start sound missing: " + path)); yield break; } UnityWebRequest request = UnityWebRequestMultimedia.GetAudioClip(new Uri(path).AbsoluteUri, (AudioType)13); try { yield return request.SendWebRequest(); if ((int)request.result != 1) { Log.LogWarning((object)("Failed loading spotlight start sound '" + path + "': " + request.error)); yield break; } AudioClip content = DownloadHandlerAudioClip.GetContent(request); if ((Object)(object)content == (Object)null) { Log.LogWarning((object)("Spotlight start sound decoded null: " + path)); yield break; } ((Object)content).name = "SimonSays_SpotlightStart"; SpotlightStartClip = content; Log.LogInfo((object)("Loaded spotlight start sound from '" + path + "'.")); } finally { ((IDisposable)request)?.Dispose(); } } private static void SetupPrefabComponents(GameObject prefab) { //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_0039: Unknown result type (might be due to invalid IL or missing references) //IL_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_0053: Expected O, but got Unknown //IL_0055: Unknown result type (might be due to invalid IL or missing references) //IL_005a: Unknown result type (might be due to invalid IL or missing references) //IL_0065: Unknown result type (might be due to invalid IL or missing references) //IL_006c: Unknown result type (might be due to invalid IL or missing references) //IL_0077: Unknown result type (might be due to invalid IL or missing references) //IL_007f: Expected O, but got Unknown //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_0091: Unknown result type (might be due to invalid IL or missing references) //IL_0098: Unknown result type (might be due to invalid IL or missing references) //IL_00a4: Expected O, but got Unknown //IL_00a6: Unknown result type (might be due to invalid IL or missing references) //IL_00ab: Unknown result type (might be due to invalid IL or missing references) //IL_00b6: Unknown result type (might be due to invalid IL or missing references) //IL_00bd: Unknown result type (might be due to invalid IL or missing references) //IL_00c9: Expected O, but got Unknown //IL_00cb: Unknown result type (might be due to invalid IL or missing references) //IL_00d0: Unknown result type (might be due to invalid IL or missing references) //IL_00db: Unknown result type (might be due to invalid IL or missing references) //IL_00e2: Unknown result type (might be due to invalid IL or missing references) //IL_00ed: Unknown result type (might be due to invalid IL or missing references) //IL_00f5: Expected O, but got Unknown //IL_00f7: Unknown result type (might be due to invalid IL or missing references) //IL_00fc: Unknown result type (might be due to invalid IL or missing references) //IL_0107: Unknown result type (might be due to invalid IL or missing references) //IL_010e: Unknown result type (might be due to invalid IL or missing references) //IL_011a: Expected O, but got Unknown //IL_011c: Unknown result type (might be due to invalid IL or missing references) //IL_0121: Unknown result type (might be due to invalid IL or missing references) //IL_012c: Unknown result type (might be due to invalid IL or missing references) //IL_0133: Unknown result type (might be due to invalid IL or missing references) //IL_013f: Expected O, but got Unknown //IL_0141: Unknown result type (might be due to invalid IL or missing references) //IL_0146: Unknown result type (might be due to invalid IL or missing references) //IL_0151: Unknown result type (might be due to invalid IL or missing references) //IL_0158: Unknown result type (might be due to invalid IL or missing references) //IL_0163: Unknown result type (might be due to invalid IL or missing references) //IL_016b: Expected O, but got Unknown EnsureScanNode(prefab); SimonSaysAI component = prefab.GetComponent<SimonSaysAI>(); if ((Object)(object)component != (Object)null) { EnsureNavigation(prefab, component); ((EnemyAI)component).enemyBehaviourStates = (EnemyBehaviourState[])(object)new EnemyBehaviourState[8] { new EnemyBehaviourState { name = "Roaming", IsAnimTrigger = false, parameterString = "isWalking", boolValue = true }, new EnemyBehaviourState { name = "Approaching", IsAnimTrigger = false, parameterString = "isWalking", boolValue = true }, new EnemyBehaviourState { name = "Intro", IsAnimTrigger = true, parameterString = "command" }, new EnemyBehaviourState { name = "Commanding", IsAnimTrigger = true, parameterString = "command" }, new EnemyBehaviourState { name = "Judging", IsAnimTrigger = false, parameterString = "isWalking", boolValue = false }, new EnemyBehaviourState { name = "Punishing", IsAnimTrigger = true, parameterString = "playerFailed" }, new EnemyBehaviourState { name = "Celebrating", IsAnimTrigger = true, parameterString = "playerPassed" }, new EnemyBehaviourState { name = "Departing", IsAnimTrigger = false, parameterString = "isWalking", boolValue = true } }; EnsureCollision(prefab, component); if ((Object)(object)prefab.GetComponent<SimonHeadLook>() == (Object)null) { prefab.AddComponent<SimonHeadLook>(); } } } private static void EnsureNavigation(GameObject prefab, SimonSaysAI ai) { NavMeshAgent val = prefab.GetComponent<NavMeshAgent>(); if ((Object)(object)val == (Object)null) { val = prefab.AddComponent<NavMeshAgent>(); val.radius = 0.6f; val.height = 1.8f; val.baseOffset = 0.9f; val.angularSpeed = 120f; val.acceleration = 8f; val.stoppingDistance = 3.5f; val.autoBraking = true; val.areaMask = -1; Log.LogWarning((object)"[SimonSays] Prefab was missing a root NavMeshAgent; added a vanilla-compatible runtime agent."); } val.speed = ModConfig?.ApproachSpeed?.Value ?? 3.5f; ((EnemyAI)ai).agent = val; } internal static void EnsureScanNode(GameObject prefab) { //IL_0144: Unknown result type (might be due to invalid IL or missing references) //IL_0168: Unknown result type (might be due to invalid IL or missing references) //IL_0173: Unknown result type (might be due to invalid IL or missing references) //IL_024f: Unknown result type (might be due to invalid IL or missing references) //IL_0269: Unknown result type (might be due to invalid IL or missing references) ScanNodeProperties val = null; ScanNodeProperties[] componentsInChildren = prefab.GetComponentsInChildren<ScanNodeProperties>(true); foreach (ScanNodeProperties val2 in componentsInChildren) { if (!((Object)(object)val2 == (Object)null) && !((Object)(object)((Component)val2).gameObject == (Object)(object)prefab)) { bool flag = val2.creatureScanID >= 0; bool flag2 = (Object)(object)val != (Object)null && val.creatureScanID >= 0; bool flag3 = string.Equals(((Object)((Component)val2).gameObject).name, "ScanNode", StringComparison.Ordinal); bool flag4 = (Object)(object)val != (Object)null && string.Equals(((Object)((Component)val).gameObject).name, "ScanNode", StringComparison.Ordinal); if ((Object)(object)val == (Object)null || (flag && !flag2) || (flag == flag2 && flag3 && !flag4)) { val = val2; } } } if (componentsInChildren.Length > 1) { ManualLogSource log = Log; if (log != null) { log.LogWarning((object)$"[SimonSays] Found {componentsInChildren.Length} scan nodes; retiring every duplicate."); } } for (int j = 0; j < componentsInChildren.Length; j++) { if ((Object)(object)componentsInChildren[j] != (Object)(object)val) { RetireExtraScanNode(componentsInChildren[j], val, prefab); } } Transform val3 = (((Object)(object)val != (Object)null) ? ((Component)val).transform : FindOrCreateChild(prefab.transform, "ScanNode", new Vector3(0f, 1.25f, 0f))); ((Object)((Component)val3).gameObject).name = "ScanNode"; val3.localRotation = Quaternion.identity; val3.localScale = Vector3.one; TrySetTag(((Component)val3).gameObject, "DoNotSet"); TrySetLayer(((Component)val3).gameObject, "ScanNode"); EnsureHierarchyActive(val3, prefab.transform); ((Component)val3).gameObject.SetActive(true); if (!_loggedScanNodeLayer) { _loggedScanNodeLayer = true; ManualLogSource log2 = Log; if (log2 != null) { log2.LogInfo((object)($"[SimonSays] Scan node layer resolved to {((Component)val3).gameObject.layer} " + string.Format("(NameToLayer(\"ScanNode\")={0}, fallback 22); ", LayerMask.NameToLayer("ScanNode")) + $"active={((Component)val3).gameObject.activeInHierarchy}.")); } } BoxCollider val4 = ((Component)val3).GetComponent<BoxCollider>(); if ((Object)(object)val4 == (Object)null) { val4 = ((Component)val3).gameObject.AddComponent<BoxCollider>(); } ((Collider)val4).enabled = true; ((Collider)val4).isTrigger = true; val4.center = Vector3.zero; val4.size = new Vector3(1.2f, 1.8f, 1.2f); if ((Object)(object)val == (Object)null) { val = ((Component)val3).gameObject.AddComponent<ScanNodeProperties>(); } val.headerText = "Simon Says"; val.subText = string.Empty; val.maxRange = 13; val.minRange = 1; val.requiresLineOfSight = true; val.nodeType = 1; } private static void RetireExtraScanNode(ScanNodeProperties extra, ScanNodeProperties preferred, GameObject root) { //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_0087: Unknown result type (might be due to invalid IL or missing references) //IL_008c: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)extra == (Object)null) { return; } Scene scene; if ((Object)(object)((Component)extra).gameObject == (Object)(object)root || ((Object)(object)preferred != (Object)null && (Object)(object)((Component)extra).gameObject == (Object)(object)((Component)preferred).gameObject)) { ((Behaviour)extra).enabled = false; scene = root.scene; if (((Scene)(ref scene)).IsValid()) { Object.Destroy((Object)(object)extra); } else { Object.DestroyImmediate((Object)(object)extra, true); } return; } GameObject gameObject = ((Component)extra).gameObject; gameObject.SetActive(false); Collider[] components = gameObject.GetComponents<Collider>(); for (int i = 0; i < components.Length; i++) { components[i].enabled = false; } scene = root.scene; if (((Scene)(ref scene)).IsValid()) { Object.Destroy((Object)(object)gameObject); } else { Object.DestroyImmediate((Object)(object)gameObject, true); } } private static void EnsureCollision(GameObject prefab, SimonSaysAI ai) { //IL_0030: Unknown result type (might be due to invalid IL or missing references) //IL_007f: Unknown result type (might be due to invalid IL or missing references) //IL_0098: Unknown result type (might be due to invalid IL or missing references) TrySetTag(prefab, "Enemy"); TrySetLayer(prefab, "Enemies"); Transform val = FindOrCreateChild(prefab.transform, "Collision", new Vector3(0f, 1f, 0f)); TrySetTag(((Component)val).gameObject, "Enemy"); TrySetLayer(((Component)val).gameObject, "Enemies"); BoxCollider obj = ((Component)val).GetComponent<BoxCollider>() ?? ((Component)val).gameObject.AddComponent<BoxCollider>(); ((Collider)obj).enabled = true; ((Collider)obj).isTrigger = true; obj.center = Vector3.zero; obj.size = new Vector3(1.25f, 1.85f, 1.25f); Rigidbody obj2 = ((Component)val).GetComponent<Rigidbody>() ?? ((Component)val).gameObject.AddComponent<Rigidbody>(); obj2.isKinematic = true; obj2.useGravity = false; obj2.detectCollisions = true; EnemyAICollisionDetect obj3 = ((Component)val).GetComponent<EnemyAICollisionDetect>() ?? ((Component)val).gameObject.AddComponent<EnemyAICollisionDetect>(); obj3.mainScript = (EnemyAI)(object)ai; obj3.alwaysAllowHitting = true; obj3.canCollideWithEnemies = false; obj3.onlyCollideWhenGrounded = false; } private static EnemyType CreateEnemyType(GameObject prefab) { //IL_007a: Unknown result type (might be due to invalid IL or missing references) //IL_00ba: Unknown result type (might be due to invalid IL or missing references) //IL_00bf: Unknown result type (might be due to invalid IL or missing references) //IL_00d0: Unknown result type (might be due to invalid IL or missing references) //IL_00d5: Unknown result type (might be due to invalid IL or missing references) //IL_00da: Unknown result type (might be due to invalid IL or missing references) //IL_00e4: Expected O, but got Unknown //IL_00f7: Unknown result type (might be due to invalid IL or missing references) //IL_00fc: Unknown result type (might be due to invalid IL or missing references) //IL_010d: Unknown result type (might be due to invalid IL or missing references) //IL_0112: Unknown result type (might be due to invalid IL or missing references) //IL_0117: Unknown result type (might be due to invalid IL or missing references) //IL_0121: Expected O, but got Unknown EnemyType val = ScriptableObject.CreateInstance<EnemyType>(); val.enemyName = "Simon Says"; val.enemyPrefab = prefab; val.PowerLevel = ModConfig.PowerLevel.Value; val.DiversityPowerLevel = 1; val.MaxCount = 1; val.canDie = false; val.canBeStunned = false; val.canBeDestroyed = true; val.stunTimeMultiplier = 1f; val.stunGameDifficultyMultiplier = 1f; val.destroyOnDeath = false; val.doorSpeedMultiplier = 1f; val.SizeLimit = (NavSizeLimit)1; CreatureSfx.Apply(val, (EnemyAI)(object)prefab.GetComponent<SimonSaysAI>()); val.isOutsideEnemy = false; val.isDaytimeEnemy = false; val.normalizedTimeInDayToLeave = 1f; val.probabilityCurve = new AnimationCurve((Keyframe[])(object)new Keyframe[2] { new Keyframe(0f, 1f), new Keyframe(1f, 1f) }); val.numberSpawnedFalloff = new AnimationCurve((Keyframe[])(object)new Keyframe[2] { new Keyframe(0f, 1f), new Keyframe(1f, 1f) }); return val; } private static Transform FindOrCreateChild(Transform parent, string name, Vector3 localPosition) { //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_0028: Unknown result type (might be due to invalid IL or missing references) Transform val = parent.Find(name); if ((Object)(object)val != (Object)null) { return val; } val = new GameObject(name).transform; val.SetParent(parent, false); val.localPosition = localPosition; return val; } private static void TrySetTag(GameObject gameObject, string tag) { try { gameObject.tag = tag; } catch { } } private static void TrySetLayer(GameObject gameObject, string layerName) { if ((Object)(object)gameObject == (Object)null) { return; } int num = LayerMask.NameToLayer(layerName); if (num < 0) { num = ResolveLayerFallback(layerName); } if (num >= 0 && num <= 31) { gameObject.layer = num; return; } ManualLogSource log = Log; if (log != null) { log.LogWarning((object)$"[SimonSays] Layer '{layerName}' unresolved; '{((Object)gameObject).name}' stays on layer {gameObject.layer}."); } } private static int ResolveLayerFallback(string layerName) { if (string.Equals(layerName, "ScanNode", StringComparison.OrdinalIgnoreCase)) { return 22; } if (string.Equals(layerName, "Enemies", StringComparison.OrdinalIgnoreCase)) { return 19; } return -1; } private static void EnsureHierarchyActive(Transform child, Transform stopAt) { Transform val = child; while ((Object)(object)val != (Object)null) { ((Component)val).gameObject.SetActive(true); if (!((Object)(object)val == (Object)(object)stopAt)) { val = val.parent; continue; } break; } } } public static class PluginInfo { public const string PLUGIN_GUID = "y4ngz.lethalcompany.simonsays"; public const string PLUGIN_NAME = "Y4NGZ Simon Says"; public const string PLUGIN_VERSION = "2.0.0"; } internal static class SimonSaysBloodFxBridge { internal const string PluginGuid = "com.y4ngz.bloodfx"; internal const string SourceKey = "SimonSays"; internal const int GibKindFull = 1; private const string GibApiTypeName = "Y4NGZCompany.Experience.BloodFX.BloodFXGibApi"; private static bool _resolved; private static Func<bool> _isAvailable; private static Func<PlayerControllerB, string, int, bool> _requestGib; internal static bool RequestGib(PlayerControllerB victim, string sourceKey, int kind) { try { if (!_resolved) { Resolve(); } if (_requestGib == null || !_isAvailable()) { return false; } return _requestGib(victim, sourceKey, kind); } catch (Exception ex) { _isAvailable = null; _requestGib = null; ManualLogSource log = Plugin.Log; if (log != null) { log.LogWarning((object)("[SimonSays] Disabled optional BloodFX gib bridge: " + ex.GetBaseException().Message)); } return false; } } private static void Resolve() { _resolved = true; if (!Chainloader.PluginInfos.TryGetValue("com.y4ngz.bloodfx", out var value) || (Object)(object)value.Instance == (Object)null) { return; } Type? type = ((object)value.Instance).GetType().Assembly.GetType("Y4NGZCompany.Experience.BloodFX.BloodFXGibApi", throwOnError: false); PropertyInfo propertyInfo = type?.GetProperty("IsAvailable", BindingFlags.Static | BindingFlags.Public); MethodInfo methodInfo = ((propertyInfo != null && propertyInfo.PropertyType == typeof(bool)) ? propertyInfo.GetGetMethod() : null); MethodInfo methodInfo2 = type?.GetMethod("RequestGib", BindingFlags.Static | BindingFlags.Public, null, new Type[3] { typeof(PlayerControllerB), typeof(string), typeof(int) }, null); if (methodInfo == null || methodInfo2 == null || methodInfo2.ReturnType != typeof(bool)) { ManualLogSource log = Plugin.Log; if (log != null) { log.LogWarning((object)"[SimonSays] BloodFX is installed but Y4NGZCompany.Experience.BloodFX.BloodFXGibApi is missing or incompatible; punishment keeps the vanilla death."); } return; } _isAvailable = (Func<bool>)Delegate.CreateDelegate(typeof(Func<bool>), methodInfo); _requestGib = (Func<PlayerControllerB, string, int, bool>)Delegate.CreateDelegate(typeof(Func<PlayerControllerB, string, int, bool>), methodInfo2); ManualLogSource log2 = Plugin.Log; if (log2 != null) { log2.LogInfo((object)"[SimonSays] BloodFX gib bridge bound (Y4NGZCompany.Experience.BloodFX.BloodFXGibApi)."); } } } public sealed class SimonSaysConfig { private const string SectionGeneral = "General"; private const string SectionSpawning = "Spawning"; private const string SectionMovement = "Movement"; private const string SectionAbilities = "Abilities"; private const string SectionPresentation = "Audio and Presentation"; private const string SectionDiagnostics = "Diagnostics"; public ConfigEntry<bool> Enabled { get; } public ConfigEntry<float> SpawnWeightMultiplier { get; } public ConfigEntry<string> MoonWeightOverrides { get; } public ConfigEntry<float> PowerLevel { get; } public ConfigEntry<float> ApproachSpeed { get; } public ConfigEntry<float> RetreatDuration { get; } public ConfigEntry<int> RoundsPerEncounter { get; } public ConfigEntry<float> ComplianceWindowSeconds { get; } public ConfigEntry<float> TrapWindowSeconds { get; } public ConfigEntry<float> SimonSaysChance { get; } public ConfigEntry<float> TwoActionRoundChance { get; } public ConfigEntry<float> BetweenRoundPause { get; } public ConfigEntry<float> SpotlightLumens { get; } public ConfigEntry<float> SpotlightVolumetricDimmer { get; } public ConfigEntry<bool> DebugLogs { get; } public ConfigEntry<bool> VanishSmokeForceHdrpShaders { get; } public int Rounds => Mathf.Clamp(RoundsPerEncounter.Value, 1, 8); public float Window => Mathf.Clamp(ComplianceWindowSeconds.Value, 0.75f, 30f); public float TrapWindow => Mathf.Clamp(TrapWindowSeconds.Value, 0.5f, 30f); public float SimonChance => Mathf.Clamp01(SimonSaysChance.Value); public float TwoActionChance => Mathf.Clamp01(TwoActionRoundChance.Value); public float RoundPause => Mathf.Clamp(BetweenRoundPause.Value, 0f, 5f); public SimonSaysConfig(ConfigFile config) { //IL_0086: Unknown result type (might be due to invalid IL or missing references) //IL_0090: Expected O, but got Unknown //IL_00df: Unknown result type (might be due to invalid IL or missing references) //IL_00e9: Expected O, but got Unknown //IL_0118: Unknown result type (might be due to invalid IL or missing references) //IL_0122: Expected O, but got Unknown //IL_0151: Unknown result type (might be due to invalid IL or missing references) //IL_015b: Expected O, but got Unknown //IL_017e: Unknown result type (might be due to invalid IL or missing references) //IL_0188: Expected O, but got Unknown //IL_01b7: Unknown result type (might be due to invalid IL or missing references) //IL_01c1: Expected O, but got Unknown //IL_01f0: Unknown result type (might be due to invalid IL or missing references) //IL_01fa: Expected O, but got Unknown //IL_0229: Unknown result type (might be due to invalid IL or missing references) //IL_0233: Expected O, but got Unknown //IL_0262: Unknown result type (might be due to invalid IL or missing references) //IL_026c: Expected O, but got Unknown //IL_029b: Unknown result type (might be due to invalid IL or missing references) //IL_02a5: Expected O, but got Unknown //IL_02d4: Unknown result type (might be due to invalid IL or missing references) //IL_02de: Expected O, but got Unknown //IL_033a: Unknown result type (might be due to invalid IL or missing references) //IL_0344: Expected O, but got Unknown using (ConfigPersistence.BeginBinding(config, Plugin.Log, "Simon Says")) { SimonSaysConfigMigration.TryMigrate(config, Plugin.Log); ConfigSectionNameMigration.TryMigrate(config, Plugin.Log, "Simon Says"); float? num = SimonSaysConfigMigration.RetireSpotlightIntensity(config, Plugin.Log); Enabled = config.Bind<bool>("General", "Enabled", true, "Enable the Simon Says encounter. Host-only: the host's value decides whether it spawns; every install still registers the creature so clients stay in sync."); SpawnWeightMultiplier = config.Bind<float>("Spawning", "SpawnWeightMultiplier", 1f, new ConfigDescription("Multiplier applied to Simon Says' contextual moon/interior spawn policy. 0 disables natural spawns.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 5f), Array.Empty<object>())); MoonWeightOverrides = config.Bind<string>("Spawning", "MoonWeightOverrides", string.Empty, "Optional comma-separated base moon weights, e.g. Experimentation:8,Offense:15 or namespace:moon=12. Use 0 to disable a moon; unlisted moons keep authored defaults."); PowerLevel = config.Bind<float>("Spawning", "PowerLevel", 2.5f, new ConfigDescription("Indoor enemy power budget cost for Simon Says.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.5f, 20f), Array.Empty<object>())); ApproachSpeed = config.Bind<float>("Movement", "ApproachSpeed", 3.5f, new ConfigDescription("Movement speed while rolling toward the selected worker.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.1f, 20f), Array.Empty<object>())); RetreatDuration = config.Bind<float>("Movement", "RetreatDuration", 3f, new ConfigDescription("Seconds Simon stays in place after goodbye begins before vanishing in smoke.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.5f, 15f), Array.Empty<object>())); RoundsPerEncounter = config.Bind<int>("Abilities", "RoundsPerEncounter", 3, new ConfigDescription("Number of challenges issued during one encounter.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 8), Array.Empty<object>())); ComplianceWindowSeconds = config.Bind<float>("Abilities", "ComplianceWindowSeconds", 4f, new ConfigDescription("Seconds available to obey a command prefixed with 'Simon says'.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.75f, 30f), Array.Empty<object>())); TrapWindowSeconds = config.Bind<float>("Abilities", "TrapWindowSeconds", 0.85f, new ConfigDescription("Seconds after speech that an unprefixed command remains dangerous. Named actions are also judged while their words are spoken.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.5f, 30f), Array.Empty<object>())); SimonSaysChance = config.Bind<float>("Abilities", "SimonSaysChance", 0.6f, new ConfigDescription("Chance that a round is a genuine 'Simon says' command instead of a trap.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 1f), Array.Empty<object>())); TwoActionRoundChance = config.Bind<float>("Abilities", "TwoActionRoundChance", 0.5f, new ConfigDescription("Chance that a round requests two actions instead of one.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 1f), Array.Empty<object>())); BetweenRoundPause = config.Bind<float>("Abilities", "BetweenRoundPause", 0.05f, new ConfigDescription("Additional pause after a successful genuine command. Traps advance directly into the next command boundary cue.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 5f), Array.Empty<object>())); SpotlightLumens = config.Bind<float>("Audio and Presentation", "SpotlightLumens", 2000f, new ConfigDescription("HDRP spotlight brightness in lumens, following the selected player for them and everyone watching. 0 turns it off.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 20000f), Array.Empty<object>())); if (num.HasValue && SpotlightLumens.Value == 2000f) { SpotlightLumens.Value = num.Value; } SpotlightVolumetricDimmer = config.Bind<float>("Audio and Presentation", "SpotlightVolumetricDimmer", 1.5f, new ConfigDescription("Brightness multiplier of the spotlight's visible fog beam (HDRP volumetric lighting).", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 16f), Array.Empty<object>())); DebugLogs = config.Bind<bool>("Diagnostics", "DebugLogs", false, "Write verbose encounter and RPC diagnostics."); VanishSmokeForceHdrpShaders = config.Bind<bool>("Diagnostics", "VanishSmokeForceHdrpShaders", false, "Force fallback HDRP particle shaders when intact source materials render incorrectly."); } } } internal static class SimonSaysConfigMigration { private static readonly ConfigDefinition LegacySpawnWeight = new ConfigDefinition("Spawning", "SpawnWeight"); private static readonly ConfigDefinition RetiredSpotlightIntensity = new ConfigDefinition("Audio and Presentation", "SpotlightIntensity"); private const string AbsentSentinel = "\0absent"; private static readonly LegacyMigrationSpec Spec = new LegacyMigrationSpec("SimonSays", (IReadOnlyList<ConfigDefinition>)(object)new ConfigDefinition[1] { LegacySpawnWeight }, new string[4] { "Visuals", "Behavior", "Encounter", "Detection" }, new Dictionary<ConfigDefinition, string> { { new ConfigDefinition("Movement", "StoppingDistance"), "3.5" }, { new ConfigDefinition("Encounter", "WordGapSeconds"), "0.06" }, { new ConfigDefinition("Detection", "TurnAroundYawDegrees"), "150" }, { new ConfigDefinition("Detection", "AllowTurnAroundInTrapRounds"), "false" } }, Build); internal static bool TryMigrate(ConfigFile config, ManualLogSource log) { return LegacyConfigMigrator.TryMigrate(config, log, Spec); } internal static float? RetireSpotlightIntensity(ConfigFile config, ManualLogSource log) { string value = config.Bind<string>(RetiredSpotlightIntensity, "\0absent", (ConfigDescription)null).Value; config.Remove(RetiredSpotlightIntensity); if (value == "\0absent") { return null; } if (log != null) { log.LogInfo((object)("[SimonSays] Removed retired setting Audio and Presentation.SpotlightIntensity = " + value + "; SpotlightLumens now uses HDRP lumens.")); } if (!float.TryParse(value, NumberStyles.Float, CultureInfo.InvariantCulture, out var result) || float.IsNaN(result) || result == 24f) { return null; } return MapSpotlightIntensityToLumens(result); } internal static float MapSpotlightIntensityToLumens(float intensity) { if (float.IsNaN(intensity)) { return 2000f; } double val = Math.Round((double)intensity / 24.0 * 2000.0); return (float)Math.Max(0.0, Math.Min(20000.0, val)); } private static void Build(LegacyConfigValues values, MigratedConfigWriter output) { //IL_0081: Unknown result type (might be due to invalid IL or missing references) //IL_0087: Expected O, but got Unknown //IL_00a9: Unknown result type (might be due to invalid IL or missing references) //IL_00af: Expected O, but got Unknown //IL_00d1: Unknown result type (might be due to invalid IL or missing references) //IL_00d7: Expected O, but got Unknown //IL_00f9: Unknown result type (might be due to invalid IL or missing references) //IL_00ff: Expected O, but got Unknown //IL_0121: Unknown result type (might be due to invalid IL or missing references) //IL_0127: Expected O, but got Unknown //IL_0149: Unknown result type (might be due to invalid IL or missing references) //IL_014f: Expected O, but got Unknown //IL_0171: Unknown result type (might be due to invalid IL or missing references) //IL_0177: Expected O, but got Unknown //IL_0199: Unknown result type (might be due to invalid IL or missing references) //IL_019f: Expected O, but got Unknown //IL_01eb: Unknown result type (might be due to invalid IL or missing references) //IL_01f1: Expected O, but got Unknown //IL_0213: Unknown result type (might be due to invalid IL or missing references) //IL_0219: Expected O, but got Unknown output.Carry("General", "Enabled"); output.CarrySpawnWeightMultiplier(LegacySpawnWeight, 30f); output.Carry("Spawning", "MoonWeightOverrides"); output.Carry("Spawning", "PowerLevel"); output.Carry("Movement", "ApproachSpeed"); output.Carry("Movement", "RetreatDuration", new ConfigDefinition("Behavior", "RetreatDuration")); output.Carry("Abilities", "RoundsPerEncounter", new ConfigDefinition("Encounter", "RoundsPerEncounter")); output.Carry("Abilities", "ComplianceWindowSeconds", new ConfigDefinition("Encounter", "ComplianceWindowSeconds")); output.Carry("Abilities", "TrapWindowSeconds", new ConfigDefinition("Encounter", "TrapWindowSeconds")); output.Carry("Abilities", "SimonSaysChance", new ConfigDefinition("Encounter", "SimonSaysChance")); output.Carry("Abilities", "TwoActionRoundChance", new ConfigDefinition("Encounter", "TwoActionRoundChance")); output.Carry("Abilities", "BetweenRoundPause", new ConfigDefinition("Encounter", "BetweenRoundPause")); output.Carry("Audio and Presentation", "SpotlightIntensity", new ConfigDefinition("Visuals", "SpotlightIntensity")); output.Carry("Audio and Presentation", "SpotlightLumens"); output.Carry("Audio and Presentation", "SpotlightVolumetricDimmer"); output.Carry("Diagnostics", "DebugLogs", new ConfigDefinition("Behavior", "DebugLogs")); output.Carry("Diagnostics", "VanishSmokeForceHdrpShaders", new ConfigDefinition("Visuals", "VanishSmokeForceHdrpShaders")); } } internal sealed class SimonSaysSpawnWeights : ContextualSpawnWeights { internal SimonSaysSpawnWeights(Func<float> multiplier, Func<string> moonOverrides, Action<string> logWarning) : base(SpawnWeightTable.SimonSays, "Simon Says", multiplier, moonOverrides, logWarning) { } } internal static class SimonSaysTuning { internal const int MaxCount = 1; internal const float StoppingDistance = 3.5f; internal const float ApproachBudgetSeconds = 25f; internal const float ApproachPathFailureGraceSeconds = 1f; internal const float ApproachCooldownSeconds = 30f; internal const float WordGapSeconds = 0.04f; internal const float CommandBoundarySeconds = 0.2f; internal const float IntroPause = 1.2f; internal const float FinalJudgmentPause = 0.55f; internal const float CongratulationsPause = 0.9f; internal const float ReportGrace = 2.5f; internal const float TurnAroundYawDegrees = 150f; internal const bool AllowTurnAroundInTrapRounds = false; internal const float SpotlightConeDegrees = 20f; internal const float DefaultSpotlightLumens = 2000f; internal const float MaxSpotlightLumens = 20000f; internal const float DefaultSpotlightVolumetricDimmer = 1.5f; internal const float AudioSpatialBlend = 1f; internal const float AudioMinDistance = 2f; internal const float AudioMaxDistance = 35f; internal const float AudioSpread = 0f; internal const float PunishHoldSeconds = 1.5f; internal const float PunishBlackoutSeconds = 0.3f; internal const float VanishVisibleSeconds = 0.3f; internal const float VanishFadeSeconds = 1.5f; internal const float VanishSinkMetres = 0.5f; internal const float VanishEndScale = 0.7f; internal const float DespawnRpcGraceSeconds = 0.4f; internal const float VanishSmokeLifetimeSeconds = 3f; internal const float VanishSmokeFadeInSeconds = 0.1f; internal const float VanishSmokeUnlitBrightness = 1.5f; internal const float PoofLightLumens = 1500f; internal const float PoofLightFadeSeconds = 0.3f; internal const float PoofLightRangeMetres = 4f; internal const float PoofLightColorR = 1f; internal const float PoofLightColorG = 0.75f; internal const float PoofLightColorB = 0.45f; } } namespace SimonSays.Utils { public static class CreatureAudio { public static void StartLoop(AudioSource source, AudioClip clip) { if (!((Object)(object)source == (Object)null) && !((Object)(object)clip == (Object)null) && (!source.isPlaying || !((Object)(object)source.clip == (Object)(object)clip))) { source.loop = true; source.clip = clip; source.Play(); } } public static void StopLoop(AudioSource source) { if (!((Object)(object)source == (Object)null) && source.isPlaying) { source.Stop(); source.clip = null; } } } } namespace SimonSays.AI { public static class BlackHoleEffect { public static void BeginFor(PlayerControllerB player) { //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Unknown result type (might be due to invalid IL or missing references) //IL_0039: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)player == (Object)null || player.isPlayerDead || !player.isPlayerControlled) { return; } try { SimonSaysBloodFxBridge.RequestGib(player, "SimonSays", 1); player.KillPlayer(Vector3.zero, true, (CauseOfDeath)2, 0, default(Vector3), false); } catch (Exception arg) { Plugin.Log.LogError((object)$"BlackHoleEffect.BeginFor: {arg}"); } } } internal static class SimonCommandAudio { internal sealed class Sentence { internal AudioClip Clip; internal float FirstAt; internal float SecondAt; } private const int Rate = 44100; private static readonly Dictionary<int, Sentence> Cache = new Dictionary<int, Sentence>(); internal static Sentence Build(SimonRound round) { //IL_0139: Unknown result type (might be due to invalid IL or missing references) int key = round.Pack(); if (Cache.TryGetValue(key, out var value) && (Object)(object)value.Clip != (Object)null) { return value; } List<AudioClip> list = SimonSaysWords.BuildUtterance(round); float num = 0.04f; float num2 = 0.2f + SimonSaysWords.SequenceLength(list, num); float num3 = 0.2f + (round.SimonSaid ? (Plugin.SimonSaysWordClip.length + num) : 0f); float secondAt = (round.HasSecond ? (num3 + Plugin.ActionClip(round.First).length + num + ((round.Connector == RoundConnector.Then) ? Plugin.ThenClip.length : Plugin.AndClip.length) + num) : float.PositiveInfinity); float[] array = new float[Mathf.CeilToInt(num2 * 44100f)]; for (int i = 0; i < Mathf.Min(array.Length, 5733); i++) { float num4 = (float)i / 44100f; array[i] = Tick(num4, 0.22f) + ((num4 >= 0.018f) ? Tick(num4 - 0.018f, 0.12f) : 0f); } float num5 = 0.2f; foreach (AudioClip item in list) { if ((int)item.loadState == 0) { item.LoadAudioData(); } float[] array2 = new float[item.samples * item.channels]; if (!item.GetData(array2, 0)) { throw new InvalidOperationException("Cannot read Simon word PCM: " + ((Object)item).name); } int num6 = Mathf.RoundToInt(num5 * 44100f); int num7 = Mathf.RoundToInt(item.length * 44100f); for (int j = 0; j < num7 && num6 + j < array.Length; j++) { float num8 = (float)j * (float)item.frequency / 44100f; int num9 = Mathf.Min((int)num8, item.samples - 1); int num10 = Mathf.Min(num9 + 1, item.samples - 1); float num11 = 0f; for (int k = 0; k < item.channels; k++) { num11 += Mathf.Lerp(array2[num9 * item.channels + k], array2[num10 * item.channels + k], num8 - (float)num9); } array[num6 + j] = num11 / (float)item.channels; } num5 += item.length + num; } AudioClip val = AudioClip.Create("SimonCommand_" + key, array.Length, 1, 44100, false); val.SetData(array, 0); value = new Sentence { Clip = val, FirstAt = num3, SecondAt = secondAt }; Cache[key] = value; return value; } private static float Tick(float t, float volume) { float num = Mathf.Min(1f, t / 0.001f); return volume * num * Mathf.Exp((0f - t) * 75f) * (Mathf.Sin(MathF.PI * 3700f * t) + 0.3f * Mathf.Sin(MathF.PI * 6540f * t)); } } internal sealed class SimonCommandJudge { private int _previous; private int _eligible; private int _first; private int _second; private bool _hasSecond; private bool _ordered; private bool _simonSaid; private bool _firstDone; private bool _secondDone; public bool Complete { get; private set; } public bool Violated { get; private set; } public void Begin(int first, int second, bool hasSecond, bool ordered, bool simonSaid, int held) { _first = 1 << first; _second = 1 << second; _hasSecond = hasSecond; _ordered = ordered; _simonSaid = simonSaid; _previous = held; _eligible = 0; bool flag = (Violated = false); bool secondDone = (Complete = flag); _firstDone = (_secondDone = secondDone); } public void Activate(int action) { _eligible |= 1 << action; } public void Observe(int held) { int num = held & ~_previous & _eligible; _previous = held; if (Complete || Violated) { return; } if (!_simonSaid) { Violated = (num & (_first | (_hasSecond ? _second : 0))) != 0; return; } if ((num & _first) != 0) { _firstDone = true; } if (_hasSecond && (num & _second) != 0 && (!_ordered || _firstDone)) { _secondDone = true; } Complete = _firstDone && (!_hasSecond || _secondDone); } } [DisallowMultipleComponent] public sealed class SimonHeadLook : MonoBehaviour { private const float MinSqrMagnitude = 0.0001f; private SimonSaysAI _ai; private Transform _head; private Vector3 _headLocalForward; private Quaternion _animatedLocalRotation; private bool _poseApplied; private float _yaw; private float _pitch; private float _targetYaw; private float _targetPitch; private float _weight; private void Awake() { //IL_004f: Unknown result type (might be due to invalid IL or missing references) //IL_0054: Unknown result type (might be due to invalid IL or missing references) //IL_0059: Unknown result type (might be due to invalid IL or missing references) _ai = ((Component)this).GetComponent<SimonSaysAI>(); _head = FindHead(((Component)this).transform); if ((Object)(object)_head == (Object)null) { Plugin.Log.LogWarning((object)"[SimonSays] Head look disabled: prefab has no 'head' bone."); ((Behaviour)this).enabled = false; } else { _headLocalForward = _head.InverseTransformDirection(((Component)this).transform.forward); } } private void Update() { RestoreAnimatedPose(); } private void LateUpdate() { //IL_0053: Unknown result type (might be due to invalid IL or missing references) //IL_0058: Unknown result type (might be due to invalid IL or missing references) //IL_0060: Unknown result type (might be due to invalid IL or missing references) //IL_0065: Unknown result type (might be due to invalid IL or missing references) //IL_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_006c: Unknown result type (might be due to invalid IL or missing references) //IL_006d: Unknown result type (might be due to invalid IL or missing references) //IL_0072: Unknown result type (might be due to invalid IL or missing references) //IL_0094: Unknown result type (might be due to invalid IL or missing references) //IL_009f: Unknown result type (might be due to invalid IL or missing references) //IL_00a4: Unknown result type (might be due to invalid IL or missing references) //IL_00a9: Unknown result type (might be due to invalid IL or missing references) //IL_00ab: Unknown result type (might be due to invalid IL or missing references) //IL_00ad: Unknown result type (might be due to invalid IL or missing references) //IL_00ae: Unknown result type (might be due to invalid IL or missing references) //IL_00b3: Unknown result type (might be due to invalid IL or missing references) //IL_015b: Unknown result type (might be due to invalid IL or missing references) //IL_015c: Unknown result type (might be due to invalid IL or missing references) //IL_015e: Unknown result type (might be due to invalid IL or missing references) //IL_0163: Unknown result type (might be due to invalid IL or missing references) //IL_0167: Unknown result type (might be due to invalid IL or missing references) //IL_013a: Unknown result type (might be due to invalid IL or missing references) //IL_0146: Unknown result type (might be due to invalid IL or missing references) //IL_014b: Unknown result type (might be due to invalid IL or missing references) //IL_0150: Unknown result type (might be due to invalid IL or missing references) //IL_0154: Unknown result type (might be due to invalid IL or missing references) //IL_00d2: Unknown result type (might be due to invalid IL or missing references) //IL_00d4: Unknown result type (might be due to invalid IL or missing references) //IL_00d6: Unknown result type (might be due to invalid IL or missing references) //IL_00e2: Unknown result type (might be due to invalid IL or missing references) //IL_00e3: Unknown result type (might be due to invalid IL or missing references) //IL_00e9: Unknown result type (might be due to invalid IL or missing references) //IL_00eb: Unknown result type (might be due to invalid IL or missing references) //IL_016c: Unknown result type (might be due to invalid IL or missing references) //IL_0174: Unknown result type (might be due to invalid IL or missing references) //IL_0175: Unknown result type (might be due to invalid IL or missing references) //IL_0181: Unknown result type (might be due to invalid IL or missing references) //IL_0183: Unknown result type (might be due to invalid IL or missing references) //IL_0188: Unknown result type (might be due to invalid IL or missing references) //IL_018d: Unknown result type (might be due to invalid IL or missing references) //IL_0196: Unknown result type (might be due to invalid IL or missing references) //IL_019b: Unknown result type (might be due to invalid IL or missing references) //IL_01ad: Unknown result type (might be due to invalid IL or missing references) //IL_01b5: Unknown result type (might be due to invalid IL or missing references) //IL_01ba: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)_ai == (Object)null || (Object)(object)_head == (Object)null) { return; } Transform headLookTarget = _ai.HeadLookTarget; float deltaTime = Time.deltaTime; _weight = SimonHeadLookLogic.StepWeight(_weight, (Object)(object)headLookTarget != (Object)null, deltaTime); Vector3 up = ((Component)_ai).transform.up; Vector3 val = _head.TransformDirection(_headLocalForward); Vector3 val2 = Vector3.ProjectOnPlane(val, up); bool flag = ((Vector3)(ref val2)).sqrMagnitude >= 0.0001f; if ((Object)(object)headLookTarget != (Object)null && flag) { Vector3 val3 = headLookTarget.position - _head.position; Vector3 val4 = Vector3.ProjectOnPlane(val3, up); if (((Vector3)(ref val3)).sqrMagnitude >= 0.0001f && ((Vector3)(ref val4)).sqrMagnitude >= 0.0001f) { _targetYaw = Vector3.SignedAngle(val2, val4, up); _targetPitch = Vector3.Angle(val, up) - Vector3.Angle(val3, up); } } SimonHeadLookLogic.StepAppliedAngles(ref _yaw, ref _pitch, _targetYaw, _targetPitch, _weight, deltaTime); if (_yaw != 0f || _pitch != 0f) { Vector3 val5; Vector3 normalized; if (!flag) { val5 = Vector3.Cross(up, ((Component)_ai).transform.forward); normalized = ((Vector3)(ref val5)).normalized; } else { val5 = Vector3.Cross(up, val2); normalized = ((Vector3)(ref val5)).normalized; } Vector3 val6 = normalized; Quaternion val7 = Quaternion.AngleAxis(_yaw, up) * Quaternion.AngleAxis(0f - _pitch, val6); _animatedLocalRotation = _head.localRotation; _poseApplied = true; _head.rotation = val7 * _head.rotation; } } private void OnDisable() { RestoreAnimatedPose(); _yaw = 0f; _pitch = 0f; _targetYaw = 0f; _targetPitch = 0f; _weight = 0f; } private void RestoreAnimatedPose() { //IL_001d: Unknown result type (might be due to invalid IL or missing references) if (_poseApplied && (Object)(object)_head != (Object)null) { _head.localRotation = _animatedLocalRotation; } _poseApplied = false; } private static Transform FindHead(Transform root) { if (((Object)root).name == "head") { return root; } for (int i = 0; i < root.childCount; i++) { Transform val = FindHead(root.GetChild(i)); if ((Object)(object)val != (Object)null) { return val; } } return null; } } internal static class SimonHeadLookLogic { internal const float MaxYaw = 75f; internal const float MaxPitchDown = 35f; internal const float MaxPitchUp = 25f; internal const float DegreesPerSecond = 120f; internal const float FadeSeconds = 0.25f; internal static float ClampYaw(float yaw) { return Math.Max(-75f, Math.Min(75f, yaw)); } internal static float ClampPitch(float pitch) { return Math.Max(-35f, Math.Min(25f, pitch)); } internal static void StepAppliedAngles(ref float yaw, ref float pitch, float targetYaw, float targetPitch, float weight, float deltaTime) { float num = AppliedWeight(weight); float num2 = ClampYaw(targetYaw) * num; float num3 = ClampPitch(targetPitch) * num; float num4 = num2 - yaw; float num5 = num3 - pitch; float num6 = num4 * num4 + num5 * num5; float num7 = 120f * Math.Max(0f, deltaTime); if (num6 <= num7 * num7) { yaw = num2; pitch = num3; } else { float num8 = (float)((double)num7 / Math.Sqrt(num6)); yaw += num4 * num8; pitch += num5 * num8; } } internal static float StepWeight(float current, bool hasTarget, float deltaTime) { current = Math.Max(0f, Math.Min(1f, current)); return MoveTowards(current, hasTarget ? 1f : 0f, Math.Max(0f, deltaTime) / 0.25f); } internal static float AppliedWeight(float weight) { weight = Math.Max(0f, Math.Min(1f, weight)); return weight * weight * (3f - 2f * weight); } private static float MoveTowards(float current, float target, float maxDelta) { float value = target - current; if (!(Math.Abs(value) <= maxDelta)) { return current + (float)Math.Sign(value) * maxDelta; } return target; } } public enum SimonState { ROAMING, APPROACHING, INTRO, COMMANDING, JUDGING, PUNISHING, CELEBRATING, DEPARTING } public class SimonSaysAI : EnemyAI { private struct VanishTint { public Renderer Renderer; public int Slot; public bool HasBase; public Color Base; public bool HasEmissive; public Color Emissive; } private struct VanishPart { public Transform Transform; public Vector3 Position; public Vector3 Scale; } private sealed class VanishFade { internal VanishTint[] Tints; internal VanishPart[] Parts; internal Vector3 SinkLocal; internal readonly MaterialPropertyBlock Block = new MaterialPropertyBlock(); } private AudioSource _sfxSource; private AudioSource _voiceSource; private const float VoiceVolume = 1.35f; private const float SfxVolume = 1.15f; private const float FocusLeadIn = 0.8f; public AudioClip wheelsRollLoopClip; public AudioClip jesterSwingClip; public AudioSource loopSource; private bool _wheelsLoopDesired; private Coroutine _stateCoroutine; private Coroutine _speechCoroutine; private bool _encounterStarted; private bool _encounterFinished; private int _targetPlayerSlot = -1; private bool _hasTarget; private float _approachStartedAt; private float _pathFailingSince = -1f; private float[] _approachCooldownUntil; private readonly NetworkVariable<int> _targetSlot = new NetworkVariable<int>(-1, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); private SimonTargetSlotLogic.Presentation _presentation = SimonTargetSlotLogic.Initial; private readonly NoiseMemory _noiseMemory = new NoiseMemory(); private float _nextNoiseReseedTime; private const float NoiseMinLoudness = 0.5f; private const float NoiseHearingRange = 20f; private const float NoiseMemorySeconds = 3f; private const float NoiseReseedCooldown = 4f; private const int NoiseMaxRepeatsInOneSpot = 10; private const float SightWidth = 70f; private const float SightRange = 30f; private readonly ServerOwnershipGuard _ownership = new ServerOwnershipGuard(); private bool _audioRouted; private int _awaitingRoundIndex = -1; private bool _roundReported; private bool _roundComplied; private bool _roundImplausible; private float _roundBegan; private float _roundSpeechSeconds; private float _roundWindow; private bool _roundSimonSaid; private const float ReportClockTolerance = 0.25f; private bool _judging; private SimonRound _judgeRound; private int _judgeRoundIndex = -1; private bool _judgeReported; private readonly SimonCommandJudge _inputJudge = new SimonCommandJudge(); private PlayerControllerB _judgedPlayer; private SimonCommandAudio.Sentence _localSentence; private double _speechStartedAt; private bool _firstActivated; private bool _secondActivated; private bool _jumpLatched; private bool _vanished; private float _yawNet; private float _lastYaw; private bool _turnAroundFired; private SpotlightController _observerSpotlight; private static readonly Color PunishSpotlightColor = new Color(1f, 0.06f, 0.04f); private static readonly int BaseColorId = Shader.PropertyToID("_BaseColor"); private static readonly int EmissiveColorId = Shader.PropertyToID("_EmissiveColor"); private bool _punishKillSent; private bool _punishKillApplied; private Vector3 _lastAnimPosition; private bool _animInitialized; private float _smoothedSpeed; private bool _walkAnimOn; private static SimonSaysConfig Cfg => Plugin.ModConfig; private float ApproachSpeed => Cfg?.ApproachSpeed?.Value ?? 3.5f; private float StoppingDist => 3.5f; private float RetreatDuration => Cfg?.RetreatDuration?.Value ?? 3f; private bool DebugLogs => Cfg?.DebugLogs?.Value == true; private float SpotlightLumens => Cfg?.SpotlightLumens?.Value ?? 2000f; private float SpotlightVolumetricDimmer => Cfg?.SpotlightVolumetricDimmer?.Value ?? 1.5f; private float WordGap => 0.04f; internal Transform HeadLookTarget { get { if (!((Behaviour)this).isActiveAndEnabled || base.isEnemyDead || _vanished || !_presentation.Presents || base.currentBehaviourStateIndex >= 7) { return null; } PlayerControllerB val = VictimRpc.FromSlot(_presentation.Slot); if ((Object)(object)val == (Object)null || val.isPlayerDead || (Object)(object)val.gameplayCamera == (Object)null) { return null; } return ((Component)val.gameplayCamera).transform; } } internal AudioSource VoiceSource { get { if (!((Object)(object)_voiceSource != (Object)null)) { return base.creatureVoice; } return _voiceSource; } } private void DLog(string m) { if (DebugLogs) { Plugin.Log.LogInfo((object)("[SimonSays] " + m)); } } private static float ClipLen(AudioClip c) { if (!((Object)(object)c != (Object)null)) { return 0f; } return c.length; } public override void Awake() { try { ((EnemyAI)this).Awake(); Transform val = ((Component)this).transform.Find("CreatureSFX"); if ((Object)(object)val != (Object)null) { _sfxSource = ((Component)val).GetComponent<AudioSource>(); } Transform val2 = ((Component)this).transform.Find("CreatureVoice"); if ((Object)(object)val2 != (Object)null) { _voiceSource = ((Component)val2).GetComponent<AudioSource>(); } if ((Object)(object)base.creatureSFX == (Object)null && (Object)(object)_sfxSource != (Object)null) { base.creatureSFX = _sfxSource; } if ((Object)(object)base.creatureVoice == (Object)null && (Object)(object)_voiceSource != (Object)null) { base.creatureVoice = _voiceSource; } if ((Object)(object)_sfxSource == (Object)null) { _sfxSource = base.creatureSFX; } if ((Object)(object)_voiceSource == (Object)null) { _voiceSource = base.creatureVoice; } if ((Object)(object)base.creatureAnimator == (Object)null) { base.creatureAnimator = ((Component)this).GetComponent<Animator>(); } if ((Object)(object)base.eye == (Object)null) { Transform val3 = ((Component)this).transform.Find("Eye"); if ((Object)(object)val3 != (Object)null) { base.eye = val3; } } ConfigureVoiceMix(); } catch (Exception arg) { Plugin.Log.LogError((object)$"SimonSaysAI.Awake: {arg}"); } } public override void Start() { //IL_00c6: Unknown result type (might be due to invalid IL or missing references) //IL_00cb: Unknown result type (might be due to invalid IL or missing references) try { ((EnemyAI)this).Start(); Plugin.EnsureScanNode(((Component)this).gameObject); ConfigureVoiceMix(); _audioRouted = RouteAudioSources(); if ((Object)(object)base.agent != (Object)null) { base.agent.speed = ApproachSpeed; base.agent.stoppingDistance = 0f; if (base.agent.areaMask == 0) { base.agent.areaMask = -1; } base.agent.autoTraverseOffMeshLink = true; if (base.openDoorSpeedMultiplier <= 0f) { base.openDoorSpeedMultiplier = (((Object)(object)base.enemyType != (Object)null && base.enemyType.doorSpeedMultiplier > 0f) ? base.enemyType.doorSpeedMultiplier : 1f); } } _lastAnimPosition = ((Component)this).transform.position; _animInitialized = true; if (((NetworkBehaviour)this).IsServer) { ((EnemyAI)this).SwitchToBehaviourClientRpc(0); } DLog($"spawned. IsServer={((NetworkBehaviour)this).IsServer} agentOnNavMesh={(Object)(object)base.agent != (Object)null && base.agent.isOnNavMesh} " + $"areaMask={(((Object)(object)base.agent != (Object)null) ? base.agent.areaMask : 0)} doorSpeed={base.openDoorSpeedMultiplier}"); if (((NetworkBehaviour)this).IsServer && (Object)(object)RoundManager.Instance != (Object)null && (Object)(object)base.enemyType != (Object)null) { DLog($"inside enemy power with Simon spawned: {RoundManager.Instance.currentEnemyPower} (PowerLevel {base.enemyType.PowerLevel})"); } } catch (Exception arg) { Plugin.Log.LogError((object)$"SimonSaysAI.Start: {arg}"); } } public override void OnNetworkSpawn() { ((NetworkBehaviour)this).OnNetworkSpawn(); try { NetworkVariable<int> targetSlot = _targetSlot; targetSlot.OnValueChanged = (OnValueChangedDelegate<int>)(object)Delegate.Combine((Delegate?)(object)targetSlot.OnValueChanged, (Delegate?)(object)new OnValueChangedDelegate<int>(OnTargetSlotChanged)); OnTargetSlotChanged(-1, _targetSlot.Value); } catch (Exception arg) { Plugin.Log.LogError((object)$"SimonSaysAI.OnNetworkSpawn: {arg}"); } } public override void OnNetworkDespawn() { try { NetworkVariable<int> targetSlot = _targetSlot; targetSlot.OnValueChanged = (OnValueChangedDelegate<int>)(object)Delegate.Remove((Delegate?)(object)targetSlot.OnValueChanged, (Delegate?)(object)new OnValueChangedDelegate<int>(OnTargetSlotChanged)); EndPresentation(); } catch (Exception arg) { Plugin.Log.LogError((object)$"SimonSaysAI.OnNetworkDespawn: {arg}"); } ((NetworkBehaviour)this).OnNetworkDespawn(); } public override void Update() { //IL_005a: Unknown result type (might be due to invalid IL or missing references) //IL_005f: Unknown result type (might be due to invalid IL or missing references) try { _ownership.Ensure((EnemyAI)(object)this, Plugin.Log); if (_vanished) { return; } ((EnemyAI)this).Update(); if (!_audioRouted) { _audioRouted = RouteAudioSources(); } UpdateWalkAnimation(); if (((NetworkBehaviour)this).IsServer) { int num; if ((Object)(object)base.agent != (Object)null) { Vector3 velocity = base.agent.velocity; num = ((((Vector3)(ref velocity)).sqrMagnitude > 0.01f) ? 1 : 0); } else { num = 0; } bool flag = (byte)num != 0; if (flag != _wheelsLoopDesired) { _wheelsLoopDesired = flag; SetWheelsLoopClientRpc(flag); } } } catch (Exception arg) { Plugin.Log.LogError((object)$"SimonSaysAI.Update: {arg}"); } } private void UpdateWalkAnimation() { //IL_0036: 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_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_005a: Unknown result type (might be due to invalid IL or missing references) //IL_005f: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)base.creatureAnimator == (Object)null) { return; } if (!_animInitialized) { _lastAnimPosition = ((Component)this).transform.position; _animInitialized = true; return; } Vector3 val = ((Component)this).transform.position - _lastAnimPosition; val.y = 0f; _lastAnimPosition = ((Component)this).transform.position; float num = ((Time.deltaTime > 0f) ? (((Vector3)(ref val)).magnitude / Time.deltaTime) : 0f); _smoothedSpeed = Mathf.Lerp(_smoothedSpeed, num, 1f - Mathf.Exp(-8f * Time.deltaTime)); if (_walkAnimOn && _smoothedSpeed < 0.1f) { _walkAnimOn = false; } else if (!_walkAnimOn && _smoothedSpeed > 0.22f) { _walkAnimOn = true; } base.creatureAnimator.SetBool("isWalking", _walkAnimOn); } public override void DoAIInterval() { try { if (_vanished) { return; } ((EnemyAI)this).DoAIInterval(); if (((NetworkBehaviour)this).IsServer && !((Object)(object)StartOfRound.Instance == (Object)null) && !StartOfRound.Instance.allPlayersDead && !_encounterFinished) { switch ((SimonState)base.currentBehaviourStateIndex) { case SimonState.ROAMING: DoRoaming(); break; case SimonState.APPROACHING: DoApproaching(); break; } } } catch (Exception arg) { Plugin.Log.LogError((object)$"SimonSaysAI.DoAIInterval: {arg}"); } } public override void HitEnemy(int force = 1, PlayerControllerB playerWhoHit = null, bool playHitSFX = false, int hitID = -1) { try { if (playHitSFX && !_vanished) { CreatureAudioSetup.TransmitOneShot(base.creatureSFX, jesterSwingClip, 1.15f); } } catch (Exception arg) { Plugin.Log.LogError((object)$"SimonSaysAI.HitEnemy: {arg}"); } } public override void KillEnemy(bool destroy = false) { try { if (((NetworkBehaviour)this).IsServer) { StopEncounterRoutine(); WriteTargetSlot(SimonTargetSlotLogic.HostEvent.SimonDeath); } CleanupEffects(); if (destroy && (Object)(object)base.enemyType != (Object)null && base.enemyType.canBeDestroyed) { ((EnemyAI)this).KillEnemy(true); } else if (((NetworkBehaviour)this).IsServer) { DespawnSelf(); } } catch (Exception arg) { Plugin.Log.LogError((object)$"SimonSaysAI.KillEnemy: {arg}"); } } public override void DetectNoise(Vector3 noisePosition, float noiseLoudness, int timesPlayedInOneSpot = 0, int noiseID = 0) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0057: Unknown result type (might be due to invalid IL or missing references) //IL_005f: Unknown result type (might be due to invalid IL or missing references) try { ((EnemyAI)this).DetectNoise(noisePosition, noiseLoudness, timesPlayedInOneSpot, noiseID); if (((NetworkBehaviour)this).IsServer && !_vanished && !_encounterFinished && timesPlayedInOneSpot <= 10 && base.currentBehaviourStateIndex == 0) { Transform val = (((Object)(object)base.eye != (Object)null) ? base.eye : ((Component)this).transform); _noiseMemory.Record(noisePosition, noiseLoudness, 0.5f, val.position, 20f); } } catch (Exception arg) { Plugin.Log.LogError((object)$"SimonSaysAI.DetectNoise: {arg}"); } } private void DoRoaming() { //IL_0075: Unknown result type (might be due to invalid IL or missing references) if (!((Object)(object)base.agent == (Object)null) && !_hasTarget) { base.agent.speed = ApproachSpeed; base.agent.stoppingDistance = 0f; PlayerControllerB val = FindTargetInSight(); if ((Object)(object)val != (Object)null) { BeginApproach(val); } else if (!TryReseedSearchAtNoise() && (base.currentSearch == null || !base.currentSearch.inProgress)) { ((EnemyAI)this).StartSearch(((Component)this).transform.position, (AISearchRoutine)null); } } } private PlayerControllerB FindTargetInSight() { //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_0031: Unknown result type (might be due to invalid IL or missing references) //IL_007d: Unknown result type (might be due to invalid IL or missing references) //IL_0082: Unknown result type (might be due to invalid IL or missing references) //IL_0084: Unknown result type (might be due to invalid IL or missing references) //IL_0086: Unknown result type (might be due to invalid IL or missing references) //IL_0087: Unknown result type (might be due to invalid IL or missing references) //IL_008c: Unknown result type (might be due to invalid IL or missing references) //IL_00a2: Unknown result type (might be due to invalid IL or missing references) //IL_00a7: Unknown result type (might be due to invalid IL or missing references) //IL_00b5: Unknown result type (might be due to invalid IL or missing references) //IL_00b6: Unknown result type (might be due to invalid IL or missing references) //IL_00c1: Unknown result type (might be due to invalid IL or missing references) //IL_00c3: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)base.eye == (Object)null) { return null; } PlayerControllerB[] allPlayerScripts = StartOfRound.Instance.allPlayerScripts; int collidersAndRoomMaskAndDefault = StartOfRound.Instance.collidersAndRoomMaskAndDefault; Vector3 position = base.eye.position; foreach (PlayerControllerB val in allPlayerScripts) { if (!((Object)(object)val == (Object)null) && !((Object)(object)val.gameplayCamera == (Object)null) && ((EnemyAI)this).PlayerIsTargetable(val, false, false, true) && !OnApproachCooldown(val)) { Vector3 position2 = ((Component)val.gameplayCamera).transform.position; Vector3 val2 = position2 - position; if (!(((Vector3)(ref val2)).sqrMagnitude >= 900f) && !(Vector3.Angle(base.eye.forward, val2) >= 70f) && !Physics.Linecast(position, position2, collidersAndRoomMaskAndDefault, (QueryTriggerInteraction)1) && !Physics.Linecast(position2, position, collidersAndRoomMaskAndDefault, (QueryTriggerInteraction)1)) { return val; } } } return null; } private bool TryReseedSearchAtNoise() { //IL_0044: Unknown result type (might be due to invalid IL or missing references) if (Time.time < _nextNoiseReseedTime) { return false; } if (!_noiseMemory.TryTake(3f, out var position)) { return false; } _nextNoiseReseedTime = Time.time + 4f; ((EnemyAI)this).StopSearch(base.currentSearch, true); ((EnemyAI)this).StartSearch(position, base.currentSearch); return true; } private void BeginApproach(PlayerControllerB player) { ((EnemyAI)this).StopSearch(base.currentSearch, true); _noiseMemory.Clear(); _targetPlayerSlot = (int)player.playerClientId; _hasTarget = true; base.targetPlayer = player; _approachStartedAt = Time.time; _pathFailingSince = -1f; DLog("acquired target " + player.playerUsername); SetTargetPlayerClientRpc(_targetPlayerSlot); ((EnemyAI)this).SwitchToBehaviourClientRpc(1); } private void DoApproaching() { //IL_0092: Unknown result type (might be due to invalid IL or missing references) //IL_00eb: Unknown result type (might be due to invalid IL or missing references) //IL_00fb: Unknown result type (might be due to invalid IL or missing references) if (_encounterStarted || !_hasTarget) { return; } if (!TargetStillValid() || !((EnemyAI)this).PlayerIsTargetable(base.targetPlayer, false, false, true)) { AbandonApproach("target is no longer targetable"); } else if (Time.time - _approachStartedAt > 25f) { AbandonApproach("approach budget spent"); } else { if ((Object)(object)base.agent == (Object)null) { return; } base.agent.speed = ApproachSpeed; base.agent.stoppingDistance = StoppingDist; if (((EnemyAI)this).SetDestinationToPosition(((Component)base.targetPlayer).transform.position, true)) { _pathFailingSince = -1f; } else if (_pathFailingSince < 0f) { _pathFailingSince = Time.time; } else if (Time.time - _pathFailingSince >= 1f) { AbandonApproach("no path to the target"); return; } if (!(Vector3.Distance(((Component)this).transform.position, ((Component)base.targetPlayer).transform.position) > StoppingDist)) { _encounterStarted = true; if (base.currentSearch != null && base.currentSearch.inProgress) { ((EnemyAI)this).StopSearch(base.currentSearch, true); } HoldStationForEncounter(); _stateCoroutine = ((MonoBehaviour)this).StartCoroutine(EncounterRoutine()); } } } private void AbandonApproach(string reason) { DLog("giving up the approach: " + reason); if ((Object)(object)base.targetPlayer != (Object)null) { StartApproachCooldown(base.targetPlayer); } _hasTarget = false; base.targetPlayer = null; _targetPlayerSlot = -1; WriteTargetSlot(SimonTargetSlotLogic.HostEvent.Abort); if ((Object)(object)base.agent != (Object)null) { base.agent.stoppingDistance = 0f; } ClearTargetPlayerClientRpc(); ((EnemyAI)this).SwitchToBehaviourClientRpc(0); } private void StartApproachCooldown(PlayerControllerB player) { PlayerControllerB[] allPlayerScripts = StartOfRound.Instance.allPlayerScripts; if (_approachCooldownUntil == null || _approachCooldownUntil.Length != allPlayerScripts.Length) { _approachCooldownUntil = new float[allPlayerScripts.Length]; } int num = (int)player.playerClientId; if (num >= 0 && num < _approachCooldownUntil.Length) { _approachCooldownUntil[num] = Time.time + 30f; } } private bool OnApproachCooldown(PlayerControllerB player) { int num = (int)player.playerClientId; if (_approachCooldownUntil != null && num >= 0 && num < _approachCooldownUntil.Length) { return Time.time < _approachCooldownUntil[num]; } return false; } private void HoldStationForEncounter() { //IL_0048: Unknown result type (might be due to invalid IL or missing references) base.movingTowardsTargetPlayer = false; base.moveTowardsDestination = false; if (!((Object)(object)base.agent == (Object)null) && ((Behaviour)base.agent).enabled && base.agent.isOnNavMesh) { base.agent.ResetPath(); base.agent.velocity = Vector3.zero; base.agent.isStopped = true; } } private bool TargetStillValid() { if (_hasTarget && (Object)(object)base.targetPlayer != (Object)null && !base.targetPlayer.isPlayerDead && base.targetPlayer.isPlayerControlled && base.targetPlayer.isInsideFactory == !base.isOutside) { if (((NetworkBehaviour)this).IsServer) { if ((Object)(object)((NetworkBehaviour)this).NetworkManager != (Object)null) { return ((NetworkBehaviour)this).NetworkManager.ConnectedClients.ContainsKey(base.targetPlayer.actualClientId); } return false; } return true; } return false; } private IEnumerator WaitWhileTargetValid(float seconds) { float until = Time.time + seconds; while (Time.time < until && TargetStillValid()) { yield return null; } } private void FaceTarget() { //IL_001a: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_0050: Unknown result type (might be due to invalid IL or missing references) //IL_0051: Unknown result type (might be due to invalid IL or missing references) if (!((Object)(object)base.targetPlayer == (Object)null)) { Vector3 val = ((Component)base.targetPlayer).transform.position - ((Component)this).transform.position; val.y = 0f; if (((Vector3)(ref val)).sqrMagnitude > 0.01f) { ((Component)this).transform.rotation = Quaternion.LookRotation(val); } } } private IEnumerator EncounterRoutine() { FaceTarget(); ((EnemyAI)this).SwitchToBehaviourClientRpc(2); WriteTargetSlot(SimonTargetSlotLogic.HostEvent.FocusStart); BeginFocusClientRpc(_targetPlayerSlot); yield return WaitWhileTargetValid(0.8f); if (TargetStillValid()) { PlayIntroClientRpc(); yield return WaitWhileTargetValid(ClipLen(Plugin.LetsPlayClip) + 1.2f); } int rounds = ((Cfg != null) ? Cfg.Rounds : 3); List<SimonRound> sequence = new List<SimonRound>(rounds); for (int i = 0; i < 32; i++) { sequence.Clear(); bool flag = false; bool flag2 = false; for (int j = 0; j < rounds; j++) { SimonRound item = SimonSaysWords.Roll((Cfg != null) ? Cfg.SimonChance : 0.6f, (Cfg != null) ? Cfg.TwoActionChance : 0.5f, allowTurnAroundInTraps: false); sequence.Add(item); flag |= item.SimonSaid; flag2 |= !item.SimonSaid; } float num = ((Cfg != null) ? Cfg.SimonChance : 0.6f); if (rounds < 2 || num <= 0f || num >= 1f || (flag && flag2)) { break; } } float num2 = ((Cfg != null) ? Cfg.SimonChance : 0.6f); if (rounds > 1 && num2 > 0f && num2 < 1f) { bool flag3 = sequence.TrueForAll((SimonRound r) => r.SimonSaid); bool flag4 = sequence.TrueForAll((SimonRound r) => !r.SimonSaid); if (flag3 || flag4) { int index = Random.Range(0, rounds); sequence[index] = SimonSaysWords.Roll(flag3 ? 0f : 1f, (Cfg != null) ? Cfg.TwoActionChance : 0.5f, allowTurnAroundInTraps: false); } } for (int i2 = 0; i2 < rounds; i2++) { if (!TargetStillValid()) { EndFocusForAll(SimonTargetSlotLogic.HostEvent.TargetLost); yield return DepartRoutine(); yield break; } SimonRound round = sequence[i2]; float window = ((!round.SimonSaid) ? ((Cfg != null) ? Cfg.TrapWindow : 0.85f) : ((Cfg != null) ? Cfg.Window : 4f)); SimonCommandAudio.Sentence sentence = null; try { sentence = SimonCommandAudio.Build(round); } catch (Exception arg) { Plugin.Log.LogError((object)$"[SimonSays] Cannot compose command: {arg}"); } if (sentence == null) { EndFocusForAll(SimonTargetSlotLogic.HostEvent.Abort); yield return DepartRoutine(); yield break; } DLog($"round {i2 + 1}/{rounds}: {round}"); _awaitingRoundIndex = i2; SimonSaysAI simonSaysAI = this; SimonSaysAI simonSaysAI2 = this; SimonSaysAI simonSaysAI3 = this; bool roundComplied = false; simonSaysAI3._roundImplausible = false; simonSaysAI._roundReported = (simonSaysAI2._roundComplied = roundComplied); _roundSpeechSeconds = sentence.Clip.length; _roundWindow = window; _roundSimonSaid = round.SimonSaid; ((EnemyAI)this).SwitchToBehaviourClientRpc(3); float began = (_roundBegan = Time.realtimeSinceStartup); SpeakRoundClientRpc(round.Pack(), i2, window); bool judgingState = false; while (!_roundReported && Time.realtimeSinceStartup - began < sentence.Clip.length + window + 2.5f && TargetStillValid()) { if (!judgingState && Time.realtimeSinceStartup - began >= sentence.Clip.length) { judgingState = true; ((EnemyAI)this).SwitchToBehaviourClientRpc(4); } yield return null; } CloseWindowClientRpc(); _awaitingRoundIndex = -1; if (!TargetStillValid() || !_roundReported || _roundImplausible) { if (!_roundReported) { Plugin.Log.LogWarning((object)"[SimonSays] Round report timed out; releasing the encounter."); } EndFocusForAll(TargetStillValid() ? SimonTargetSlotLogic.HostEvent.Abort : SimonTargetSlotLogic.HostEvent.TargetLost); yield return DepartRoutine(); yield break; } bool flag5 = (round.SimonSaid ? _roundComplied : (!_roundComplied)); DLog(string.Format("round {0}: {1}", i2 + 1, flag5 ? "PASS" : "FAIL")); if (!flag5) { yield return PunishRoutine(i2 + 1); yield break; } if (i2 + 1 < rounds && round.SimonSaid) { yield return WaitWhileTargetValid((Cfg != null) ? Cfg.RoundPause : 0.05f); } } yield return WaitWhileTargetValid(0.55f); if (!TargetStillValid()) { EndFocusForAll(SimonTargetSlotLogic.HostEvent.TargetLost); yield return DepartRoutine(); yield break; } ((EnemyAI)this).SwitchToBehaviourClientRpc(6); PlayCongratulationsClientRpc(); yield return WaitWhileTargetValid(ClipLen(Plugin.CongratulationsClip) + 0.9f); if (!TargetStillValid()) { EndFocusForAll(SimonTargetSlotLogic.HostEvent.TargetLost); } yield return DepartRoutine(); } private IEnumerator PunishRoutine(int roundNumber) { float num = 0f; for (SimonSaysEncounterTimeline.PunishBeat beat = SimonSaysEncounterTimeline.PunishBeat.RedSnap; beat != SimonSaysEncounterTimeline.PunishBeat.Done; beat = SimonSaysEncounterTimeline.NextPunishBeat(beat)) { float num2 = SimonSaysEncounterTimeline.PunishBeatAt(beat) - num; if (num2 > 0f) { yield return (object)new WaitForSeconds(num2); } num = SimonSaysEncounterTimeline.PunishBeatAt(beat); if (_encounterFinished) { Plugin.Log.LogInfo((object)$"[SimonSays] Punish: stopped before {beat}; the encounter already ended."); yield break; } RunPunishBeat(beat, roundNumber); } EndFocusForAll(SimonTargetSlotLogic.HostEvent.FocusEnd); yield return DepartRoutine(); } private void RunPunishBeat(SimonSaysEncounterTimeline.PunishBeat beat, int roundNumber) { switch (beat) { case SimonSaysEncounterTimeline.PunishBeat.RedSnap: ((EnemyAI)this).SwitchToBehaviourClientRpc(5); PlayerFailedClientRpc(); Plugin.Log.LogInfo((object)($"[SimonSays] Punish: {TargetName()} failed round {roundNumber}; spotlight red, " + $"kill due in {SimonSaysEncounterTimeline.PunishKillAt:F1} s.")); break; case SimonSaysEncounterTimeline.PunishBeat.Blackout: PunishBlackoutClientRpc(); Plugin.Log.LogInfo((object)$"[SimonSays] Punish: blackout for {0.3f:F1} s."); break; case SimonSaysEncounterTimeline.PunishBeat.Kill: SendPunishKill(); break; } } private void SendPunishKill() { //IL_0106: Unknown result type (might be due to invalid IL or missing references) StartOfRound instance = StartOfRound.Instance; bool roundLive = (Object)(object)instance != (Object)null && SimonSaysEncounterTimeline.RoundLive(instance.shipHasLanded, instance.inShipPhase, instance.shipIsLeaving, instance.newGameIsLoading, instance.allPlayersDead); bool encounterRunning = !_encounterFinished && !base.isEnemyDead && (Object)(object)((NetworkBehaviour)this).NetworkObject != (Object)null && ((NetworkBehaviour)this).NetworkObject.IsSpawned; int num = (((Object)(object)base.targetPlayer != (Object)null) ? ((int)base.targetPlayer.playerClientId) : (-1)); bool targetValid = TargetStillValid() && (Object)(object)VictimRpc.FromSlot(num) == (Object)(object)base.targetPlayer; SimonSaysEncounterTimeline.KillVerdict killVerdict = SimonSaysEncounterTimeline.DecideKill(_punishKillSent, encounterRunning, roundLive, targetValid); if (killVerdict != SimonSaysEncounterTimeline.KillVerdict.Kill) { Plugin.Log.LogInfo((object)("[SimonSays] Punish: no kill for " + TargetName() + " (" + DescribeNoKill(killVerdict) + ").")); } else { _punishKillSent = true; KillFailedTargetClientRpc((ulong)num, VictimRpc.TargetOwner(base.targetPlayer)); Plugin.Log.LogInfo((object)$"[SimonSays] Punish: kill sent for {TargetName()} (slot {num}, owner client {((NetworkBehaviour)base.targetPlayer).OwnerClientId})."); } } private string DescribeNoKill(SimonSaysEncounterTimeline.KillVerdict verdict) { switch (verdict) { case SimonSaysEncounterTimeline.KillVerdict.AlreadyKilled: return "kill already sent"; case SimonSaysEncounterTimeline.KillVerdict.EncounterStopped: return "encounter stopped"; case SimonSaysEncounterTimeline.KillVerdict.RoundEnding: return "round ending"; default: if (!_hasTarget || (Object)(object)base.targetPlayer == (Object)null) { return "no target"; } if (base.targetPlayer.isPlayerDead) { return "target already dead"; } if (!base.targetPlayer.isPlayerControlled) { return "target not controlled"; } if (base.targetPlayer.isInsideFactory == base.isOutside) { return "target left his side of the building"; } if ((Object)(object)((NetworkBehaviour)this).NetworkManager == (Object)null || !((NetworkBehaviour)this).NetworkManager.ConnectedClients.ContainsKey(base.targetPlayer.actualClientId)) { return "target disconnected"; } return "target slot does not resolve"; } } private string TargetName() { if (!((Object)(object)base.targetPlayer != (Object)null)) { return "no target"; } return base.targetPlayer.playerUsername; } private IEnumerator DepartRoutine() { if (_encounterFinished) { yield break; } _encounterFinished = true; ((EnemyAI)this).SwitchToBehaviourClientRpc(7); CloseWindowClientRpc(); PlayGoodbyeClientRpc(); HoldStationForEncounter(); float holdUntil = Time.time + Mathf.Max(RetreatDuration, ClipLen(Plugin.GoodbyeClip) + 0.2f); if (TargetStillValid()) { yield return WaitWhileTargetValid(holdUntil - Time.time); if (!TargetStillValid()) { EndFocusForAll(SimonTargetSlotLogic.HostEvent.TargetLost); } } float num = holdUntil - Time.time; if (num > 0f) { yield return (object)new WaitForSeconds(num); } HoldStationForEncounter(); WriteTargetSlot(SimonTargetSlotLogic.HostEvent.Vanish); VanishClientRpc(((Component)this).transform.position); Plugin.Log.LogInfo((object)($"[SimonSays] Vanish: smoke at {((Component)this).transform.position}; fade " + $"{SimonSaysEncounterTimeline.VanishFadeStart:F1}-{SimonSaysEncounterTimeline.VanishRenderersOffAt:F1} s, " + $"despawn in {SimonSaysEncounterTimeline.VanishDespawnAfter:F1} s.")); yield return (object)new WaitForSeconds(SimonSaysEncounterTimeline.VanishDespawnAfter); DespawnSelf(); } private void DespawnSelf() { try { if (((NetworkBehaviour)this).IsServer && (Object)(object)((NetworkBehaviour)this).NetworkObject != (Object)null && ((NetworkBehaviour)this).NetworkObject.IsSpawned) { ((NetworkBehaviour)this).NetworkObject.Despawn(true); } } catch (Exception arg) { Plugin.Log.LogError((object)$"despawn failed: {arg}"); } } private void StopEncounterRoutine() { _encounterFinished = true; if (_stateCoroutine != null) { ((MonoBehaviour)this).StopCoroutine(_stateCoroutine); _stateCoroutine = null; } } private void AbortForCommandAudio() { //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_0038: Unknown result type (might be due to invalid IL or missing references) if (((NetworkBehaviour)this).IsServer) { if (_encounterStarted && !_encounterFinished) { Plugin.Log.LogWarning((object)"[SimonSays] Releasing the game: a command sentence could not be com
Y4NGZBeetleBull.dll
Decompiled a day ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security.Cryptography; using System.Text; using System.Text.RegularExpressions; using BepInEx; using BepInEx.Configuration; using BepInEx.Logging; using Dawn; using GameNetcodeStuff; using HarmonyLib; using Microsoft.CodeAnalysis; using Unity.Netcode; using Unity.Netcode.Components; using UnityEngine; using UnityEngine.AI; using UnityEngine.Audio; using Y4NGZBeetleBull.AI; using Y4NGZBeetleBull.NetcodePatcher; using Y4NGZMonsters.Shared; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: AssemblyCompany("Y4NGZBeetleBull")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0+3460ec64f0cec4948e51ddb3f02a4b0e414f105e")] [assembly: AssemblyProduct("Y4NGZBeetleBull")] [assembly: AssemblyTitle("Y4NGZBeetleBull")] [assembly: AssemblyVersion("1.0.0.0")] [module: RefSafetyRules(11)] [module: NetcodePatchedAssembly] 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 Y4NGZBeetleBull { internal sealed class BeetleBullConfig { private HashSet<string> _hostileEnemyNames = new HashSet<string>(StringComparer.OrdinalIgnoreCase); public ConfigEntry<bool> Enabled { get; } public ConfigEntry<float> SpawnWeightMultiplier { get; } public ConfigEntry<string> MoonWeightOverrides { get; } public ConfigEntry<int> MaxCount { get; } public ConfigEntry<float> PowerLevel { get; } public ConfigEntry<int> GroupSize { get; } public ConfigEntry<int> Health { get; } public ConfigEntry<float> WalkSpeed { get; } public ConfigEntry<float> ChargeSpeed { get; } public ConfigEntry<int> RamDamage { get; } public ConfigEntry<float> RamLaunchForce { get; } public ConfigEntry<float> ChargeMaxSeconds { get; } public ConfigEntry<float> CalmAfterSeconds { get; } public ConfigEntry<float> TrotSpeed { get; } public ConfigEntry<bool> TurnInPlace { get; } public ConfigEntry<float> FollowDistanceMin { get; } public ConfigEntry<float> FollowDistanceMax { get; } public ConfigEntry<float> NightSpacing { get; } public ConfigEntry<float> GrazeSecondsMin { get; } public ConfigEntry<float> GrazeSecondsMax { get; } public ConfigEntry<float> GrazeNoiseRange { get; } public ConfigEntry<float> GrazeNoiseLoudness { get; } public ConfigEntry<float> MeetRadius { get; } public ConfigEntry<float> SeekCompanyRange { get; } public ConfigEntry<float> SeekCompanyChance { get; } public ConfigEntry<float> MigrationMinutesMin { get; } public ConfigEntry<float> MigrationMinutesMax { get; } public ConfigEntry<bool> ListenEnabled { get; } public ConfigEntry<float> ListenRange { get; } public ConfigEntry<float> StareDistance { get; } public ConfigEntry<bool> ReactToEmotes { get; } public ConfigEntry<bool> ReactToMusic { get; } public ConfigEntry<float> AmbientChance { get; } public ConfigEntry<float> AmbientMinGap { get; } public ConfigEntry<float> LieSecondsMin { get; } public ConfigEntry<float> LieSecondsMax { get; } public ConfigEntry<int> WeightIdleKick { get; } public ConfigEntry<int> WeightHeadShake { get; } public ConfigEntry<int> WeightSniff { get; } public ConfigEntry<int> WeightScratch { get; } public ConfigEntry<int> WeightFlutter { get; } public ConfigEntry<int> WeightMoo { get; } public ConfigEntry<int> WeightLieDown { get; } public ConfigEntry<int> WeightSparring { get; } public ConfigEntry<int> WeightDustBath { get; } public ConfigEntry<bool> MiddayRest { get; } public ConfigEntry<bool> NightRest { get; } public ConfigEntry<bool> HeadUpOnApproach { get; } public ConfigEntry<float> HeadUpRange { get; } public ConfigEntry<float> StepBackRange { get; } public ConfigEntry<bool> DriftFromSprinters { get; } public ConfigEntry<bool> StartleOnNoise { get; } public ConfigEntry<bool> PredatorAwareness { get; } public ConfigEntry<float> PredatorRange { get; } public ConfigEntry<bool> EveningHuddle { get; } public ConfigEntry<bool> ShipExclusionEverywhere { get; } public ConfigEntry<float> RompChance { get; } public ConfigEntry<float> TrotBurstChance { get; } public ConfigEntry<bool> CuriousApproach { get; } public ConfigEntry<float> CuriousStillSeconds { get; } public ConfigEntry<float> CuriousRange { get; } public ConfigEntry<float> FleeSecondsMin { get; } public ConfigEntry<float> FleeSecondsMax { get; } public ConfigEntry<float> HostileRange { get; } public ConfigEntry<string> HostileEnemies { get; } public ConfigEntry<float> GunshotRange { get; } public ConfigEntry<float> ExplosionRange { get; } public ConfigEntry<float> LoudNoiseLoudness { get; } public ConfigEntry<float> LoudNoiseRange { get; } public ConfigEntry<float> SprintFleeRange { get; } public ConfigEntry<float> SprintClosingSpeed { get; } public ConfigEntry<float> SprintConeDegrees { get; } public ConfigEntry<float> SfxMaxDistance { get; } public ConfigEntry<float> FootstepVolume { get; } public ConfigEntry<bool> DebugLogs { get; } public BeetleBullConfig(ConfigFile config) { //IL_006d: Unknown result type (might be due to invalid IL or missing references) //IL_0077: Expected O, but got Unknown //IL_00bb: Unknown result type (might be due to invalid IL or missing references) //IL_00c5: Expected O, but got Unknown //IL_00f4: Unknown result type (might be due to invalid IL or missing references) //IL_00fe: Expected O, but got Unknown //IL_0121: Unknown result type (might be due to invalid IL or missing references) //IL_012b: Expected O, but got Unknown //IL_014f: Unknown result type (might be due to invalid IL or missing references) //IL_0159: Expected O, but got Unknown //IL_0188: Unknown result type (might be due to invalid IL or missing references) //IL_0192: Expected O, but got Unknown //IL_01c1: Unknown result type (might be due to invalid IL or missing references) //IL_01cb: Expected O, but got Unknown //IL_01f0: Unknown result type (might be due to invalid IL or missing references) //IL_01fa: Expected O, but got Unknown //IL_0229: Unknown result type (might be due to invalid IL or missing references) //IL_0233: Expected O, but got Unknown //IL_0262: Unknown result type (might be due to invalid IL or missing references) //IL_026c: Expected O, but got Unknown //IL_029b: Unknown result type (might be due to invalid IL or missing references) //IL_02a5: Expected O, but got Unknown //IL_02d4: Unknown result type (might be due to invalid IL or missing references) //IL_02de: Expected O, but got Unknown //IL_0329: Unknown result type (might be due to invalid IL or missing references) //IL_0333: Expected O, but got Unknown //IL_0362: Unknown result type (might be due to invalid IL or missing references) //IL_036c: Expected O, but got Unknown //IL_039b: Unknown result type (might be due to invalid IL or missing references) //IL_03a5: Expected O, but got Unknown //IL_03d4: Unknown result type (might be due to invalid IL or missing references) //IL_03de: Expected O, but got Unknown //IL_040d: Unknown result type (might be due to invalid IL or missing references) //IL_0417: Expected O, but got Unknown //IL_0446: Unknown result type (might be due to invalid IL or missing references) //IL_0450: Expected O, but got Unknown //IL_047f: Unknown result type (might be due to invalid IL or missing references) //IL_0489: Expected O, but got Unknown //IL_04b8: Unknown result type (might be due to invalid IL or missing references) //IL_04c2: Expected O, but got Unknown //IL_04f1: Unknown result type (might be due to invalid IL or missing references) //IL_04fb: Expected O, but got Unknown //IL_052a: Unknown result type (might be due to invalid IL or missing references) //IL_0534: Expected O, but got Unknown //IL_0563: Unknown result type (might be due to invalid IL or missing references) //IL_056d: Expected O, but got Unknown //IL_059c: Unknown result type (might be due to invalid IL or missing references) //IL_05a6: Expected O, but got Unknown //IL_05f1: Unknown result type (might be due to invalid IL or missing references) //IL_05fb: Expected O, but got Unknown //IL_062a: Unknown result type (might be due to invalid IL or missing references) //IL_0634: Expected O, but got Unknown //IL_069b: Unknown result type (might be due to invalid IL or missing references) //IL_06a5: Expected O, but got Unknown //IL_06d4: Unknown result type (might be due to invalid IL or missing references) //IL_06de: Expected O, but got Unknown //IL_070d: Unknown result type (might be due to invalid IL or missing references) //IL_0717: Expected O, but got Unknown //IL_0746: Unknown result type (might be due to invalid IL or missing references) //IL_0750: Expected O, but got Unknown //IL_08a8: Unknown result type (might be due to invalid IL or missing references) //IL_08b2: Expected O, but got Unknown //IL_08e1: Unknown result type (might be due to invalid IL or missing references) //IL_08eb: Expected O, but got Unknown //IL_096e: Unknown result type (might be due to invalid IL or missing references) //IL_0978: Expected O, but got Unknown //IL_09df: Unknown result type (might be due to invalid IL or missing references) //IL_09e9: Expected O, but got Unknown //IL_0a18: Unknown result type (might be due to invalid IL or missing references) //IL_0a22: Expected O, but got Unknown //IL_0a6d: Unknown result type (might be due to invalid IL or missing references) //IL_0a77: Expected O, but got Unknown //IL_0aa6: Unknown result type (might be due to invalid IL or missing references) //IL_0ab0: Expected O, but got Unknown //IL_0adf: Unknown result type (might be due to invalid IL or missing references) //IL_0ae9: Expected O, but got Unknown //IL_0b18: Unknown result type (might be due to invalid IL or missing references) //IL_0b22: Expected O, but got Unknown //IL_0b51: Unknown result type (might be due to invalid IL or missing references) //IL_0b5b: Expected O, but got Unknown //IL_0baa: Unknown result type (might be due to invalid IL or missing references) //IL_0bb4: Expected O, but got Unknown //IL_0be3: Unknown result type (might be due to invalid IL or missing references) //IL_0bed: Expected O, but got Unknown //IL_0c1c: Unknown result type (might be due to invalid IL or missing references) //IL_0c26: Expected O, but got Unknown //IL_0c55: Unknown result type (might be due to invalid IL or missing references) //IL_0c5f: Expected O, but got Unknown //IL_0c8e: Unknown result type (might be due to invalid IL or missing references) //IL_0c98: Expected O, but got Unknown //IL_0cc7: Unknown result type (might be due to invalid IL or missing references) //IL_0cd1: Expected O, but got Unknown //IL_0d00: Unknown result type (might be due to invalid IL or missing references) //IL_0d0a: Expected O, but got Unknown //IL_0d56: Unknown result type (might be due to invalid IL or missing references) //IL_0d60: Expected O, but got Unknown //IL_0d8f: Unknown result type (might be due to invalid IL or missing references) //IL_0d99: Expected O, but got Unknown using (ConfigPersistence.BeginBinding(config, Plugin.Log, "Beetle Bull")) { Enabled = config.Bind<bool>("General", "Enabled", true, "Enable the Beetle Bull encounter. Host-only: the host's value decides whether it spawns; every install still registers the creature so clients stay in sync."); SpawnWeightMultiplier = config.Bind<float>("Spawning", "SpawnWeightMultiplier", 1f, new ConfigDescription("Multiplier applied to the Beetle Bull's daytime moon spawn policy. 0 disables natural spawns.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 5f), Array.Empty<object>())); MoonWeightOverrides = config.Bind<string>("Spawning", "MoonWeightOverrides", string.Empty, "Optional comma-separated base moon weights, e.g. Experimentation:8,Offense:15 or namespace:moon=12. Use 0 to disable a moon; unlisted moons keep authored defaults."); MaxCount = config.Bind<int>("Spawning", "MaxCount", 8, new ConfigDescription("Maximum number of Beetle Bulls spawned in one day, counting every herd member. The game checks it before each spawn roll, so the last spawn group can end up to GroupSize - 1 above it.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 20), Array.Empty<object>())); PowerLevel = config.Bind<float>("Spawning", "PowerLevel", 1f, new ConfigDescription("Daytime enemy power budget cost for each Beetle Bull; a herd costs this once per bull.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.1f, 10f), Array.Empty<object>())); GroupSize = config.Bind<int>("Spawning", "GroupSize", 3, new ConfigDescription("Beetle Bulls the game spawns together per daytime spawn roll (vanilla's enemy group size). Each bull costs PowerLevel, and the group stops early once the moon's daytime power budget is spent. The bulls start at separate outside nodes and herd up when they meet (see [Herd] MeetRadius).", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 4), Array.Empty<object>())); Health = config.Bind<int>("Core Stats", "Health", 8, new ConfigDescription("Hits a Beetle Bull can take before dying (a shovel hit removes 1, an Eyeless Dog bite 2).", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 100), Array.Empty<object>())); WalkSpeed = config.Bind<float>("Core Stats", "WalkSpeed", 1.41f, new ConfigDescription("Grazing and herd-following speed in metres per second. 1.41 matches the walk animation.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.5f, 5f), Array.Empty<object>())); ChargeSpeed = config.Bind<float>("Core Stats", "ChargeSpeed", 7f, new ConfigDescription("Charge speed in metres per second. 7 matches the charge animation.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 15f), Array.Empty<object>())); RamDamage = config.Bind<int>("Core Stats", "RamDamage", 35, new ConfigDescription("Damage a ram deals to the player it hits. The host's value applies to every player.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 100), Array.Empty<object>())); RamLaunchForce = config.Bind<float>("Core Stats", "RamLaunchForce", 32f, new ConfigDescription("Strength of the up-and-forward push a ram gives the player it hits. The host's value applies to every player.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 60f), Array.Empty<object>())); ChargeMaxSeconds = config.Bind<float>("Core Stats", "ChargeMaxSeconds", 4f, new ConfigDescription("Seconds a charge lasts before the bull gives up without contact.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.5f, 15f), Array.Empty<object>())); CalmAfterSeconds = config.Bind<float>("Core Stats", "CalmAfterSeconds", 10f, new ConfigDescription("Seconds after a charge ends before the bull returns to grazing.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 60f), Array.Empty<object>())); TrotSpeed = config.Bind<float>("Movement", "TrotSpeed", 3.5f, new ConfigDescription("Trot speed in metres per second, used by a follower catching up from more than 10 m behind its place (6 m while its leader trots), by a leader regrouping its scattered herd, by romps (RompChance, the morning trip, TrotBurstChance), stepping back and fleeing. 3.5 matches the trot animation. Host-only.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(2f, 6f), Array.Empty<object>())); TurnInPlace = config.Bind<bool>("Movement", "TurnInPlace", true, "A walking bull whose path bends more than 60 degrees stops and turns on the spot, then walks on once it faces within 20 degrees, so its feet do not slide sideways. Host-only."); FollowDistanceMin = config.Bind<float>("Herd", "FollowDistanceMin", 3f, new ConfigDescription("Closest daytime spacing in metres a follower keeps from the herd leader. Raised to 3.5 m so herd members never crowd each other.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 20f), Array.Empty<object>())); FollowDistanceMax = config.Bind<float>("Herd", "FollowDistanceMax", 8f, new ConfigDescription("Widest daytime spacing in metres a follower keeps from the herd leader. A value below FollowDistanceMin is raised to it.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 30f), Array.Empty<object>())); NightSpacing = config.Bind<float>("Herd", "NightSpacing", 4f, new ConfigDescription("Distance in metres each follower stands from the leader from sundown, when the herd stops grazing and stands. A value below the slot floor (3.5 m, or the ring floor for the herd size) is raised to the floor.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 10f), Array.Empty<object>())); GrazeSecondsMin = config.Bind<float>("Herd", "GrazeSecondsMin", 6f, new ConfigDescription("Shortest time the herd grazes at one spot.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 60f), Array.Empty<object>())); GrazeSecondsMax = config.Bind<float>("Herd", "GrazeSecondsMax", 15f, new ConfigDescription("Longest time the herd grazes at one spot. A value below GrazeSecondsMin is raised to it.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 120f), Array.Empty<object>())); GrazeNoiseRange = config.Bind<float>("Herd", "GrazeNoiseRange", 18f, new ConfigDescription("Range in metres of the noise a grazing bull makes; other creatures such as Eyeless Dogs hear it. 0 makes grazing silent to them.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 60f), Array.Empty<object>())); GrazeNoiseLoudness = config.Bind<float>("Herd", "GrazeNoiseLoudness", 0.6f, new ConfigDescription("Loudness of the grazing noise other creatures hear.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 1f), Array.Empty<object>())); MeetRadius = config.Bind<float>("Herd", "MeetRadius", 25f, new ConfigDescription("Two calmly grazing herds merge once a bull of one comes within this many metres of a bull of the other (and within 4 m of height), up to 6 bulls together. The larger herd's leader leads the merged herd; the others walk over to it. Host-only.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(5f, 60f), Array.Empty<object>())); SeekCompanyRange = config.Bind<float>("Herd", "SeekCompanyRange", 120f, new ConfigDescription("A herd smaller than the maximum (6) biases SeekCompanyChance of its graze-spot picks toward the nearest bull of another herd it could merge with, when that bull is farther than MeetRadius but within this many metres, so scattered group members meet. 0 disables the bias. Host-only.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 300f), Array.Empty<object>())); SeekCompanyChance = config.Bind<float>("Herd", "SeekCompanyChance", 0.5f, new ConfigDescription("Fraction of a small herd's graze-spot picks biased toward the nearest other herd within SeekCompanyRange. 0 never, 1 every pick. Host-only.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 1f), Array.Empty<object>())); MigrationMinutesMin = config.Bind<float>("Herd", "MigrationMinutesMin", 3f, new ConfigDescription("Shortest calm daytime in minutes before a herd of two or more moves on: its next graze trip becomes a walk to a spot 35-80 m away with the herd in single file behind the leader (each bull 3.5 m behind the one in front), after which it grazes there. Counted from when the herd formed or from its last move; a flee, a merge, nightfall, a hit, the leader's death or a blocked path ends the move early. Host-only.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 20f), Array.Empty<object>())); MigrationMinutesMax = config.Bind<float>("Herd", "MigrationMinutesMax", 6f, new ConfigDescription("Longest calm daytime in minutes before a herd moves on in single file (see MigrationMinutesMin; a value below MigrationMinutesMin counts as MigrationMinutesMin). Host-only.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 20f), Array.Empty<object>())); ListenEnabled = config.Bind<bool>("Listen", "Enabled", true, "Grazing bulls walk over to an emoting player or a playing boombox and stare at it. Host-only."); ListenRange = config.Bind<float>("Listen", "ListenRange", 20f, new ConfigDescription("Distance in metres at which a bull notices an emote or music. A boombox is only heard within its own 16 m noise range. Host-only.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 60f), Array.Empty<object>())); StareDistance = config.Bind<float>("Listen", "StareDistance", 5f, new ConfigDescription("Distance in metres a listening bull stops from what it listens to. Host-only.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(2f, 15f), Array.Empty<object>())); ReactToEmotes = config.Bind<bool>("Listen", "ReactToEmotes", true, "Bulls listen to players performing an emote in their line of sight. Host-only."); ReactToMusic = config.Bind<bool>("Listen", "ReactToMusic", true, "Bulls listen to a playing boombox. Host-only."); AmbientChance = config.Bind<float>("Ambience", "AmbientChance", 0.6f, new ConfigDescription("Chance that a standing bull plays an idle action (kick, head shake, sniff, scratch, shell flutter, moo, lying down, sparring or dust bathing) in each pause between graze bouts. Host-only. 0 disables idle actions.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 1f), Array.Empty<object>())); AmbientMinGap = config.Bind<float>("Ambience", "AmbientMinGap", 4f, new ConfigDescription("Shortest time in seconds between the end of one idle action and the start of the next on the same bull.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 60f), Array.Empty<object>())); LieSecondsMin = config.Bind<float>("Ambience", "LieSecondsMin", 20f, new ConfigDescription("Shortest time a bull stays lying down and chewing in an idle lie-down (not a midday or night rest) before it stands up. At most half of a herd (rounded up) is down at once, idle lie-downs and rests together; a hit makes it stand up first.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 300f), Array.Empty<object>())); LieSecondsMax = config.Bind<float>("Ambience", "LieSecondsMax", 45f, new ConfigDescription("Longest time a bull stays lying down in an idle lie-down (not a midday or night rest). A value below LieSecondsMin is raised to it.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 300f), Array.Empty<object>())); WeightIdleKick = BindAmbientWeight(config, "WeightIdleKick", 20, "pawing and kicking dirt"); WeightHeadShake = BindAmbientWeight(config, "WeightHeadShake", 20, "shaking flies off its head"); WeightSniff = BindAmbientWeight(config, "WeightSniff", 15, "sniffing the ground"); WeightScratch = BindAmbientWeight(config, "WeightScratch", 10, "scratching a horn along the ground"); WeightFlutter = BindAmbientWeight(config, "WeightFlutter", 10, "fluttering its shell covers"); WeightMoo = BindAmbientWeight(config, "WeightMoo", 10, "mooing (other creatures hear it; a herd member may answer)"); WeightLieDown = BindAmbientWeight(config, "WeightLieDown", 5, "lying down to chew"); WeightSparring = BindAmbientWeight(config, "WeightSparring", 8, "playful sparring with a nearby calm herd mate during the day"); WeightDustBath = BindAmbientWeight(config, "WeightDustBath", 8, "shaking and fluttering dust through its shell"); MiddayRest = config.Bind<bool>("Ambience", "MiddayRest", true, "Between 10:00 and 16:00 on the clock each bull lies down to sleep for 40-90 s once every 2-3 game hours, the herd taking turns with at most half of it (rounded up) down at once, when it stands calm in Graze, its herd is not fleeing or moving on and no player is within HeadUpRange. A bull that cannot lie yet tries again shortly; a rest cut short is retried 60 s later. Host-only."); NightRest = config.Bind<bool>("Ambience", "NightRest", true, "From sundown, once the herd leader has stood still for 10 s, herd members lie down to sleep one after another until half the herd (rounded up) is down, while at least one keeps watch (a lone bull only keeps watch); every 60-120 s the watch wakes the next sleeper and the bull awake longest lies down in its place. A hit, a flee, or the leader listening or charging wakes them; idle lie-downs are off at night. Host-only."); HeadUpOnApproach = config.Bind<bool>("Liveliness", "HeadUpOnApproach", true, "A grazing bull lifts its head for 1-2 s and looks at the nearest player it can see within HeadUpRange (again once he went 2 m beyond it or after 8 s), and a calm standing bull trots 2-3 m directly away from a player within StepBackRange (at most every 3 s). Host-only."); HeadUpRange = config.Bind<float>("Liveliness", "HeadUpRange", 12f, new ConfigDescription("Distance in metres at which a grazing bull looks up at an approaching player. Host-only.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(2f, 40f), Array.Empty<object>())); StepBackRange = config.Bind<float>("Liveliness", "StepBackRange", 4f, new ConfigDescription("Distance in metres inside which a calm bull steps back from a player. 0 disables stepping back. Host-only.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 10f), Array.Empty<object>())); DriftFromSprinters = config.Bind<bool>("Liveliness", "DriftFromSprinters", true, "While a player sprints within 8 m of a herd member (until none sprints within 14 m), the herd leader picks its next graze spots on the side away from him. Host-only."); StartleOnNoise = config.Bind<bool>("Liveliness", "StartleOnNoise", true, "A loud noise (loudness above 0.6 within 15 m, not a boombox, a player's footsteps or the herd's own moo) startles a calm bull: it freezes for 1 s facing the noise and flutters its shell covers, and herd mates within 8 m lift their heads towards it. At most once every 4 s per bull. A noise loud and near enough for [Flee] LoudNoiseLoudness and LoudNoiseRange sets the herd fleeing instead. Host-only."); PredatorAwareness = config.Bind<bool>("Liveliness", "PredatorAwareness", true, "Every bull watches for Eyeless Dogs, Old Birds and Forest Keepers within PredatorRange in its line of sight, each on its own scan about once a second; on sight it and its herd flee at the trot, every bull to its own spot 18-30 m away from the predator, for [Flee] FleeSecondsMin-FleeSecondsMax seconds, renewed while the predator stays in sight. Host-only."); PredatorRange = config.Bind<float>("Liveliness", "PredatorRange", 25f, new ConfigDescription("Distance in metres at which a bull notices a predator. Host-only.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(5f, 60f), Array.Empty<object>())); EveningHuddle = config.Bind<bool>("Liveliness", "EveningHuddle", true, "When the herd huddles at sundown each bull moos once, a few seconds apart, and the huddled followers turn to face the leader. Host-only."); ShipExclusionEverywhere = config.Bind<bool>("Liveliness", "ShipExclusionEverywhere", true, "Every calm destination (herd places, listening, backing off, stepping back, fleeing) is kept 30 m from the ship and 20 m from the main entrance, like graze spots; a destination inside is pulled back along the bull's line to the edge. Host-only."); RompChance = config.Bind<float>("Liveliness", "RompChance", 0.35f, new ConfigDescription("Chance that the herd leader trots instead of walking to a graze spot more than 20 m away; its followers trot along (from 6 m behind their places). The herd's first trip after it spawns, or after the night, is always at the trot. Host-only. 0 keeps every other graze trip at the walk.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 1f), Array.Empty<object>())); TrotBurstChance = config.Bind<float>("Liveliness", "TrotBurstChance", 0.2f, new ConfigDescription("Chance that a follower, after standing up or shaking its head in the day, trots 6-10 m off to a free spot and then rejoins its place; at most once every 30 s per bull. A reaction, a flee or a hit ends the burst. Host-only. 0 disables it.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 1f), Array.Empty<object>())); CuriousApproach = config.Bind<bool>("Liveliness", "CuriousApproach", true, "A player standing still outside for CuriousStillSeconds draws the nearest calm bull of a herd within CuriousRange that can see him: it walks up to about 4.5 m, hesitates, comes in to about 2 m, sniffs at him and backs off, then rejoins its herd. One bull per herd at a time, then the herd waits 60-120 s; moving more than 1 m, sprinting, entering the ship, a flee, a hit or nightfall ends it. Host-only."); CuriousStillSeconds = config.Bind<float>("Liveliness", "CuriousStillSeconds", 6f, new ConfigDescription("Seconds a player must stand still (within 0.4 m) before a bull comes over to sniff at him (CuriousApproach). Host-only.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(2f, 30f), Array.Empty<object>())); CuriousRange = config.Bind<float>("Liveliness", "CuriousRange", 12f, new ConfigDescription("Distance in metres within which a calm bull that can see a still player comes over to sniff at him (CuriousApproach). Host-only.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(4f, 20f), Array.Empty<object>())); FleeSecondsMin = config.Bind<float>("Flee", "FleeSecondsMin", 15f, new ConfigDescription("Shortest flight in seconds. A fleeing bull trots away from its threat for a random time between FleeSecondsMin and FleeSecondsMax (renewed while a sighted enemy stays in sight), then grazes again and rejoins its herd. Host-only.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(5f, 90f), Array.Empty<object>())); FleeSecondsMax = config.Bind<float>("Flee", "FleeSecondsMax", 30f, new ConfigDescription("Longest flight in seconds (see FleeSecondsMin; a value below FleeSecondsMin counts as FleeSecondsMin). Host-only.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(5f, 90f), Array.Empty<object>())); HostileRange = config.Bind<float>("Flee", "HostileRange", 15f, new ConfigDescription("Distance in metres at which a bull in line of sight of a night-time enemy, or of one HostileEnemies names, flees with its herd. The named predators use [Liveliness] PredatorRange. Host-only. 0 disables it.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 40f), Array.Empty<object>())); HostileEnemies = config.Bind<string>("Flee", "HostileEnemies", string.Empty, "Comma-separated enemy names (as the scanner shows them, e.g. \"Baboon hawk, Manticoil\") a bull also flees from within HostileRange although they roam by day. Not case-sensitive. Host-only."); GunshotRange = config.Bind<float>("Flee", "GunshotRange", 40f, new ConfigDescription("A shotgun fired within this many metres of a bull sets it fleeing with its herd. Host-only. 0 disables it.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 100f), Array.Empty<object>())); ExplosionRange = config.Bind<float>("Flee", "ExplosionRange", 40f, new ConfigDescription("An explosion (a landmine, or anything that uses vanilla's landmine explosion) within this many metres of a bull sets it fleeing with its herd. Host-only. 0 disables it.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 100f), Array.Empty<object>())); LoudNoiseLoudness = config.Bind<float>("Flee", "LoudNoiseLoudness", 0.9f, new ConfigDescription("Loudness (vanilla's 0-1 noise scale) from which a noise within LoudNoiseRange sets a bull fleeing with its herd. Boomboxes and footsteps never do; quieter noises only startle ([Liveliness] StartleOnNoise). Host-only.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.5f, 1f), Array.Empty<object>())); LoudNoiseRange = config.Bind<float>("Flee", "LoudNoiseRange", 30f, new ConfigDescription("Distance in metres within which a noise of at least LoudNoiseLoudness sets a bull fleeing. Host-only. 0 disables it.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 80f), Array.Empty<object>())); SprintFleeRange = config.Bind<float>("Flee", "SprintFleeRange", 12f, new ConfigDescription("Distance in metres within which a player sprinting straight at a bull (SprintClosingSpeed, SprintConeDegrees) sets it fleeing with its herd. Other sprinting players only make the herd graze away from them ([Liveliness] DriftFromSprinters). Host-only. 0 disables it.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 30f), Array.Empty<object>())); SprintClosingSpeed = config.Bind<float>("Flee", "SprintClosingSpeed", 4.5f, new ConfigDescription("Speed in metres per second at which a sprinting player must close on a bull to set it fleeing. Host-only.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 15f), Array.Empty<object>())); SprintConeDegrees = config.Bind<float>("Flee", "SprintConeDegrees", 25f, new ConfigDescription("Largest angle in degrees between a sprinting player's motion and the line from him to a bull that still counts as running straight at it. Host-only.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(5f, 90f), Array.Empty<object>())); ParseHostileEnemies(); HostileEnemies.SettingChanged += delegate { ParseHostileEnemies(); }; SfxMaxDistance = config.Bind<float>("Audio", "SfxMaxDistance", 40f, new ConfigDescription("Maximum audible distance for Beetle Bull sounds.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(8f, 80f), Array.Empty<object>())); FootstepVolume = config.Bind<float>("Audio", "FootstepVolume", 0.9f, new ConfigDescription("Volume of Beetle Bull footsteps (its own clip for the ground it walks on; a charge step adds a ground-shaking thud). 0 silences them.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 1f), Array.Empty<object>())); DebugLogs = config.Bind<bool>("Debug", "DebugLogs", false, "Log Beetle Bull decisions (state changes, herd formation, graze spots, listening, idle actions, liveliness reactions, rams) at Info level."); } } public bool IsHostileEnemyName(string enemyName) { if (!string.IsNullOrEmpty(enemyName)) { return _hostileEnemyNames.Contains(enemyName); } return false; } private void ParseHostileEnemies() { HashSet<string> hashSet = new HashSet<string>(StringComparer.OrdinalIgnoreCase); string value = HostileEnemies.Value; if (!string.IsNullOrEmpty(value)) { string[] array = value.Split(','); for (int i = 0; i < array.Length; i++) { string text = array[i].Trim(); if (text.Length > 0) { hashSet.Add(text); } } } _hostileEnemyNames = hashSet; } private static ConfigEntry<int> BindAmbientWeight(ConfigFile config, string key, int defaultValue, string action) { //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Expected O, but got Unknown return config.Bind<int>("Ambience", key, defaultValue, new ConfigDescription("Relative weight of " + action + " among the idle actions. 0 disables it.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 100), Array.Empty<object>())); } } internal enum BullSurface { Grass, Dirt, Gravel, Rock, Metal, Wood, Snow, Water } internal static class BeetleBullSounds { private sealed class Loader { private readonly AssetBundle _bundle; private readonly ManualLogSource _log; private readonly string _bundleName; private int _loaded; private int _missing; internal Loader(AssetBundle bundle, ManualLogSource log, string bundleName) { _bundle = bundle; _log = log; _bundleName = bundleName; } internal AudioClip Load(string name) { AudioClip val = (((Object)(object)_bundle != (Object)null) ? _bundle.LoadAsset<AudioClip>(name) : null); if ((Object)(object)val != (Object)null) { _loaded++; return val; } _missing++; ManualLogSource log = _log; if (log != null) { log.LogWarning((object)("[BeetleBull] " + _bundleName + ": no '" + name + "' AudioClip, so that sound is silent or falls back.")); } return null; } internal AudioClip[] LoadSet(string prefix, int count) { List<AudioClip> list = new List<AudioClip>(count); for (int i = 1; i <= count; i++) { AudioClip val = Load(prefix + i); if ((Object)(object)val != (Object)null) { list.Add(val); } } if (list.Count <= 0) { return NoClips; } return list.ToArray(); } internal void LogSummary() { ManualLogSource log = _log; if (log != null) { log.LogInfo((object)$"[BeetleBull] {_bundleName}: {_loaded} sound clips loaded, {_missing} missing."); } } } private static readonly string[] SurfaceNames = new string[8] { "Grass", "Dirt", "Gravel", "Rock", "Metal", "Wood", "Snow", "Water" }; private static readonly AudioClip[] NoClips = (AudioClip[])(object)new AudioClip[0]; private static readonly AudioClip[][] Steps = NewSteps(); private static AudioClip _lastHurt; internal static AudioClip[] ChargeThud { get; private set; } = NoClips; internal static AudioClip[] Moo { get; private set; } = NoClips; internal static AudioClip[] Hurt { get; private set; } = NoClips; internal static AudioClip[] Graze { get; private set; } = NoClips; internal static AudioClip[] SparClack { get; private set; } = NoClips; internal static AudioClip[] DustShake { get; private set; } = NoClips; internal static AudioClip[] FleeBellow { get; private set; } = NoClips; internal static AudioClip ChargeRumble { get; private set; } internal static AudioClip Alert { get; private set; } internal static AudioClip ChargeBellow { get; private set; } internal static AudioClip Death { get; private set; } internal static AudioClip Stunned { get; private set; } internal static AudioClip Sniff { get; private set; } internal static AudioClip Scratch { get; private set; } internal static AudioClip Flutter { get; private set; } internal static AudioClip KickDust { get; private set; } internal static AudioClip HeadShake { get; private set; } internal static AudioClip SleepBreath { get; private set; } internal static AudioClip LieDown { get; private set; } internal static AudioClip StandUp { get; private set; } internal static AudioClip RamHit { get; private set; } internal static AudioClip PickHurtClip() { return PickRandom(Hurt, ref _lastHurt); } internal static AudioClip[] StepClips(BullSurface surface) { return Steps[(int)surface]; } internal static BullSurface SurfaceFromTag(string tag) { switch (tag) { case "Grass": case "Tree": return BullSurface.Grass; case "Gravel": return BullSurface.Gravel; case "Tiles": case "Rock": case "Concrete": case "Untagged": return BullSurface.Rock; case "Metal": case "Aluminum": case "Catwalk": return BullSurface.Metal; case "Slime": case "Puddle": return BullSurface.Water; case "Snow": return BullSurface.Snow; case "Wood": return BullSurface.Wood; default: return BullSurface.Dirt; } } internal static AudioClip PickRandom(AudioClip[] clips, ref AudioClip previous) { if (clips == null || clips.Length == 0) { return null; } int num = Random.Range(0, clips.Length); if (clips.Length > 1 && (Object)(object)clips[num] == (Object)(object)previous) { num = (num + 1) % clips.Length; } previous = clips[num]; return previous; } internal static void Load(AssetBundle bundle, ManualLogSource log, string bundleName) { Loader loader = new Loader(bundle, log, bundleName); for (int i = 0; i < SurfaceNames.Length; i++) { Steps[i] = loader.LoadSet("BB_Step_" + SurfaceNames[i] + "_", 4); } ChargeThud = loader.LoadSet("BB_ChargeThud_", 4); ChargeRumble = loader.Load("BB_ChargeRumble"); AudioClip[] array = loader.LoadSet("BB_Moo_", 3); if (array.Length == 0) { AudioClip val = loader.Load("BB_Moo"); array = (AudioClip[])((!((Object)(object)val != (Object)null)) ? ((Array)NoClips) : ((Array)new AudioClip[1] { val })); } Moo = array; Alert = loader.Load("BB_Alert"); ChargeBellow = loader.Load("BB_ChargeBellow"); Hurt = loader.LoadSet("BB_Hurt_", 2); Death = loader.Load("BB_Death"); Stunned = loader.Load("BB_Stunned"); Sniff = loader.Load("BB_Sniff"); Scratch = loader.Load("BB_Scratch"); Flutter = loader.Load("BB_Flutter"); KickDust = loader.Load("BB_KickDust"); HeadShake = loader.Load("BB_HeadShake"); Graze = loader.LoadSet("BB_Graze_", 3); SparClack = loader.LoadSet("BB_SparClack_", 3); DustShake = loader.LoadSet("BB_DustShake_", 2); FleeBellow = loader.LoadSet("BB_FleeBellow_", 2); SleepBreath = loader.Load("BB_SleepBreath"); LieDown = loader.Load("BB_LieDown"); StandUp = loader.Load("BB_StandUp"); RamHit = loader.Load("BB_RamHit"); loader.LogSummary(); } private static AudioClip[][] NewSteps() { AudioClip[][] array = new AudioClip[SurfaceNames.Length][]; for (int i = 0; i < array.Length; i++) { array[i] = NoClips; } return array; } } internal sealed class BeetleBullSpawnWeights : ContextualSpawnWeights { internal BeetleBullSpawnWeights(Func<float> multiplier, Func<string> moonOverrides, Action<string> logWarning) : base(SpawnWeightTable.BeetleBull, "Beetle Bull", multiplier, moonOverrides, logWarning) { } } [HarmonyPatch] internal static class BeetleBullThreatPatches { private const float RepeatSeconds = 0.1f; private const float RepeatDistance = 0.5f; private static float _lastGunshotTime = float.NegativeInfinity; private static Vector3 _lastGunshotPosition; private static float _lastExplosionTime = float.NegativeInfinity; private static Vector3 _lastExplosionPosition; private static bool _failureLogged; [HarmonyPatch(typeof(ShotgunItem), "ShootGun")] [HarmonyPostfix] private static void ShootGunPostfix(Vector3 shotgunPosition) { //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_003f: Unknown result type (might be due to invalid IL or missing references) try { float num = ((Plugin.ModConfig != null) ? Plugin.ModConfig.GunshotRange.Value : 0f); if (num > 0f && IsHost() && !IsRepeat(shotgunPosition, ref _lastGunshotTime, ref _lastGunshotPosition)) { BeetleBullAI.OnLoudNoiseServer(shotgunPosition, num, BeetleBullAI.FleeCause.Gunshot); } } catch (Exception e) { LogFailureOnce("ShootGun", e); } } [HarmonyPatch(typeof(Landmine), "SpawnExplosion")] [HarmonyPostfix] private static void SpawnExplosionPostfix(Vector3 explosionPosition) { //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_003f: Unknown result type (might be due to invalid IL or missing references) try { float num = ((Plugin.ModConfig != null) ? Plugin.ModConfig.ExplosionRange.Value : 0f); if (num > 0f && IsHost() && !IsRepeat(explosionPosition, ref _lastExplosionTime, ref _lastExplosionPosition)) { BeetleBullAI.OnLoudNoiseServer(explosionPosition, num, BeetleBullAI.FleeCause.Explosion); } } catch (Exception e) { LogFailureOnce("SpawnExplosion", e); } } [HarmonyPatch(typeof(StartOfRound), "ReviveDeadPlayers")] [HarmonyPostfix] private static void ReviveDeadPlayersPostfix() { try { BeetleBullPlayerMotion.Clear(); } catch (Exception e) { LogFailureOnce("ReviveDeadPlayers", e); } } private static bool IsHost() { NetworkManager singleton = NetworkManager.Singleton; if ((Object)(object)singleton != (Object)null) { return singleton.IsServer; } return false; } private static bool IsRepeat(Vector3 position, ref float lastTime, ref Vector3 lastPosition) { //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Unknown result type (might be due to invalid IL or missing references) float time = Time.time; if (time - lastTime < 0.1f) { Vector3 val = position - lastPosition; if (((Vector3)(ref val)).sqrMagnitude < 0.25f) { return true; } } lastTime = time; lastPosition = position; return false; } private static void LogFailureOnce(string patch, Exception e) { if (!_failureLogged) { _failureLogged = true; ManualLogSource log = Plugin.Log; if (log != null) { log.LogError((object)$"[BeetleBull] {patch} postfix failed (further failures are not logged): {e}"); } } } } [BepInPlugin("y4ngz.lethalcompany.beetlebull", "Y4NGZ Beetle Bull", "2.0.0")] [BepInDependency(/*Could not decode attribute arguments.*/)] public sealed class Plugin : BaseUnityPlugin { internal const string BundleFilename = "beetlebull.bundle"; internal const string PrefabName = "BeetleBull"; internal const string DawnNamespace = "y4ngz_monsters"; internal const string DawnEnemyKey = "beetle_bull"; internal const string TerminalKeyword = "beetlebull"; internal const string BestiaryText = "Beetle Bull\n\nDanger level: low, unless struck\n\nA heavy armoured grazer that roams the open ground of a moon in small herds and ignores anyone who leaves it alone. Strike one and that bull lowers its horns and charges, throwing its attacker through the air. Eyeless Dogs and Old Birds hunt it.\n\n"; internal const int VariantCount = 3; internal const string BodyMaterialPrefix = "BB_Body_"; internal const string EyesMaterialPrefix = "BB_Eyes_"; internal const string BodyRendererName = "BeetleBull_Body"; internal const string EyesRendererName = "BeetleBull_Eyes"; internal const string HeadBoneName = "Head"; internal const string RamHitPointName = "RamHitPoint"; internal const string KickDustFxName = "KickDustFx"; internal const string DustBathFxName = "DustBathFx"; private static readonly string[] VariantSuffixes = new string[3] { "A", "B", "C" }; private const string BundleBuilderPath = "Assets/Y4NGZ/BeetleBull/Editor/BeetleBullAssetBuilder.cs"; private const int ScanNodeLayerFallback = 22; internal static ManualLogSource Log; internal static BeetleBullConfig ModConfig; internal static AssetBundle ModAssets; internal static EnemyType EnemyType; internal static string AssemblyDirectory; internal static readonly Material[] BodyVariantMaterials = (Material[])(object)new Material[3]; internal static readonly Material[] EyesVariantMaterials = (Material[])(object)new Material[3]; private static bool _netcodeInitialized; private void Awake() { //IL_0039: Unknown result type (might be due to invalid IL or missing references) Log = ((BaseUnityPlugin)this).Logger; try { InitializeNetcodeRPCs(); ModConfig = new BeetleBullConfig(((BaseUnityPlugin)this).Config); AssemblyDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); try { new Harmony("y4ngz.lethalcompany.beetlebull").PatchAll(typeof(Plugin).Assembly); } catch (Exception arg) { Log.LogError((object)$"[BeetleBull] Harmony patching failed: {arg}"); } if (!LoadBundle()) { return; } BeetleBullSounds.Load(ModAssets, Log, "beetlebull.bundle"); GameObject val = ModAssets.LoadAsset<GameObject>("BeetleBull"); if ((Object)(object)val == (Object)null) { Log.LogError((object)"Prefab 'BeetleBull' not found in beetlebull.bundle. Bundle contents:"); DumpBundleAssets(); return; } LoadVariantMaterials(); ValidateAuthoredPrefab(val); BeetleBullAI beetleBullAI = PreparePrefab(val); EnemyType = CreateEnemyType(val, beetleBullAI); ((EnemyAI)beetleBullAI).enemyType = EnemyType; RegisterWithDawn(val); if (!ModConfig.Enabled.Value) { Log.LogInfo((object)"Y4NGZ Beetle Bull: registered network prefab; spawning disabled by config."); } Log.LogInfo((object)"Y4NGZ Beetle Bull v2.0.0 loaded. Registered as 'Beetle Bull'."); } catch (Exception arg2) { Log.LogError((object)string.Format("[{0}] Initialization failed: {1}", "Y4NGZ Beetle Bull", arg2)); } } private static void RegisterWithDawn(GameObject prefab) { BeetleBullSpawnWeights spawnWeights = new BeetleBullSpawnWeights(() => (!ModConfig.Enabled.Value) ? 0f : ModConfig.SpawnWeightMultiplier.Value, () => ModConfig.MoonWeightOverrides.Value, delegate(string message) { Log.LogWarning((object)message); }); DawnLib.RegisterNetworkPrefab(prefab); DawnLib.DefineEnemy(NamespacedKey<DawnEnemyInfo>.From("y4ngz_monsters", "beetle_bull"), EnemyType, (Action<EnemyInfoBuilder>)delegate(EnemyInfoBuilder builder) { ((BaseInfoBuilder<DawnEnemyInfo, EnemyType, EnemyInfoBuilder>)(object)builder.DefineDaytime((Action<EnemyLocationBuilder>)delegate(EnemyLocationBuilder location) { location.SetWeights((Action<WeightTableBuilder<DawnMoonInfo, SpawnWeightContext>>)delegate(WeightTableBuilder<DawnMoonInfo, SpawnWeightContext> table) { table.SetGlobalWeight((IWeighted)(object)spawnWeights); }); }).CreateBestiaryNode("Beetle Bull\n\nDanger level: low, unless struck\n\nA heavy armoured grazer that roams the open ground of a moon in small herds and ignores anyone who leaves it alone. Strike one and that bull lowers its horns and charges, throwing its attacker through the air. Eyeless Dogs and Old Birds hunt it.\n\n").CreateNameKeyword("beetlebull")).AddTags((IEnumerable<NamespacedKey>)(object)new NamespacedKey[4] { Tags.Passive, Tags.Organic, Tags.Killable, Tags.Large }); }); } private static void InitializeNetcodeRPCs() { if (_netcodeInitialized) { return; } _netcodeInitialized = true; Type[] types = Assembly.GetExecutingAssembly().GetTypes(); foreach (Type type in types) { MethodInfo[] methods; try { methods = type.GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); } catch { continue; } foreach (MethodInfo methodInfo in methods) { if (methodInfo.GetCustomAttributes(typeof(RuntimeInitializeOnLoadMethodAttribute), inherit: false).Length == 0) { continue; } try { methodInfo.Invoke(null, null); } catch (Exception ex) { ManualLogSource log = Log; if (log != null) { log.LogWarning((object)("[NetcodeInit] " + type.Name + "." + methodInfo.Name + " failed: " + ex.Message)); } } } } } private static bool LoadBundle() { if (string.IsNullOrEmpty(AssemblyDirectory)) { Log.LogError((object)"Could not resolve plugin assembly directory."); return false; } string text = Path.Combine(AssemblyDirectory, "beetlebull.bundle"); if (!File.Exists(text)) { Log.LogError((object)("Missing asset bundle: " + text)); return false; } ModAssets = AssetBundle.LoadFromFile(text); if ((Object)(object)ModAssets == (Object)null) { Log.LogError((object)("AssetBundle.LoadFromFile returned null for " + text + ".")); return false; } return true; } private static void LoadVariantMaterials() { for (int i = 0; i < 3; i++) { BodyVariantMaterials[i] = LoadVariantMaterial("BB_Body_" + VariantSuffixes[i]); EyesVariantMaterials[i] = LoadVariantMaterial("BB_Eyes_" + VariantSuffixes[i]); } } private static Material LoadVariantMaterial(string materialName) { Material val = ModAssets.LoadAsset<Material>(materialName); if ((Object)(object)val == (Object)null) { LogBundleError("variant material '" + materialName + "' is missing, so bulls of that variant keep the authored colour"); } else if ((Object)(object)val.shader == (Object)null || !val.shader.isSupported) { LogBundleError("variant material '" + materialName + "' has no supported shader"); } return val; } private static void ValidateAuthoredPrefab(GameObject prefab) { if ((Object)(object)prefab.transform.Find("VisualRoot") == (Object)null) { LogBundleError("the VisualRoot child is missing"); } if ((Object)(object)prefab.GetComponentInChildren<Animator>(true) == (Object)null) { LogBundleError("no Animator, so the bull cannot animate"); } if ((Object)(object)FindChildRecursive(prefab.transform, "Head") == (Object)null) { LogBundleError("no 'Head' bone, so the eye and the ram fallback use fixed offsets"); } if ((Object)(object)FindChildRecursive(prefab.transform, "RamHitPoint") == (Object)null) { LogBundleError("no 'RamHitPoint' under the Head bone, so the ram uses the fallback point"); } if ((Object)(object)FindSkinnedRenderer(prefab, "BeetleBull_Body") == (Object)null) { LogBundleError("no 'BeetleBull_Body' SkinnedMeshRenderer, so colour variants cannot apply"); } if ((Object)(object)FindSkinnedRenderer(prefab, "BeetleBull_Eyes") == (Object)null) { LogBundleError("no 'BeetleBull_Eyes' SkinnedMeshRenderer, so eye variants cannot apply"); } SkinnedMeshRenderer[] componentsInChildren = prefab.GetComponentsInChildren<SkinnedMeshRenderer>(true); if (componentsInChildren.Length == 0) { LogBundleError("no SkinnedMeshRenderer"); } for (int i = 0; i < componentsInChildren.Length; i++) { Material[] sharedMaterials = ((Renderer)componentsInChildren[i]).sharedMaterials; for (int j = 0; j < sharedMaterials.Length; j++) { Material val = sharedMaterials[j]; if ((Object)(object)val == (Object)null || (Object)(object)val.shader == (Object)null || !val.shader.isSupported) { LogBundleError(string.Format("'{0}' material slot {1} ('{2}') has no supported shader", ((Object)componentsInChildren[i]).name, j, ((Object)(object)val != (Object)null) ? ((Object)val).name : "null")); } } } ScanNodeProperties componentInChildren = prefab.GetComponentInChildren<ScanNodeProperties>(true); if ((Object)(object)componentInChildren == (Object)null) { LogBundleError("no ScanNode with ScanNodeProperties, so the Beetle Bull cannot be scanned"); } else { Collider component = ((Component)componentInChildren).GetComponent<Collider>(); if ((Object)(object)component == (Object)null || !component.isTrigger) { LogBundleError("the ScanNode has no trigger collider"); } int num = LayerMask.NameToLayer("ScanNode"); if (num < 0) { num = 22; } if (((Component)componentInChildren).gameObject.layer != num) { LogBundleError($"the ScanNode is on layer {((Component)componentInChildren).gameObject.layer}, not ScanNode ({num})"); } } if ((Object)(object)prefab.GetComponentInChildren<NetworkTransform>(true) != (Object)null) { LogBundleError("the prefab carries a NetworkTransform; remove it in the builder, because EnemyAI already replicates position through serverPosition and two writers jitter clients"); } } private static void LogBundleError(string problem) { Log.LogError((object)("[BeetleBull] beetlebull.bundle: " + problem + ". Fix it in Assets/Y4NGZ/BeetleBull/Editor/BeetleBullAssetBuilder.cs and rebuild the bundle; the plugin does not repair authored parts.")); } private static BeetleBullAI PreparePrefab(GameObject prefab) { //IL_00d1: Unknown result type (might be due to invalid IL or missing references) //IL_00d6: Unknown result type (might be due to invalid IL or missing references) //IL_00e1: Unknown result type (might be due to invalid IL or missing references) //IL_00e6: Unknown result type (might be due to invalid IL or missing references) //IL_00eb: Unknown result type (might be due to invalid IL or missing references) //IL_012f: Unknown result type (might be due to invalid IL or missing references) //IL_0189: Unknown result type (might be due to invalid IL or missing references) //IL_01c6: Unknown result type (might be due to invalid IL or missing references) //IL_01b2: Unknown result type (might be due to invalid IL or missing references) AssignUniqueNetworkHash(prefab, "BeetleBull"); TrySetTag(prefab, "Enemy"); TrySetLayer(prefab, "Enemies"); BeetleBullAI orAddComponent = GetOrAddComponent<BeetleBullAI>(prefab); ((EnemyAI)orAddComponent).updatePositionThreshold = 0.3f; Animator componentInChildren = prefab.GetComponentInChildren<Animator>(true); if ((Object)(object)componentInChildren != (Object)null) { componentInChildren.cullingMode = (AnimatorCullingMode)1; ((EnemyAI)orAddComponent).creatureAnimator = componentInChildren; GetOrAddComponent<BeetleBullJawDriver>(((Component)componentInChildren).gameObject); EnsureAnimationRelay(componentInChildren, orAddComponent); } Transform val = (orAddComponent.headAimBodyFrame = prefab.transform.Find("VisualRoot")); if ((Object)(object)val != (Object)null) { GetOrAddComponent<BeetleBullGroundConform>(((Component)val).gameObject); } NavMeshAgent orAddComponent2 = GetOrAddComponent<NavMeshAgent>(prefab); ConfigureAgent(orAddComponent2); ((EnemyAI)orAddComponent).agent = orAddComponent2; orAddComponent.headBone = FindChildRecursive(prefab.transform, "Head"); if ((Object)(object)orAddComponent.headBone != (Object)null) { orAddComponent.headRestForwardLocal = Quaternion.Inverse(orAddComponent.headBone.rotation) * prefab.transform.forward; } orAddComponent.ramHitPoint = FindChildRecursive(prefab.transform, "RamHitPoint"); ((EnemyAI)orAddComponent).eye = (((Object)(object)orAddComponent.headBone != (Object)null) ? orAddComponent.headBone : GetOrCreateChild(prefab.transform, "EyeTransform", new Vector3(0f, 2.6f, 1.6f))); orAddComponent.bodyRenderer = FindSkinnedRenderer(prefab, "BeetleBull_Body"); orAddComponent.eyesRenderer = FindSkinnedRenderer(prefab, "BeetleBull_Eyes"); Vector3 localPosition = default(Vector3); ((Vector3)(ref localPosition))..ctor(0f, 1.9f, 0f); AudioSource orCreateAudioSource = GetOrCreateAudioSource(prefab.transform, "BeetleBullSFX", localPosition); ApplyAudioDistance(orCreateAudioSource); AudioSource val2 = (((Object)(object)orAddComponent.headBone != (Object)null) ? GetOrCreateAudioSource(orAddComponent.headBone, "BeetleBullVoice", Vector3.zero) : GetOrCreateAudioSource(prefab.transform, "BeetleBullVoice", localPosition)); ApplyAudioDistance(val2); ((EnemyAI)orAddComponent).creatureSFX = orCreateAudioSource; ((EnemyAI)orAddComponent).creatureVoice = val2; AssignAmbientAssets(prefab, orAddComponent); PrepareScanNode(prefab); BuildCollision(prefab, orAddComponent); EnsureBehaviourStates(orAddComponent); return orAddComponent; } private static void ConfigureAgent(NavMeshAgent agent) { agent.speed = Mathf.Max(0.1f, ModConfig.WalkSpeed.Value); agent.acceleration = 6f; agent.angularSpeed = 90f; agent.stoppingDistance = 0.8f; agent.radius = 1.3f; agent.height = 2.9f; agent.baseOffset = 0f; agent.autoBraking = true; agent.autoRepath = true; agent.obstacleAvoidanceType = (ObstacleAvoidanceType)4; agent.avoidancePriority = 50; } private static void EnsureAnimationRelay(Animator animator, BeetleBullAI ai) { GetOrAddComponent<BeetleBullAnimationRelay>(((Component)animator).gameObject).owner = ai; } private static void AssignAmbientAssets(GameObject prefab, BeetleBullAI ai) { ai.kickDustClip = BeetleBullSounds.KickDust; ai.alertClip = BeetleBullSounds.Alert; ai.ramClip = BeetleBullSounds.RamHit; Transform val = FindChildRecursive(prefab.transform, "KickDustFx"); ai.kickDustFx = (((Object)(object)val != (Object)null) ? ((Component)val).GetComponent<ParticleSystem>() : null); Transform val2 = FindChildRecursive(prefab.transform, "DustBathFx"); ai.dustBathFx = (((Object)(object)val2 != (Object)null) ? ((Component)val2).GetComponent<ParticleSystem>() : null); if ((Object)(object)ai.kickDustFx == (Object)null) { Log.LogInfo((object)"[BeetleBull] beetlebull.bundle: optional kick dust: ParticleSystem child 'KickDustFx' missing."); } } internal static void ApplyAudioDistance(AudioSource sfx) { if ((Object)(object)sfx != (Object)null) { sfx.maxDistance = Mathf.Max(3.5f, ModConfig.SfxMaxDistance.Value); } } private static void EnsureBehaviourStates(BeetleBullAI ai) { //IL_0009: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Expected O, but got Unknown //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_003a: Unknown result type (might be due to invalid IL or missing references) //IL_0045: Unknown result type (might be due to invalid IL or missing references) //IL_004c: Unknown result type (might be due to invalid IL or missing references) //IL_0057: Unknown result type (might be due to invalid IL or missing references) //IL_005f: Expected O, but got Unknown //IL_0061: Unknown result type (might be due to invalid IL or missing references) //IL_0066: Unknown result type (might be due to invalid IL or missing references) //IL_0071: Unknown result type (might be due to invalid IL or missing references) //IL_0078: Unknown result type (might be due to invalid IL or missing references) //IL_0083: Unknown result type (might be due to invalid IL or missing references) //IL_008b: Expected O, but got Unknown //IL_008d: Unknown result type (might be due to invalid IL or missing references) //IL_0092: Unknown result type (might be due to invalid IL or missing references) //IL_009d: Unknown result type (might be due to invalid IL or missing references) //IL_00a4: Unknown result type (might be due to invalid IL or missing references) //IL_00af: Unknown result type (might be due to invalid IL or missing references) //IL_00b7: Expected O, but got Unknown //IL_00b9: Unknown result type (might be due to invalid IL or missing references) //IL_00be: Unknown result type (might be due to invalid IL or missing references) //IL_00c9: Unknown result type (might be due to invalid IL or missing references) //IL_00d0: Unknown result type (might be due to invalid IL or missing references) //IL_00db: Unknown result type (might be due to invalid IL or missing references) //IL_00e3: Expected O, but got Unknown //IL_00e5: Unknown result type (might be due to invalid IL or missing references) //IL_00ea: Unknown result type (might be due to invalid IL or missing references) //IL_00f5: Unknown result type (might be due to invalid IL or missing references) //IL_00fc: Unknown result type (might be due to invalid IL or missing references) //IL_0107: Unknown result type (might be due to invalid IL or missing references) //IL_010f: Expected O, but got Unknown ((EnemyAI)ai).enemyBehaviourStates = (EnemyBehaviourState[])(object)new EnemyBehaviourState[6] { new EnemyBehaviourState { name = "Graze", IsAnimTrigger = false, parameterString = "Charging", boolValue = false }, new EnemyBehaviourState { name = "Alert", IsAnimTrigger = false, parameterString = "Charging", boolValue = true }, new EnemyBehaviourState { name = "Charge", IsAnimTrigger = false, parameterString = "Charging", boolValue = true }, new EnemyBehaviourState { name = "Recover", IsAnimTrigger = false, parameterString = "Charging", boolValue = false }, new EnemyBehaviourState { name = "Dead", IsAnimTrigger = false, parameterString = "Charging", boolValue = false }, new EnemyBehaviourState { name = "Fleeing", IsAnimTrigger = false, parameterString = "Charging", boolValue = false } }; ((EnemyAI)ai).currentBehaviourStateIndex = 0; ((EnemyAI)ai).previousBehaviourStateIndex = 0; ((EnemyAI)ai).currentBehaviourState = ((EnemyAI)ai).enemyBehaviourStates[0]; } private static void PrepareScanNode(GameObject prefab) { ScanNodeProperties componentInChildren = prefab.GetComponentInChildren<ScanNodeProperties>(true); if (!((Object)(object)componentInChildren == (Object)null)) { componentInChildren.headerText = "Beetle Bull"; componentInChildren.subText = string.Empty; Rigidbody orAddComponent = GetOrAddComponent<Rigidbody>(((Component)componentInChildren).gameObject); orAddComponent.isKinematic = true; orAddComponent.useGravity = false; orAddComponent.detectCollisions = true; } } private static void BuildCollision(GameObject prefab, BeetleBullAI ai) { //IL_003a: Unknown result type (might be due to invalid IL or missing references) //IL_0040: Unknown result type (might be due to invalid IL or missing references) //IL_006b: Unknown result type (might be due to invalid IL or missing references) //IL_00a8: Unknown result type (might be due to invalid IL or missing references) //IL_00ae: Unknown result type (might be due to invalid IL or missing references) //IL_00b4: Unknown result type (might be due to invalid IL or missing references) Vector3 val = default(Vector3); ((Vector3)(ref val))..ctor(2.4f, 2f, 3.4f); Vector3 center = default(Vector3); ((Vector3)(ref center))..ctor(0f, 1.9f, 0f); BoxCollider orAddComponent = GetOrAddComponent<BoxCollider>(prefab); ((Collider)orAddComponent).isTrigger = false; orAddComponent.center = center; orAddComponent.size = val; Rigidbody orAddComponent2 = GetOrAddComponent<Rigidbody>(prefab); orAddComponent2.isKinematic = true; orAddComponent2.useGravity = false; orAddComponent2.detectCollisions = true; Transform orCreateChild = GetOrCreateChild(prefab.transform, "Collision", Vector3.zero); TrySetTag(((Component)orCreateChild).gameObject, "Enemy"); TrySetLayer(((Component)orCreateChild).gameObject, "Enemies"); BoxCollider orAddComponent3 = GetOrAddComponent<BoxCollider>(((Component)orCreateChild).gameObject); ((Collider)orAddComponent3).isTrigger = true; orAddComponent3.center = center; orAddComponent3.size = val * 1.1f; Rigidbody orAddComponent4 = GetOrAddComponent<Rigidbody>(((Component)orCreateChild).gameObject); orAddComponent4.isKinematic = true; orAddComponent4.useGravity = false; orAddComponent4.detectCollisions = true; EnemyAICollisionDetect orAddComponent5 = GetOrAddComponent<EnemyAICollisionDetect>(((Component)orCreateChild).gameObject); orAddComponent5.mainScript = (EnemyAI)(object)ai; orAddComponent5.alwaysAllowHitting = true; orAddComponent5.canCollideWithEnemies = true; orAddComponent5.onlyCollideWhenGrounded = false; } private static EnemyType CreateEnemyType(GameObject prefab, BeetleBullAI ai) { //IL_011f: Unknown result type (might be due to invalid IL or missing references) //IL_0126: Unknown result type (might be due to invalid IL or missing references) //IL_012d: Unknown result type (might be due to invalid IL or missing references) EnemyType obj = ScriptableObject.CreateInstance<EnemyType>(); obj.enemyName = "Beetle Bull"; obj.enemyPrefab = prefab; obj.PowerLevel = ModConfig.PowerLevel.Value; obj.DiversityPowerLevel = 1; obj.MaxCount = Mathf.Max(1, ModConfig.MaxCount.Value); obj.spawnInGroupsOf = Mathf.Clamp(ModConfig.GroupSize.Value, 1, 4); obj.canDie = true; obj.canBeStunned = true; obj.canBeDestroyed = true; obj.stunTimeMultiplier = 1f; obj.stunGameDifficultyMultiplier = 1f; obj.destroyOnDeath = false; obj.doorSpeedMultiplier = 1f; obj.isOutsideEnemy = true; obj.isDaytimeEnemy = true; obj.pushPlayerDistance = 0f; obj.pushPlayerForce = 0f; obj.normalizedTimeInDayToLeave = 1f; obj.probabilityCurve = AnimationCurve.Constant(0f, 1f, 1f); obj.numberSpawnedFalloff = AnimationCurve.Linear(0f, 1f, 1f, 0f); obj.useNumberSpawnedFalloff = true; obj.disableAnimatorWhenFar = false; obj.SizeLimit = (NavSizeLimit)1; obj.EnemySize = (EnemySize)1; obj.WaterType = (EnemyWaterType)0; CreatureSfx.Apply(obj, (EnemyAI)(object)ai, BeetleBullSounds.Stunned, null, BeetleBullSounds.Death); return obj; } private static T GetOrAddComponent<T>(GameObject target) where T : Component { T component = target.GetComponent<T>(); if (!((Object)(object)component != (Object)null)) { return target.AddComponent<T>(); } return component; } private static AudioSource GetOrCreateAudioSource(Transform parent, string childName, Vector3 localPosition) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) Transform orCreateChild = GetOrCreateChild(parent, childName, localPosition); AudioSource val = ((Component)orCreateChild).GetComponent<AudioSource>(); if ((Object)(object)val == (Object)null) { val = ((Component)orCreateChild).gameObject.AddComponent<AudioSource>(); val.playOnAwake = false; val.loop = false; val.spatialBlend = 1f; val.rolloffMode = (AudioRolloffMode)0; val.minDistance = 2.5f; val.dopplerLevel = 0f; val.spread = 0f; } return val; } private static Transform GetOrCreateChild(Transform parent, string name, Vector3 localPosition) { //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_0028: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_003a: Unknown result type (might be due to invalid IL or missing references) Transform val = parent.Find(name); if ((Object)(object)val != (Object)null) { return val; } val = new GameObject(name).transform; val.SetParent(parent, false); val.localPosition = localPosition; val.localRotation = Quaternion.identity; val.localScale = Vector3.one; return val; } private static Transform FindChildRecursive(Transform parent, string name) { if ((Object)(object)parent == (Object)null || string.IsNullOrWhiteSpace(name)) { return null; } if (string.Equals(((Object)parent).name, name, StringComparison.Ordinal)) { return parent; } for (int i = 0; i < parent.childCount; i++) { Transform val = FindChildRecursive(parent.GetChild(i), name); if ((Object)(object)val != (Object)null) { return val; } } return null; } private static SkinnedMeshRenderer FindSkinnedRenderer(GameObject prefab, string rendererName) { SkinnedMeshRenderer[] componentsInChildren = prefab.GetComponentsInChildren<SkinnedMeshRenderer>(true); for (int i = 0; i < componentsInChildren.Length; i++) { if (string.Equals(((Object)componentsInChildren[i]).name, rendererName, StringComparison.Ordinal)) { return componentsInChildren[i]; } } return null; } private static void AssignUniqueNetworkHash(GameObject prefab, string key) { try { NetworkObject orAddComponent = GetOrAddComponent<NetworkObject>(prefab); uint num = BitConverter.ToUInt32(MD5.Create().ComputeHash(Encoding.UTF8.GetBytes("y4ngz.lethalcompany.beetlebull." + key)), 0); PropertyInfo property = typeof(NetworkObject).GetProperty("GlobalObjectIdHash", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); if (property != null && property.CanWrite) { property.SetValue(orAddComponent, num); return; } FieldInfo fieldInfo = typeof(NetworkObject).GetField("GlobalObjectIdHash", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic) ?? typeof(NetworkObject).GetField("<GlobalObjectIdHash>k__BackingField", BindingFlags.Instance | BindingFlags.NonPublic); if (fieldInfo != null) { fieldInfo.SetValue(orAddComponent, num); } } catch (Exception ex) { Log.LogWarning((object)("[BeetleBull] Could not assign NetworkObject hash: " + ex.Message)); } } private static void TrySetTag(GameObject obj, string tag) { try { obj.tag = tag; } catch { } } private static void TrySetLayer(GameObject obj, string layerName) { if ((Object)(object)obj == (Object)null) { return; } int num = LayerMask.NameToLayer(layerName); if (num < 0) { num = ResolveLayerFallback(layerName); } if (num >= 0 && num <= 31) { obj.layer = num; return; } ManualLogSource log = Log; if (log != null) { log.LogWarning((object)$"[BeetleBull] Layer '{layerName}' unresolved; '{((Object)obj).name}' stays on layer {obj.layer}."); } } private static int ResolveLayerFallback(string layerName) { if (string.Equals(layerName, "ScanNode", StringComparison.OrdinalIgnoreCase)) { return 22; } if (string.Equals(layerName, "Enemies", StringComparison.OrdinalIgnoreCase)) { return 19; } return -1; } private static void DumpBundleAssets() { if (!((Object)(object)ModAssets == (Object)null)) { string[] allAssetNames = ModAssets.GetAllAssetNames(); foreach (string text in allAssetNames) { Log.LogError((object)(" - " + text)); } } } } internal static class PluginInfo { public const string PLUGIN_GUID = "y4ngz.lethalcompany.beetlebull"; public const string PLUGIN_NAME = "Y4NGZ Beetle Bull"; public const string PLUGIN_VERSION = "2.0.0"; } } namespace Y4NGZBeetleBull.AI { public sealed class BeetleBullAI : EnemyAI, IVisibleThreat { internal enum AmbientAction : byte { None = 0, IdleKick = 1, HeadShake = 2, Sniff = 3, Scratch = 4, Flutter = 5, Moo = 6, LieDown = 7, StandUp = 8, FleeBellow = 9, DustBath = 10, CuriousSniff = 12, BackOff = 13, Sparring = 14 } private enum RestKind : byte { None, Midday, Night } private enum ClearanceFault : byte { None, NoNavMesh, Edge, Probe } private enum BlockedRepick : byte { Stand, GrazeSpot, FleeSpot, SlotPoint, StepBackEnd, BurstEnd, SeparationEnd, StareHere, MigrationEnd, CuriousEnd } private enum GrazePhase { Stand, Walk, Graze, HeadUp } private enum MotionTier : byte { Walk, Trot, Charge } private sealed class Herd { public readonly int Id; public readonly List<BeetleBullAI> Members = new List<BeetleBullAI>(); public BeetleBullAI Leader; public int SlotCount; public float SlotOffset; public float CalmSeconds; public float MigrationDueSeconds; public bool Migrating; public Vector3 MigrationTarget; public float MigrationEndTime; public readonly Vector3[] Trail = (Vector3[])(object)new Vector3[64]; public int TrailCount; public int TrailHead; public float NextCuriousTime; public Vector3 NewestTrailPoint => Trail[(TrailHead - 1 + Trail.Length) % Trail.Length]; public Herd(int id) { Id = id; SlotCount = 1; SlotOffset = Random.Range(0f, 360f); } public void ClearTrail(Vector3 start) { //IL_000f: Unknown result type (might be due to invalid IL or missing references) TrailCount = 0; TrailHead = 0; PushTrail(start); } public void PushTrail(Vector3 point) { //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) Trail[TrailHead] = point; TrailHead = (TrailHead + 1) % Trail.Length; if (TrailCount < Trail.Length) { TrailCount++; } } public bool TryGetTrailPoint(Vector3 leaderPosition, float back, out Vector3 point) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_006e: Unknown result type (might be due to invalid IL or missing references) //IL_006f: Unknown result type (might be due to invalid IL or missing references) //IL_005d: Unknown result type (might be due to invalid IL or missing references) //IL_005f: Unknown result type (might be due to invalid IL or missing references) //IL_0045: Unknown result type (might be due to invalid IL or missing references) //IL_0046: Unknown result type (might be due to invalid IL or missing references) //IL_004c: Unknown result type (might be due to invalid IL or missing references) //IL_0051: Unknown result type (might be due to invalid IL or missing references) int num = Trail.Length; float num2 = back; Vector3 val = leaderPosition; for (int i = 0; i < TrailCount; i++) { Vector3 val2 = Trail[(TrailHead - 1 - i + num) % num]; float num3 = PlanarDistance(val, val2); if (num3 >= num2 && num3 > 0.0001f) { point = Vector3.Lerp(val, val2, num2 / num3); return true; } num2 -= num3; val = val2; } point = val; return TrailCount == num; } } private struct GrazeFallback { public bool Has; public Vector3 Point; public bool Complete; public bool Accepted; public float Clearance; public float Score; public void Offer(Vector3 point, bool complete, bool accepted, float clearance, float score) { //IL_004c: Unknown result type (might be due to invalid IL or missing references) //IL_004d: Unknown result type (might be due to invalid IL or missing references) if (Has) { if (complete != Complete) { if (!complete) { return; } } else if (accepted != Accepted) { if (!accepted) { return; } } else if (accepted ? (clearance <= Clearance) : (score <= Score)) { return; } } Has = true; Point = point; Complete = complete; Accepted = accepted; Clearance = clearance; Score = score; } } private struct GrazeTally { public int Tries; public int Path; public int Edge; public int Probe; public int Other; public string Note; public int Rejected => Path + Edge + Probe + Other; public string Describe(bool wander) { string text = (wander ? $"wander {Rejected} tries rejected (" : $"{Rejected} node tries rejected ("); bool first = true; Append(ref text, ref first, "path", Path); Append(ref text, ref first, "edge", Edge); Append(ref text, ref first, "probe", Probe); Append(ref text, ref first, "other", Other); return text + ")"; } private static void Append(ref string text, ref bool first, string name, int count) { if (count != 0) { text = text + (first ? string.Empty : ", ") + name + " " + count; first = false; } } } private enum Reaction : byte { None, HeadUp, StepBack, Startle, HeadLift, TrotBurst, Curious } private enum CuriousPhase : byte { Approach, Hesitate, Close, Sniff, BackOff, StepAway } private enum GrazeAvoidKind : byte { None, AwayFromPlayer, FromThreat } private readonly struct GrazeAvoid { public readonly GrazeAvoidKind Kind; public readonly Vector3 Point; public readonly Vector3 Origin; public bool IsActive => Kind != GrazeAvoidKind.None; public bool NeedsCompletePath => Kind == GrazeAvoidKind.FromThreat; public GrazeAvoid(GrazeAvoidKind kind, Vector3 point, Vector3 origin) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_0009: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) Kind = kind; Point = point; Origin = origin; } public bool Accepts(Vector3 position) { //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_003b: Unknown result type (might be due to invalid IL or missing references) //IL_0071: Unknown result type (might be due to invalid IL or missing references) //IL_0073: Unknown result type (might be due to invalid IL or missing references) return Kind switch { GrazeAvoidKind.AwayFromPlayer => (position.x - Origin.x) * (Origin.x - Point.x) + (position.z - Origin.z) * (Origin.z - Point.z) >= 0f, GrazeAvoidKind.FromThreat => PlanarDistance(position, Point) >= 20f, _ => true, }; } public float Score(Vector3 position) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Unknown result type (might be due to invalid IL or missing references) return PlanarDistance(position, Point); } } internal enum FleeCause : byte { Damage, HitMate, Predator, Hostile, Noise, Gunshot, Explosion, Sprint } private const float IdleKickClipSeconds = 2f; private const float HeadShakeClipSeconds = 1.2f; private const float SniffClipSeconds = 2f; private const float ScratchClipSeconds = 3f; private const float FlutterClipSeconds = 1.5f; private const float MooClipSeconds = 3.5f; private const float LieDownClipSeconds = 2f; private const float StandUpClipSeconds = 2f; private const float DownResponseDelaySeconds = 1.5f; private const float BoutSettleSecondsMin = 0.3f; private const float BoutSettleSecondsMax = 1.2f; private const float IdleRerollSecondsMin = 8f; private const float IdleRerollSecondsMax = 14f; private const float MooEchoChance = 0.4f; private const float MooEchoDelayMin = 1f; private const float MooEchoDelayMax = 3f; private const float MooNoiseRange = 25f; private const float MooNoiseLoudness = 0.8f; private const float MooVoiceRepeatGuardSeconds = 1f; private const float KickDustVolume = 0.6f; private const float ClockStartHour = 6f; private const float MiddayRestStartHour = 10f; private const float MiddayRestEndHour = 16f; private const float MiddayRestIntervalHoursMin = 2f; private const float MiddayRestIntervalHoursMax = 3f; private const float MiddayRestStaggerHours = 0.6f; private const float MiddayRestSecondsMin = 40f; private const float MiddayRestSecondsMax = 90f; private const float RestRetrySeconds = 60f; private const float RestCheckSeconds = 0.5f; private const float NightSettleSeconds = 10f; private const float NightLieGapSecondsMin = 1f; private const float NightLieGapSecondsMax = 3f; private const float NightWatchSecondsMin = 60f; private const float NightWatchSecondsMax = 120f; private static readonly string[] AmbientParameterNames = new string[14] { "Listening", "Lying", "IdleKick", "Moo", "HeadShake", "Sniff", "Scratch", "Flutter", "LieDown", "StandUp", "Trotting", "Speed", "Turn", "Sleeping" }; private static bool _missingParametersLogged; private static readonly int SparringHash = Animator.StringToHash("Sparring"); private static readonly int DustBathHash = Animator.StringToHash("DustBath"); private static readonly int CuriousHash = Animator.StringToHash("Curious"); private static readonly int CuriousSniffHash = Animator.StringToHash("CuriousSniff"); private static readonly int BackOffHash = Animator.StringToHash("BackOff"); private const byte SparringFallbackFlag = 128; private static bool _missingDustFxLogged; public AudioClip kickDustClip; public ParticleSystem kickDustFx; public ParticleSystem dustBathFx; private readonly NetworkVariable<bool> _lying = new NetworkVariable<bool>(false, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); private readonly NetworkVariable<bool> _sleeping = new NetworkVariable<bool>(false, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); private readonly NetworkVariable<bool> _sparring = new NetworkVariable<bool>(false, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); private readonly NetworkVariable<bool> _curious = new NetworkVariable<bool>(false, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); private BeetleBullAI _sparPartner; private bool _sparInitiator; private Vector3 _sparSetupTarget; private float _sparSetupEndTime; private float _sparEndTime; private float _sparStoppingDistance; private float _sparKickTime; private float _sparCooldownUntil; private float _dustBathEndTime; private bool _ambientIdle; private float _nextAmbientRollTime; private float _ambientBusyUntil; private float _ambientGapEnd; private float _lieEndTime; private float _standUpStartTime; private float _standUpEndTime; private float _mooEchoTime = -1f; private bool _hasDownResponse; private float _downResponseTime; private PlayerControllerB _downResponseAttacker; private RestKind _restKind; private float _restEndTime; private bool _middayRestScheduled; private float _nextMiddayRestHour; private float _restRetryTime; private float _nextRestCheckTime; private bool _nightStill; private BeetleBullAI _nightWatch; private BeetleBullAI _watchSuccessor; private float _nextWatchChangeTime; private float _nextNightRestCheckTime; private readonly HashSet<int> _animatorParameters = new HashSet<int>(); private Animator _parameterCacheAnimator; private float _lastMooVoiceTime = float.NegativeInfinity; private bool _hasSparringParameter; private bool _hasDustBathParameter; private bool _hasCuriousParameter; private float _dustBathLocalStart = -1f; private byte _dustBathFallbackStage; private const int VanillaCollidersAndRoomMaskAndDefault = 1107298561; private static readonly float[] RingSearchBearings = new float[7] { 0f, 15f, -15f, 30f, -30f, 45f, -45f }; private NavMeshPath _clearancePath; private readonly Vector3[] _pathCorners = (Vector3[])(object)new Vector3[32]; private readonly RaycastHit[] _probeHits = (RaycastHit[])(object)new RaycastHit[8]; private int _clearanceMask = 1107298561; private int _footprintMask = 1107298561; private readonly Vector3[] _stuckSamples = (Vector3[])(object)new Vector3[5]; private int _stuckSampleCount; private int _stuckSampleHead; private float _nextStuckSampleTime; private float _nextProbeTime; private int _probeHitStreak; private bool _probeSlowed; private float _blockedGraceUntil; private bool _turnFootprintBlocked; private bool _slotPickValid; private bool _slotPickFound; private float _slotPickRetryTime; private Vector3 _slotPickRaw; private Vector3 _slotPickPoint; private Vector3 _slotAvoidPoint; private float _slotAvoidUntil; public const int StateGraze = 0; public const int StateAlert = 1; public const int StateCharge = 2; public const int StateRecover = 3; public const int StateDead = 4; public const int StateFlee = 5; internal const string AnimWalking = "Walking"; internal const string AnimGrazing = "Grazing"; internal const string AnimCharging = "Charging"; internal const string AnimStunned = "Stunned"; private static readonly int WalkingHash = Animator.StringToHash("Walking"); private static readonly int GrazingHash = Animator.StringToHash("Grazing"); private static readonly int ChargingHash = Animator.StringToHash("Charging"); private static readonly int StunnedHash = Animator.StringToHash("Stunned"); private static readonly int HeadDuckHash = Animator.StringToHash("HeadDuck"); private static readonly int RamHitHash = Animator.StringToHash("RamHit"); private static readonly int HitHash = Animator.StringToHash("Hit"); private static readonly int DeathHash = Animator.StringToHash("Death"); private static readonly int IdleStateHash = Animator.StringToHash("Idle"); private static readonly int ChargeStateHash = Animator.StringToHash("Charge"); private static readonly int RamHitStateHash = Animator.StringToHash("RamHit"); private static readonly int DeadIdleStateHash = Animator.StringToHash("DeadIdle"); private const string AnimListening = "Listening"; private const string AnimLying = "Lying"; private const string AnimIdleKick = "IdleKick"; private const string AnimMoo = "Moo"; private const string AnimHeadShake = "HeadShake"; private const string AnimSniff = "Sniff"; private const string AnimScratch = "Scratch"; private const string AnimFlutter = "Flutter"; private const string AnimLieDown = "LieDown"; private const string AnimStandUp = "StandUp"; private static readonly int ListeningHash = Animator.StringToHash("Listening"); private static readonly int LyingHash = Animator.StringToHash("Lying"); private static readonly int IdleKickHash = Animator.StringToHash("IdleKick"); private static readonly int MooHash = Animator.StringToHash("Moo"); private static readonly int HeadShakeHash = Animator.StringToHash("HeadShake"); private static readonly int SniffHash = Animator.StringToHash("Sniff"); private static readonly int ScratchHash = Animator.StringToHash("Scratch"); private static readonly int FlutterHash = Animator.StringToHash("Flutter"); private static readonly int LieDownHash = Animator.StringToHash("LieDown"); private static readonly int StandUpHash = Animator.StringToHash("StandUp"); private static readonly int LieIdleStateHash = Animator.StringToHash("LieIdle"); private const string AnimTrotting = "Trotting"; private const string AnimSpeed = "Speed"; private static readonly int TrottingHash = Animator.StringToHash("Trotting"); private static readonly int SpeedHash = Animator.StringToHash("Speed"); private static readonly int WalkStateHash = Animator.StringToHash("Walk"); private static readonly int TrotStateHash = Animator.StringToHash("Trot"); internal const string AnimTurn = "Turn"; internal const string AnimSleeping = "Sleeping"; private static readonly int TurnHash = Animator.StringToHash("Turn"); private static readonly int SleepingHash = Animator.StringToHash("Sleeping"); private static readonly int TurnLStateHash = Animator.StringToHash("TurnL"); private static readonly int TurnRStateHash = Animator.StringToHash("TurnR"); private const float RamHitClipSeconds = 0.7f; private const int NoHerd = 0; private const ulong NoLeader = ulong.MaxValue; private static readonly List<Herd> Herds = new List<Herd>(); private static int _nextHerdId = 1; public Transform headBone; public Transform ramHitPoint; public SkinnedMeshRenderer bodyRenderer; public SkinnedMeshRenderer eyesRenderer; public AudioClip alertClip; public AudioClip ramClip; private readonly NetworkVariable<int> _herdId = new NetworkVariable<int>(0, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); private readonly NetworkVariable<ulong> _herdLeaderId = new NetworkVariable<ulong>(ulong.MaxValue, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); private readonly NetworkVariable<byte> _variant = new NetworkVariable<byte>((byte)0, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); private readonly NetworkVariable<bool> _grazing = new NetworkVariable<bool>(false, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); private readonly NetworkVariable<byte> _networkState = new NetworkVariable<byte>((byte)0, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); private readonly NetworkVariable<byte> _motionTier = new NetworkVariable<byte>((byte)0, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); private readonly ServerOwnershipGuard _ownership = new ServerOwnershipGuard(); private readonly Collider[] _ramHits = (Collider[])(object)new Collider[16]; private readonly HashSet<EnemyAI> _ramHitEnemies = new HashSet<EnemyAI>(); private Herd _herd; private GrazePhase _grazePhase; private float _phaseEndTime; private float _nextGrazeNoiseTime; private float _followDistance; private float _followAngle; private int _slotIndex = -1; private float _slotHoldAngle; private bool _followerSettled; private GrazePhase _followerGrazePhase; private float _followerGrazePhaseEndTime; private bool _separating; private float _separationStartTime; private float _separationEndTime; private float _nextSeparationTime; private bool _moving; private Vector3 _requestedTarget; private Vector3 _moveTarget; private float _moveStartTime; private float _alertEndTime; private float _chargeEndTime; private float _calmTime; private Vector3 _shipPosition; private Vector3 _mainEntrancePosition; private bool _hasShipPosition; private bool _hasMainEntrance; private int _ramMask; private float _backAwayTime; private bool _ramBlockedLogged; private PlayerControllerB _grudgePlayer; private float _grudgeUntil; private bool _grudgeFirstRamDone; private bool _grudgeFollowUpCharge; private MotionTier _agentTier; private bool _turningInPlace; private readonly int[] _triedGrazeNodes = new int[4]; private bool _nextGrazeIsWander; private float _nextHerdMeetTime; private int _migrationRank; private Vector3 _lastFramePosition; private float _planarSpeed; private float _lastFrameYaw; private float _yawRate; private float _ramPresentationEndTime; private int _animatedState; private int _appliedVariant = -1; private bool _wasStunned; private bool _audioRouted; private bool _deathPresented; private const float FootstepRayStartHeight = 1f; private const float FootstepRayLength = 3f; private const float FootstepPitchMin = 0.8f; private const float FootstepPitchMax = 0.95f; private const float ChargeFootstepPitch = 0.7f; private const float ChargeFootstepVolumeScale = 1.1111112f; private const float FootstepSourceHeight = 0.3f; private const int TerrainFootstepSurface = 4; private const int TerrainGrassFootstepSurface = 5; private const float BullWalkPitchMin = 0.9f; private const float BullWalkPitchMax = 1.05f; private const float BullTrotPitchMin = 0.85f; private const float BullTrotPitchMax = 0.95f; private const float BullChargePitch = 0.8f; private const int NotOnTerrain = -1; private static StartOfRound _footstepSurfacesOwner; private static FootstepSurface[] _footstepSurfaces; private static bool _footstepSurfacesMissingLogged; private AudioSource _footstepSource; private bool _footstepSourceRouted; private int _footstepSurfaceIndex; private int _previousFootstepClip = -1; private AudioClip _previousBullStepClip; private AudioClip _previousChargeThudClip; private int _terrainFootstepGrass = -1; private const byte ListenKindNone = 0; private const byte ListenKindPlayer = 1; private const byte ListenKindPoint = 2; private const byte ListenKindGlancePlayer = 3; private const byte ListenKindGlancePoint = 4; private const ulong NoListenPlayer = ulong.MaxValue; private const int BoomboxNoiseId = 5; private const float ListenHoldSeconds = 3f; private const float ListenScanIntervalSeconds = 0.25f; private const float ListenReactionMinSeconds = 4f; private const float ListenReactionMaxSeconds = 8f; private const float ListenFlutterChance = 0.4f; private const float ListenMooChance = 0.15f; private const float ListenCurrentSourceBias = 2f; private const float ListenRestageDistance = 2f; private const float ListenPointResendDistance = 0.25f; private const int StareRingCount = 3; private const float HeadAimYawLimit = 60f; private const float HeadAimPitchLimit = 30f; private const float HeadAimSmoothing = 6f; private const float HeadAimBlendSeconds = 0.5f; private const float HeadAimPoseZeroPitch = -50f; private const float HeadAimPoseFullPitch = -25f; private const float HeadAimPoseYawLimit = 100f; private static readonly int SleepStateHash = Animator.StringToHash("Sleep"); private static readonly int SparPushStateHash = Animator.StringToHash("SparPush"); private static readonly int SparBreakStateHash = Animator.StringToHash("SparBreak"); private static readonly int DustBathStateHash = Animator.StringToHash("DustBath"); private static readonly int CuriousSniffStateHash = Animator.StringToHash("CuriousSniff"); private readonly NetworkVariable<byte> _listenKind = new NetworkVariable<byte>((byte)0, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); private readonly NetworkVariable<ulong> _listenPlayer = new NetworkVariable<ulong>(ulong.MaxValue, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); private readonly NetworkVariable<Vector3> _listenPoint = new NetworkVariable<Vector3>(Vector3.zero, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); private bool _listenActive; private bool _listenStaring; private float _listenConfirmedTime; private float _nextListenScanTime; private float _nextListenReactionTime; private float _boomboxHeardTime = float.NegativeInfinity; private Vector3 _boomboxPosition; private bool _hasStareSlot; private Vector3 _stareSlot; private Vector3 _stareSlotSource; private bool _stareSlotClear; private bool _stareSlotIssued; private bool _listenHeld; public Vector3 headRestForwardLocal; public Transform headAimBodyFrame; private float _headAimYaw; private float _headAimPitch; private float _headAimWeight; private bool _headAimApplied; private Quaternion _headAimBaseLocal; private Quaternion _headAimWrittenLocal; private const int RemoteFootstepNoiseId = 7; private const int LocalFootstepNoiseId = 6; private static readonly int PlayerSprintingTagHash = Animator.StringToHash("Sprinting"); private const float RompMinDistance = 20f; private const float RompCatchUpDistance = 6f; private const float TrotBurstDistanceMin = 6f; private const float TrotBurstDistanceMax = 10f; private const float TrotBurstNavMeshSample = 2f; private const int TrotBurstAttempts = 4; private const float TrotBurstCooldownSeconds = 30f; private const float TrotBurstMaxSeconds = 6f; private Random _bullRng; private Reaction _reaction; private float _reactionStartTime; private float _reactionEndTime; private Vector3 _reactionPoint; private float _nextApproachScanTime; private float _nextHeadReactionTime; private ulong _headUpPlayer = ulong.MaxValue; private float _headUpRearmTime; private float _nextStepBackTime; private ulong _slotHoldPlayer = ulong.MaxValue; private float _slotHoldDistance; private float _slotHoldTime; private float _slotHoldRearmSeconds; private float _nextStartleTime; private bool _headLiftPending; private float _headLiftTime; private Vector3 _headLiftPoint; private bool _drift
Y4NGZBoiledOne.dll
Decompiled a day ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security.Cryptography; using System.Text; using System.Text.RegularExpressions; using BepInEx; using BepInEx.Configuration; using BepInEx.Logging; using Dawn; using GameNetcodeStuff; using HarmonyLib; using Microsoft.CodeAnalysis; using Unity.Netcode; using UnityEngine; using UnityEngine.AI; using UnityEngine.Audio; using UnityEngine.Rendering; using UnityEngine.Rendering.HighDefinition; using UnityEngine.UI; using Y4NGZBoiledOne; using Y4NGZBoiledOne.NetcodePatcher; using Y4NGZMonsters.Shared; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: AssemblyCompany("Y4NGZBoiledOne")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0+3460ec64f0cec4948e51ddb3f02a4b0e414f105e")] [assembly: AssemblyProduct("Y4NGZBoiledOne")] [assembly: AssemblyTitle("Y4NGZBoiledOne")] [assembly: AssemblyVersion("1.0.0.0")] [module: RefSafetyRules(11)] [module: NetcodePatchedAssembly] 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 Y4NGZBoiledOne { public sealed class BoiledOneAI : EnemyAI, IBoiledOneHaunt { private static readonly List<BoiledOneAI> Live = new List<BoiledOneAI>(); private readonly NetworkVariable<BoiledOneHauntSnapshot> _snapshot = new NetworkVariable<BoiledOneHauntSnapshot>(new BoiledOneHauntSnapshot { State = new BoiledOneHauntState { TargetSlot = -1 } }, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); private readonly ServerOwnershipGuard _ownership = new ServerOwnershipGuard(); private readonly Random _random = new Random(); private BoiledOneHauntLogic _logic; private BoiledOneHauntPlayer[] _players; private BoiledOneHauntState _state = new BoiledOneHauntState { TargetSlot = -1 }; private PlayerControllerB _target; private bool _started; private bool _firstApply = true; private Vector3 _placedPosition; private float _placedYaw; private float _eyeHeight; private static readonly FieldRef<EnemyAI, float> VanillaTargetYaw = AccessTools.FieldRefAccess<EnemyAI, float>("targetYRotation"); private static readonly FieldRef<EnemyAI, float> VanillaPreviousYaw = AccessTools.FieldRefAccess<EnemyAI, float>("previousYRotation"); private readonly List<AudioSource> _audioSources = new List<AudioSource>(); private Collider _scanCollider; private float _hiddenUntil; private bool _shown; public BoiledOnePhase Phase => _state.Phase; public PlayerControllerB Target => _target; public bool TargetInShip => _state.TargetInShip; public bool IsLocalTarget { get { GameNetworkManager instance = GameNetworkManager.Instance; if ((Object)(object)_target != (Object)null && (Object)(object)instance != (Object)null) { return (Object)(object)_target == (Object)(object)instance.localPlayerController; } return false; } } public bool IsPresent => _state.IsPresent; public event Action StateChanged; internal static void ResetRoundState() { Live.RemoveAll((BoiledOneAI ai) => (Object)(object)ai == (Object)null || !((NetworkBehaviour)ai).IsSpawned); } public override void OnNetworkSpawn() { //IL_0047: Unknown result type (might be due to invalid IL or missing references) //IL_004c: Unknown result type (might be due to invalid IL or missing references) ((NetworkBehaviour)this).OnNetworkSpawn(); Live.Add(this); NetworkVariable<BoiledOneHauntSnapshot> snapshot = _snapshot; snapshot.OnValueChanged = (OnValueChangedDelegate<BoiledOneHauntSnapshot>)(object)Delegate.Combine((Delegate?)(object)snapshot.OnValueChanged, (Delegate?)(object)new OnValueChangedDelegate<BoiledOneHauntSnapshot>(OnSnapshotChanged)); if (((NetworkBehaviour)this).IsServer) { NetworkTime serverTime = ((NetworkBehaviour)this).NetworkManager.ServerTime; _logic = new BoiledOneHauntLogic(((NetworkTime)(ref serverTime)).Time); } _firstApply = true; if (_started) { ApplySnapshot(_snapshot.Value); } } public override void Start() { //IL_007b: Unknown result type (might be due to invalid IL or missing references) //IL_008b: Unknown result type (might be due to invalid IL or missing references) ((EnemyAI)this).Start(); ApplyMeshVisibility(); base.moveTowardsDestination = false; base.movingTowardsTargetPlayer = false; base.agent.updateRotation = false; base.agent.avoidancePriority = 99; if (((Behaviour)base.agent).enabled && base.agent.isOnNavMesh) { base.agent.isStopped = true; } _scanCollider = ((Component)((Component)this).transform.Find("ScanNode")).GetComponent<Collider>(); _eyeHeight = base.eye.position.y - ((Component)this).transform.position.y; ((Component)((Component)this).transform.Find("Collision")).GetComponent<Collider>().enabled = false; _started = true; if (((NetworkBehaviour)this).IsSpawned) { ApplySnapshot(_snapshot.Value); } } public override void Update() { //IL_003e: Unknown result type (might be due to invalid IL or missing references) //IL_0043: Unknown result type (might be due to invalid IL or missing references) //IL_0044: Unknown result type (might be due to invalid IL or missing references) //IL_004a: Unknown result type (might be due to invalid IL or missing references) //IL_004b: Unknown result type (might be due to invalid IL or missing references) _ownership.Ensure((EnemyAI)(object)this, Plugin.Log); ((EnemyAI)this).Update(); if (!((NetworkBehaviour)this).IsServer && _state.Placed) { Vector3 serverPosition = (((Component)this).transform.position = _snapshot.Value.Position); base.serverPosition = serverPosition; } TickHost(); UpdatePresentation(); } public override void DoAIInterval() { } public override void OnNetworkDespawn() { NetworkVariable<BoiledOneHauntSnapshot> snapshot = _snapshot; snapshot.OnValueChanged = (OnValueChangedDelegate<BoiledOneHauntSnapshot>)(object)Delegate.Remove((Delegate?)(object)snapshot.OnValueChanged, (Delegate?)(object)new OnValueChangedDelegate<BoiledOneHauntSnapshot>(OnSnapshotChanged)); Live.Remove(this); _logic = null; bool num = _state.TargetSlot >= 0; _state = new BoiledOneHauntState { TargetSlot = -1 }; _target = null; UpdatePresentation(); RefreshAudio(); if (num) { this.StateChanged?.Invoke(); } ((NetworkBehaviour)this).OnNetworkDespawn(); } public override void OnDestroy() { NetworkVariable<BoiledOneHauntSnapshot> snapshot = _snapshot; snapshot.OnValueChanged = (OnValueChangedDelegate<BoiledOneHauntSnapshot>)(object)Delegate.Remove((Delegate?)(object)snapshot.OnValueChanged, (Delegate?)(object)new OnValueChangedDelegate<BoiledOneHauntSnapshot>(OnSnapshotChanged)); Live.Remove(this); ((EnemyAI)this).OnDestroy(); } public bool TryBeginKill(BoiledOneKillTrigger trigger) { //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Unknown result type (might be due to invalid IL or missing references) if (!((NetworkBehaviour)this).IsServer || !((NetworkBehaviour)this).IsSpawned || _logic == null) { return false; } int playerCount = FillPlayers(StartOfRound.Instance); BoiledOneHauntLogic logic = _logic; NetworkTime serverTime = ((NetworkBehaviour)this).NetworkManager.ServerTime; if (!logic.TryBeginKill(((NetworkTime)(ref serverTime)).Time, _players, playerCount, ReadSettings())) { return false; } Plugin.Log.LogInfo((object)$"[BoiledOne] Kill begins on player {_logic.State.TargetSlot} ({trigger})."); Commit(); return true; } public void EndKill() { //IL_0031: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Unknown result type (might be due to invalid IL or missing references) if (((NetworkBehaviour)this).IsServer && ((NetworkBehaviour)this).IsSpawned && _logic != null) { int playerCount = FillPlayers(StartOfRound.Instance); BoiledOneHauntLogic logic = _logic; NetworkTime serverTime = ((NetworkBehaviour)this).NetworkManager.ServerTime; if (logic.EndKill(((NetworkTime)(ref serverTime)).Time, _players, playerCount, ReadSettings(), _random)) { Commit(); } } } public override void HitEnemy(int force = 1, PlayerControllerB playerWhoHit = null, bool playHitSFX = false, int hitID = -1) { } public override void HitFromExplosion(float distance) { } public override void SetEnemyStunned(bool setToStunned, float setToStunTime = 1f, PlayerControllerB setStunnedByPlayer = null) { } public override void KillEnemy(bool destroy = false) { } private void TickHost() { //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) StartOfRound instance = StartOfRound.Instance; if (!((NetworkBehaviour)this).IsServer || !((NetworkBehaviour)this).IsSpawned || _logic == null || (Object)(object)instance == (Object)null) { return; } int playerCount = FillPlayers(instance); BoiledOneHauntSettings settings = ReadSettings(); NetworkTime serverTime = ((NetworkBehaviour)this).NetworkManager.ServerTime; double time = ((NetworkTime)(ref serverTime)).Time; _logic.Tick(time, _players, playerCount, in settings, _random); int targetSlot = _logic.State.TargetSlot; PlayerControllerB val = VictimRpc.FromSlot(targetSlot); if ((Object)(object)val != (Object)null) { if (_logic.WantsPlacement(time) && TryPlace(instance, val, targetSlot)) { _logic.NotePlaced(time, in settings, _random); } TurnTowards(instance, val); } Commit(); } private int FillPlayers(StartOfRound round) { if ((Object)(object)round == (Object)null) { return 0; } PlayerControllerB[] allPlayerScripts = round.allPlayerScripts; if (_players == null) { _players = new BoiledOneHauntPlayer[allPlayerScripts.Length]; } int num = Math.Min(allPlayerScripts.Length, _players.Length); for (int i = 0; i < num; i++) { PlayerControllerB val = allPlayerScripts[i]; _players[i].Alive = (Object)(object)val != (Object)null && val.isPlayerControlled && !val.isPlayerDead; _players[i].InShip = (Object)(object)val != (Object)null && val.isInHangarShipRoom; _players[i].HauntedByOther = IsHauntedByOther(i); } return num; } private bool IsHauntedByOther(int slot) { for (int i = 0; i < Live.Count; i++) { BoiledOneAI boiledOneAI = Live[i]; if (!((Object)(object)boiledOneAI == (Object)(object)this) && !((Object)(object)boiledOneAI == (Object)null) && boiledOneAI._logic != null) { BoiledOneHauntState state = boiledOneAI._logic.State; if (state.TargetSlot == slot && (state.Phase == BoiledOnePhase.Haunting || state.Phase == BoiledOnePhase.Killing)) { return true; } } } return false; } private static BoiledOneHauntSettings ReadSettings() { BoiledOneConfig modConfig = Plugin.ModConfig; return new BoiledOneHauntSettings { KillEnabled = modConfig.KillEnabled.Value, CountdownEnabled = modConfig.CountdownEnabled.Value, CountdownSeconds = modConfig.CountdownSeconds.Value, RestSeconds = modConfig.RestSeconds.Value, TeleportIntervalMinSeconds = modConfig.TeleportIntervalMinSeconds.Value, TeleportIntervalMaxSeconds = modConfig.TeleportIntervalMaxSeconds.Value }; } private void Commit() { //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Unknown result type (might be due to invalid IL or missing references) BoiledOneHauntSnapshot value = new BoiledOneHauntSnapshot { State = _logic.State, Position = _placedPosition, Yaw = _placedYaw }; if (!value.Equals(_snapshot.Value)) { _snapshot.Value = value; } } private bool TryPlace(StartOfRound round, PlayerControllerB target, int slot) { //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Unknown result type (might be due to invalid IL or missing references) //IL_0038: Unknown result type (might be due to invalid IL or missing references) //IL_005a: Unknown result type (might be due to invalid IL or missing references) //IL_005f: Unknown result type (might be due to invalid IL or missing references) //IL_0062: Unknown result type (might be due to invalid IL or missing references) //IL_006d: Unknown result type (might be due to invalid IL or missing references) //IL_006f: Unknown result type (might be due to invalid IL or missing references) //IL_0070: Unknown result type (might be due to invalid IL or missing references) //IL_0075: Unknown result type (might be due to invalid IL or missing references) //IL_007d: Unknown result type (might be due to invalid IL or missing references) //IL_0082: Unknown result type (might be due to invalid IL or missing references) //IL_0096: Unknown result type (might be due to invalid IL or missing references) //IL_00a4: Unknown result type (might be due to invalid IL or missing references) //IL_00b2: Unknown result type (might be due to invalid IL or missing references) //IL_00c0: Unknown result type (might be due to invalid IL or missing references) //IL_00ce: Unknown result type (might be due to invalid IL or missing references) //IL_00ea: Unknown result type (might be due to invalid IL or missing references) //IL_00ef: Unknown result type (might be due to invalid IL or missing references) //IL_00f3: Unknown result type (might be due to invalid IL or missing references) //IL_00f5: Unknown result type (might be due to invalid IL or missing references) //IL_00ff: Unknown result type (might be due to invalid IL or missing references) //IL_0104: Unknown result type (might be due to invalid IL or missing references) //IL_0120: Unknown result type (might be due to invalid IL or missing references) //IL_0125: Unknown result type (might be due to invalid IL or missing references) //IL_0127: Unknown result type (might be due to invalid IL or missing references) //IL_0132: Unknown result type (might be due to invalid IL or missing references) //IL_0137: Unknown result type (might be due to invalid IL or missing references) //IL_014e: Unknown result type (might be due to invalid IL or missing references) //IL_0150: Unknown result type (might be due to invalid IL or missing references) //IL_0166: Unknown result type (might be due to invalid IL or missing references) //IL_016b: Unknown result type (might be due to invalid IL or missing references) //IL_0170: Unknown result type (might be due to invalid IL or missing references) //IL_0172: Unknown result type (might be due to invalid IL or missing references) //IL_018e: Unknown result type (might be due to invalid IL or missing references) //IL_0193: Unknown result type (might be due to invalid IL or missing references) //IL_01c2: Unknown result type (might be due to invalid IL or missing references) //IL_01c4: Unknown result type (might be due to invalid IL or missing references) //IL_01ee: Unknown result type (might be due to invalid IL or missing references) //IL_01df: Unknown result type (might be due to invalid IL or missing references) //IL_01f6: Unknown result type (might be due to invalid IL or missing references) //IL_01f8: Unknown result type (might be due to invalid IL or missing references) //IL_020f: Unknown result type (might be due to invalid IL or missing references) //IL_022a: Unknown result type (might be due to invalid IL or missing references) //IL_0236: Unknown result type (might be due to invalid IL or missing references) //IL_0238: Unknown result type (might be due to invalid IL or missing references) //IL_0245: Unknown result type (might be due to invalid IL or missing references) //IL_024c: Unknown result type (might be due to invalid IL or missing references) //IL_0253: Unknown result type (might be due to invalid IL or missing references) //IL_0258: Unknown result type (might be due to invalid IL or missing references) //IL_025f: Unknown result type (might be due to invalid IL or missing references) //IL_0266: Unknown result type (might be due to invalid IL or missing references) BoiledOneHauntPlacement.CandidateOffset(_random.NextDouble(), _random.NextDouble(), out var offsetX, out var offsetZ); Vector3 position = ((Component)target).transform.position; NavMeshHit val = default(NavMeshHit); if (!NavMesh.SamplePosition(position + new Vector3(offsetX, 0f, offsetZ), ref val, 1.905f, base.agent.areaMask)) { return false; } Vector3 position2 = ((NavMeshHit)(ref val)).position; if (((EnemyAI)this).IsInsideMineshaftElevator(position2)) { return false; } Vector3 val2 = position2 - position; Vector3 forward = ((Component)target).transform.forward; int collidersAndRoomMaskAndDefault = round.collidersAndRoomMaskAndDefault; BoiledOnePlacementCandidate boiledOnePlacementCandidate = new BoiledOnePlacementCandidate { OffsetX = val2.x, OffsetY = val2.y, OffsetZ = val2.z, ViewX = forward.x, ViewZ = forward.z, OnNavMesh = true }; Bounds bounds = round.shipBounds.bounds; boiledOnePlacementCandidate.InShip = ((Bounds)(ref bounds)).Contains(position2 + Vector3.up * 0.25f); boiledOnePlacementCandidate.LineClear = !Physics.Linecast(((Component)target.gameplayCamera).transform.position, position2 + Vector3.up * _eyeHeight, collidersAndRoomMaskAndDefault, (QueryTriggerInteraction)1); boiledOnePlacementCandidate.BodyRoom = !Physics.CheckCapsule(position2 + Vector3.up * (base.agent.radius + 0.2f), position2 + Vector3.up * (base.agent.height - base.agent.radius), base.agent.radius, collidersAndRoomMaskAndDefault, (QueryTriggerInteraction)1); BoiledOnePlacementCandidate candidate = boiledOnePlacementCandidate; if (BoiledOneHauntPlacement.Check(in candidate) != BoiledOnePlacementVerdict.Accepted) { return false; } float num = YawTowards(position2, position); if (!((Behaviour)base.agent).enabled || !base.agent.Warp(position2)) { ((Component)this).transform.position = position2; } base.serverPosition = position2; ((Component)this).transform.rotation = Quaternion.Euler(0f, num, 0f); VanillaPreviousYaw.Invoke((EnemyAI)(object)this) = ((Component)this).transform.eulerAngles.y; _placedPosition = position2; _placedYaw = num; float num2 = Vector2.Angle(new Vector2(forward.x, forward.z), new Vector2(val2.x, val2.z)); Plugin.Log.LogInfo((object)$"[BoiledOne] Placed for player {slot}: {((Vector3)(ref val2)).magnitude:F1} m away, {num2:F0} degrees from their facing."); return true; } private void TurnTowards(StartOfRound round, PlayerControllerB target) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_0034: Unknown result type (might be due to invalid IL or missing references) //IL_004e: 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_0069: Unknown result type (might be due to invalid IL or missing references) //IL_0095: Unknown result type (might be due to invalid IL or missing references) BoiledOneHauntState state = _logic.State; if (state.Phase == BoiledOnePhase.Haunting && state.IsPresent && !Physics.Linecast(base.eye.position, ((Component)target.gameplayCamera).transform.position, round.collidersAndRoomMaskAndDefault, (QueryTriggerInteraction)1)) { float num = Mathf.MoveTowardsAngle(((Component)this).transform.eulerAngles.y, YawTowards(((Component)this).transform.position, ((Component)target).transform.position), 160f * Time.deltaTime); ((Component)this).transform.rotation = Quaternion.Euler(0f, num, 0f); } } private static float YawTowards(Vector3 from, Vector3 to) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_0013: Unknown result type (might be due to invalid IL or missing references) return Mathf.Atan2(to.x - from.x, to.z - from.z) * 57.29578f; } public override void EnableEnemyMesh(bool enable, bool overrideDoNotSet = false, bool tamperWithMeshes = false) { if (_started) { ApplyMeshVisibility(); } } private void ApplyMeshVisibility() { ((EnemyAI)this).EnableEnemyMesh(_shown, true, !_shown); for (int i = 0; i < base.skinnedMeshRenderers.Length; i++) { ((Renderer)base.skinnedMeshRenderers[i]).enabled = _shown; } for (int j = 0; j < base.meshRenderers.Length; j++) { ((Renderer)base.meshRenderers[j]).enabled = _shown; } } private void OnSnapshotChanged(BoiledOneHauntSnapshot previous, BoiledOneHauntSnapshot current) { if (_started) { ApplySnapshot(current); } } private void ApplySnapshot(BoiledOneHauntSnapshot snapshot) { //IL_006c: Unknown result type (might be due to invalid IL or missing references) //IL_0078: Unknown result type (might be due to invalid IL or missing references) //IL_007d: Unknown result type (might be due to invalid IL or missing references) //IL_0098: Unknown result type (might be due to invalid IL or missing references) BoiledOneHauntState state = _state; bool firstApply = _firstApply; _firstApply = false; _state = snapshot.State; _target = VictimRpc.FromSlot(_state.TargetSlot); if (_state.Placed && (firstApply || _state.Placement != state.Placement)) { if (!((NetworkBehaviour)this).IsServer) { ((Component)this).transform.position = snapshot.Position; base.serverPosition = snapshot.Position; ((Component)this).transform.rotation = Quaternion.Euler(0f, snapshot.Yaw, 0f); VanillaTargetYaw.Invoke((EnemyAI)(object)this) = snapshot.Yaw; } if (!firstApply) { _hiddenUntil = Time.time + 0.1f; } } RefreshAudio(); if (firstApply || state.Phase != _state.Phase || state.TargetSlot != _state.TargetSlot || state.TargetInShip != _state.TargetInShip || state.IsPresent != _state.IsPresent) { this.StateChanged?.Invoke(); } } private void RefreshAudio() { bool mute = !IsLocalTarget; ((Component)this).GetComponentsInChildren<AudioSource>(true, _audioSources); for (int i = 0; i < _audioSources.Count; i++) { _audioSources[i].mute = mute; } } private void UpdatePresentation() { bool flag = IsLocalTarget && _state.IsPresent && Time.time >= _hiddenUntil && (_state.Phase == BoiledOnePhase.Killing || (!_target.isInHangarShipRoom && !_target.isPlayerDead)); if (flag != _shown) { _shown = flag; ApplyMeshVisibility(); if ((Object)(object)_scanCollider != (Object)null) { _scanCollider.enabled = flag; } } } protected override void __initializeVariables() { if (_snapshot == null) { throw new Exception("BoiledOneAI._snapshot cannot be null. All NetworkVariableBase instances must be initialized."); } ((NetworkVariableBase)_snapshot).Initialize((NetworkBehaviour)(object)this); ((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)_snapshot, "_snapshot"); ((NetworkBehaviour)this).NetworkVariableFields.Add((NetworkVariableBase)(object)_snapshot); ((EnemyAI)this).__initializeVariables(); } protected override void __initializeRpcs() { ((EnemyAI)this).__initializeRpcs(); } protected internal override string __getTypeName() { return "BoiledOneAI"; } } internal static class BoiledOneBestiary { internal const string Text = "The Boiled One\n\nDanger level: high\n\nA tall, scalded figure that fixes on one worker and is never seen by anyone else on the crew. It does not walk; it is simply standing somewhere new each time its chosen worker looks away. Workers it follows report whispering, sudden exhaustion and images at the edge of their vision. Do not let it close the distance.\n\n"; } internal sealed class BoiledOneConfig { private const string SectionGeneral = "General"; private const string SectionSpawning = "Spawning"; private const string SectionMovement = "Movement"; private const string SectionCombat = "Combat"; private const string SectionAbilities = "Abilities"; private const string SectionPresentation = "Presentation"; public ConfigEntry<bool> Enabled { get; } public ConfigEntry<float> SpawnWeightMultiplier { get; } public ConfigEntry<string> MoonWeightOverrides { get; } public ConfigEntry<int> MaxCount { get; } public ConfigEntry<float> PowerLevel { get; } public ConfigEntry<float> TeleportIntervalMinSeconds { get; } public ConfigEntry<float> TeleportIntervalMaxSeconds { get; } public ConfigEntry<bool> KillEnabled { get; } public ConfigEntry<bool> CountdownEnabled { get; } public ConfigEntry<float> CountdownSeconds { get; } public ConfigEntry<float> RestSeconds { get; } public ConfigEntry<bool> DoorsEnabled { get; } public ConfigEntry<float> DoorIntervalMinSeconds { get; } public ConfigEntry<float> DoorIntervalMaxSeconds { get; } public ConfigEntry<float> DoorHoldSeconds { get; } public ConfigEntry<bool> ExhaustionEnabled { get; } public ConfigEntry<int> ExhaustionMovingGain { get; } public ConfigEntry<int> ExhaustionWhisperGain { get; } public ConfigEntry<int> ExhaustionScareFlashGain { get; } public ConfigEntry<float> TeammateExhaustionMultiplier { get; } public ConfigEntry<bool> HornAndDim { get; } public ConfigEntry<bool> WhisperEnabled { get; } public ConfigEntry<int> WhisperCooldownMin { get; } public ConfigEntry<int> WhisperCooldownMax { get; } public ConfigEntry<bool> ScareFlashEnabled { get; } public ConfigEntry<int> ScareFlashCooldownMin { get; } public ConfigEntry<int> ScareFlashCooldownMax { get; } public ConfigEntry<bool> ColourLoss { get; } public ConfigEntry<bool> FearEnabled { get; } public BoiledOneConfig(ConfigFile config) { //IL_005d: Unknown result type (might be due to invalid IL or missing references) //IL_0067: Expected O, but got Unknown //IL_00aa: Unknown result type (might be due to invalid IL or missing references) //IL_00b4: Expected O, but got Unknown //IL_00e3: Unknown result type (might be due to invalid IL or missing references) //IL_00ed: Expected O, but got Unknown //IL_011c: Unknown result type (might be due to invalid IL or missing references) //IL_0126: Expected O, but got Unknown //IL_0155: Unknown result type (might be due to invalid IL or missing references) //IL_015f: Expected O, but got Unknown //IL_01c6: Unknown result type (might be due to invalid IL or missing references) //IL_01d0: Expected O, but got Unknown //IL_01ff: Unknown result type (might be due to invalid IL or missing references) //IL_0209: Expected O, but got Unknown //IL_0254: Unknown result type (might be due to invalid IL or missing references) //IL_025e: Expected O, but got Unknown //IL_028d: Unknown result type (might be due to invalid IL or missing references) //IL_0297: Expected O, but got Unknown //IL_02c6: Unknown result type (might be due to invalid IL or missing references) //IL_02d0: Expected O, but got Unknown //IL_0310: Unknown result type (might be due to invalid IL or missing references) //IL_031a: Expected O, but got Unknown //IL_033f: Unknown result type (might be due to invalid IL or missing references) //IL_0349: Expected O, but got Unknown //IL_036e: Unknown result type (might be due to invalid IL or missing references) //IL_0378: Expected O, but got Unknown //IL_03a7: Unknown result type (might be due to invalid IL or missing references) //IL_03b1: Expected O, but got Unknown //IL_040f: Unknown result type (might be due to invalid IL or missing references) //IL_0419: Expected O, but got Unknown //IL_043f: Unknown result type (might be due to invalid IL or missing references) //IL_0449: Expected O, but got Unknown //IL_048b: Unknown result type (might be due to invalid IL or missing references) //IL_0495: Expected O, but got Unknown //IL_04bb: Unknown result type (might be due to invalid IL or missing references) //IL_04c5: Expected O, but got Unknown using (ConfigPersistence.BeginBinding(config, Plugin.Log, "Boiled One")) { Enabled = config.Bind<bool>("General", "Enabled", true, "Enable the Boiled One encounter. Host-only: the host's value decides whether it spawns; every install still registers the creature so clients stay in sync."); SpawnWeightMultiplier = config.Bind<float>("Spawning", "SpawnWeightMultiplier", 1f, new ConfigDescription("Multiplier applied to the Boiled One's contextual moon/interior spawn policy. 0 disables natural spawns.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 5f), Array.Empty<object>())); MoonWeightOverrides = config.Bind<string>("Spawning", "MoonWeightOverrides", string.Empty, "Optional comma-separated base moon weights, e.g. Experimentation:8,Offense:15 or namespace:moon=12. Use 0 to disable a moon; unlisted moons keep authored defaults."); MaxCount = config.Bind<int>("Spawning", "MaxCount", 1, new ConfigDescription("Maximum number of Boiled Ones at once.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 4), Array.Empty<object>())); PowerLevel = config.Bind<float>("Spawning", "PowerLevel", 2f, new ConfigDescription("Indoor enemy power budget cost for each Boiled One.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.5f, 20f), Array.Empty<object>())); TeleportIntervalMinSeconds = config.Bind<float>("Movement", "TeleportIntervalMinSeconds", 28f, new ConfigDescription("Fewest seconds between the Boiled One's moves to a new spot near its target; each gap is chosen at random between TeleportIntervalMinSeconds and TeleportIntervalMaxSeconds, and a maximum below the minimum is treated as the minimum. Host-only.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(5f, 120f), Array.Empty<object>())); TeleportIntervalMaxSeconds = config.Bind<float>("Movement", "TeleportIntervalMaxSeconds", 38f, new ConfigDescription("Most seconds between the Boiled One's moves to a new spot near its target. Host-only.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(5f, 120f), Array.Empty<object>())); KillEnabled = config.Bind<bool>("Combat", "KillEnabled", true, "Let the Boiled One kill its target, by full exhaustion or when the target walks into it. Off: it only haunts. Host-only."); CountdownEnabled = config.Bind<bool>("Abilities", "CountdownEnabled", true, "Run the countdown that makes the Boiled One let go of its target. Off: it keeps its target until that player dies or leaves. Host-only."); CountdownSeconds = config.Bind<float>("Abilities", "CountdownSeconds", 100f, new ConfigDescription("Seconds the target must outlast before the Boiled One lets go. The countdown pauses while the target is inside the ship. Host-only.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(10f, 600f), Array.Empty<object>())); RestSeconds = config.Bind<float>("Abilities", "RestSeconds", 50f, new ConfigDescription("Seconds the Boiled One rests after letting go before it picks a new target. Host-only.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 600f), Array.Empty<object>())); DoorsEnabled = config.Bind<bool>("Abilities", "DoorsEnabled", true, "Close and hold shut doors around the haunted player. Host-only."); DoorIntervalMinSeconds = config.Bind<float>("Abilities", "DoorIntervalMinSeconds", 20f, new ConfigDescription("Shortest wait between two door closings, in seconds. Host-only.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 600f), Array.Empty<object>())); DoorIntervalMaxSeconds = config.Bind<float>("Abilities", "DoorIntervalMaxSeconds", 30f, new ConfigDescription("Longest wait between two door closings, in seconds. Host-only.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 600f), Array.Empty<object>())); DoorHoldSeconds = config.Bind<float>("Abilities", "DoorHoldSeconds", 12f, new ConfigDescription("How long each closed door is held shut, in seconds. Host-only.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 120f), Array.Empty<object>())); ExhaustionEnabled = config.Bind<bool>("Abilities", "ExhaustionEnabled", true, "Host-only: the haunted player's exhaustion. Off means no exhaustion, no horn and dim, and no exhaustion kill; whispers and scare flashes still play but add nothing."); ExhaustionMovingGain = config.Bind<int>("Abilities", "ExhaustionMovingGain", 4, new ConfigDescription("Host-only: exhaustion added each time moving wears the haunted player down by another step. Standing still wears them down more slowly.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(2, 12), Array.Empty<object>())); ExhaustionWhisperGain = config.Bind<int>("Abilities", "ExhaustionWhisperGain", 10, new ConfigDescription("Host-only: exhaustion added by each whisper.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(2, 17), Array.Empty<object>())); ExhaustionScareFlashGain = config.Bind<int>("Abilities", "ExhaustionScareFlashGain", 20, new ConfigDescription("Host-only: exhaustion added by each scare flash.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(2, 20), Array.Empty<object>())); TeammateExhaustionMultiplier = config.Bind<float>("Abilities", "TeammateExhaustionMultiplier", 0.5f, new ConfigDescription("Host-only: while another living player is within 17 metres of the haunted player, every exhaustion gain is multiplied by this. 1 turns the rule off; 0 means no exhaustion is gained near a teammate.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 1f), Array.Empty<object>())); HornAndDim = config.Bind<bool>("Abilities", "HornAndDimEnabled", true, "Host-only: play the horn and dim the haunted player's screen for half a second each time moving adds exhaustion."); WhisperEnabled = config.Bind<bool>("Abilities", "WhisperEnabled", true, "Host-only: let the Boiled One whisper to the haunted player."); WhisperCooldownMin = config.Bind<int>("Abilities", "WhisperCooldownMinSeconds", 20, new ConfigDescription("Host-only: shortest wait in seconds before the next whisper. Keep at or below WhisperCooldownMaxSeconds.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(20, 35), Array.Empty<object>())); WhisperCooldownMax = config.Bind<int>("Abilities", "WhisperCooldownMaxSeconds", 40, new ConfigDescription("Host-only: longest wait in seconds before the next whisper. Keep at or above WhisperCooldownMinSeconds.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(40, 60), Array.Empty<object>())); ScareFlashEnabled = config.Bind<bool>("Abilities", "ScareFlashEnabled", true, "Host-only: let the Boiled One flash its face at the haunted player."); ScareFlashCooldownMin = config.Bind<int>("Abilities", "ScareFlashCooldownMinSeconds", 55, new ConfigDescription("Host-only: shortest wait in seconds before the next scare flash. Keep at or below ScareFlashCooldownMaxSeconds.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(20, 90), Array.Empty<object>())); ScareFlashCooldownMax = config.Bind<int>("Abilities", "ScareFlashCooldownMaxSeconds", 75, new ConfigDescription("Host-only: longest wait in seconds before the next scare flash. Keep at or above ScareFlashCooldownMinSeconds.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(40, 120), Array.Empty<object>())); ColourLoss = config.Bind<bool>("Presentation", "ColourLossEnabled", true, "Local: the colour drains from your view when the Boiled One is near."); FearEnabled = config.Bind<bool>("Presentation", "FearEnabled", true, "Local: when the Boiled One scares you, your character gets frightened too, which can bring on the game's heartbeat, screen filter and tense music. Off: its scares leave your fear alone."); } } public BoiledOneExhaustionSettings ReadExhaustionSettings() { BoiledOneExhaustionSettings result = default(BoiledOneExhaustionSettings); result.Exhaustion = ExhaustionEnabled.Value; result.HornAndDim = HornAndDim.Value; result.Whisper = WhisperEnabled.Value; result.ScareFlash = ScareFlashEnabled.Value; result.MovingGain = ExhaustionMovingGain.Value; result.WhisperGain = ExhaustionWhisperGain.Value; result.ScareFlashGain = ExhaustionScareFlashGain.Value; result.WhisperCooldownMin = WhisperCooldownMin.Value; result.WhisperCooldownMax = WhisperCooldownMax.Value; result.ScareFlashCooldownMin = ScareFlashCooldownMin.Value; result.ScareFlashCooldownMax = ScareFlashCooldownMax.Value; return result; } } internal sealed class BoiledOneDoorHold : MonoBehaviour { private readonly BoiledOneDoorHoldState _state = new BoiledOneDoorHoldState(); private DoorLock _door; private AnimatedObjectTrigger _picture; private bool _writing; internal static BoiledOneDoorHold For(NetworkBehaviour door) { if ((Object)(object)door == (Object)null) { return null; } BoiledOneDoorHold result = default(BoiledOneDoorHold); if (((Component)door).TryGetComponent<BoiledOneDoorHold>(ref result)) { return result; } DoorLock val = (DoorLock)(object)((door is DoorLock) ? door : null); if ((Object)(object)val == (Object)null) { TerminalAccessibleObject val2 = (TerminalAccessibleObject)(object)((door is TerminalAccessibleObject) ? door : null); if (val2 == null || !val2.isBigDoor) { return null; } } AnimatedObjectTrigger picture = default(AnimatedObjectTrigger); if (!((Component)door).TryGetComponent<AnimatedObjectTrigger>(ref picture)) { return null; } result = ((Component)door).gameObject.AddComponent<BoiledOneDoorHold>(); result._door = val; result._picture = picture; ((Behaviour)result).enabled = false; return result; } internal static bool IsHeld(Component door) { BoiledOneDoorHold boiledOneDoorHold = default(BoiledOneDoorHold); if (door.TryGetComponent<BoiledOneDoorHold>(ref boiledOneDoorHold)) { return boiledOneDoorHold._state.Held; } return false; } internal static bool BlocksPicture(AnimatedObjectTrigger picture, bool setTo) { BoiledOneDoorHold boiledOneDoorHold = default(BoiledOneDoorHold); if (((Component)picture).TryGetComponent<BoiledOneDoorHold>(ref boiledOneDoorHold) && !boiledOneDoorHold._writing) { return boiledOneDoorHold._state.Intercept(setTo); } return false; } internal void Acquire() { if (_state.Acquire(_picture.boolValue)) { if ((Object)(object)_door != (Object)null) { Refuse(_door.doorTrigger); Refuse(_door.doorTriggerB); } ((Behaviour)this).enabled = true; Shut(); } } internal void Release() { if (_state.Release()) { ((Behaviour)this).enabled = false; if ((Object)(object)_door != (Object)null) { bool usable = BoiledOneDoorHoldState.RegularDoorUsable(_door.isLocked); SetUsable(_door.doorTrigger, usable); SetUsable(_door.doorTriggerB, usable); } else if (_picture.boolValue != _state.ShownOpenAtRelease) { Write(_state.ShownOpenAtRelease); } } } private void Update() { Shut(); } private void Shut() { if (_picture.boolValue) { Write(open: false); if ((Object)(object)_door != (Object)null) { _door.SetDoorAsOpen(false); } } } private void Write(bool open) { _writing = true; try { _picture.SetBoolOnClientOnly(open); } finally { _writing = false; } } private static void Refuse(InteractTrigger trigger) { if (!((Object)(object)trigger == (Object)null)) { trigger.interactable = false; trigger.disabledHoverTip = "Locked"; } } private static void SetUsable(InteractTrigger trigger, bool usable) { if ((Object)(object)trigger != (Object)null) { trigger.interactable = usable; } } } internal enum BoiledOneDoorKind : byte { Regular, Big } internal struct BoiledOneDoorCandidate { public BoiledOneDoorKind Kind; public float DistanceMeters; public bool Networked; public bool InShip; public bool Locked; public bool BeingPicked; public bool Held; public bool HasTwin; public int Twin; } internal static class BoiledOneDoorRules { internal static bool MayPick(bool enabled, bool haunting, bool hasTarget, bool targetInShip, double now, double nextPickTime) { if (enabled && haunting && hasTarget && !targetInShip) { return now >= nextPickTime; } return false; } internal static double NextPickTime(double now, float minSeconds, float maxSeconds, float roll) { float num = Math.Min(minSeconds, maxSeconds); float num2 = Math.Max(minSeconds, maxSeconds); return now + (double)num + (double)((num2 - num) * roll); } internal static bool Eligible(in BoiledOneDoorCandidate door, float radiusMeters) { if (Free(in door)) { return door.DistanceMeters <= radiusMeters; } return false; } internal static void Pick(IReadOnlyList<BoiledOneDoorCandidate> candidates, float radiusMeters, int cap, Func<int, int> nextIndex, List<int> picked) { picked.Clear(); for (int i = 0; i < candidates.Count; i++) { BoiledOneDoorCandidate door = candidates[i]; int num = TwinOf(candidates, i); if (num < 0) { if (Eligible(in door, radiusMeters)) { picked.Add(i); } } else if (num > i) { BoiledOneDoorCandidate door2 = candidates[num]; if (Free(in door) && Free(in door2) && Math.Min(door.DistanceMeters, door2.DistanceMeters) <= radiusMeters) { picked.Add(i); } } } int num2 = Math.Min(cap, picked.Count); for (int j = 0; j < num2; j++) { int num3 = j + nextIndex(picked.Count - j); int index = j; int index2 = num3; int value = picked[num3]; int value2 = picked[j]; picked[index] = value; picked[index2] = value2; } picked.RemoveRange(num2, picked.Count - num2); for (int k = 0; k < num2; k++) { int num4 = TwinOf(candidates, picked[k]); if (num4 >= 0) { picked.Add(num4); } } } private static bool Free(in BoiledOneDoorCandidate door) { if (door.Networked && !door.InShip && !door.Locked && !door.BeingPicked) { return !door.Held; } return false; } private static int TwinOf(IReadOnlyList<BoiledOneDoorCandidate> candidates, int index) { BoiledOneDoorCandidate boiledOneDoorCandidate = candidates[index]; if (!boiledOneDoorCandidate.HasTwin || boiledOneDoorCandidate.Twin == index || boiledOneDoorCandidate.Twin < 0 || boiledOneDoorCandidate.Twin >= candidates.Count) { return -1; } BoiledOneDoorCandidate boiledOneDoorCandidate2 = candidates[boiledOneDoorCandidate.Twin]; if (!boiledOneDoorCandidate2.HasTwin || boiledOneDoorCandidate2.Twin != index) { return -1; } return boiledOneDoorCandidate.Twin; } internal static bool Expired(double endTime, double now) { return now >= endTime; } internal static void Reconcile<T>(List<T> applied, List<T> desired, Func<T, bool> alive, Action<T> acquire, Action<T> release) where T : class { for (int num = applied.Count - 1; num >= 0; num--) { T val = applied[num]; if (!alive(val) || !desired.Contains(val)) { applied.RemoveAt(num); if (alive(val)) { release(val); } } } for (int i = 0; i < desired.Count; i++) { T val2 = desired[i]; if (!applied.Contains(val2)) { applied.Add(val2); acquire(val2); } } } internal static void ReleaseAll<T>(List<T> applied, Func<T, bool> alive, Action<T> release) where T : class { for (int num = applied.Count - 1; num >= 0; num--) { T val = applied[num]; applied.RemoveAt(num); if (alive(val)) { release(val); } } } } internal sealed class BoiledOneDoorHoldState { private int _holders; internal bool Held => _holders > 0; internal bool ShownOpenAtRelease { get; private set; } internal bool Acquire(bool shownOpen) { if (_holders++ > 0) { return false; } ShownOpenAtRelease = shownOpen; return true; } internal bool Release() { if (_holders == 0) { return false; } return --_holders == 0; } internal bool Intercept(bool setTo) { if (!Held) { return false; } ShownOpenAtRelease = setTo; return true; } internal static bool RegularDoorUsable(bool locked) { return !locked; } } internal struct BoiledOneHeldDoor : INetworkSerializeByMemcpy, IEquatable<BoiledOneHeldDoor> { public NetworkBehaviourReference Door; public double EndTime; public BoiledOneHeldDoor(NetworkBehaviourReference door, double endTime) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Unknown result type (might be due to invalid IL or missing references) Door = door; EndTime = endTime; } public bool Equals(BoiledOneHeldDoor other) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) if (((NetworkBehaviourReference)(ref Door)).Equals(other.Door)) { return EndTime.Equals(other.EndTime); } return false; } public override bool Equals(object obj) { if (obj is BoiledOneHeldDoor other) { return Equals(other); } return false; } public override int GetHashCode() { return (((object)Unsafe.As<NetworkBehaviourReference, NetworkBehaviourReference>(ref Door)/*cast due to .constrained prefix*/).GetHashCode() * 397) ^ EndTime.GetHashCode(); } } internal sealed class BoiledOneDoors : NetworkBehaviour { private static readonly Func<BoiledOneDoorHold, bool> Alive = (BoiledOneDoorHold hold) => (Object)(object)hold != (Object)null; private static readonly Action<BoiledOneDoorHold> AcquireHold = delegate(BoiledOneDoorHold hold) { hold.Acquire(); }; private static readonly Action<BoiledOneDoorHold> ReleaseHold = delegate(BoiledOneDoorHold hold) { hold.Release(); }; private static readonly Func<int, int> RandomIndex = (int count) => Random.Range(0, count); private NetworkList<BoiledOneHeldDoor> _held; private IBoiledOneHaunt _haunt; private double _nextPickTime; private bool _reconcile; private readonly List<BoiledOneDoorHold> _applied = new List<BoiledOneDoorHold>(); private readonly List<BoiledOneDoorHold> _desired = new List<BoiledOneDoorHold>(); private readonly List<NetworkBehaviour> _candidateDoors = new List<NetworkBehaviour>(); private readonly List<BoiledOneDoorCandidate> _candidates = new List<BoiledOneDoorCandidate>(); private readonly List<int> _picked = new List<int>(); private void Awake() { _held = new NetworkList<BoiledOneHeldDoor>((IEnumerable<BoiledOneHeldDoor>)null, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); _haunt = ((Component)this).GetComponent<IBoiledOneHaunt>(); } public override void OnNetworkSpawn() { ((NetworkBehaviour)this).OnNetworkSpawn(); _held.OnListChanged += OnHeldChanged; _reconcile = true; } public override void OnNetworkDespawn() { _held.OnListChanged -= OnHeldChanged; ReleaseApplied(); ((NetworkBehaviour)this).OnNetworkDespawn(); } public override void OnDestroy() { ReleaseApplied(); ((NetworkBehaviour)this).OnDestroy(); } private void OnHeldChanged(NetworkListEvent<BoiledOneHeldDoor> change) { _reconcile = true; } private void Update() { if (((NetworkBehaviour)this).IsSpawned) { if (((NetworkBehaviour)this).IsServer) { HostStep(); } if (_reconcile) { Reconcile(); } } } private void HostStep() { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_00cd: Unknown result type (might be due to invalid IL or missing references) NetworkTime serverTime = ((NetworkBehaviour)this).NetworkManager.ServerTime; double time = ((NetworkTime)(ref serverTime)).Time; bool flag = _haunt != null && _haunt.Phase == BoiledOnePhase.Haunting; bool flag2 = false; for (int num = _held.Count - 1; num >= 0; num--) { if (!flag || BoiledOneDoorRules.Expired(_held[num].EndTime, time)) { _held.RemoveAt(num); flag2 = true; } } PlayerControllerB val = (flag ? _haunt.Target : null); BoiledOneConfig modConfig = Plugin.ModConfig; if (BoiledOneDoorRules.MayPick(modConfig.DoorsEnabled.Value, flag, (Object)(object)val != (Object)null, flag && _haunt.TargetInShip, time, _nextPickTime)) { flag2 |= Pick(((Component)val).transform.position, time, modConfig.DoorHoldSeconds.Value); _nextPickTime = BoiledOneDoorRules.NextPickTime(time, modConfig.DoorIntervalMinSeconds.Value, modConfig.DoorIntervalMaxSeconds.Value, Random.value); } if (flag2) { Reconcile(); } } private bool Pick(Vector3 targetPosition, double now, float holdSeconds) { //IL_0033: Unknown result type (might be due to invalid IL or missing references) //IL_0028: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_0038: Unknown result type (might be due to invalid IL or missing references) //IL_005d: Unknown result type (might be due to invalid IL or missing references) //IL_005f: Unknown result type (might be due to invalid IL or missing references) //IL_0095: Unknown result type (might be due to invalid IL or missing references) //IL_0097: Unknown result type (might be due to invalid IL or missing references) //IL_00f6: Unknown result type (might be due to invalid IL or missing references) Collider val = (((Object)(object)StartOfRound.Instance != (Object)null) ? StartOfRound.Instance.shipBounds : null); bool flag = (Object)(object)val != (Object)null; Bounds shipBounds = (Bounds)(flag ? val.bounds : default(Bounds)); DoorLock[] array = Object.FindObjectsByType<DoorLock>((FindObjectsSortMode)0); foreach (DoorLock val2 in array) { AddCandidate((NetworkBehaviour)(object)val2, BoiledOneDoorKind.Regular, val2.isLocked, val2.isPickingLock, targetPosition, flag, shipBounds); } TerminalAccessibleObject[] array2 = Object.FindObjectsByType<TerminalAccessibleObject>((FindObjectsSortMode)0); foreach (TerminalAccessibleObject val3 in array2) { if (val3.isBigDoor) { AddCandidate((NetworkBehaviour)(object)val3, BoiledOneDoorKind.Big, locked: false, beingPicked: false, targetPosition, flag, shipBounds); } } LinkTwins(); BoiledOneDoorRules.Pick(_candidates, 11.43f, 8, RandomIndex, _picked); double endTime = now + (double)holdSeconds; for (int k = 0; k < _picked.Count; k++) { _held.Add(new BoiledOneHeldDoor(new NetworkBehaviourReference(_candidateDoors[_picked[k]]), endTime)); } bool result = _picked.Count > 0; _candidateDoors.Clear(); _candidates.Clear(); _picked.Clear(); return result; } private void AddCandidate(NetworkBehaviour door, BoiledOneDoorKind kind, bool locked, bool beingPicked, Vector3 targetPosition, bool hasShip, Bounds shipBounds) { //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_003b: Unknown result type (might be due to invalid IL or missing references) //IL_003d: Unknown result type (might be due to invalid IL or missing references) //IL_005d: Unknown result type (might be due to invalid IL or missing references) AnimatedObjectTrigger val = default(AnimatedObjectTrigger); if (((Component)door).TryGetComponent<AnimatedObjectTrigger>(ref val)) { Vector3 position = ((Component)door).transform.position; _candidateDoors.Add(door); _candidates.Add(new BoiledOneDoorCandidate { Kind = kind, DistanceMeters = Vector3.Distance(targetPosition, position), Networked = door.IsSpawned, InShip = (hasShip && ((Bounds)(ref shipBounds)).Contains(position)), Locked = locked, BeingPicked = beingPicked, Held = BoiledOneDoorHold.IsHeld((Component)(object)door) }); } } private void LinkTwins() { for (int i = 0; i < _candidateDoors.Count; i++) { if (_candidates[i].HasTwin) { continue; } NetworkBehaviour obj = _candidateDoors[i]; DoorLock val = (DoorLock)(object)((obj is DoorLock) ? obj : null); if (val != null && !((Object)(object)val.twinDoor == (Object)null)) { int num = _candidateDoors.IndexOf((NetworkBehaviour)(object)val.twinDoor); if (num >= 0 && num != i && !_candidates[num].HasTwin) { SetTwin(i, num); SetTwin(num, i); } } } } private void SetTwin(int index, int twin) { BoiledOneDoorCandidate value = _candidates[index]; value.HasTwin = true; value.Twin = twin; _candidates[index] = value; } private void Reconcile() { _reconcile = false; _desired.Clear(); NetworkBehaviour door = default(NetworkBehaviour); for (int i = 0; i < _held.Count; i++) { BoiledOneHeldDoor boiledOneHeldDoor = _held[i]; BoiledOneDoorHold boiledOneDoorHold = (((NetworkBehaviourReference)(ref boiledOneHeldDoor.Door)).TryGet(ref door, ((NetworkBehaviour)this).NetworkManager) ? BoiledOneDoorHold.For(door) : null); if ((Object)(object)boiledOneDoorHold == (Object)null) { _reconcile = true; } else { _desired.Add(boiledOneDoorHold); } } BoiledOneDoorRules.Reconcile(_applied, _desired, Alive, AcquireHold, ReleaseHold); _desired.Clear(); } private void ReleaseApplied() { BoiledOneDoorRules.ReleaseAll(_applied, Alive, ReleaseHold); } protected override void __initializeVariables() { if (_held == null) { throw new Exception("BoiledOneDoors._held cannot be null. All NetworkVariableBase instances must be initialized."); } ((NetworkVariableBase)_held).Initialize((NetworkBehaviour)(object)this); ((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)_held, "_held"); base.NetworkVariableFields.Add((NetworkVariableBase)(object)_held); ((NetworkBehaviour)this).__initializeVariables(); } protected override void __initializeRpcs() { ((NetworkBehaviour)this).__initializeRpcs(); } protected internal override string __getTypeName() { return "BoiledOneDoors"; } } internal static class BoiledOneDoorTuning { internal const float RadiusMeters = 11.43f; internal const int MaxDoorsPerPick = 8; internal const string HeldTip = "Locked"; } public sealed class BoiledOneExhaustion : NetworkBehaviour { private IBoiledOneHaunt _haunt; private BoiledOneScreen _screen; private BoiledOneExhaustionModel _model; private PlayerControllerB _movingTarget; private bool _targetMoving; private bool _wasLocalTarget; private bool _sentMoving; private float _nextReportTime; private void Awake() { _haunt = ((Component)this).GetComponent<IBoiledOneHaunt>(); _screen = ((Component)this).GetComponent<BoiledOneScreen>(); } public override void OnNetworkSpawn() { ((NetworkBehaviour)this).OnNetworkSpawn(); if (((NetworkBehaviour)this).IsServer) { _model = new BoiledOneExhaustionModel(new Random()); } } private void Update() { if (_haunt != null && ((NetworkBehaviour)this).IsSpawned) { if (((NetworkBehaviour)this).IsServer && _model != null) { AdvanceHost(); } ReportMoving(); } } private void AdvanceHost() { //IL_007a: Unknown result type (might be due to invalid IL or missing references) PlayerControllerB target = _haunt.Target; if ((Object)(object)target != (Object)(object)_movingTarget) { _movingTarget = target; _targetMoving = false; } BoiledOneExhaustionSettings settings = Plugin.ModConfig.ReadExhaustionSettings(); BoiledOneExhaustionEvents boiledOneExhaustionEvents = _model.Advance(Time.deltaTime, _haunt, _targetMoving, in settings, TeammateGainMultiplier(target)); if (boiledOneExhaustionEvents != BoiledOneExhaustionEvents.None) { target = _haunt.Target; if ((Object)(object)target != (Object)null) { PlayEffectsClientRpc((byte)boiledOneExhaustionEvents, target.actualClientId, VictimRpc.TargetOnly(target)); } } } private static float TeammateGainMultiplier(PlayerControllerB target) { //IL_0043: Unknown result type (might be due to invalid IL or missing references) //IL_0048: Unknown result type (might be due to invalid IL or missing references) //IL_0074: Unknown result type (might be due to invalid IL or missing references) //IL_007c: Unknown result type (might be due to invalid IL or missing references) //IL_0081: Unknown result type (might be due to invalid IL or missing references) //IL_0086: Unknown result type (might be due to invalid IL or missing references) float value = Plugin.ModConfig.TeammateExhaustionMultiplier.Value; StartOfRound instance = StartOfRound.Instance; if (value >= 1f || (Object)(object)target == (Object)null || (Object)(object)instance == (Object)null) { return 1f; } PlayerControllerB[] allPlayerScripts = instance.allPlayerScripts; Vector3 position = ((Component)target).transform.position; foreach (PlayerControllerB val in allPlayerScripts) { if ((Object)(object)val != (Object)null) { bool isTarget = (Object)(object)val == (Object)(object)target; bool isPlayerControlled = val.isPlayerControlled; bool isPlayerDead = val.isPlayerDead; Vector3 val2 = position - ((Component)val).transform.position; if (BoiledOneExhaustionRules.CountsAsTeammate(isTarget, isPlayerControlled, isPlayerDead, ((Vector3)(ref val2)).sqrMagnitude)) { return value; } } } return 1f; } private void ReportMoving() { //IL_0096: Unknown result type (might be due to invalid IL or missing references) //IL_009b: Unknown result type (might be due to invalid IL or missing references) //IL_00f7: Unknown result type (might be due to invalid IL or missing references) //IL_00fd: Unknown result type (might be due to invalid IL or missing references) bool isLocalTarget = _haunt.IsLocalTarget; if (isLocalTarget && !_wasLocalTarget) { _sentMoving = false; _nextReportTime = 0f; } _wasLocalTarget = isLocalTarget; if (!isLocalTarget || _haunt.Phase != BoiledOnePhase.Haunting || _haunt.TargetInShip) { return; } GameNetworkManager instance = GameNetworkManager.Instance; PlayerControllerB val = (((Object)(object)instance != (Object)null) ? instance.localPlayerController : null); if (!((Object)(object)val == (Object)null) && !val.isPlayerDead && val.isPlayerControlled && !((Object)(object)val.thisController == (Object)null)) { Vector3 velocity = val.thisController.velocity; velocity.y = 0f; bool flag = ((Vector3)(ref velocity)).magnitude > 1.905f || val.isFallingFromJump; if (flag != _sentMoving && !(Time.time < _nextReportTime)) { _sentMoving = flag; _nextReportTime = Time.time + 0.25f; ReportMovingServerRpc(flag); } } } [ServerRpc(RequireOwnership = false)] private void ReportMovingServerRpc(bool moving, ServerRpcParams rpcParams = default(ServerRpcParams)) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Invalid comparison between Unknown and I4 //IL_00a7: Unknown result type (might be due to invalid IL or missing references) //IL_00b1: Invalid comparison between Unknown and I4 //IL_005f: Unknown result type (might be due to invalid IL or missing references) //IL_0068: Unknown result type (might be due to invalid IL or missing references) //IL_006d: Unknown result type (might be due to invalid IL or missing references) //IL_007d: Unknown result type (might be due to invalid IL or missing references) //IL_0083: Unknown result type (might be due to invalid IL or missing references) //IL_0097: Unknown result type (might be due to invalid IL or missing references) //IL_00dc: Unknown result type (might be due to invalid IL or missing references) //IL_00f7: Unknown result type (might be due to invalid IL or missing references) //IL_00f8: Unknown result type (might be due to invalid IL or missing references) NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager; if (networkManager == null || !networkManager.IsListening) { return; } if ((int)base.__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost)) { FastBufferWriter val = ((NetworkBehaviour)this).__beginSendServerRpc(1009249452u, rpcParams, (RpcDelivery)0); ((FastBufferWriter)(ref val)).WriteValueSafe<bool>(ref moving, default(ForPrimitives)); ((NetworkBehaviour)this).__endSendServerRpc(ref val, 1009249452u, rpcParams, (RpcDelivery)0); } if ((int)base.__rpc_exec_stage != 1 || (!networkManager.IsServer && !networkManager.IsHost)) { return; } base.__rpc_exec_stage = (__RpcExecStage)0; try { if (_haunt != null) { PlayerControllerB target = _haunt.Target; if (VictimRpc.SenderOwnsSlot(rpcParams.Receive.SenderClientId, target)) { _movingTarget = target; _targetMoving = moving; } } } catch (Exception arg) { Plugin.Log.LogError((object)$"ReportMovingServerRpc: {arg}"); } } [ClientRpc] private void PlayEffectsClientRpc(byte events, ulong targetClientId, ClientRpcParams clientRpcParams = default(ClientRpcParams)) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Invalid comparison between Unknown and I4 //IL_00b4: Unknown result type (might be due to invalid IL or missing references) //IL_00be: Invalid comparison between Unknown and I4 //IL_005f: Unknown result type (might be due to invalid IL or missing references) //IL_0068: Unknown result type (might be due to invalid IL or missing references) //IL_006d: Unknown result type (might be due to invalid IL or missing references) //IL_007d: Unknown result type (might be due to invalid IL or missing references) //IL_0083: Unknown result type (might be due to invalid IL or missing references) //IL_008c: Unknown result type (might be due to invalid IL or missing references) //IL_00a4: Unknown result type (might be due to invalid IL or missing references) //IL_00e9: Unknown result type (might be due to invalid IL or missing references) NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager; if (networkManager == null || !networkManager.IsListening) { return; } if ((int)base.__rpc_exec_stage != 1 && (networkManager.IsServer || networkManager.IsHost)) { FastBufferWriter val = ((NetworkBehaviour)this).__beginSendClientRpc(899736488u, clientRpcParams, (RpcDelivery)0); ((FastBufferWriter)(ref val)).WriteValueSafe<byte>(ref events, default(ForPrimitives)); BytePacker.WriteValueBitPacked(val, targetClientId); ((NetworkBehaviour)this).__endSendClientRpc(ref val, 899736488u, clientRpcParams, (RpcDelivery)0); } if ((int)base.__rpc_exec_stage == 1 && (networkManager.IsClient || networkManager.IsHost)) { base.__rpc_exec_stage = (__RpcExecStage)0; if (_haunt != null && VictimRpc.IsLocalVictim(targetClientId) && _haunt.IsLocalTarget) { _screen.Play((BoiledOneExhaustionEvents)events); } } } protected override void __initializeVariables() { ((NetworkBehaviour)this).__initializeVariables(); } protected override void __initializeRpcs() { //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Expected O, but got Unknown //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_0038: Expected O, but got Unknown ((NetworkBehaviour)this).__registerRpc(1009249452u, new RpcReceiveHandler(__rpc_handler_1009249452), "ReportMovingServerRpc"); ((NetworkBehaviour)this).__registerRpc(899736488u, new RpcReceiveHandler(__rpc_handler_899736488), "PlayEffectsClientRpc"); ((NetworkBehaviour)this).__initializeRpcs(); } private static void __rpc_handler_1009249452(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams) { //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_003e: Unknown result type (might be due to invalid IL or missing references) //IL_003f: Unknown result type (might be due to invalid IL or missing references) //IL_0044: Unknown result type (might be due to invalid IL or missing references) //IL_004e: Unknown result type (might be due to invalid IL or missing references) //IL_005d: Unknown result type (might be due to invalid IL or missing references) //IL_006c: Unknown result type (might be due to invalid IL or missing references) NetworkManager networkManager = target.NetworkManager; if (networkManager != null && networkManager.IsListening) { bool moving = default(bool); ((FastBufferReader)(ref reader)).ReadValueSafe<bool>(ref moving, default(ForPrimitives)); ServerRpcParams server = rpcParams.Server; target.__rpc_exec_stage = (__RpcExecStage)1; ((BoiledOneExhaustion)(object)target).ReportMovingServerRpc(moving, server); target.__rpc_exec_stage = (__RpcExecStage)0; } } private static void __rpc_handler_899736488(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams) { //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_003e: 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_004c: Unknown result type (might be due to invalid IL or missing references) //IL_0051: Unknown result type (might be due to invalid IL or missing references) //IL_005b: Unknown result type (might be due to invalid IL or missing references) //IL_006e: Unknown result type (might be due to invalid IL or missing references) //IL_007d: Unknown result type (might be due to invalid IL or missing references) NetworkManager networkManager = target.NetworkManager; if (networkManager != null && networkManager.IsListening) { byte events = default(byte); ((FastBufferReader)(ref reader)).ReadValueSafe<byte>(ref events, default(ForPrimitives)); ulong targetClientId = default(ulong); ByteUnpacker.ReadValueBitPacked(reader, ref targetClientId); ClientRpcParams client = rpcParams.Client; target.__rpc_exec_stage = (__RpcExecStage)1; ((BoiledOneExhaustion)(object)target).PlayEffectsClientRpc(events, targetClientId, client); target.__rpc_exec_stage = (__RpcExecStage)0; } } protected internal override string __getTypeName() { return "BoiledOneExhaustion"; } } internal struct BoiledOneExhaustionSettings { public bool Exhaustion; public bool HornAndDim; public bool Whisper; public bool ScareFlash; public int MovingGain; public int WhisperGain; public int ScareFlashGain; public int WhisperCooldownMin; public int WhisperCooldownMax; public int ScareFlashCooldownMin; public int ScareFlashCooldownMax; } [Flags] internal enum BoiledOneExhaustionEvents : byte { None = 0, HornAndDim = 1, Whisper = 2, ScareFlash = 4 } internal sealed class BoiledOneExhaustionModel { private const int ThousandthsPerPoint = 1000; private const int FullThousandths = 100000; private readonly Random _random; private int _exhaustionThousandths; private int _pool = 100; private int _lastCheck = 100; private float _poolTimer; private float _whisperCooldown; private float _scareFlashCooldown; private float _pendingSeconds; private BoiledOnePhase _seenPhase; private PlayerControllerB _seenTarget; public float Exhaustion => (float)_exhaustionThousandths / 1000f; public int Pool => _pool; public float WhisperCooldownLeft => _whisperCooldown; public float ScareFlashCooldownLeft => _scareFlashCooldown; public BoiledOneExhaustionModel(Random random) { _random = random; } public BoiledOneExhaustionEvents Advance(float deltaSeconds, IBoiledOneHaunt haunt, bool targetMoving, in BoiledOneExhaustionSettings settings, float gainMultiplier = 1f) { BoiledOnePhase phase = haunt.Phase; PlayerControllerB target = haunt.Target; ObserveHaunt(phase, target); if (!settings.Exhaustion) { _exhaustionThousandths = 0; _pool = (_lastCheck = 100); } BoiledOneExhaustionEvents boiledOneExhaustionEvents = BoiledOneExhaustionEvents.None; if (phase == BoiledOnePhase.Haunting && haunt.TargetInShip) { _pendingSeconds = 0f; } else { if (deltaSeconds > 0f) { _pendingSeconds += deltaSeconds; } bool active = phase == BoiledOnePhase.Haunting && (Object)(object)target != (Object)null; int num = 0; while (_pendingSeconds >= 0.075f) { if (num == 10) { _pendingSeconds = 0f; break; } _pendingSeconds -= 0.075f; num++; boiledOneExhaustionEvents |= Think(active, targetMoving, in settings, gainMultiplier); } } if (settings.Exhaustion && _exhaustionThousandths >= 100000 && phase == BoiledOnePhase.Haunting && haunt.TryBeginKill(BoiledOneKillTrigger.Exhaustion)) { _exhaustionThousandths = 0; _pool = (_lastCheck = 100); return BoiledOneExhaustionEvents.None; } return boiledOneExhaustionEvents; } private void ObserveHaunt(BoiledOnePhase phase, PlayerControllerB target) { bool num = _seenPhase == BoiledOnePhase.Killing && phase != BoiledOnePhase.Killing; bool flag = _seenTarget != null && _seenTarget != target; _seenPhase = phase; _seenTarget = target; if (num || (flag && phase != BoiledOnePhase.Resting)) { _exhaustionThousandths = 0; _pool = (_lastCheck = 100); } else if (flag) { _exhaustionThousandths = 0; } } private BoiledOneExhaustionEvents Think(bool active, bool targetMoving, in BoiledOneExhaustionSettings settings, float gainMultiplier) { _whisperCooldown = Math.Max(0f, _whisperCooldown - 0.075f); _scareFlashCooldown = Math.Max(0f, _scareFlashCooldown - 0.075f); _poolTimer = Math.Max(0f, _poolTimer - 0.075f); if (!active) { return BoiledOneExhaustionEvents.None; } BoiledOneExhaustionEvents boiledOneExhaustionEvents = BoiledOneExhaustionEvents.None; if (settings.ScareFlash && _scareFlashCooldown <= 0f && _random.Next(80) == 0) { boiledOneExhaustionEvents |= BoiledOneExhaustionEvents.ScareFlash; AddExhaustion(settings.ScareFlashGain, gainMultiplier, in settings); _scareFlashCooldown = PickCooldown(settings.ScareFlashCooldownMin, settings.ScareFlashCooldownMax); } if (settings.Exhaustion && _poolTimer <= 0f) { _poolTimer = 2f; boiledOneExhaustionEvents |= TickPool(targetMoving, in settings, gainMultiplier); } if (settings.Whisper && _whisperCooldown <= 0f && _random.Next(60) == 0) { boiledOneExhaustionEvents |= BoiledOneExhaustionEvents.Whisper; AddExhaustion(settings.WhisperGain, gainMultiplier, in settings); _whisperCooldown = PickCooldown(settings.WhisperCooldownMin, settings.WhisperCooldownMax); } return boiledOneExhaustionEvents; } private BoiledOneExhaustionEvents TickPool(bool targetMoving, in BoiledOneExhaustionSettings settings, float gainMultiplier) { BoiledOneExhaustionEvents boiledOneExhaustionEvents = BoiledOneExhaustionEvents.None; _pool -= (targetMoving ? 5 : 2); if (_lastCheck - _pool >= 30) { AddExhaustion(settings.MovingGain, gainMultiplier, in settings); if (settings.HornAndDim) { boiledOneExhaustionEvents |= BoiledOneExhaustionEvents.HornAndDim; } _lastCheck = _pool; } if (_pool <= 0) { _pool = (_lastCheck = 100); } return boiledOneExhaustionEvents; } private void AddExhaustion(int gain, float gainMultiplier, in BoiledOneExhaustionSettings settings) { if (settings.Exhaustion) { double val = Math.Round((double)gain * (double)gainMultiplier * 1000.0, MidpointRounding.AwayFromZero); _exhaustionThousandths = (int)Math.Min(100000.0, (double)_exhaustionThousandths + Math.Max(0.0, val)); } } private int PickCooldown(int min, int max) { return _random.Next(min, Math.Max(min, max) + 1); } } internal static class BoiledOneExhaustionRules { public static bool CountsAsTeammate(bool isTarget, bool isControlled, bool isDead, float distanceSquared) { if (!isTarget && isControlled && !isDead) { return distanceSquared < 289f; } return false; } public static float FearLevel(BoiledOneExhaustionEvents events) { float num = 0f; if ((events & BoiledOneExhaustionEvents.HornAndDim) != BoiledOneExhaustionEvents.None) { num = Math.Max(num, 0.3f); } if ((events & BoiledOneExhaustionEvents.Whisper) != BoiledOneExhaustionEvents.None) { num = Math.Max(num, 0.6f); } if ((events & BoiledOneExhaustionEvents.ScareFlash) != BoiledOneExhaustionEvents.None) { num = Math.Max(num, 0.9f); } return num; } } internal static class BoiledOneExhaustionTuning { public const float SourceUnitMetres = 0.01905f; public const int MaxExhaustion = 100; public const int PoolFull = 100; public const int PoolDropMoving = 5; public const int PoolDropStill = 2; public const int PoolDropPerGain = 30; public const float PoolTickSeconds = 2f; public const float MovingSpeedMetresPerSecond = 1.905f; public const float MovingReportSeconds = 0.25f; public const float TeammateRadiusMetres = 17f; public const float FearHornAndDim = 0.3f; public const float FearWhisper = 0.6f; public const float FearScareFlash = 0.9f; public const float ThinkSeconds = 0.075f; public const int MaxThinksPerAdvance = 10; public const int WhisperRollSides = 60; public const int ScareFlashRollSides = 80; public const float DimSeconds = 0.5f; public const float DimAlpha = 40f / 51f; public const float HornVolume = 1f; public const float SmearRiseSeconds = 4.1666665f; public const float SmearMaxAmount = 0.6f; public const float SmearUpdateSeconds = 0.027f; public const float SmearAddAlpha = 0.04f; public const float WhisperSlowSeconds = 5f; public const float WhisperSpeedFactor = 0.4f; public const float WhisperVolume = 0.8f; public const int WhisperLineCount = 5; public const float ScreamVolume = 0.8f; public const int ScreamCount = 2; public const int ScareFrameCount = 20; public const float ScareFrameSeconds = 0.05f; public const int ScareSetCount = 3; public const float ScareUvWidth = 0.9987805f; public const float ColourLossStartMetres = 11.43f; public const float ColourLossFullMetres = 5.715f; public const float ColourLossDarken = 0.15f; public const float ColourLossRedTint = 0.2f; public const float ColourLossLumaRedPercent = 27.2f; public const float ColourLossLumaGreenPercent = 67.4f; public const float ColourLossLumaBluePercent = 5.4f; } public enum BoiledOnePhase : byte { Dormant, Haunting, Resting, Killing } public enum BoiledOneKillTrigger : byte { Exhaustion, Proximity } public interface IBoiledOneHaunt { BoiledOnePhase Phase { get; } PlayerControllerB Target { get; } bool TargetInShip { get; } bool IsLocalTarget { get; } bool IsPresent { get; } event Action StateChanged; bool TryBeginKill(BoiledOneKillTrigger trigger); void EndKill(); } [DisallowMultipleComponent] internal sealed class BoiledOneKill : MonoBehaviour { private readonly BoiledOneKillHost _host = new BoiledOneKillHost(); private IBoiledOneHaunt _haunt; private EnemyAI _enemy; private BoiledOneVictimHold _hold; private bool _wasLocalKill; private void Start() { _haunt = ((Component)this).GetComponent<IBoiledOneHaunt>(); _enemy = ((Component)this).GetComponent<EnemyAI>(); if (_haunt == null || (Object)(object)_enemy == (Object)null) { ((Behaviour)this).enabled = false; } } private void Update() { if (((NetworkBehaviour)_enemy).IsServer && ((NetworkBehaviour)_enemy).IsSpawned) { TickHost(); } bool flag = _haunt.Phase == BoiledOnePhase.Killing && _haunt.IsLocalTarget; if (flag && !_wasLocalKill) { BeginLocalHold(_haunt.Target); } _wasLocalKill = flag; } private void TickHost() { //IL_0052: Unknown result type (might be due to invalid IL or missing references) //IL_005d: Unknown result type (might be due to invalid IL or missing references) //IL_0062: Unknown result type (might be due to invalid IL or missing references) //IL_0067: Unknown result type (might be due to invalid IL or missing references) PlayerControllerB target = _haunt.Target; bool targetLost = (Object)(object)target == (Object)null || target.isPlayerDead || !target.isPlayerControlled || target.disconnectedMidGame; float num; if (!((Object)(object)target != (Object)null) || !_haunt.IsPresent) { num = float.PositiveInfinity; } else { Vector3 val = ((Component)this).transform.position - ((Component)target).transform.position; num = ((Vector3)(ref val)).sqrMagnitude; } float sqrDistanceMetres = num; bool targetInShip = _haunt.TargetInShip || ((Object)(object)target != (Object)null && target.isInHangarShipRoom); _host.Tick(_haunt, sqrDistanceMetres, targetLost, targetInShip, Time.deltaTime); } private void BeginLocalHold(PlayerControllerB target) { GameNetworkManager instance = GameNetworkManager.Instance; if ((Object)(object)target == (Object)null || (Object)(object)instance == (Object)null || (Object)(object)target != (Object)(object)instance.localPlayerController || !((NetworkBehaviour)target).IsOwner || target.isPlayerDead || !target.isPlayerControlled) { return; } if ((Object)(object)_hold == (Object)null) { _hold = ((Component)this).GetComponent<BoiledOneVictimHold>(); if ((Object)(object)_hold == (Object)null) { _hold = ((Component)this).gameObject.AddComponent<BoiledOneVictimHold>(); } } _hold.Begin(target, _haunt, _enemy.creatureAnimator); } } internal sealed class BoiledOneKillHost { private PlayerControllerB _victim; private float _killSeconds; private float _secondsSinceRefusal = 0.5f; internal void Tick(IBoiledOneHaunt haunt, float sqrDistanceMetres, bool targetLost, bool targetInShip, float deltaTime) { if (haunt.Phase == BoiledOnePhase.Killing) { PlayerControllerB target = haunt.Target; if (target != _victim) { _victim = target; _killSeconds = 0f; } else { _killSeconds += deltaTime; } if (BoiledOneKillTimeline.HostEndsKill(_killSeconds, targetLost, targetInShip)) { _victim = null; haunt.EndKill(); } } else { _victim = null; _secondsSinceRefusal += deltaTime; if (BoiledOneKillTimeline.ProximityKillDue(haunt.Phase, haunt.IsPresent, targetInShip, sqrDistanceMetres, _secondsSinceRefusal) && !haunt.TryBeginKill(BoiledOneKillTrigger.Proximity)) { _secondsSinceRefusal = 0f; } } } } [Flags] internal enum BoiledOneKillCues : byte { None = 0, Down = 1, Speak = 2, Heartbeat = 4, HorrorFx = 8 } internal enum BoiledOneVictimStep : byte { Hold, Kill, Abort, Finish } internal static class BoiledOneKillTimeline { private const float FramesPerSecond = 30f; internal const float ClipSeconds = 5f; internal const float SpeakSeconds = 2f / 15f; internal const float HeartbeatSeconds = 19f / 30f; internal const float HorrorFxSeconds = 3.6333334f; internal const float KillPlayerSeconds = 4.4f; internal const float EndCameraSeconds = 4.633333f; internal const float FadeHoldSeconds = 0.6f; internal const float FadeClearSeconds = 1f; internal const float FadeSeconds = 1.6f; internal const float ProximityMetres = 1.7145001f; internal const float ProximityRetrySeconds = 0.5f; internal static BoiledOneKillCues CuesDue(float previousSeconds, float seconds) { BoiledOneKillCues boiledOneKillCues = BoiledOneKillCues.None; if (Crossed(0f, previousSeconds, seconds)) { boiledOneKillCues |= BoiledOneKillCues.Down; } if (Crossed(2f / 15f, previousSeconds, seconds)) { boiledOneKillCues |= BoiledOneKillCues.Speak; } if (Crossed(19f / 30f, previousSeconds, seconds)) { boiledOneKillCues |= BoiledOneKillCues.Heartbeat; } if (Crossed(3.6333334f, previousSeconds, seconds)) { boiledOneKillCues |= BoiledOneKillCues.HorrorFx; } return boiledOneKillCues; } internal static float FadeAlpha(float secondsSinceFadeStart) { if (!(secondsSinceFadeStart >= 0f) || secondsSinceFadeStart >= 1.6f) { return 0f; } if (secondsSinceFadeStart <= 0.6f) { return 1f; } return (1.6f - secondsSinceFadeStart) / 1f; } internal static bool ProximityKillDue(BoiledOnePhase phase, bool isPresent, bool targetInShip, float sqrDistanceMetres, float secondsSinceRefusal) { if (phase == BoiledOnePhase.Haunting && isPresent && !targetInShip && sqrDistanceMetres <= 2.9395106f) { return secondsSinceRefusal >= 0.5f; } return false; } internal static bool HostEndsKill(float seconds, bool targetLost, bool targetInShip) { if (!(targetLost || targetInShip)) { return seconds >= 5f; } return true; } internal static BoiledOneVictimStep VictimStep(float seconds, bool killed, bool stillKilling, bool playerDead, bool playerControlled, bool playerInShip) { if (killed) { if (!(seconds >= 4.633333f)) { return BoiledOneVictimStep.Hold; } return BoiledOneVictimStep.Finish; } if (!stillKilling || playerDead || !playerControlled || playerInShip) { return BoiledOneVictimStep.Abort; } if (!(seconds >= 4.4f)) { return BoiledOneVictimStep.Hold; } return BoiledOneVictimStep.Kill; } internal static bool StopsHeldItemAtStart(bool holdToUse, bool inUse, bool releaseActs) { if (holdToUse && inUse) { return !releaseActs; } return false; } private static bool Crossed(float cueSeconds, float previousSeconds, float seconds) { if (previousSeconds < cueSeconds) { return cueSeconds <= seconds; } return false; } } internal sealed class BoiledOneScreen : MonoBehaviour { private GameObject _colourLossHost; private Volume _colourLossVolume; private VolumeProfile _colourLossProfile; private ColorAdjustments _colourAdjustments; private ChannelMixer _channelMixer; private LiftGammaGain _liftGammaGain; private bool _colourLossFailed; private IBoiledOneHaunt _haunt; private GameObject _audioHost; private AudioSource _hornSource; private AudioSource _voiceSource; private AudioSource _screamSource; private GameObject _overlayRoot; private Image _dimImage; private RawImage _scareImage; private bool _dimRunning; private float _dimStart; private bool _flashRunning; private float _flashStart; private int _flashSet; private int _shownFrame = -1; private bool _frameShown; private RawImage _smearScreen; private GameObject _smearObject; private RawImage _smearImage; private RenderTexture _smearAccumulation; private RenderTexture _smearScratch; private Material _smearOpaqueMaterial; private Material _smearBlendMaterial; private bool _smearRunning; private float _smearStart; private float _nextSmearBlend; private void UpdateColourLoss(PlayerControllerB local) { //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_0035: Unknown result type (might be due to invalid IL or missing references) float num = 0f; if (Plugin.ModConfig.ColourLoss.Value && _haunt.IsPresent) { num = BoiledOneScreenCurves.ColourLossStrength(Vector3.Distance(((Component)local).transform.position, ((Component)this).transform.position)); } if (num > 0f && (Object)(object)_colourLossVolume == (Object)null && !_colourLossFailed) { CreateColourLoss(); } if ((Object)(object)_colourLossVolume != (Object)null) { _colourLossVolume.weight = num; } } private void CreateColourLoss() { //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Expected O, but got Unknown //IL_01de: Unknown result type (might be due to invalid IL or missing references) HUDManager instance = HUDManager.Instance; if ((Object)(object)instance == (Object)null) { return; } try { _colourLossHost = new GameObject("BoiledOneColourLoss"); _colourLossHost.layer = (((Object)(object)instance.insanityScreenFilter != (Object)null) ? ((Component)instance.insanityScreenFilter).gameObject.layer : 0); _colourLossVolume = _colourLossHost.AddComponent<Volume>(); _colourLossVolume.isGlobal = true; _colourLossVolume.priority = HighestHudVolumePriority(instance) + 1f; _colourLossVolume.weight = 0f; _colourLossProfile = ScriptableObject.CreateInstance<VolumeProfile>(); _colourLossVolume.sharedProfile = _colourLossProfile; _colourAdjustments = _colourLossProfile.Add<ColorAdjustments>(false); ((VolumeParameter<float>)(object)_colourAdjustments.postExposure).Override(Mathf.Log(0.85f, 2f)); _channelMixer = _colourLossProfile.Add<ChannelMixer>(false); ((VolumeParameter<float>)(object)_channelMixer.redOutRedIn).Override(27.2f); ((VolumeParameter<float>)(object)_channelMixer.redOutGreenIn).Override(67.4f); ((VolumeParameter<float>)(object)_channelMixer.redOutBlueIn).Override(5.4f); ((VolumeParameter<float>)(object)_channelMixer.greenOutRedIn).Override(27.2f); ((VolumeParameter<float>)(object)_channelMixer.greenOutGreenIn).Override(67.4f); ((VolumeParameter<float>)(object)_channelMixer.greenOutBlueIn).Override(5.4f); ((VolumeParameter<float>)(object)_channelMixer.blueOutRedIn).Override(27.2f); ((VolumeParameter<float>)(object)_channelMixer.blueOutGreenIn).Override(67.4f); ((VolumeParameter<float>)(object)_channelMixer.blueOutBlueIn).Override(5.4f); _liftGammaGain = _colourLossProfile.Add<LiftGammaGain>(false); ((VolumeParameter<Vector4>)(object)_liftGammaGain.gain).Override(new Vector4(1.2f, 1f, 1f, 0f)); } catch (Exception ex) { Plugin.Log.LogWarning((object)("The Boiled One colour loss volume could not be created; no colour loss this haunt: " + ex.Message)); DestroyColourLoss(); _colourLossFailed = true; } } private static float HighestHudVolumePriority(HUDManager hud) { return Higher(Higher(Higher(Higher(Higher(Higher(Higher(0f, hud.playerGraphicsVolume), hud.drunknessFilter), hud.poisonFilter), hud.insanityScreenFilter), hud.flashbangScreenFilter), hud.CadaverBloomFilter), hud.underwaterScreenFilter); } private static float Higher(float priority, Volume volume) { if (!((Object)(object)volume != (Object)null) || !(volume.priority > priority)) { return priority; } return volume.priority; } private void DestroyColourLoss() { if ((Object)(object)_colourLossHost != (Object)null) { Object.Destroy((Object)(object)_colourLossHost); } if ((Object)(object)_colourAdjustments != (Object)null) { Object.Destroy((Object)(object)_colourAdjustments); } if ((Object)(object)_channelMixer != (Object)null) { Object.Destroy((Object)(object)_channelMixer); } if ((Object)(object)_liftGammaGain != (Object)null) { Object.Destroy((Object)(object)_liftGammaGain); } if ((Object)(object)_colourLossProfile != (Object)null) { Object.Destroy((Object)(object)_colourLossProfile); } _colourLossHost = null; _colourLossVolume = null; _colourLossProfile = null; _colourAdjustments = null; _channelMixer = null; _liftGammaGain = null; } private void Awake() { _haunt = ((Component)this).GetComponent<IBoiledOneHaunt>(); } private void Update() { if (!IsActive(out var local)) { Release(); return; } BoiledOneScreenAssets.EnsureLoaded(); if (_haunt.Phase != BoiledOnePhase.Haunting) { StopWhisperAndFlash(); } BoiledOneScreenSlow.Tick(Time.time); UpdateOverlay(); UpdateSmear(); UpdateColourLoss(local); } private void OnDisable() { Release(); } private void OnDestroy() { Release(); } public void Play(BoiledOneExhaustionEvents events) { if (!IsActive(out var local) || _haunt.Phase != BoiledOnePhase.Haunting || _haunt.TargetInShip || local.isInHangarShipRoom) { return; } float num = BoiledOneExhaustionRules.FearLevel(events); if (num > 0f && Plugin.ModConfig.FearEnabled.Value) { local.JumpToFearLevel(num, true); } BoiledOneScreenAssets.EnsureLoaded(); EnsureAudio(); if ((events & BoiledOneExhaustionEvents.HornAndDim) != BoiledOneExhaustionEvents.None) { if ((Object)(object)BoiledOneScreenAssets.Horn != (Object)null) { _hornSource.PlayOneShot(BoiledOneScreenAssets.Horn, 1f); } StartDim(); } if ((events & BoiledOneExhaustionEvents.Whisper) != BoiledOneExhaustionEvents.None) { PlayLine(_voiceSource, BoiledOneScreenAssets.WhisperLines, 0.8f); StartSmear(); BoiledOneScreenSlow.Hold(this, local, Time.time + 5f); } if ((events & BoiledOneExhaustionEvents.ScareFlash) != BoiledOneExhaustionEvents.None) { StartFlash(Random.Range(0, 3)); PlayLine(_screamSource, BoiledOneScreenAssets.Screams, 0.8f); } } private bool IsActive(out PlayerControllerB local) { local = null; if (_haunt == null || !_haunt.IsLocalTarget) { return false; } BoiledOnePhase phase = _haunt.Phase; if (phase != BoiledOnePhase.Haunting && phase != BoiledOnePhase.Killing) { return false; } GameNetworkManager instance = GameNetworkManager.Instance; local = (((Object)(object)instance != (Object)null) ? instance.localPlayerController : null); if ((Object)(object)local != (Object)null && !local.isPlayerDead) { return local.isPlayerControlled; } return false; } private void StopWhisperAndFlash() { if ((Object)(object)_voiceSource != (Object)null && _voiceSource.isPlaying) { _voiceSource.Stop(); } EndFlash(); } private void Release() { BoiledOneScreenSlow.Drop(this); EndSmear(); DestroyOverlay(); DestroyAudio(); DestroyColourLoss(); _colourLossFailed = false; } private void EnsureAudio() { //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Expected O, but got Unknown if (!((Object)(object)_audioHost != (Object)null)) { _audioHost = new GameObject("BoiledOneScreenAudio"); _hornSource = AddSource(_audioHost); _voiceSource = AddSource(_audioHost); _screamSource = AddSource(_audioHost); } } private static AudioSource AddSource(GameObject host) { AudioSource obj = host.AddComponent<AudioSource>(); CreatureAudioSetup.ConfigureSpatial(obj, occlude: false); obj.spatialBlend = 0f; obj.playOnAwake = false; obj.bypassReverbZones = true; return obj; } private static void PlayLine(AudioSource source, AudioClip[] clips, float volume) { source.Stop(); AudioClip val = clips[Random.Range(0, clips.Length)]; if (!((Object)(object)val == (Object)null)) { source.clip = val; source.volume = volume; source.Play(); } } private void DestroyAudio() { if ((Object)(object)_audioHost != (Object)null) { Object.Destroy((Object)(object)_audioHost); } _audioHost = null; _hornSource = null; _voiceSource = null; _screamSource = null; } private void StartDim() { _dimRunning = true; _dimStart = Time.time; EnsureOverlay(); } private void StartFlash(int set) { _flashRunning = true; _flashStart = Time.time; _flashSet = set; _shownFrame = -1; _frameShown = false; EnsureOverlay(); } private void EndFlash() { if (_flashRunning) { _flashRunning = false; _shownFrame = -1; _frameShown = false; if ((Object)(object)_screamSource != (Object)null) { _screamSource.Stop(); } } } private void UpdateOverlay() { //IL_004f: Unknown result type (might be due to invalid IL or missing references) if (_dimRunning) { float num = Time.time - _dimStart; if (num >= 0.5f) { _dimRunning = false; } else if ((Object)(object)_dimImage != (Object)null) { ((Graphic)_dimImage).color = new Color(0f, 0f, 0f, BoiledOneScreenCurves.DimAlpha(num)); } } if (_flashRunning) { int num2 = BoiledOneScreenCurves.ScareFrameAt(Time.time - _flashStart); if (num2 < 0) { EndFlash(); } else if (num2 != _shownFrame) { _shownFrame = num2; Texture2D val = BoiledOneScreenAssets.ScareFrames[_flashSet, num2]; _frameShown = (Object)(object)val != (Object)null && (Object)(object)_scareImage != (Object)null; if (_frameShown) { _scareImage.texture = (Texture)(object)val; } } } if ((Object)(object)_overlayRoot == (Object)null) { return; } Show((Graphic)(object)_dimImage, _dimRunning); Show((Graphic)(object)_scareImage, _flashRunning && _frameShown); bool flag = _dimRunning || (_flashRunning && _frameShown); if (_overlayRoot.activeSelf != flag) { _overlayRoot.SetActive(flag); if (flag) { _overlayRoot.transform.SetAsLastSibling(); } } } private static void Show(Graphic graphic, bool show) { if ((Object)(object)graphic != (Object)null && ((Component)graphic).gameObject.activeSelf != show) { ((Component)graphic).gameObject.SetActive(show); } } private void EnsureOverlay() { //IL_005f: Unknown result type (might be due to invalid IL or missing references) //IL_0069: Expected O, but got Unknown //IL_0074: Unknown result type (might be due to invalid IL or missing references) //IL_007a: Expected O, but got Unknown //IL_00aa: 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)_overlayRoot != (Object)null) { return; } HUDManager instance = HUDManager.Instance; RawImage val = (((Object)(object)instance != (Object)null) ? instance.playerScreenTexture : null); Canvas val2 = (((Object)(object)val != (Object)null) ? ((Graphic)val).canvas : null); if ((Object)(object)val2 == (Object)null) { return; } try { _overlayRoot = new GameObject("BoiledOneScreen", new Type[1] { typeof(RectTransform) }); RectTransform val3 = (RectTransform)_overlayRoot.transform; ((Transform)val3).SetParent(((Component)val2).transform, false); Stretch(val3); ((Transform)val3).SetAsLastSibling(); _dimImage = AddLayer<Image>(val3, "Dim"); ((Graphic)_dimImage).color = Color.clear; _scareImage = AddLayer<RawImage>(val3, "ScareFlash"); _scareImage.uvRect = new Rect(0f, 0f, 0.9987805f, 1f); ((Component)_dimImage).gameObject.SetActive(false); ((Component)_scareImage).gameObject.SetActive(false); _overlayRoot.SetActive(false); } catch (Exception ex) { Plugin.Log.LogWarning((object)("The Boiled One screen overlay could not be created; no dim or scare flash this time: " + ex.Message)); DestroyOverlay(); } } private static T AddLayer<T>(RectTransform parent, string name) where T : Graphic { //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_0031: Expected O, but got Unknown GameObject val = new GameObject(name, new Type[1] { typeof(RectTransform) }); RectTransform val2 = (RectTransform)val.transform; ((Transform)val2).SetParent((Transform)(object)parent, false); Stretch(val2); T val3 = val.AddComponent<T>(); ((Graphic)val3).raycastTarget = false; return val3; } private static void Stretch(RectTransform rect) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Unknown result type (might be due to invalid IL or missing references) rect.anchorMin = Vector2.zero; rect.anchorMax = Vector2.one; rect.offsetMin = Vector2.zero; rect.offsetMax = Vector2.zero; ((Transform)rect).localScale = Vector3.one; } private void DestroyOverlay() { _dimRunning = false; EndFlash(); if ((Object)(object)_overlayRoot != (Object)null) { Object.Destroy((Object)(object)_overlayRoot); } _overlayRoot = null; _dimImage = null; _scareImage = null; } private void StartSmear() { //IL_0071: Unknown result type (might be due to invalid IL or missing references) //IL_0076: Unknown result type (might be due to invalid IL or missing references) //IL_0090: Unknown result type (might be due to invalid IL or missing references) //IL_0091: Unknown result type (might be due to invalid IL or missing references) //IL_0096: Unknown result type (might be due to invalid IL or missing references) //IL_00a6: Expected O, but got Unknown //IL_00b3: Unknown result type (might be due to invalid IL or missing references) //IL_00b4: Unknown result type (might be due to invalid IL or missing references) //IL_00b9: Unknown result type (might be due to invalid IL or missing references) //IL_00c9: Expected O, but got Unknown //IL_00f9: Unknown result type (might be due to invalid IL or missing references) //IL_00fe: Unknown result type (might be due to invalid IL or missing references) //IL_00ff: Unknown result type (might be due to invalid IL or missing references) //IL_010e: Expected O, but got Unknown //IL_012d: Unknown result type (might be due to invalid IL or missing references) //IL_014f: Unknown result type (might be due to invalid IL or missing references) //IL_0154: Unknown result type (might be due to invalid IL or missing references) //IL_0169: Unknown result type (might be due to invalid IL or missing references) //IL_0178: Expected O, but got Unknown //IL_0183: Unknown result type (might be due to invalid IL or missing references) //IL_01c8: Unknown result type (might be due to invalid IL or missing references) //IL_01d2: Expected O, but got Unknown //IL_01dd: Unknown result type (might be due to invalid IL or missing references) //IL_01ea: Unknown result type (might be due to invalid IL or missing references) //IL_01f8: Unknown result type (might be due to invalid IL or missing references) //IL_0207: Unknown result ty
Y4NGZCreepyDoll.dll
Decompiled a day ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security.Cryptography; using System.Text; using System.Text.RegularExpressions; using System.Threading; using BepInEx; using BepInEx.Configuration; using BepInEx.Logging; using Dawn; using GameNetcodeStuff; using Microsoft.CodeAnalysis; using Unity.Netcode; using UnityEngine; using UnityEngine.AI; using UnityEngine.Audio; using UnityEngine.Events; using UnityEngine.Networking; using UnityEngine.Rendering; using UnityEngine.SceneManagement; using Y4NGZCreepyDoll; using Y4NGZCreepyDoll.NetcodePatcher; using Y4NGZMonsters.Shared; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: AssemblyCompany("Y4NGZCreepyDoll")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0+3460ec64f0cec4948e51ddb3f02a4b0e414f105e")] [assembly: AssemblyProduct("Y4NGZCreepyDoll")] [assembly: AssemblyTitle("Y4NGZCreepyDoll")] [assembly: AssemblyVersion("1.0.0.0")] [module: RefSafetyRules(11)] [module: NetcodePatchedAssembly] 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 Y4NGZCreepyDoll { public sealed class CreepyDollAI : EnemyAI { private enum ServerNavigationOwner { None, Pursuit, Investigation, PeekApproach } private struct HushdollSharedSettings : INetworkSerializable, IEquatable<HushdollSharedSettings> { private const float DefaultCatchBackAngle = 90f; private const float DefaultContactRange = 2.15f; private const float DefaultAttackCooldown = 2.4f; public bool Published; public float WalkSpeedMin; public float WalkSpeedMax; public float WalkRampSeconds; public float CrawlSpeedMin; public float CrawlSpeedMax; public float CrawlRampSeconds; public float CatchBackAngle; public float ContactRange; public float AttackCooldown; public HushdollSpeedRamps SpeedRamps => new HushdollSpeedRamps(WalkSpeedMin, WalkSpeedMax, WalkRampSeconds, CrawlSpeedMin, CrawlSpeedMax, CrawlRampSeconds); public static HushdollSharedSettings FromLocalConfig() { CreepyDollConfig modConfig = Plugin.ModConfig; HushdollSharedSettings hushdollSharedSettings = new HushdollSharedSettings { WalkSpeedMin = (modConfig?.WalkSpeedMin?.Value ?? 0.6f), WalkSpeedMax = (modConfig?.WalkSpeedMax?.Value ?? 3f), WalkRampSeconds = (modConfig?.WalkRampSeconds?.Value ?? 10f), CrawlSpeedMin = (modConfig?.CrawlSpeedMin?.Value ?? 2.5f), CrawlSpeedMax = (modConfig?.CrawlSpeedMax?.Value ?? 6.5f), CrawlRampSeconds = (modConfig?.CrawlRampSeconds?.Value ?? 8f), CatchBackAngle = (modConfig?.CatchBackAngle?.Value ?? 90f), ContactRange = (modConfig?.ContactRange?.Value ?? 2.15f), AttackCooldown = (modConfig?.AttackCooldown?.Value ?? 2.4f) }; return hushdollSharedSettings.Sanitized(); } public HushdollSharedSettings Sanitized() { HushdollSharedSettings result = this; result.WalkSpeedMin = Sanitize(WalkSpeedMin, 0.6f, 0.6f, 3f); result.WalkSpeedMax = Mathf.Max(result.WalkSpeedMin, Sanitize(WalkSpeedMax, 3f, 0.6f, 3f)); result.WalkRampSeconds = Sanitize(WalkRampSeconds, 10f, 0.1f, 120f); result.CrawlSpeedMin = Sanitize(CrawlSpeedMin, 2.5f, 2.5f, 6.5f); result.CrawlSpeedMax = Mathf.Max(result.CrawlSpeedMin, Sanitize(CrawlSpeedMax, 6.5f, 2.5f, 6.5f)); result.CrawlRampSeconds = Sanitize(CrawlRampSeconds, 8f, 0.1f, 60f); result.CatchBackAngle = Sanitize(CatchBackAngle, 90f, 0f, 180f); result.ContactRange = Sanitize(ContactRange, 2.15f, 0.5f, 5f); result.AttackCooldown = Sanitize(AttackCooldown, 2.4f, 0.1f, 30f); return result; } private static float Sanitize(float value, float fallback, float minimum, float maximum) { return Mathf.Clamp(HushdollPerception.IsFinite(value) ? value : fallback, minimum, maximum); } public unsafe void NetworkSerialize<T>(BufferSerializer<T> serializer) where T : IReaderWriter { //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_0036: 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_004c: Unknown result type (might be due to invalid IL or missing references) //IL_0052: Unknown result type (might be due to invalid IL or missing references) //IL_0062: Unknown result type (might be due to invalid IL or missing references) //IL_0068: Unknown result type (might be due to invalid IL or missing references) //IL_0078: Unknown result type (might be due to invalid IL or missing references) //IL_007e: Unknown result type (might be due to invalid IL or missing references) //IL_008e: Unknown result type (might be due to invalid IL or missing references) //IL_0094: Unknown result type (might be due to invalid IL or missing references) //IL_00a4: Unknown result type (might be due to invalid IL or missing references) //IL_00aa: 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_00c0: Unknown result type (might be due to invalid IL or missing references) //IL_00d1: Unknown result type (might be due to invalid IL or missing references) //IL_00d7: Unknown result type (might be due to invalid IL or missing references) ((BufferSerializer<bool>*)(&serializer))->SerializeValue<bool>(ref Published, default(ForPrimitives)); ((BufferSerializer<float>*)(&serializer))->SerializeValue<float>(ref WalkSpeedMin, default(ForPrimitives)); ((BufferSerializer<float>*)(&serializer))->SerializeValue<float>(ref WalkSpeedMax, default(ForPrimitives)); ((BufferSerializer<float>*)(&serializer))->SerializeValue<float>(ref WalkRampSeconds, default(ForPrimitives)); ((BufferSerializer<float>*)(&serializer))->SerializeValue<float>(ref CrawlSpeedMin, default(ForPrimitives)); ((BufferSerializer<float>*)(&serializer))->SerializeValue<float>(ref CrawlSpeedMax, default(ForPrimitives)); ((BufferSerializer<float>*)(&serializer))->SerializeValue<float>(ref CrawlRampSeconds, default(ForPrimitives)); ((BufferSerializer<float>*)(&serializer))->SerializeValue<float>(ref CatchBackAngle, default(ForPrimitives)); ((BufferSerializer<float>*)(&serializer))->SerializeValue<float>(ref ContactRange, default(ForPrimitives)); ((BufferSerializer<float>*)(&serializer))->SerializeValue<float>(ref AttackCooldown, default(ForPrimitives)); } public bool Equals(HushdollSharedSettings other) { if (Published == other.Published && WalkSpeedMin == other.WalkSpeedMin && WalkSpeedMax == other.WalkSpeedMax && WalkRampSeconds == other.WalkRampSeconds && CrawlSpeedMin == other.CrawlSpeedMin && CrawlSpeedMax == other.CrawlSpeedMax && CrawlRampSeconds == other.CrawlRampSeconds && CatchBackAngle == other.CatchBackAngle && ContactRange == other.ContactRange) { return AttackCooldown == other.AttackCooldown; } return false; } } private struct HushdollLookTarget : INetworkSerializable, IEquatable<HushdollLookTarget> { public byte Kind; public ulong ClientId; public Vector3 Point; public int SnapEpoch; public unsafe void NetworkSerialize<T>(BufferSerializer<T> serializer) where T : IReaderWriter { //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_003a: Unknown result type (might be due to invalid IL or missing references) //IL_0040: Unknown result type (might be due to invalid IL or missing references) serializer.SerializeValue(ref Kind); ((BufferSerializer<ulong>*)(&serializer))->SerializeValue<ulong>(ref ClientId, default(ForPrimitives)); serializer.SerializeValue(ref Point); ((BufferSerializer<int>*)(&serializer))->SerializeValue<int>(ref SnapEpoch, default(ForPrimitives)); } public bool Equals(HushdollLookTarget other) { //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Unknown result type (might be due to invalid IL or missing references) if (Kind == other.Kind && ClientId == other.ClientId && Point == other.Point) { return SnapEpoch == other.SnapEpoch; } return false; } } private struct HushdollPeekState : INetworkSerializable, IEquatable<HushdollPeekState> { public byte Phase; public Vector3 Point; public float LeanPitchDegrees; public float LeanRollDegrees; public unsafe void NetworkSerialize<T>(BufferSerializer<T> serializer) where T : IReaderWriter { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_003a: Unknown result type (might be due to invalid IL or missing references) //IL_0040: Unknown result type (might be due to invalid IL or missing references) serializer.SerializeValue(ref Phase); serializer.SerializeValue(ref Point); ((BufferSerializer<float>*)(&serializer))->SerializeValue<float>(ref LeanPitchDegrees, default(ForPrimitives)); ((BufferSerializer<float>*)(&serializer))->SerializeValue<float>(ref LeanRollDegrees, default(ForPrimitives)); } public bool Equals(HushdollPeekState other) { //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Unknown result type (might be due to invalid IL or missing references) if (Phase == other.Phase && Point == other.Point && LeanPitchDegrees == other.LeanPitchDegrees) { return LeanRollDegrees == other.LeanRollDegrees; } return false; } } private struct WatchedProbe : IWatchedPointProbe { public CreepyDollAI Doll; public Vector3 Head; public Vector3 Chest; public Vector3 Hips; public float RangeSqr; public Vector3 CameraPosition; public Quaternion WorldToCamera; public ViewFrustum Frustum; public Transform PlayerRoot; public Vector3 Point(WatchedPoint point) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Unknown result type (might be due to invalid IL or missing references) return (Vector3)(point switch { WatchedPoint.Head => Head, WatchedPoint.Chest => Chest, _ => Hips, }); } public bool OnScreen(WatchedPoint point) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_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_0037: Unknown result type (might be due to invalid IL or missing references) //IL_003d: Unknown result type (might be due to invalid IL or missing references) //IL_0043: Unknown result type (might be due to invalid IL or missing references) Vector3 val = Point(point) - CameraPosition; if (((Vector3)(ref val)).sqrMagnitude > RangeSqr) { return false; } Vector3 val2 = WorldToCamera * val; return Frustum.Contains(val2.x, val2.y, val2.z); } public bool LineOfSightClear(WatchedPoint point) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_0031: Unknown result type (might be due to invalid IL or missing references) Vector3 val = Point(point) - CameraPosition; float magnitude = ((Vector3)(ref val)).magnitude; if (!(magnitude <= 0.05f)) { return Doll.HasClearLineOfSight(CameraPosition, val / magnitude, magnitude, PlayerRoot); } return true; } } private sealed class RaycastHitDistanceComparer : IComparer<RaycastHit> { internal static readonly RaycastHitDistanceComparer Instance = new RaycastHitDistanceComparer(); public int Compare(RaycastHit x, RaycastHit y) { return ((RaycastHit)(ref x)).distance.CompareTo(((RaycastHit)(ref y)).distance); } } private enum PeekCandidateKind : byte { Opening, WallEdge } private struct PeekCandidate { internal PeekCandidateKind Kind; internal Vector3 Point; internal Vector3 Axis; internal float AheadMeters; internal int SampleIndex; internal float ApertureHeight; internal float ApertureWidth; internal DoorLock Door; } private struct PeekPlan { internal Vector3 Stop; internal bool StopOnNavMesh; internal float StopWalkMeters; internal Vector3 Eye; internal float Crouch; internal float Lean; internal float Pitch; internal float Roll; internal Collider ViewBlocker; } private enum PeekSearchEnd : byte { PathEnd, ClosedDoor, DoorSearchSaturated } private enum DarknessLightKind : byte { Scene, Powered, Ship, Item, Helmet } private struct DarknessLightSource { public Light Light; public DarknessLightKind Kind; public bool Flashlight; public GrabbableObject Item; public PlayerControllerB Player; } private enum ExecutionRelease : byte { End, Abort, Despawn } private struct HushdollExecutionState : INetworkSerializable, IEquatable<HushdollExecutionState> { public byte Kind; public byte Serial; public ulong VictimClientId; public Vector3 Anchor; public float AnchorYaw; public float Distance; public double StartServerTime; public unsafe void NetworkSerialize<T>(BufferSerializer<T> serializer) where T : IReaderWriter { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_0047: Unknown result type (might be due to invalid IL or missing references) //IL_004d: Unknown result type (might be due to invalid IL or missing references) //IL_005d: Unknown result type (might be due to invalid IL or missing references) //IL_0063: Unknown result type (might be due to invalid IL or missing references) //IL_0073: Unknown result type (might be due to invalid IL or missing references) //IL_0079: Unknown result type (might be due to invalid IL or missing references) serializer.SerializeValue(ref Kind); serializer.SerializeValue(ref Serial); ((BufferSerializer<ulong>*)(&serializer))->SerializeValue<ulong>(ref VictimClientId, default(ForPrimitives)); serializer.SerializeValue(ref Anchor); ((BufferSerializer<float>*)(&serializer))->SerializeValue<float>(ref AnchorYaw, default(ForPrimitives)); ((BufferSerializer<float>*)(&serializer))->SerializeValue<float>(ref Distance, default(ForPrimitives)); ((BufferSerializer<double>*)(&serializer))->SerializeValue<double>(ref StartServerTime, default(ForPrimitives)); } public bool Equals(HushdollExecutionState other) { //IL_002b: Unknown result type (might be due to invalid IL or missing references) //IL_0031: Unknown result type (might be due to invalid IL or missing references) if (Kind == other.Kind && Serial == other.Serial && VictimClientId == other.VictimClientId && Anchor == other.Anchor && AnchorYaw == other.AnchorYaw && Distance == other.Distance) { return StartServerTime == other.StartServerTime; } return false; } } private sealed class ServerExecutionAnchorProbe : IExecutionAnchorProbe { private readonly Collider[] _overlaps = (Collider[])(object)new Collider[32]; private readonly RaycastHit[] _hits = (RaycastHit[])(object)new RaycastHit[16]; private readonly CreepyDollAI _doll; private PlayerControllerB _victim; private int _mask; internal bool Clamped { get; private set; } internal ServerExecutionAnchorProbe(CreepyDollAI doll) { _doll = doll; } internal void Bind(PlayerControllerB victim, int mask) { _victim = victim; _mask = mask; Clamped = false; } internal void Release() { _victim = null; } public bool VictimClear() { //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_0034: Unknown result type (might be due to invalid IL or missing references) //IL_003b: 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_005f: Unknown result type (might be due to invalid IL or missing references) //IL_008b: Unknown result type (might be due to invalid IL or missing references) //IL_0090: Unknown result type (might be due to invalid IL or missing references) //IL_0093: Unknown result type (might be due to invalid IL or missing references) //IL_0098: Unknown result type (might be due to invalid IL or missing references) //IL_009d: Unknown result type (might be due to invalid IL or missing references) //IL_009e: Unknown result type (might be due to invalid IL or missing references) //IL_00aa: Unknown result type (might be due to invalid IL or missing references) //IL_00af: Unknown result type (might be due to invalid IL or missing references) //IL_00b4: Unknown result type (might be due to invalid IL or missing references) //IL_00b6: Unknown result type (might be due to invalid IL or missing references) //IL_00c2: Unknown result type (might be due to invalid IL or missing references) //IL_00c7: Unknown result type (might be due to invalid IL or missing references) //IL_00cc: Unknown result type (might be due to invalid IL or missing references) //IL_00ce: Unknown result type (might be due to invalid IL or missing references) //IL_00d0: Unknown result type (might be due to invalid IL or missing references) //IL_00d2: Unknown result type (might be due to invalid IL or missing references) //IL_00d7: Unknown result type (might be due to invalid IL or missing references) //IL_00e9: Unknown result type (might be due to invalid IL or missing references) //IL_00eb: Unknown result type (might be due to invalid IL or missing references) //IL_00e5: Unknown result type (might be due to invalid IL or missing references) //IL_00e7: Unknown result type (might be due to invalid IL or missing references) CharacterController val = (((Object)(object)_victim != (Object)null) ? _victim.thisController : null); if ((Object)(object)val == (Object)null) { return false; } Transform transform = ((Component)val).transform; Vector3 lossyScale = transform.lossyScale; float num = val.radius * Mathf.Max(Mathf.Abs(lossyScale.x), Mathf.Abs(lossyScale.z)); float num2 = Mathf.Max(num, val.height * Mathf.Abs(lossyScale.y) * 0.5f); float num3 = Mathf.Max(0.01f, num - 0.05f); Vector3 up = transform.up; Vector3 val2 = transform.TransformPoint(val.center); Vector3 val3 = val2 + up * (0.3f + num3 - num2); Vector3 val4 = val2 + up * (num2 - 0.05f - num3); if (Vector3.Dot(val4 - val3, up) < 0f) { val4 = val3; } int count = Physics.OverlapCapsuleNonAlloc(val3, val4, num3, _overlaps, _mask, (QueryTriggerInteraction)1); return OverlapsClear(count); } public bool TryProjectAnchor(float x, float z, out float anchorX, out float anchorY, out float anchorZ) { //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_0034: 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_005b: 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_006c: Unknown result type (might be due to invalid IL or missing references) //IL_008c: Unknown result type (might be due to invalid IL or missing references) //IL_0087: Unknown result type (might be due to invalid IL or missing references) //IL_0091: Unknown result type (might be due to invalid IL or missing references) //IL_0094: Unknown result type (might be due to invalid IL or missing references) //IL_009e: Unknown result type (might be due to invalid IL or missing references) //IL_00a8: Unknown result type (might be due to invalid IL or missing references) anchorX = (anchorY = (anchorZ = 0f)); Clamped = false; NavMeshAgent agent = ((EnemyAI)_doll).agent; Vector3 nextPosition = agent.nextPosition; Vector3 val = default(Vector3); ((Vector3)(ref val))..ctor(x, nextPosition.y, z); NavMeshHit val2 = default(NavMeshHit); if (!NavMesh.SamplePosition(val, ref val2, 2f, agent.areaMask)) { return false; } val.y = ((NavMeshHit)(ref val2)).position.y; NavMeshHit val3 = default(NavMeshHit); Clamped = NavMesh.Raycast(nextPosition, val, ref val3, agent.areaMask); Vector3 val4 = (Clamped ? ((NavMeshHit)(ref val3)).position : val); anchorX = val4.x; anchorY = val4.y; anchorZ = val4.z; return true; } public bool BodyClear(float x, float y, float z) { //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_001a: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Unknown result type (might be due to invalid IL or missing references) Vector3 val = default(Vector3); ((Vector3)(ref val))..ctor(x, y, z); int count = Physics.OverlapCapsuleNonAlloc(val + Vector3.up * 0.75f, val + Vector3.up * 2.3f, 0.3f, _overlaps, _mask, (QueryTriggerInteraction)1); return OverlapsClear(count); } public bool LensClear(float x, float y, float z) { //IL_0003: Unknown result type (might be due to invalid IL or missing references) int count = Physics.OverlapSphereNonAlloc(new Vector3(x, y, z), 0.07f, _overlaps, _mask, (QueryTriggerInteraction)1); return OverlapsClear(count); } public bool SightClear(float fromX, float fromY, float fromZ, float toX, float toY, float toZ) { //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_003d: Unknown result type (might be due to invalid IL or missing references) //IL_003f: Unknown result type (might be due to invalid IL or missing references) Vector3 val = default(Vector3); ((Vector3)(ref val))..ctor(fromX, fromY, fromZ); Vector3 val2 = default(Vector3); ((Vector3)(ref val2))..ctor(toX - fromX, toY - fromY, toZ - fromZ); float magnitude = ((Vector3)(ref val2)).magnitude; float num = magnitude - 0.3f; if (num <= 0f) { return false; } int num2 = Physics.SphereCastNonAlloc(val, 0.07f, val2 / magnitude, _hits, num, _mask, (QueryTriggerInteraction)1); if (num2 >= _hits.Length) { return false; } for (int i = 0; i < num2; i++) { if (Blocks(((RaycastHit)(ref _hits[i])).collider)) { return false; } } return true; } private bool OverlapsClear(int count) { if (count >= _overlaps.Length) { return false; } for (int i = 0; i < count; i++) { if (Blocks(_overlaps[i])) { return false; } } return true; } private bool Blocks(Collider collider) { if ((Object)(object)collider == (Object)null) { return false; } Transform transform = ((Component)collider).transform; if (!transform.IsChildOf(((Component)_doll).transform)) { if (!((Object)(object)_victim == (Object)null)) { return !transform.IsChildOf(((Component)_victim).transform); } return true; } return false; } } private struct HushdollLocomotionState : INetworkSerializable, IEquatable<HushdollLocomotionState> { public byte SpeedSteps; public bool Low; public byte TurnSerial; public bool TurnClockwise; public bool Dark; public static HushdollLocomotionState FromSnapshot(LocomotionSnapshot snapshot) { return new HushdollLocomotionState { SpeedSteps = snapshot.SpeedSteps, Low = snapshot.Low, TurnSerial = snapshot.TurnSerial, TurnClockwise = snapshot.TurnClockwise, Dark = snapshot.Dark }; } public LocomotionSnapshot ToSnapshot() { return new LocomotionSnapshot { SpeedSteps = SpeedSteps, Low = Low, TurnSerial = TurnSerial, TurnClockwise = TurnClockwise, Dark = Dark }; } public unsafe void NetworkSerialize<T>(BufferSerializer<T> serializer) where T : IReaderWriter { //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_003a: Unknown result type (might be due to invalid IL or missing references) //IL_0040: Unknown result type (might be due to invalid IL or missing references) //IL_0050: Unknown result type (might be due to invalid IL or missing references) //IL_0056: Unknown result type (might be due to invalid IL or missing references) serializer.SerializeValue(ref SpeedSteps); ((BufferSerializer<bool>*)(&serializer))->SerializeValue<bool>(ref Low, default(ForPrimitives)); serializer.SerializeValue(ref TurnSerial); ((BufferSerializer<bool>*)(&serializer))->SerializeValue<bool>(ref TurnClockwise, default(ForPrimitives)); ((BufferSerializer<bool>*)(&serializer))->SerializeValue<bool>(ref Dark, default(ForPrimitives)); } public bool Equals(HushdollLocomotionState other) { if (SpeedSteps == other.SpeedSteps && Low == other.Low && TurnSerial == other.TurnSerial && TurnClockwise == other.TurnClockwise) { return Dark == other.Dark; } return false; } } public const int StateIdle = 0; public const int StateMoving = 1; private const float IdleBeatVolume = 0.4f; private const int IdleBeatMinimumSteps = 5; private const int IdleBeatMaximumSteps = 9; private const float MinimumAcceleration = 22.5f; private const float MinimumAngularSpeed = 120f; private const float MinimumGazeRange = 80f; private const float NavigationRadius = 0.5f; private const float NavigationHeight = 2f; private const float NavigationStoppingDistance = 0.6f; private const float HeadFocusHeardSeconds = 4.5f; private const float HeadTrackingAimDeadZoneDegrees = 0.35f; private const float NoisePlayerMatchRadius = 4f; private const float VoiceHearingMinimumAmplitude = 0.02f; private const float OccludedHearingRangeFraction = 0.5f; private const float NeckPitchShare = 0.38f; private const float IdleSoundMinDistance = 2f; private const float IdleSoundMaxDistance = 30f; private const float CreatureAudioSpread = 40f; private const float ClawHeadFocusRefreshSeconds = 0.08f; private const float PursuitLostSeconds = 12f; private const float SearchVocalIntervalSeconds = 4f; private const float SearchScanSpeedMultiplier = 2f; private const float SearchScanHoldScale = 0.5f; private const float InvestigateTravelTimeoutSeconds = 12f; private const float InvestigateArriveRadius = 1.6f; private const float InvestigateLookHoldSeconds = 5f; private const float SearchLingerSeconds = 30f; private const int MinLingerSearchNodes = 4; private const float SpotConfirmHysteresisDegrees = 8f; private const float SpotConfirmRangeHysteresis = 1.15f; private const float NoiseAcceptCooldownSeconds = 1.75f; private const float NoiseMinimumLoudness = 0.3f; private const float NoiseMinimumPerceivedLoudness = 0.04f; private const float SightFocusOcclusionGraceSeconds = 0.4f; private const float ObservationHoldSeconds = 4.5f; private const float ObservationPlantMaximumSeconds = 4.5f; private const float ObservationReplantCooldownSeconds = 10f; private const float DoorwayDuckCastRadius = 0.13f; private const float DoorwayDuckChestProbeHeight = 0.95f; private const float DoorwayDuckMinimumClearanceHeight = 1.25f; private const float DoorwayDuckMinimumLocomotionSpeed = 0.06f; private const float DoorwayLintelProbeInset = 0.21f; private const float HeadPostureSyncStepDegrees = 1.5f; private const float GazeAuthorityBlendPerSecond = 8f; private const float NeckRollShare = 0.3f; private const double IdleScanEpochCellSeconds = 60.0; private const long IdleScanBeatsPerCell = 128L; private const float IdleScanGlanceHoldMinSeconds = 0.6f; private const float IdleScanGlanceHoldMaxSeconds = 1.2f; private const float IdleScanDownwardPitchDegrees = 4f; private const float StandingHeadHeightDecayPerSecond = 0.15f; private const float FootstepGainCeiling = 64f; private const float FolleyGainQuietClip = 5.6f; private const string FolleyQuietClipName = "folley02"; public Transform attackOrigin; public AudioSource stepAudioSource; public AudioSource idleAudioSource; public AudioSource constantAudioSource; public AudioClip[] stepClips = (AudioClip[])(object)new AudioClip[0]; public AudioClip[] stepClipsConcrete = (AudioClip[])(object)new AudioClip[0]; public AudioClip[] stepClipsMetal = (AudioClip[])(object)new AudioClip[0]; public AudioClip[] stepClipsWood = (AudioClip[])(object)new AudioClip[0]; public AudioClip[] idleClips = (AudioClip[])(object)new AudioClip[0]; public AudioClip idleBeatClip; public AudioClip[] folleyClips = (AudioClip[])(object)new AudioClip[0]; public AudioClip constantClip; public AudioClip killClip; public AudioClip headSnapClip; public AISearchRoutine facilitySearch = new AISearchRoutine(); private static readonly string[] VoiceSpeakingMemberNames = new string[4] { "IsSpeaking", "isSpeaking", "Speaking", "speaking" }; private static readonly string[] VoiceAmplitudeMemberNames = new string[2] { "Amplitude", "amplitude" }; private static readonly float[] VoiceOutputSamples = new float[64]; private const BindingFlags VoiceMemberFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic; private static FieldInfo _voicePlayerStateField; private static bool _voicePlayerStateFieldResolved; private static readonly Dictionary<Type, MemberInfo[]> VoiceSpeakingMembers = new Dictionary<Type, MemberInfo[]>(); private static readonly Dictionary<Type, MemberInfo[]> VoiceAmplitudeMembers = new Dictionary<Type, MemberInfo[]>(); private static readonly Dictionary<Type, FieldInfo> VoiceSettingsStateFields = new Dictionary<Type, FieldInfo>(); private static readonly MemberInfo[] NoVoiceMembers = new MemberInfo[0]; private EncounterState _encounterState; private float _encounterStateEnteredTime; private ulong _encounterTargetClientId = ulong.MaxValue; private float _nextSearchVocalTime; private bool _serverPendingDetected; private Vector3 _serverStimulusPoint; private WatchedDebounce _serverWatched; private ulong _serverNearestWatcherClientId = ulong.MaxValue; private ContactMotionSample[] _serverPlayerMotion; private StartOfRound _serverTeleportEventSource; private StanceRampClock _serverStanceRamp; private PlayerControllerB _serverPursuitPlayer; private ulong _serverPursuitClientId = ulong.MaxValue; private float _serverPursuitLastVisibleTime; private float _serverPursuitAcquiredTime; private string _serverPursuitSource = "none"; private Vector3 _serverPursuitLastSeenPosition; private bool _hasServerPursuitLastSeen; private bool _serverInvestigating; private bool _serverInvestigateLooking; private Vector3 _serverInvestigatePoint; private float _serverInvestigateStartedTime; private float _serverInvestigateLookUntilTime; private bool _serverInvestigateLingering; private float _serverInvestigateLingerUntilTime; private GameObject _roamLegNode; private int _roamLegPass; private float _roamLegStartTime; private float _roamLegStartDistance; private const float NavigationRefreshSeconds = 0.25f; private NavMeshPath _serverNavigationPath; private readonly Vector3[] _serverNavigationCorners = (Vector3[])(object)new Vector3[64]; private HushdollProgressMonitor _serverNavigationProgress; private ServerNavigationOwner _serverNavigationOwner; private EncounterState _serverNavigationEncounterState; private float _serverNavigationStateEnteredTime; private float _serverNavigationOwnerStartedTime; private ulong _serverNavigationTargetId = ulong.MaxValue; private byte _serverNavigationExecutionSerial; private float _nextServerNavigationRefreshTime; private float _serverNavigationRepathTime = float.NegativeInfinity; private Vector3 _serverNavigationRepathTarget; private bool _serverNavigationRepathActive; private float _serverNavigationRecoveryUntilTime; private bool _hasServerNavigationDestination; private static readonly Vector3[] NavigationRecoveryDirections = (Vector3[])(object)new Vector3[8] { new Vector3(1f, 0f, 0f), new Vector3(0.70710677f, 0f, 0.70710677f), new Vector3(0f, 0f, 1f), new Vector3(-0.70710677f, 0f, 0.70710677f), new Vector3(-1f, 0f, 0f), new Vector3(-0.70710677f, 0f, -0.70710677f), new Vector3(0f, 0f, -1f), new Vector3(0.70710677f, 0f, -0.70710677f) }; private ulong _serverSlashTargetClientId = ulong.MaxValue; private bool _isClawing; private bool _serverClawCrouchRefusalLogged; private bool _serverStandingToClaw; private bool _serverSlashPresentationOpen; private int _serverSlashSequence; private float _serverSlashLatchedTime; private float _serverSlashLatchLimitSeconds; private Coroutine _serverClawRoutine; private float _clawWindupSeenTime = float.NegativeInfinity; private bool _audioParityApplied; private static AnimationCurve _footstepRolloffCurve; private const string StunSparkName = "StunSpark"; private ParticleSystem _stunSpark; private bool _stunSparkMissingLogged; private static readonly int EmissiveColorId = Shader.PropertyToID("_EmissiveColor"); private float _eyeNoticeEdgeTime = float.NegativeInfinity; private float _eyeStunEdgeTime = float.NegativeInfinity; private float _eyeGlowAppliedScale = 1f; private float _eyeGlowWrittenScale = 1f; private int _eyeFlickerSample = -1; private float _eyeFlickerValue = 1f; private Renderer[] _eyeGlowRenderers; private int[] _eyeGlowSlots; private Color _eyeGlowBaseColor; private bool _eyeGlowDedicated; private MaterialPropertyBlock _eyeGlowBlock; private AudioSource _constantLoopConfiguredSource; private AudioSource _idleAudioConfiguredSource; private float _nextContactTime; private ulong _serverObservationClientId = ulong.MaxValue; private bool _serverObservationFromNoise; private float _serverObservationUntilTime; private float _serverGazeContactSeconds; private float _serverGazeLastContactTime; private bool _serverGazeGraceLogged; private bool _serverSpotConfirmed; private int _serverSpotConfirmEpoch; private Vector3 _serverNoiseStimulusPoint; private float _serverSightLastSeenTime; private float _nextNoiseAcceptTime; private float _nextVoiceAcceptTime; private float _nextMovementDiagnosticTime; private readonly RaycastHit[] _lineOfSightHits = (RaycastHit[])(object)new RaycastHit[32]; private bool _headTrackingReferencesResolved; private readonly Vector3[] _bodyProbePoints = (Vector3[])(object)new Vector3[3]; private int _lastFolleyClipIndex = -1; private int _stepsUntilIdleBeat = -1; private Transform _headBone; private Transform _neckBone; private Transform _lowerSpineBone; private Transform _upperSpineBone; private Transform _hipBone; private float _headFocusUntilTime; private float _headBodyFollowAllowedTime; private float _serverLastSnapTime = float.NegativeInfinity; private HushdollLookTarget _serverPendingLook = new HushdollLookTarget { Kind = 0, ClientId = ulong.MaxValue }; private bool _serverPendingForceSnap; private HushdollPerception.HeadAimState _headAim; private float _headAimRollDegrees; private float _headAimRollVelocity; private float _headAimBodyYawDegrees; private bool _headAimInitialized; private float _headAimTargetYawDegrees; private bool _headAimHasLookTarget; private int _localSeenSnapEpoch; private bool _localSnapEpochPrimed; private Quaternion _headRestToRoot = Quaternion.identity; private Quaternion _neckRestToRoot = Quaternion.identity; private bool _hasHeadChainRestPose; private string _headRestPoseSource = "none"; private float _gazeAuthorityWeight; private static readonly int AnimStateTic = Animator.StringToHash("Tic"); private Animator _ticGazeAnimator; private int _ticGazeLayerIndex = -1; private Quaternion _headTicRestLocal = Quaternion.identity; private Quaternion _neckTicRestLocal = Quaternion.identity; private bool _hasHeadTicRest; private bool _hasNeckTicRest; private bool _ticRestReadDone; private readonly NetworkVariable<byte> _networkCrouchSteps = new NetworkVariable<byte>((byte)0, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); private const float NetworkPositionSyncThreshold = 0.05f; private const float NetworkPositionSmoothSeconds = 0.25f; private readonly NetworkVariable<byte> _networkEncounterState = new NetworkVariable<byte>((byte)0, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); private readonly NetworkVariable<int> _networkStepSeed = new NetworkVariable<int>(0, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); private readonly NetworkVariable<HushdollSharedSettings> _networkSharedSettings = new NetworkVariable<HushdollSharedSettings>(default(HushdollSharedSettings), (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); private ulong _serverReportedForeignOwner = ulong.MaxValue; private bool _networkDespawning; private const byte LookKindNone = 0; private const byte LookKindPlayer = 1; private const byte LookKindPoint = 2; private readonly NetworkVariable<HushdollLookTarget> _networkLookTarget = new NetworkVariable<HushdollLookTarget>(new HushdollLookTarget { Kind = 0, ClientId = ulong.MaxValue }, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); private HushdollLookTarget _serverLookTarget = new HushdollLookTarget { Kind = 0, ClientId = ulong.MaxValue }; private readonly NetworkVariable<HushdollPeekState> _networkPeekState = new NetworkVariable<HushdollPeekState>(default(HushdollPeekState), (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); private HushdollPeekState _serverPeekState; private ulong _serverPeekTargetClientId = ulong.MaxValue; private float _serverPeekPhaseStartTime; private float _serverPeekHoldSeconds; private Vector3 _serverPeekStopPoint; private Vector3 _serverPeekAxis; private Vector3 _serverPeekEyePoint; private Vector3 _serverPeekLineDirection; private float _serverPeekSightLostSeconds; private float _serverPeekCrouchAmount; private float _serverPeekLeanMeters; private float _serverPeekApertureHeight; private float _serverPeekApertureWidth; private bool _serverPeekIsWallEdge; private DoorLock _serverPeekDoor; private AnimatedObjectTrigger _serverPeekDoorTrigger; private ulong _serverPeekCooldownClientId = ulong.MaxValue; private float _serverPeekCooldownUntilTime; private Vector3 _serverLastPeekOpening; private float _serverLastPeekOpeningUntilTime; private readonly Vector3[] _serverPeekRefusalLogged = (Vector3[])(object)new Vector3[4]; private int _serverPeekRefusalLoggedCount; private float _serverPeekRefusalEncounterTime = -1f; private ulong _serverPeekRefusalTargetId = ulong.MaxValue; private bool _serverPeekSearchRefusalLogged; private readonly PeekCandidate[] _peekCandidates = new PeekCandidate[3]; private float _peekFitRequiredDrop; private float _peekFitThrowClear; private float _peekFitWantedLean; private float _peekFitHeadClear; private float _peekFitChestClear; private bool _peekCastSaturated; private readonly RaycastHit[] _peekCastHits = (RaycastHit[])(object)new RaycastHit[16]; private readonly Collider[] _peekOverlapBuffer = (Collider[])(object)new Collider[32]; private readonly RaycastHit[] _peekDoorRouteHits = (RaycastHit[])(object)new RaycastHit[8]; private float _peekLeanPitchDegrees; private float _peekLeanRollDegrees; private float _nextHeadPostureMeasureTime; private float _serverDoorwayCrouchAmount; private bool _serverDuckActive; private float _serverRequiredDoorwayDropMeters; private bool _serverDuckHoldActive; private float _serverDuckHoldDropMeters; private float _serverDuckHoldApertureHeight; private Vector3 _serverDuckLowestOverheadPoint; private Vector3 _serverDuckLowestOverheadAxis; private Collider _serverDuckHoldCollider; private float _serverDuckHoldAheadMeters; private float _serverDuckHoldFloorOffset; private bool _serverDuckHoldFromFootprint; private readonly Vector3[] _duckPathCornerBuffer = (Vector3[])(object)new Vector3[16]; private readonly Vector3[] _duckSampleBuffer = (Vector3[])(object)new Vector3[24]; private readonly Vector3[] _duckSampleAxisBuffer = (Vector3[])(object)new Vector3[24]; private readonly float[] _duckSampleAheadBuffer = new float[24]; private long _idleScanBeatIndex; private long _idleScanCell; private long _idleScanBeatStep; private double _idleScanBeatStartTime; private double _idleScanBeatEndTime; private bool _hasIdleScanCursor; private float _idleScanHoldScale = 1f; private bool _idleScanActive; private readonly HushdollFootfallScheduler _footfallScheduler = new HushdollFootfallScheduler(); private readonly FootfallContact[] _footfallFired = new FootfallContact[4]; private bool _footfallLastLow; private Transform _visualRoot; private float _localCrouchAmount; private CapsuleCollider _upperBodyCollider; private float _upperBodyColliderHeight = -1f; private bool _crouchCapHeadLogged; private bool _localCrouchWasAtCap; private float _standingHeadHeight; private bool _hasStandingHeadHeight; private bool _standingHeadHeightIsBoundsSeed; private BodyRestPose _bodyRest; private bool _hasBodyRest; private bool _bodyRestLogged; private int _bodyRestAccumulatedFrames; private Vector3 _bodyRestAccumulatedLower; private Vector3 _bodyRestAccumulatedUpper; private Vector3 _bodyRestAccumulatedNeck; private Vector3 _bodyRestAccumulatedHead; private bool _bodyRestAccumulatedHasLowerSpine; private bool _bodyRestAccumulatedHasUpperSpine; private bool _serverObservationPlanted; private float _serverObservationPlantStartTime; private float _serverObservationPlantAlignedTime; private bool _serverObservationPlantSpent; private ulong _serverLastPlantedClientId = ulong.MaxValue; private float _serverLastPlantCompletedTime = float.NegativeInfinity; private bool _loggedRuntimeDiagnostics; private float _nextHeadDiagnosticTime; private float _nextRoamDiagnosticTime; private string _lastHeadStateLogLine; private float _nextHeadStateLogTime; private bool _loggedEyeOrigin; private bool _serverBodyTurnInProgress; private int _footfallFootContacts; private int _footfallHandContacts; private float _nextFootfallDiagnosticTime; private static bool _audioRoutingLogged; private const float BodyProbeLowHeight = 0.5f; private const int GazeAngleProbePointCount = 2; private const float PeekWallEdgeMinimumLateralMeters = 0.25f; private const int PeekDoorLayerMask = 576; private const string DarknessLogPrefix = "[CreepyDollAI][dark] "; private DarknessHysteresis _serverDarkness; private float _serverDarkNextEvaluationTime; private float _serverDarkNextItemRefreshTime; private bool _serverDarkCacheDirty = true; private BreakerBox _serverDarkBreaker; private bool _serverDarkObservedHasBreaker; private bool _serverDarkObservedBreakerOn; private bool _serverDarkObservedPowerOffPermanently; private readonly List<DarknessLightSource> _serverDarkSceneLights = new List<DarknessLightSource>(); private readonly List<DarknessLightSource> _serverDarkPlayerLights = new List<DarknessLightSource>(); private readonly List<DarknessLightSource> _serverDarkItemLights = new List<DarknessLightSource>(); private readonly List<(GrabbableObject Item, int Id)> _serverDarkRegisteredItems = new List<(GrabbableObject, int)>(); private readonly HashSet<int> _serverDarkRegisteredItemIds = new HashSet<int>(); private readonly HashSet<int> _serverDarkPoweredLightIds = new HashSet<int>(); private readonly List<Light> _serverDarkItemLightScratch = new List<Light>(); private readonly List<DarknessCandidate> _serverDarkCandidates = new List<DarknessCandidate>(); private readonly List<DarknessLightSource> _serverDarkCandidateSources = new List<DarknessLightSource>(); private readonly DarknessPair[] _serverDarkNearestPairs = new DarknessPair[8]; private Vector3 _serverDarkChest; private Vector3 _serverDarkHead; private DarknessRayTest _serverDarkRayTest; private const string ExecutionLogPrefix = "[CreepyDollAI][combat] "; private const string ExecutionAbortStunned = "stunned"; private const string ExecutionAbortVictimDead = "victim-dead"; private const string ExecutionAbortVictimGone = "victim-gone"; private const string ExecutionAbortCancel = "cancel"; private const string ExecutionAbortDespawn = "despawn"; private const float ExecutionMoveMetresPerSecond = 8f; private const float ExecutionTurnDegreesPerSecond = 720f; private const float ExecutionAbortCrossfadeSeconds = 0.25f; private const float ExecutionGazeSampleSeconds = 0.1f; private const float ExecutionAnchorSampleRadius = 2f; private const float ExecutionVictimSkinMeters = 0.05f; private const float ExecutionVictimFeetClearanceMeters = 0.3f; private const float ExecutionEndToleranceSeconds = 0.25f; private readonly NetworkVariable<HushdollExecutionState> _networkExecution = new NetworkVariable<HushdollExecutionState>(default(HushdollExecutionState), (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); private HushdollExecutionState _serverExecution; private byte _serverExecutionSerial; private float _serverExecutionStartTime; private bool _serverExecutionStartLow; private bool _serverExecutionAgentFrozen; private bool _serverExecutionAgentWasStopped; private ServerExecutionAnchorProbe _serverAnchorProbe; private int _serverAnchorRefusalKey = -1; private string _serverAnchorRefusal; private bool _localExecutionPrimed; private byte _localExecutionSerial; private bool _localExecutionPresenting; private HushdollExecutionState _localExecution; private ExecutionAlignment _localExecutionAlignment; private Vector3 _localExecutionPresentedAnchor; private bool _localExecutionVictimPeerAnchor; private PlayerControllerB _localExecutionVictim; private bool _localExecutionVictimFlagsSet; private bool _localExecutionLateJoin; private bool _localExecutionSnapPending; private bool _localExecutionAnimatorPending; private bool _localExecutionKillSoundPlayed; private float _localExecutionClockStart; private float _localExecutionNextGazeSample; private Vector3 _localExecutionFocusPoint; private bool _localExecutionHasFocusPoint; private HushdollVictimHold _victimHold; private static FieldInfo _targetYRotationField; private static bool _targetYRotationFieldResolved; private static readonly int AnimSpeed = Animator.StringToHash("Speed"); private static readonly int AnimLow = Animator.StringToHash("Low"); private static readonly int AnimCrouchAmount = Animator.StringToHash("CrouchAmount"); private static readonly int AnimDropToLope = Animator.StringToHash("DropToLope"); private static readonly int AnimRiseFromLope = Animator.StringToHash("RiseFromLope"); private static readonly int AnimClaw = Animator.StringToHash("Claw"); private static readonly int AnimNotice = Animator.StringToHash("Notice"); private static readonly int AnimStunFreeze = Animator.StringToHash("StunFreeze"); private static readonly int AnimHitSnap = Animator.StringToHash("HitSnap"); private static readonly int AnimHush = Animator.StringToHash("Hush"); private static readonly int AnimCatch = Animator.StringToHash("Catch"); private static readonly int AnimLowRate = Animator.StringToHash("LowRate"); private static readonly int AnimStateUpright = Animator.StringToHash("Upright"); private static readonly int AnimStateLow = Animator.StringToHash("Low"); private static readonly int AnimStateNotice = Animator.StringToHash("Notice"); private static readonly int AnimStateTurnL = Animator.StringToHash("TurnL"); private static readonly int AnimStateTurnR = Animator.StringToHash("TurnR"); private static readonly int AnimStateDropToLope = Animator.StringToHash("DropToLope"); private static readonly int AnimStateRiseFromLope = Animator.StringToHash("RiseFromLope"); private static readonly int AnimStateHush = Animator.StringToHash("Hush"); private static readonly int AnimStateCatch = Animator.StringToHash("Catch"); private const string UpperBodyLayerName = "UpperBody"; private static readonly int AnimStateEmpty = Animator.StringToHash("Empty"); private static readonly int AnimStateClaw = Animator.StringToHash("Claw"); private static readonly (string Name, AnimatorControllerParameterType Type)[] AnimatorContractParameters = new(string, AnimatorControllerParameterType)[12] { ("Speed", (AnimatorControllerParameterType)1), ("Low", (AnimatorControllerParameterType)4), ("CrouchAmount", (AnimatorControllerParameterType)1), ("DropToLope", (AnimatorControllerParameterType)9), ("RiseFromLope", (AnimatorControllerParameterType)9), ("Claw", (AnimatorControllerParameterType)9), ("Hush", (AnimatorControllerParameterType)9), ("Catch", (AnimatorControllerParameterType)9), ("Notice", (AnimatorControllerParameterType)9), ("StunFreeze", (AnimatorControllerParameterType)9), ("HitSnap", (AnimatorControllerParameterType)9), ("LowRate", (AnimatorControllerParameterType)1) }; private static bool _loggedAnimatorContract; private readonly NetworkVariable<HushdollLocomotionState> _networkLocomotion = new NetworkVariable<HushdollLocomotionState>(default(HushdollLocomotionState), (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); private readonly HushdollLocomotionOwner _locomotionOwner = new HushdollLocomotionOwner(); private float _serverFacingTargetYawDegrees; private int _serverFacingTargetFrame = int.MinValue; private int _animatorContractPresence; private int _upperBodyLayerIndex = -1; private bool _localLocomotionApplied; private byte _localAppliedTurnSerial; private float _localAnimatorSpeed; private LocomotionFamily _localLocomotionFamily; private float _localLowRate = 1f; private const string SirenSongObjectName = "SirenSong"; private const float SirenSongSourceHeight = 2f; private SirenSongSchedule _serverSirenSong; private AudioSource _sirenSongSource; private SirenSongListener _sirenSongListener; private const float StareDownHumFadeSeconds = 0.3f; private const float StareDownClatterVolume = 0.245f; private const float StareDownRatchetVolume = 0.9f; private const float StareDownClatterReferenceSpeed = 6f; private const float StareDownClatterPitchMinimum = 0.75f; private const float StareDownClatterPitchMaximum = 1.35f; private const float StareDownHumSourceHeight = 2f; private const float StareDownClatterSourceHeight = 0.2f; private const string ServoWhineObjectName = "ServoWhine"; private const float ServoWhineSourceHeight = 2f; private AudioSource _stareDownHumSource; private AudioSource _stareDownClatterSource; private AudioSource _servoWhineSource; private float _stareDownHumLevel; private EncounterState _stareDownObservedState; private bool _stareDownStateObserved; private static readonly int AnimTic = Animator.StringToHash("Tic"); private HushdollWalkTics _serverWalkTics; private ParticleSystem _walkTicSparks; private bool _walkTicSparksResolved; private int _walkTicTriggerPresence; private const int TicGlitchSirenSlot = 0; private const int TicGlitchHumSlot = 1; private const int TicGlitchClatterSlot = 2; private const int TicGlitchServoSlot = 3; private const int TicGlitchStaticSlot = 4; private const int TicGlitchSlotCount = 5; private HushdollTicGlitch _ticGlitch; private readonly AudioSource[] _ticGlitchSources = (AudioSource[])(object)new AudioSource[5]; private readonly HushdollTicGlitchChannel[] _ticGlitchChannels = new HushdollTicGlitchChannel[5]; private bool _ticGlitchFailureRestoreLogged; private HushdollSharedSettings SharedSettings { get { if (!((NetworkBehaviour)this).IsSpawned || !_networkSharedSettings.Value.Published) { return HushdollSharedSettings.FromLocalConfig(); } return _networkSharedSettings.Value.Sanitized(); } } private EncounterState ReplicatedEncounterState { get { if (!((NetworkBehaviour)this).IsServer) { return HushdollSirenSong.UnpackState(_networkEncounterState.Value); } return _encounterState; } } private HushdollLookTarget CurrentLookTarget { get { if (!((NetworkBehaviour)this).IsServer) { return _networkLookTarget.Value; } return _serverLookTarget; } } private HushdollPeekState CurrentPeekState { get { if (!((NetworkBehaviour)this).IsServer) { return _networkPeekState.Value; } return _serverPeekState; } } private PeekPhase ServerPeekPhase => (PeekPhase)_serverPeekState.Phase; private bool ServerPeekActive => _serverPeekState.Phase != 0; private bool ServerPeekLeaning => _serverPeekState.Phase == 2; private float WalkSpeedMin => SharedSettings.WalkSpeedMin; private HushdollSpeedRamps SpeedRamps => SharedSettings.SpeedRamps; private float CatchBackAngle => SharedSettings.CatchBackAngle; private float Acceleration => Mathf.Max(22.5f, 22.5f); private float AngularSpeed => Mathf.Max(120f, 150f); private float GazeHalfAngleDegrees => 18f; private float CloseRangeGazeHalfAngleDegrees => 40f; private bool HeadTrackingEnabled => true; private float HeadTrackingRange => Mathf.Max(80f, 80f); private float HeadSightRange => Mathf.Clamp(Plugin.ModConfig?.SightRange?.Value ?? 32f, 2f, HeadTrackingRange); private float HeadHearingRange => Mathf.Clamp(Plugin.ModConfig?.HearingRange?.Value ?? 20f, 4f, 80f); private float HeadVisionConeDegrees => 55f; private float HeadProximityAwareness => 3f; private float HeadRearAwarenessRange => 4.5f; private float HeadSightHoldSeconds => 3.5f; private float HeadRearTurnDelaySeconds => 1.2f; private float SpotConfirmSeconds => 0.8f; private float SpotConfirmGraceSeconds => 0.6f; private float HeadRearRegionDegrees => 78f; private float HeadPitchUpLimitDegrees => 47f; private float HeadPitchDownLimitDegrees => 75f; private float HeadTrackSpeed => 240f; private float HeadBodyFollowDelay => 3f; private float HeadBodyFollowSpeed => 60f; private float PursuitDropRange => Mathf.Clamp(Plugin.ModConfig?.PursuitRange?.Value ?? 60f, 12f, HeadTrackingRange); private float ContactRange => SharedSettings.ContactRange; private float ContactCooldown => SharedSettings.AttackCooldown; private bool PlayClawAnimation => Plugin.PlayAttackAnimation; private bool StaticVisualTestMode => Plugin.StaticVisualTestMode; private bool DoorwayDuckEnabled => true; private float DoorwayDuckCrownAboveHeadBone => 0.382f; private float DoorwayDuckSampleSpacingMeters => 0.35f; private float DoorwayDuckClearanceMargin => 0.08f; private float HeadPoseAuthority => 1f; private float HeadRestPitchTrimDegrees => 0f; private float HeadRollLimitDegrees => 18f; private bool IdleExamineEnabled => true; private float IdleScanYawRangeDegrees => 55f; private float IdleScanPitchRangeDegrees => 12f; private float IdleScanRollDegrees => 6f; private float IdleScanSpeedDegreesPerSecond => 26f; private float IdleScanHoldMinSeconds => 2.5f; private float IdleScanHoldMaxSeconds => 6f; private float IdleScanGlanceChance => 0.2f; private float FootstepVolume => Mathf.Clamp(Plugin.ModConfig?.FootstepVolume?.Value ?? 1f, 0f, 4f); private float SirenSongVolume => Mathf.Clamp01(Plugin.ModConfig?.SirenSongVolume?.Value ?? 0.5f); private bool DevSnapSpawnNearPlayer => false; private float DevSpawnDistance => 6f; private bool DebugLogs => Plugin.ModConfig?.DebugLogs?.Value == true; private bool ServerRushLow => HushdollStareDown.LowStance(_encounterState, _isClawing, ServerPeekPhase == PeekPhase.Approach || ServerPeekPhase == PeekPhase.Lean); private float ReplicatedCrouchAmount => HushdollPerception.DequantizeCrouchAmount(_networkCrouchSteps.Value); internal bool ReplicatedDark => _networkLocomotion.Value.Dark; private bool ServerDark => _serverDarkness.Dark; private bool ServerDarkLetsHerCrawl { get { if (_serverDarkness.Dark) { return Plugin.ModConfig?.AllowCrawlWhenWatched?.Value ?? true; } return false; } } private bool ServerExecutionActive => _serverExecution.Kind != 0; private HushdollExecutionState CurrentExecution { get { if (!((NetworkBehaviour)this).IsServer) { return _networkExecution.Value; } return _serverExecution; } } private ExecutionKind LocalExecutionKind => (ExecutionKind)_localExecution.Kind; private float LocalExecutionClock => Time.time - _localExecutionClockStart; private double ServerTimeNow { get { //IL_001a: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Unknown result type (might be due to invalid IL or missing references) if (!((Object)(object)((NetworkBehaviour)this).NetworkManager != (Object)null)) { return Time.timeAsDouble; } NetworkTime serverTime = ((NetworkBehaviour)this).NetworkManager.ServerTime; return ((NetworkTime)(ref serverTime)).Time; } } private ServerExecutionAnchorProbe ServerAnchorProbe => _serverAnchorProbe ?? (_serverAnchorProbe = new ServerExecutionAnchorProbe(this)); private static FieldInfo TargetYRotationField { get { if (_targetYRotationFieldResolved) { return _targetYRotationField; } _targetYRotationFieldResolved = true; FieldInfo field = typeof(EnemyAI).GetField("targetYRotation", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); _targetYRotationField = ((field != null && field.FieldType == typeof(float)) ? field : null); if (_targetYRotationField == null) { ManualLogSource log = Plugin.Log; if (log != null) { log.LogWarning((object)"[CreepyDollAI][combat] EnemyAI.targetYRotation not found: a client may turn her back toward her pre-execution yaw until the host's next rotation arrives."); } } return _targetYRotationField; } } private bool ReplicatedLow => _networkLocomotion.Value.Low; private float ReplicatedLocomotionSpeed => HushdollLocomotion.DequantizeSpeed(_networkLocomotion.Value.SpeedSteps); private bool ServerMobileClawActive => _isClawing; private SirenSongReplica CurrentSirenSong { get { if (!((NetworkBehaviour)this).IsServer) { return HushdollSirenSong.UnpackSong(_networkEncounterState.Value); } return _serverSirenSong.Replica; } } private bool WalkTicsEnabled => Plugin.ModConfig?.WalkTics?.Value ?? true; private float WalkTicIntervalMin => Plugin.ModConfig?.WalkTicIntervalMin?.Value ?? 4f; private float WalkTicIntervalMax => Plugin.ModConfig?.WalkTicIntervalMax?.Value ?? 8f; private float WalkTicStareSeconds => Plugin.ModConfig?.WalkTicStareSeconds?.Value ?? 10f; private float WalkTicStareIntervalMin => Plugin.ModConfig?.WalkTicStareIntervalMin?.Value ?? 2f; private float WalkTicStareIntervalMax => Plugin.ModConfig?.WalkTicStareIntervalMax?.Value ?? 4f; public override void Awake() { try { EnsureBehaviourStates(); ((EnemyAI)this).Awake(); ResolveRuntimeReferences(); ConfigureSearchDefaults(); } catch (Exception arg) { ManualLogSource log = Plugin.Log; if (log != null) { log.LogError((object)$"[CreepyDollAI] Awake failed: {arg}"); } } } public override void Start() { //IL_010f: Unknown result type (might be due to invalid IL or missing references) try { EnsureBehaviourStates(); base.updatePositionThreshold = 0.05f; base.syncMovementSpeed = 0.25f; ((EnemyAI)this).Start(); ResolveRuntimeReferences(); CorrectPrototypeSpawnPlacement(); ConfigureAgent(); ConfigureSearchDefaults(); Plugin.EnsureCollision(((Component)this).gameObject, this); _upperBodyCollider = ((Component)this).GetComponent<CapsuleCollider>(); _upperBodyColliderHeight = -1f; Plugin.EnsureScanNode(((Component)this).gameObject); if ((Object)(object)((Component)this).GetComponent<HushdollLocalCameraSample>() == (Object)null) { ((Component)this).gameObject.AddComponent<HushdollLocalCameraSample>(); } Plugin.DisablePhysicalVisualColliders(((Component)this).gameObject); RepairFacilityAINodes(); Plugin.RepairVisuals(((Component)this).gameObject, "spawned instance"); Plugin.ApplyVisualYawOffset(((Component)this).gameObject, "spawned instance"); SeedStandingHeadHeightFromBounds(); base.enemyHP = 999; base.isOutside = false; if ((Object)(object)base.creatureAnimator != (Object)null) { Plugin.ConfigureAnimatorForCurrentMode(base.creatureAnimator, "spawned instance"); if (!StaticVisualTestMode) { ResetAnimatorLocomotion(); } } EnsureConstantLoop(); if (((NetworkBehaviour)this).IsServer) { StartRoamingSearch(((Component)this).transform.position); } if (DebugLogs) { LogSpawnDiagnostic("Started"); } LogHushdollRuntimeDiagnostics("start"); } catch (Exception arg) { ManualLogSource log = Plugin.Log; if (log != null) { log.LogError((object)$"[CreepyDollAI] Start failed: {arg}"); } } } public override void Update() { //IL_00f4: 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) try { EnsureServerOwnership(); ((EnemyAI)this).Update(); TickServerExecution(); TickExecutionPresentation(); if (base.isEnemyDead) { EndServerPeek(PeekAbort.Killed); if (((NetworkBehaviour)this).IsServer) { ClearServerDoorwayDuck(); WriteServerCrouchTarget(0f); _serverStanceRamp.Clear(); ClearServerDarknessOnDeath(); _locomotionOwner.Reset(hasAuthority: true); PublishServerLocomotion(low: false); StopServerSirenSong(); _serverWalkTics.Reset(); } TickAnimatorLocomotion(); CancelTicGlitch(); StopConstantLoop(); StopServoWhine(); ResetFootfalls(); return; } if ((Object)(object)base.creatureAnimator == (Object)null || (Object)(object)base.agent == (Object)null) { ResolveRuntimeReferences(); } Plugin.ApplyVisualYawOffset(((Component)this).gameObject, "static visual tick", log: false); TickCreatureAudio(); UpdateEyeTransform(); VisibleThreatInsanity.Tick((EnemyAI)(object)this, ((Object)(object)_headBone != (Object)null) ? _headBone.position : GetHeadTrackingOrigin(), Time.deltaTime); TickServerDarkness(); TickServerHeadDetectionState(); TickServerEncounterState(); TickServerPeek(); TickServerStanceRamp(); TickServerLocomotion(); TickAnimatorLocomotion(); TickExecutionAnimator(); TickServerWalkTic(); TickServerSirenSong(); SyncServerReplicatedEncounter(); SyncServerLookTarget(); RefreshAgentRotationOwnership(); TickServerBodyFollowHeadFocus(); TickServerHeadPosture(); LogRoamDiagnostic(); } catch (Exception arg) { ManualLogSource log = Plugin.Log; if (log != null) { log.LogError((object)$"[CreepyDollAI] Update failed: {arg}"); } CancelTicGlitchAfterFailure(); } } public override void OnNetworkSpawn() { ((NetworkBehaviour)this).OnNetworkSpawn(); try { _networkDespawning = false; if (((NetworkBehaviour)this).IsServer) { HushdollSharedSettings value = HushdollSharedSettings.FromLocalConfig(); value.Published = true; _networkSharedSettings.Value = value; _networkLookTarget.Value = _serverLookTarget; _networkPeekState.Value = _serverPeekState; _networkExecution.Value = _serverExecution; _networkStepSeed.Value = Random.Range(1, int.MaxValue); ClearServerPursuitTarget(clearObservationForSameTarget: false); _encounterState = EncounterState.Roam; _encounterStateEnteredTime = Time.time; _encounterTargetClientId = ulong.MaxValue; _serverPendingDetected = false; _serverWatched.Clear(); _serverNearestWatcherClientId = ulong.MaxValue; _serverStanceRamp.Clear(); ResetServerDarkness(); PublishServerLocomotion(low: false); _serverSirenSong.Clear(); _networkEncounterState.Value = HushdollSirenSong.Pack(EncounterState.Roam, _serverSirenSong.Replica); SubscribeServerPlayerTeleported(); } _localSnapEpochPrimed = false; _localLocomotionApplied = false; _localLowRate = 1f; _localExecutionPrimed = false; ResetEyeGlow(); ResetFootfalls(); ResetWalkTics(); StopSirenSong(); NetworkVariable<byte> networkEncounterState = _networkEncounterState; networkEncounterState.OnValueChanged = (OnValueChangedDelegate<byte>)(object)Delegate.Combine((Delegate?)(object)networkEncounterState.OnValueChanged, (Delegate?)(object)new OnValueChangedDelegate<byte>(OnEncounterStateChanged)); } catch (Exception arg) { ManualLogSource log = Plugin.Log; if (log != null) { log.LogError((object)$"[CreepyDollAI] OnNetworkSpawn failed: {arg}"); } } } public override void OnNetworkDespawn() { try { _networkDespawning = true; CancelServerClaw(); AbortServerExecution("despawn"); ReleaseLocalExecution(ExecutionRelease.Despawn); NetworkVariable<byte> networkEncounterState = _networkEncounterState; networkEncounterState.OnValueChanged = (OnValueChangedDelegate<byte>)(object)Delegate.Remove((Delegate?)(object)networkEncounterState.OnValueChanged, (Delegate?)(object)new OnValueChangedDelegate<byte>(OnEncounterStateChanged)); CancelTicGlitch(); StopStareDownAudio(); StopServoWhine(); StopSirenSong(); StopStunSparkLocal(); ResetEyeGlow(); ResetFootfalls(); ResetWalkTics(); EndServerPeek(PeekAbort.Despawned); UnsubscribeServerPlayerTeleported(); } catch (Exception arg) { ManualLogSource log = Plugin.Log; if (log != null) { log.LogError((object)$"[CreepyDollAI] OnNetworkDespawn failed: {arg}"); } } ((NetworkBehaviour)this).OnNetworkDespawn(); } public override void OnDestroy() { try { UnsubscribeServerPlayerTeleported(); CancelTicGlitch(); StopSirenSong(); } catch (Exception arg) { ManualLogSource log = Plugin.Log; if (log != null) { log.LogError((object)$"[CreepyDollAI] OnDestroy failed: {arg}"); } } ((EnemyAI)this).OnDestroy(); } private void EnsureServerOwnership() { if (!((NetworkBehaviour)this).IsServer || !((NetworkBehaviour)this).IsSpawned) { return; } ulong ownerClientId = ((NetworkBehaviour)this).OwnerClientId; if (ownerClientId == 0L) { _serverReportedForeignOwner = ulong.MaxValue; } else if (_serverReportedForeignOwner != ownerClientId) { _serverReportedForeignOwner = ownerClientId; ManualLogSource log = Plugin.Log; if (log != null) { log.LogWarning((object)$"[CreepyDollAI] NetworkObject owner moved to client {ownerClientId}; restoring server ownership."); } ((NetworkBehaviour)this).NetworkObject.ChangeOwnership(0uL); if ((Object)(object)StartOfRound.Instance != (Object)null && StartOfRound.Instance.ClientPlayerList.TryGetValue(0uL, out var value)) { base.currentOwnershipOnThisClient = value; ((EnemyAI)this).ChangeEnemyOwnerClientRpc(value); } } } private void SyncServerReplicatedEncounter() { if (((NetworkBehaviour)this).IsServer && ((NetworkBehaviour)this).IsSpawned) { byte b = HushdollSirenSong.Pack(_encounterState, _serverSirenSong.Replica); if (_networkEncounterState.Value != b) { _networkEncounterState.Value = b; } } } private void OnEncounterStateChanged(byte previous, byte current) { EncounterState encounterState = HushdollSirenSong.UnpackState(current); if (HushdollSirenSong.UnpackState(previous) == encounterState || base.isEnemyDead) { return; } bool flag = ((Behaviour)this).isActiveAndEnabled && ((NetworkBehaviour)this).IsSpawned && !_networkDespawning; switch (encounterState) { case EncounterState.Notice: if (flag) { _eyeNoticeEdgeTime = Time.time; PlayCueLocal(HushdollCue.NoticeStinger, 1f); } if (!ReplicatedLow) { FireAnimatorReaction(AnimNotice); } break; case EncounterState.Stunned: if ((Object)(object)base.creatureAnimator != (Object)null && !StaticVisualTestMode && AnimatorContractReady()) { CancelAnimatorClaw(); } FireAnimatorReaction(AnimStunFreeze); if (flag) { _eyeStunEdgeTime = Time.time; _eyeFlickerSample = -1; PlayCueLocal(HushdollCue.StunHit, 1f); PlayStunSparkLocal(); } break; } } public override void HitEnemy(int force = 1, PlayerControllerB playerWhoHit = null, bool playHitSFX = false, int hitID = -1) { ((EnemyAI)this).HitEnemy(force, playerWhoHit, playHitSFX, hitID); try { if (!base.isEnemyDead && !ReplicatedLow && !_localExecutionPresenting) { FireAnimatorReaction(AnimHitSnap); } } catch (Exception arg) { ManualLogSource log = Plugin.Log; if (log != null) { log.LogError((object)$"[CreepyDollAI] HitEnemy failed: {arg}"); } } } private void LateUpdate() { try { StabilizeVisualRootOnGround(); ResolveHeadTrackingReferences(); TrackStandingHeadHeight(); TickHeadPostureSmoothing(); ApplyProceduralPose(); SampleExecutionGaze(); LogCrouchCapHeadOnce(); TickEyeGlow(); TickFootfalls(); } catch (Exception arg) { ManualLogSource log = Plugin.Log; if (log != null) { log.LogError((object)$"[CreepyDollAI] LateUpdate failed: {arg}"); } } } private void OnDisable() { //IL_00d3: Unknown result type (might be due to invalid IL or missing references) try { CancelTicGlitch(); StopConstantLoop(); StopServoWhine(); StopStunSparkLocal(); ResetEyeGlow(); ResetFootfalls(); ResetWalkTics(); CancelServerClaw(); AbortServerExecution("despawn"); ReleaseLocalExecution(ExecutionRelease.Despawn); EndServerPeek(PeekAbort.Disabled); ClearServerDoorwayDuck(); if (((NetworkBehaviour)this).IsServer && ((NetworkBehaviour)this).IsSpawned && !_networkDespawning) { WriteServerCrouchTarget(0f); } StopServerSirenSong(); _localCrouchAmount = 0f; _localCrouchWasAtCap = false; ApplyAnimatorCrouchAmount(0f); if ((Object)(object)_upperBodyCollider != (Object)null) { float num = (_upperBodyColliderHeight = 3.9f); _upperBodyCollider.height = num; _upperBodyCollider.center = new Vector3(0f, num * 0.5f, 0f); } _localLocomotionApplied = false; _localLowRate = 1f; } catch (Exception arg) { ManualLogSource log = Plugin.Log; if (log != null) { log.LogError((object)$"[CreepyDollAI] OnDisable failed: {arg}"); } } } public override void DoAIInterval() { try { ((EnemyAI)this).DoAIInterval(); if (!((NetworkBehaviour)this).IsServer || base.isEnemyDead || (Object)(object)StartOfRound.Instance == (Object)null || StartOfRound.Instance.allPlayersDead) { ResetServerNavigationTravel(); return; } PrepareServerNavigationContext(); TickServerNavigationProgress(); if (ServerExecutionActive || _serverExecutionAgentFrozen || base.stunNormalizedTimer > 0f) { if (!ServerExecutionActive && !_serverExecutionAgentFrozen) { StopMovingServer(); } return; } EvaluateServerWatched(); SampleServerPlayerMotion(); ConfigureAgent(); ConfigureSearchDefaults(); RepairFacilityAINodes(); if (_isClawing) { if (!ReleaseStaleClawLatch()) { PlayerControllerB val = FindPlayerByClientId(_serverSlashTargetClientId); if ((Object)(object)val != (Object)null && !val.isPlayerDead) { ContinueMobileClawPursuit(val); FocusHeadOnPlayerServer(val, 0.45f); } else { StopAgentPath(); } } return; } if (_encounterState != EncounterState.Stunned && base.stunNormalizedTimer <= 0f && Time.time >= _nextContactTime) { PlayerControllerB val2 = FindBasicAttackTarget(); if ((Object)(object)val2 != (Object)null && RaiseServerContact(ReadServerContact(val2), val2)) { return; } } switch (_encounterState) { case EncounterState.Notice: case EncounterState.Stunned: StopMovingServer(); break; case EncounterState.Stalk: case EncounterState.Rush: { PlayerControllerB val3 = ResolveServerPursuitPlayer(); if ((Object)(object)val3 == (Object)null) { StopMovingServer(); } else if (_encounterState != EncounterState.Rush || (!TickServerPeekMovement() && !TryBeginServerPeek(val3))) { PursueServerTarget(val3); } break; } case EncounterState.Search: if (!TickServerInvestigation()) { RoamServer(); } break; default: RoamServer(); break; } } catch (Exception arg) { ManualLogSource log = Plugin.Log; if (log != null) { log.LogError((object)$"[CreepyDollAI] DoAIInterval failed: {arg}"); } } } private void TickServerEncounterState() { if (!((NetworkBehaviour)this).IsServer || base.isEnemyDead) { return; } if (ServerExecutionActive) { _serverPendingDetected = false; return; } PlayerControllerB val = ResolveServerPursuitPlayer(); bool targetKnown = (Object)(object)val != (Object)null && ServerTargetKnown(val); StareDownInputs inputs = new StareDownInputs { Stunned = (base.stunNormalizedTimer > 0f), TargetKnown = targetKnown, Watched = _serverWatched.Watched, Dark = ServerDarkLetsHerCrawl, Detected = _serverPendingDetected, SecondsInState = Time.time - _encounterStateEnteredTime }; _serverPendingDetected = false; EncounterState encounterState = HushdollStareDown.Next(_encounterState, in inputs); if (encounterState != _encounterState) { TransitionEncounterState(encounterState, DescribeEncounterTransition(encounterState, targetKnown)); } if (_encounterState == EncounterState.Search && Time.time >= _nextSearchVocalTime) { _nextSearchVocalTime = Time.time + 4f; PlayIdleBeatClientRpc(0.5f, 1f); } } private bool ServerTargetKnown(PlayerControllerB target) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0043: Unknown result type (might be due to invalid IL or missing references) //IL_0048: Unknown result type (might be due to invalid IL or missing references) float num = Vector3.Distance(((Component)this).transform.position, ((Component)target).transform.position); if (num <= HeadTrackingRange && HasClearLineOfSightToPlayerFace(target)) { _serverPursuitLastVisibleTime = Time.time; _serverPursuitLastSeenPosition = ((Component)target).transform.position; _hasServerPursuitLastSeen = true; return true; } return HushdollPerception.RetainPursuit(num, visible: false, Time.time - _serverPursuitLastVisibleTime, Time.time - _serverPursuitAcquiredTime, PursuitDropRange, 12f); } private string DescribeEncounterTransition(EncounterState next, bool targetKnown) { switch (next) { case EncounterState.Stunned: return "stunned"; case EncounterState.Notice: if (!targetKnown) { return "heard"; } return "sighted"; case EncounterState.Stalk: return "target known, watched"; case EncounterState.Rush: if (!_serverWatched.Watched || !ServerDarkLetsHerCrawl) { return "target known, nobody watching"; } return "target known, watched in the dark"; case EncounterState.Search: if (_encounterState == EncounterState.Notice) { return "noticed nobody to pursue"; } if (_serverPursuitClientId != ulong.MaxValue) { return $"target lost: unseen {Time.time - _serverPursuitLastVisibleTime:0.00} s"; } return "target gone (dead, in the ship or untargetable)"; default: if (_encounterState != EncounterState.Search) { return "stun over, no target"; } return "search gave up"; } } private void TransitionEncounterState(EncounterState next, string reason) { //IL_00f2: Unknown result type (might be due to invalid IL or missing references) //IL_0104: Unknown result type (might be due to invalid IL or missing references) if (!((NetworkBehaviour)this).IsServer || next == _encounterState) { return; } EncounterState encounterState = _encounterState; float num = Time.time - _encounterStateEnteredTime; _encounterState = next; _encounterStateEnteredTime = Time.time; if (HushdollStareDown.IsRampStance(next)) { _serverStanceRamp.Restart(next, Time.time); } else { _serverStanceRamp.Clear(); } if (encounterState == EncounterState.Search) { EndServerInvestigation($"left search for {next}"); } switch (next) { case EncounterState.Roam: if (encounterState == EncounterState.Search) { PlayIdleBeatClientRpc(0.3f, 0.94f); } ClearServerPursuitTarget(clearObservationForSameTarget: true); _encounterTargetClientId = ulong.MaxValue; break; case EncounterState.Notice: { StopMovingServer(); PlayerControllerB val = ResolveServerPursuitPlayer(); if ((Object)(object)val != (Object)null) { ForceHeadSnapToPlayerServer(val, HeadSightHoldSeconds); } break; } case EncounterState.Search: if (_hasServerPursuitLastSeen) { BeginServerInvestigation(_serverPursuitLastSeenPosition); } else if (encounterState == EncounterState.Notice) { BeginServerInvestigation(_serverStimulusPoint); } ClearServerPursuitTarget(clearObservationForSameTarget: true); _nextSearchVocalTime = Time.time + 4f; PlayIdleBeatClientRpc(0.55f, 1f); break; case EncounterState.Stunned: CancelServerClaw(); StopMovingServer(); break; } ApplyAgentSpeed(); LogHeadStateEvent($"[encounter] {encounterState} -> {next}: reason={reason}, " + "target=" + ((_encounterTargetClientId == ulong.MaxValue) ? "none" : _encounterTargetClientId.ToString()) + ", " + $"watched={_serverWatched.Watched}, dark={ServerDarkLetsHerCrawl}, dwell={num:0.0}s"); } private void NoteEncounterStimulus(PlayerControllerB player, bool seen, Vector3? point = null) { //IL_0057: Unknown result type (might be due to invalid IL or missing references) //IL_004e: Unknown result type (might be due to invalid IL or missing references) //IL_005c: Unknown result type (might be due to invalid IL or missing references) //IL_0084: Unknown result type (might be due to invalid IL or missing references) //IL_008f: Unknown result type (might be due to invalid IL or missing references) //IL_0094: Unknown result type (might be due to invalid IL or missing references) //IL_0099: Unknown result type (might be due to invalid IL or missing references) //IL_00a7: Unknown result type (might be due to invalid IL or missing references) //IL_00b2: Unknown result type (might be due to invalid IL or missing references) //IL_00b7: Unknown result type (might be due to invalid IL or missing references) //IL_00bc: Unknown result type (might be due to invalid IL or missing references) if (!((NetworkBehaviour)this).IsServer || base.isEnemyDead || _encounterState == EncounterState.Stunned || (Object)(object)player == (Object)null || player.isPlayerDead || !PlayerIsTargetableByHushdoll(player, cannotBeInShip: true)) { return; } _serverPendingDetected = true; _serverStimulusPoint = (Vector3)(((??)point) ?? ((Component)player).transform.position); if (!seen) { return; } PlayerControllerB val = ResolveServerPursuitPlayer(); if ((Object)(object)val != (Object)null) { if ((Object)(object)val == (Object)(object)player) { return; } Vector3 val2 = ((Component)val).transform.position - ((Component)this).transform.position; float sqrMagnitude = ((Vector3)(ref val2)).sqrMagnitude; val2 = ((Component)player).transform.position - ((Component)this).transform.position; if (sqrMagnitude <= ((Vector3)(ref val2)).sqrMagnitude) { return; } } ulong actualClientId = player.actualClientId; SetServerPursuitTarget(player, "sight"); if (_serverPursuitClientId == actualClientId) { _serverPursuitAcquiredTime = Time.time; _encounterTargetClientId = actualClientId; if ((Object)(object)val != (Object)null) { LogHeadStateEvent($"[encounter] target switched to nearer player={actualClientId} (was {val.actualClientId})."); } } } private void EvaluateServerWatched() { //IL_004a: Unknown result type (might be due to invalid IL or missing references) //IL_004f: Unknown result type (might be due to invalid IL or missing references) //IL_0204: Unknown result type (might be due to invalid IL or missing references) //IL_00d4: Unknown result type (might be due to invalid IL or missing references) //IL_00d9: Unknown result type (might be due to invalid IL or missing references) //IL_00db: Unknown result type (might be due to invalid IL or missing references) //IL_00e0: Unknown result type (might be due to invalid IL or missing references) //IL_00e4: Unknown result type (might be due to invalid IL or missing references) //IL_00e9: Unknown result type (might be due to invalid IL or missing references) //IL_00eb: Unknown result type (might be due to invalid IL or missing references) //IL_00f0: Unknown result type (might be due to invalid IL or missing references) //IL_0102: Unknown result type (might be due to invalid IL or missing references) //IL_0104: Unknown result type (might be due to invalid IL or missing references) //IL_010b: Unknown result type (might be due to invalid IL or missing references) //IL_010d: Unknown result type (might be due to invalid IL or missing references) //IL_0112: Unknown result type (might be due to invalid IL or missing references) //IL_015e: Unknown result type (might be due to invalid IL or missing references) //IL_0165: Unknown result type (might be due to invalid IL or missing references) float time = Time.time; ulong num = ulong.MaxValue; float num2 = float.PositiveInfinity; WatchedPoint point = WatchedPoint.None; float num3 = 0f; WatchedProbe probe = default(WatchedProbe); if ((Object)(object)StartOfRound.Instance != (Object)null && StartOfRound.Instance.allPlayerScripts != null) { probe.Doll = this; probe.Head = GetFacePoint(); ResolveWatchedBodyPoints(out probe.Chest, out probe.Hips); probe.RangeSqr = HeadSightRange * HeadSightRange; PlayerControllerB[] allPlayerScripts = StartOfRound.Instance.allPlayerScripts; PlayerControllerB val = StrictLocalPlayer(); foreach (PlayerControllerB val2 in allPlayerScripts) { if (!ServerPlayerCanWatch(val2)) { continue; } Camera gameplayCamera = val2.gameplayCamera; if ((Object)(object)val2 != (Object)(object)val || !HushdollLocalCameraSample.TryGetFresh(val2, out var position, out var rotation)) { Transform transform = ((Component)gameplayCamera).transform; position = transform.position; rotation = transform.rotation; } Vector3 val3 = probe.Head - position; float sqrMagnitude = ((Vector3)(ref val3)).sqrMagnitude; if (!(sqrMagnitude >= num2)) { probe.CameraPosition = position; probe.WorldToCamera = Quaternion.Inverse(rotation); probe.Frustum = ViewFrustum.FromCamera(gameplayCamera.fieldOfView, gameplayCamera.aspect); probe.PlayerRoot = ((Component)val2).transform; WatchedPoint watchedPoint = HushdollPerception.FirstWatchedPoint(ref probe); if (watchedPoint != WatchedPoint.None) { num = val2.actualClientId; num2 = sqrMagnitude; point = watchedPoint; num3 = Vector3.Distance(probe.Point(watchedPoint), probe.CameraPosition); } } } } bool flag = num != ulong.MaxValue; bool flag2 = false; float num4 = 0f; if (!flag && _serverWatched.Watched) { CreepyDollConfig modConfig = Plugin.ModConfig; num4 = modConfig?.ObstacleGraceSeconds?.Value ?? 3.5f; flag2 = num4 > 0.5f && LastWatcherFacesChest(probe.Chest, modConfig?.ObstacleGraceAngle?.Value ?? 30f, modConfig?.ObstacleGraceRange?.Value ?? 12f); } bool num5 = _serverWatched.Sample(flag, flag2, time, 0.5f, num4); if (flag) { _serverNearestWatcherClientId = num; } else if (!_serverWatched.Watched || !ServerPlayerCanWatch(FindPlayerByClientId(_serverNearestWatcherClientId))) { _serverNearestWatcherClientId = ulong.MaxValue; } if (num5) { float num6 = (flag2 ? Mathf.Max(0.5f, num4) : 0.5f); LogHeadStateEvent(_serverWatched.Watched ? FormattableString.Invariant($"watched: player={num} via {HushdollPerception.DescribeWatchedPoint(point)}, distance={num3:F1} m.") : FormattableString.Invariant(FormattableStringFactory.Create("unwatched: last on screen {0:F2} s ago, loss grace {1:F1} s{2}.", time - _serverWatched.LastSeenTime, num6, flag2 ? " (facing)" : string.Empty))); } } private bool LastWatcherFacesChest(Vector3 chest, float maxAngleDegrees, float maxDistance) { //IL_003d: Unknown result type (might be due to invalid IL or missing references) //IL_0042: Unknown result type (might be due to invalid IL or missing references) //IL_0043: Unknown result type (might be due to invalid IL or missing references) //IL_0048: Unknown result type (might be due to invalid IL or missing references) //IL_0049: Unknown result type (might be due to invalid IL or missing references) //IL_004a: Unknown result type (might be due to invalid IL or missing references) //IL_004f: Unknown result type (might be due to invalid IL or missing references) //IL_0054: Unknown result type (might be due to invalid IL or missing references) //IL_0055: Unknown result type (might be due to invalid IL or missing references) //IL_005b: Unknown result type (might be due to invalid IL or missing references) //IL_0061: Unknown result type (might be due to invalid IL or missing references) //IL_006c: Unknown result type (might be due to invalid IL or missing references) //IL_0072: Unknown result type (might be due to invalid IL or missing references) //IL_0078: Unknown result type (might be due to invalid IL or missing references) //IL_0083: Unknown result type (might be due to invalid IL or missing references) //IL_0089: Unknown result type (might be due to invalid IL or missing references) //IL_008f: Unknown result type (might be due to invalid IL or missing references) PlayerControllerB val = FindPlayerByClientId(_serverNearestWatcherClientId); if (!ServerPlayerCanWatch(val)) { return false; } if ((Object)(object)val != (Object)(object)StrictLocalPlayer() || !HushdollLocalCameraSample.TryGetFresh(val, out var position, out var rotation)) { Transform transform = ((Component)val.gameplayCamera).transform; position = transform.position; rotation = transform.rotation; } Vector3 val2 = rotation * Vector3.forward; return HushdollPerception.IsFacing(new PerceptionPoint(position.x, position.y, position.z), new PerceptionPoint(val2.x, val2.y, val2.z), new PerceptionPoint(chest.x, chest.y, chest.z), maxAngleDegrees, maxDistance); } private bool ServerPlayerCanWatch(PlayerControllerB player) { if ((Object)(object)player != (Object)null && player.isPlayerControlled && !player.isPlayerDead && player.isInsideFactory != base.isOutside) { return (Object)(object)player.gameplayCamera != (Object)null; } return false; } private void ResolveWatchedBodyPoints(out Vector3 chest, out Vector3 hips) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_0040: Unknown result type (might be due to invalid IL or missing references) //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_0028: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Unknown result type (might be due to invalid IL or missing references) //IL_0045: Unknown result type (might be due to invalid IL or missing references) //IL_0072: 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_005a: Unknown result type (might be due to invalid IL or missing references) //IL_0060: Unknown result type (might be due to invalid IL or missing references) //IL_0065: Unknown result type (might be due to invalid IL or missing references) //IL_0077: Unknown result type (might be due to invalid IL or missing references) Vector3 position = ((Component)this).transform.position; Vector3 up = ((Component)this).transform.up; chest = (((Object)(object)_upperSpineBone != (Object)null) ? _upperSpineBone.position : (position + up * 2.8f)); hips = (((Object)(object)_hipBone != (Object)null) ? _hipBone.position : (position + up * 1.4f)); } private ContactReading ReadServerContact(PlayerControllerB victim) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Unknown result type (might be due to invalid IL or missing references) //IL_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) //IL_0048: Unknown result type (might be due to invalid IL or missing references) //IL_006e: Unknown result type (might be due to invalid IL or missing references) //IL_0074: Unknown result type (might be due to invalid IL or missing references) Vector3 forward = ((Component)victim).transform.forward; Vector3 val = ((Component)this).transform.position - ((Component)victim).transform.position; ContactMotionSample contactMotionSample = ServerPlayerMotion(victim); return new ContactReading(_encounterState, HushdollStareDown.VictimFacingAwayDegrees(forward.x, forward.z, val.x, val.z), CatchBackAngle, contactMotionSample.Speed, HushdollStareDown.VictimLateralDegrees(contactMotionSample.VelocityX, contactMotionSample.VelocityZ, val.x, val.z)); } private bool RaiseServerContact(in ContactReading contact, PlayerControllerB victim) { ExecutionKind executionKind = HushdollExecution.ForContact(contact.Kind); string refusal = null; if (executionKind != ExecutionKind.None && TryBeginServerExecution(executionKind, in contact, victim, out refusal)) { return true; } if (!BeginClawServer(victim)) { return false; } LogExecution((refusal == null) ? FormattableString.Invariant($"contact {contact.Kind}: player={victim.actualClientId} {contact.Describe()}") : FormattableString.Invariant($"contact {contact.Kind} -> Claw (exec refused: {refusal}): player={victim.actualClientId} {contact.Describe()}")); return true; } private void SampleServerPlayerMotion() { //IL_0063: Unknown result type (might be due to invalid IL or missing references) //IL_0068: Unknown result type (might be due to invalid IL or missing references) //IL_0076: Unknown result type (might be due to invalid IL or missing references) //IL_007d: Unknown result type (might be due to invalid IL or missing references) PlayerControllerB[] allPlayerScripts = StartOfRound.Instance.allPlayerScripts; if (allPlayerScripts == null) { return; } if (_serverPlayerMotion == null || _serverPlayerMotion.Length != allPlayerScripts.Length) { _serverPlayerMotion = new ContactMotionSample[allPlayerScripts.Length]; } float time = Time.time; for (int i = 0; i < allPlayerScripts.Length; i++) { PlayerControllerB val = allPlayerScripts[i]; if ((Object)(object)val == (Object)null) { _serverPlayerMotion[i] = default(ContactMotionSample); continue; } Vector3 position = ((Component)val).transform.position; _serverPlayerMotion[i].Sample(position.x, position.z, val.isInsideFactory, time); } } private ContactMotionSample ServerPlayerMotion(PlayerControllerB player) { int num = ServerPlayerMotionSlot(player); if (num < 0) { return default(ContactMotionSample); } return _serverPlayerMotion[num]; } private int ServerPlayerMotionSlot(PlayerControllerB player) { if ((Object)(object)player == (Object)null || _serverPlayerMotion == null || (Object)(object)StartOfRound.Instance == (Object)null || StartOfRound.Instance.allPlayerScripts == null) { return -1; } PlayerControllerB[] allPlayerScripts = StartOfRound.Instance.allPlayerScripts; int num = Mathf.Min(allPlayerScripts.Length, _serverPlayerMotion.Length); for (int i = 0; i < num; i++) { if ((Object)(object)allPlayerScripts[i] == (Object)(object)player) { return i; } } return -1; } private void SubscribeServerPlayerTeleported() { StartOfRound instance = StartOfRound.Instance; if (!((Object)(object)instance == (Object)null) && instance.playerTeleportedEvent != null && !((Object)(object)_serverTeleportEventSource == (Object)(object)instance)) { UnsubscribeServerPlayerTeleported(); ((UnityEvent<PlayerControllerB>)(object)instance.playerTeleportedEvent).AddListener((UnityAction<PlayerControllerB>)OnServerPlayerTeleported); _serverTeleportEventSource = instance; } } private void UnsubscribeServerPlayerTeleported() { if ((Object)(object)_serverTeleportEventSource != (Object)null && _serverTeleportEventSource.playerTeleportedEvent != null) { ((UnityEvent<PlayerControllerB>)(object)_serverTeleportEventSource.playerTeleportedEvent).RemoveListener((UnityAction<PlayerControllerB>)OnServerPlayerTeleported); } _serverTeleportEventSource = null; } private void OnServerPlayerTeleported(PlayerControllerB player) { try { if (((NetworkBehaviour)this).IsServer) { int num = ServerPlayerMotionSlot(player); if (num >= 0) { _serverPlayerMotion[num].Invalidate(); } } } catch (Exception arg) { ManualLogSource log = Plugin.Log; if (log != null) { log.LogError((object)$"[CreepyDollAI] OnServerPlayerTeleported failed: {arg}"); } } } private bool EncounterStateAllowsRoaming() { if (_encounterState != EncounterState.Roam) { if (_encounterState == EncounterState.Search) { return !_serverInvestigating; } return false; } return true; } private void PursueServerTarget(PlayerControllerB target) { //IL_0072: 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_00c6: Unknown result type (might be due to invalid IL or missing references) if (!((NetworkBehaviour)this).IsServer || (Object)(object)target == (Object)null || target.isPlayerDead || ServerExecutionActive || _serverExecutionAgentFrozen || base.stunNormalizedTimer > 0f) { return; } base.targetPlayer = target; base.movingTowardsTargetPlayer = false; StopSearchIfNeeded(clear: false); FocusHeadOnPlayerServer(target, 0.65f); PrepareServerNavigationContext(); if (EnsureAgentOnNavMesh()) { if (!TryDriveCheckedServerNavigation(((Component)target).transform.position, requireComplete: false)) { RecoverServerNavigation(((Component)target).transform.position, 0f, 0.0, "invalid-path", progressStalled: false); } } else { StopCheckedServerNavigation(); LogMovementDiagnostic("target movement skipped: agent is not on NavMesh"); } if (!AgentDrivesBodyRotation()) { FacePosition(((Component)target).transform.position); } if (!StaticVisualTestMode && base.currentBehaviourStateIndex != 1) { ((EnemyAI)this).SwitchToBehaviourState(1); } } private void PrepareServerNavigationContext() { ServerNavigationOwner serverNavigationOwner = ServerNavigationOw
Y4NGZCrookedChoir.dll
Decompiled a day ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security.Cryptography; using System.Text; using BepInEx; using BepInEx.Bootstrap; using BepInEx.Configuration; using BepInEx.Logging; using Dawn; using GameNetcodeStuff; using HarmonyLib; using Microsoft.CodeAnalysis; using Unity.Collections; using Unity.Netcode; using UnityEngine; using UnityEngine.AI; using UnityEngine.Audio; using UnityEngine.Events; using UnityEngine.Rendering.HighDefinition; using UnityEngine.SceneManagement; using Y4NGZCrookedChoir.AI; using Y4NGZCrookedChoir.Motion; using Y4NGZCrookedChoir.NetcodePatcher; using Y4NGZMonsters.Shared; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: AssemblyCompany("Y4NGZCrookedChoir")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0+3460ec64f0cec4948e51ddb3f02a4b0e414f105e")] [assembly: AssemblyProduct("Y4NGZCrookedChoir")] [assembly: AssemblyTitle("Y4NGZCrookedChoir")] [assembly: AssemblyVersion("1.0.0.0")] [module: RefSafetyRules(11)] [module: NetcodePatchedAssembly] 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 Y4NGZMonsters.Shared { internal sealed class ConfigPersistence : IDisposable { private readonly ConfigFile _config; private readonly ManualLogSource _log; private readonly string _creatureName; private readonly bool _configExisted; private readonly bool _autosaveWasEnabled; private bool _disposed; private ConfigPersistence(ConfigFile config, ManualLogSource log, string creatureName) { _config = config ?? throw new ArgumentNullException("config"); _log = log; _creatureName = (string.IsNullOrWhiteSpace(creatureName) ? "Creature" : creatureName); _configExisted = File.Exists(config.ConfigFilePath); _autosaveWasEnabled = config.SaveOnConfigSet; config.SaveOnConfigSet = false; } internal static ConfigPersistence BeginBinding(ConfigFile config, ManualLogSource log, string creatureName) { return new ConfigPersistence(config, log, creatureName); } public void Dispose() { if (_disposed) { return; } _disposed = true; _config.SaveOnConfigSet = true; if (!_autosaveWasEnabled) { ManualLogSource log = _log; if (log != null) { log.LogWarning((object)("[" + _creatureName + "] Config autosave was disabled before binding. It has been enabled so changes made through config UIs persist.")); } } try { _config.Save(); } catch (Exception ex) { ManualLogSource log2 = _log; if (log2 != null) { log2.LogError((object)("[" + _creatureName + "] Could not save config '" + _config.ConfigFilePath + "': " + ex.Message)); } return; } if (!_configExisted) { ManualLogSource log3 = _log; if (log3 != null) { log3.LogInfo((object)("[" + _creatureName + "] Created config '" + _config.ConfigFilePath + "'.")); } } } } internal abstract class ContextualSpawnWeights : IWeighted, IContextualWeighted<SpawnWeightContext> { private readonly SpawnWeightTable _table; private readonly Func<float> _multiplier; private readonly MoonWeightOverrides _moonOverrides; protected ContextualSpawnWeights(SpawnWeightTable table, string creatureName, Func<float> multiplier, Func<string> moonOverrides, Action<string> logWarning) { _table = table; _multiplier = multiplier ?? throw new ArgumentNullException("multiplier"); _moonOverrides = new MoonWeightOverrides(moonOverrides, logWarning, creatureName); } public int GetWeight() { return SpawnWeightTable.Scale(_table.DefaultWeight, 1f, _multiplier()); } public int GetWeight(SpawnWeightContext context) { int moonWeight = _table.GetMoonWeight(GetMoonTier(((SpawnWeightContext)(ref context)).Moon)); moonWeight = _moonOverrides.Resolve(((SpawnWeightContext)(ref context)).Moon, moonWeight); float interiorMultiplier = _table.GetInteriorMultiplier(GetInterior(((SpawnWeightContext)(ref context)).Dungeon)); return SpawnWeightTable.Scale(moonWeight, interiorMultiplier, _multiplier()); } private static SpawnWeightTable.MoonTier GetMoonTier(DawnMoonInfo moon) { if (moon == null) { return SpawnWeightTable.MoonTier.Default; } NamespacedKey<DawnMoonInfo> typedKey = ((DawnBaseInfo<DawnMoonInfo>)(object)moon).TypedKey; if (((DawnBaseInfo<DawnMoonInfo>)(object)moon).HasTag(Tags.Company) || ((DawnBaseInfo<DawnMoonInfo>)(object)moon).HasTag(Tags.Unimplemented) || KeyEquals<DawnMoonInfo>(typedKey, MoonKeys.Test)) { return SpawnWeightTable.MoonTier.Disabled; } if (KeyEquals<DawnMoonInfo>(typedKey, MoonKeys.Experimentation)) { return SpawnWeightTable.MoonTier.Experimentation; } if (KeyEquals<DawnMoonInfo>(typedKey, MoonKeys.Assurance) || KeyEquals<DawnMoonInfo>(typedKey, MoonKeys.Vow)) { return SpawnWeightTable.MoonTier.AssuranceVow; } if (KeyEquals<DawnMoonInfo>(typedKey, MoonKeys.Offense) || KeyEquals<DawnMoonInfo>(typedKey, MoonKeys.March) || KeyEquals<DawnMoonInfo>(typedKey, MoonKeys.Embrion)) { return SpawnWeightTable.MoonTier.OffenseMarchEmbrion; } if (KeyEquals<DawnMoonInfo>(typedKey, MoonKeys.Adamance)) { return SpawnWeightTable.MoonTier.Adamance; } if (KeyEquals<DawnMoonInfo>(typedKey, MoonKeys.Rend) || KeyEquals<DawnMoonInfo>(typedKey, MoonKeys.Dine)) { return SpawnWeightTable.MoonTier.RendDine; } if (KeyEquals<DawnMoonInfo>(typedKey, MoonKeys.Titan) || KeyEquals<DawnMoonInfo>(typedKey, MoonKeys.Artifice) || KeyEquals<DawnMoonInfo>(typedKey, MoonKeys.Liquidation)) { return SpawnWeightTable.MoonTier.TitanArtificeLiquidation; } if (!((DawnBaseInfo<DawnMoonInfo>)(object)moon).HasTag(Tags.Paid)) { return SpawnWeightTable.MoonTier.Default; } return SpawnWeightTable.MoonTier.Paid; } private SpawnWeightTable.Interior GetInterior(DawnDungeonInfo dungeon) { if (dungeon == null) { return SpawnWeightTable.Interior.Unknown; } NamespacedKey<DawnDungeonInfo> typedKey = ((DawnBaseInfo<DawnDungeonInfo>)(object)dungeon).TypedKey; bool broadInteriorTags = _table.BroadInteriorTags; bool isFacility = KeyEquals<DawnDungeonInfo>(typedKey, DungeonKeys.FacilityFlow) || KeyEquals<DawnDungeonInfo>(typedKey, DungeonKeys.FacilityFlowThreeExits) || KeyEquals<DawnDungeonInfo>(typedKey, DungeonKeys.FacilityFlowExtraLarge) || ((DawnBaseInfo<DawnDungeonInfo>)(object)dungeon).HasTag(Tags.Industrial) || ((DawnBaseInfo<DawnDungeonInfo>)(object)dungeon).HasTag(Tags.Mechanical) || ((DawnBaseInfo<DawnDungeonInfo>)(object)dungeon).HasTag(Tags.Factory) || (broadInteriorTags && ((DawnBaseInfo<DawnDungeonInfo>)(object)dungeon).HasTag(Tags.Bunker)); bool isMansion = KeyEquals<DawnDungeonInfo>(typedKey, DungeonKeys.MansionFlow) || ((DawnBaseInfo<DawnDungeonInfo>)(object)dungeon).HasTag(Tags.Gothic) || ((DawnBaseInfo<DawnDungeonInfo>)(object)dungeon).HasTag(Tags.Grand) || ((DawnBaseInfo<DawnDungeonInfo>)(object)dungeon).HasTag(Tags.Ornate) || (broadInteriorTags && (((DawnBaseInfo<DawnDungeonInfo>)(object)dungeon).HasTag(Tags.Lavish) || ((DawnBaseInfo<DawnDungeonInfo>)(object)dungeon).HasTag(Tags.Eerie))); bool isMineshaft = KeyEquals<DawnDungeonInfo>(typedKey, DungeonKeys.MineshaftFlow) || ((DawnBaseInfo<DawnDungeonInfo>)(object)dungeon).HasTag(Tags.Cavern) || ((DawnBaseInfo<DawnDungeonInfo>)(object)dungeon).HasTag(Tags.Quarry) || ((DawnBaseInfo<DawnDungeonInfo>)(object)dungeon).HasTag(Tags.Flooded); return _table.ClassifyInterior(isFacility, isMansion, isMineshaft); } private static bool KeyEquals<T>(NamespacedKey<T> left, NamespacedKey<T> right) where T : INamespaced { if (left != null && right != null) { return ((object)left).Equals((object?)right); } return false; } } internal readonly struct SpawnWeightTable { internal enum MoonTier { Default, Disabled, Experimentation, AssuranceVow, OffenseMarchEmbrion, Adamance, RendDine, TitanArtificeLiquidation, Paid } internal enum Interior { Unknown, Facility, Mansion, Mineshaft, Other } internal const int MaximumWeight = 100; internal const float MaximumMultiplier = 5f; internal static readonly SpawnWeightTable EyeMonster = new SpawnWeightTable(5, 3, 5, 7, 9, 11, 13, 10, 1f, 0.75f, 0.75f, 0.75f, mansionFirst: false, broadInteriorTags: true); internal static readonly SpawnWeightTable SimonSays = new SpawnWeightTable(3, 1, 3, 5, 7, 9, 11, 8, 1.25f, 1f, 0.5f, 0.75f, mansionFirst: false, broadInteriorTags: true); internal static readonly SpawnWeightTable Hushdoll = new SpawnWeightTable(3, 1, 3, 5, 7, 9, 11, 8, 1f, 1.25f, 0.5f, 0.75f, mansionFirst: true, broadInteriorTags: true); internal static readonly SpawnWeightTable Warden = new SpawnWeightTable(6, 4, 6, 8, 10, 11, 13, 10, 1.25f, 0.75f, 0.5f, 0.75f, mansionFirst: false, broadInteriorTags: true); internal static readonly SpawnWeightTable Type05 = new SpawnWeightTable(3, 1, 3, 5, 7, 9, 11, 8, 1f, 1.25f, 0.5f, 0.75f, mansionFirst: true, broadInteriorTags: true); internal static readonly SpawnWeightTable Harmonic = new SpawnWeightTable(6, 4, 6, 8, 10, 12, 14, 10, 1f, 0.75f, 0.5f, 0.5f, mansionFirst: false, broadInteriorTags: false); internal static readonly SpawnWeightTable Passenger = new SpawnWeightTable(3, 1, 3, 5, 7, 9, 11, 8, 1f, 1.25f, 0.5f, 0.75f, mansionFirst: true, broadInteriorTags: true); internal static readonly SpawnWeightTable BoiledOne = new SpawnWeightTable(3, 1, 3, 5, 7, 9, 11, 8, 1f, 1.25f, 0.5f, 0.75f, mansionFirst: true, broadInteriorTags: true); internal static readonly SpawnWeightTable Snipjack = new SpawnWeightTable(4, 2, 4, 6, 8, 10, 12, 9, 1f, 0.75f, 0.5f, 0.5f, mansionFirst: false, broadInteriorTags: false); internal static readonly SpawnWeightTable CookMonster = new SpawnWeightTable(6, 4, 6, 8, 10, 12, 14, 10, 1f, 1f, 0.5f, 0.75f, mansionFirst: false, broadInteriorTags: true); internal static readonly SpawnWeightTable Locust = new SpawnWeightTable(6, 4, 6, 8, 10, 12, 14, 10, 1f, 1f, 0.5f, 0.75f, mansionFirst: false, broadInteriorTags: true); internal static readonly SpawnWeightTable CrookedChoir = new SpawnWeightTable(15, 15, 15, 15, 15, 15, 15, 15, 1f, 1.3333334f, 2f / 3f, 2f / 3f, mansionFirst: true, broadInteriorTags: true); internal static readonly SpawnWeightTable BeetleBull = new SpawnWeightTable(15, 12, 25, 20, 25, 4, 3, 12, 1f, 1f, 1f, 1f, mansionFirst: false, broadInteriorTags: true); internal readonly int DefaultWeight; internal readonly int Experimentation; internal readonly int AssuranceVow; internal readonly int OffenseMarchEmbrion; internal readonly int Adamance; internal readonly int RendDine; internal readonly int TitanArtificeLiquidation; internal readonly int Paid; internal readonly float Facility; internal readonly float Mansion; internal readonly float Mineshaft; internal readonly float Other; internal readonly bool MansionFirst; internal readonly bool BroadInteriorTags; private SpawnWeightTable(int defaultWeight, int experimentation, int assuranceVow, int offenseMarchEmbrion, int adamance, int rendDine, int titanArtificeLiquidation, int paid, float facility, float mansion, float mineshaft, float other, bool mansionFirst, bool broadInteriorTags) { DefaultWeight = defaultWeight; Experimentation = experimentation; AssuranceVow = assuranceVow; OffenseMarchEmbrion = offenseMarchEmbrion; Adamance = adamance; RendDine = rendDine; TitanArtificeLiquidation = titanArtificeLiquidation; Paid = paid; Facility = facility; Mansion = mansion; Mineshaft = mineshaft; Other = other; MansionFirst = mansionFirst; BroadInteriorTags = broadInteriorTags; } internal int GetMoonWeight(MoonTier tier) { return tier switch { MoonTier.Disabled => 0, MoonTier.Experimentation => Experimentation, MoonTier.AssuranceVow => AssuranceVow, MoonTier.OffenseMarchEmbrion => OffenseMarchEmbrion, MoonTier.Adamance => Adamance, MoonTier.RendDine => RendDine, MoonTier.TitanArtificeLiquidation => TitanArtificeLiquidation, MoonTier.Paid => Paid, _ => DefaultWeight, }; } internal Interior ClassifyInterior(bool isFacility, bool isMansion, bool isMineshaft) { if (MansionFirst && isMansion) { return Interior.Mansion; } if (isFacility) { return Interior.Facility; } if (isMansion) { return Interior.Mansion; } if (isMineshaft) { return Interior.Mineshaft; } return Interior.Other; } internal float GetInteriorMultiplier(Interior interior) { return interior switch { Interior.Facility => Facility, Interior.Mansion => Mansion, Interior.Mineshaft => Mineshaft, Interior.Other => Other, _ => 1f, }; } internal static int Scale(int moonWeight, float interiorMultiplier, float configMultiplier) { if (moonWeight <= 0) { return 0; } float num = Math.Max(0f, Math.Min(5f, configMultiplier)); float num2 = (float)moonWeight * interiorMultiplier * num; if (!(num2 > 0f)) { return 0; } return Math.Min(100, Math.Max(1, (int)Math.Round(num2))); } } internal sealed class MoonWeightOverrides { internal const int MinimumWeight = 0; internal const int MaximumWeight = 100; private readonly Func<string> _getValue; private readonly Action<string> _logWarning; private readonly string _creatureName; private readonly Dictionary<string, int> _canonicalWeights = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase); private readonly Dictionary<string, int> _aliasWeights = new Dictionary<string, int>(StringComparer.Ordinal); private string _parsedValue; private bool _hasParsed; internal MoonWeightOverrides(Func<string> getValue, Action<string> logWarning, string creatureName) { _getValue = getValue ?? throw new ArgumentNullException("getValue"); _logWarning = logWarning; _creatureName = (string.IsNullOrWhiteSpace(creatureName) ? "Creature" : creatureName); } internal int Resolve(string canonicalKey, string shortKey, string configName, string displayName, int authoredWeight) { Refresh(); if (!string.IsNullOrWhiteSpace(canonicalKey) && _canonicalWeights.TryGetValue(canonicalKey.Trim(), out var value)) { return value; } if (TryResolveAlias(shortKey, out var weight) || TryResolveAlias(configName, out weight) || TryResolveAlias(displayName, out weight)) { return weight; } return authoredWeight; } private bool TryResolveAlias(string candidate, out int weight) { string text = NormalizeAlias(candidate); if (text.Length > 0) { return _aliasWeights.TryGetValue(text, out weight); } weight = 0; return false; } private void Refresh() { string text = _getValue() ?? string.Empty; if (_hasParsed && string.Equals(text, _parsedValue, StringComparison.Ordinal)) { return; } _hasParsed = true; _parsedValue = text; _canonicalWeights.Clear(); _aliasWeights.Clear(); if (!string.IsNullOrWhiteSpace(text)) { string[] array = text.Split(new char[2] { ',', ';' }, StringSplitOptions.RemoveEmptyEntries); foreach (string text2 in array) { ParseToken(text2.Trim()); } } } private void ParseToken(string token) { int num = token.LastIndexOf('='); int val = token.LastIndexOf(':'); int num2 = Math.Max(num, val); if (num2 <= 0 || num2 >= token.Length - 1) { Warn(token, "expected Moon:Weight or namespace:moon=Weight"); return; } string text = token.Substring(0, num2).Trim(); if (text.IndexOf(':') >= 0 && num2 != num) { Warn(token, "namespaced moons must use namespace:moon=Weight"); } else { ParseWeight(text, token.Substring(num2 + 1).Trim(), token); } } private void ParseWeight(string identifier, string weightText, string token) { if (!int.TryParse(weightText, NumberStyles.Integer, CultureInfo.InvariantCulture, out var result)) { Warn(token, "weight must be a whole number"); return; } int num = Math.Max(0, Math.Min(100, result)); if (num != result) { _logWarning?.Invoke($"[{_creatureName}] MoonWeightOverrides clamped '{token}' to {num}."); } if (identifier.IndexOf(':') >= 0) { if (!IsCanonicalKey(identifier)) { Warn(token, "namespaced moons must use namespace:moon=Weight"); } else { _canonicalWeights[identifier] = num; } return; } string text = NormalizeAlias(identifier); if (text.Length == 0) { Warn(token, "moon name is empty"); } else { _aliasWeights[text] = num; } } private static bool IsCanonicalKey(string identifier) { int num = identifier.IndexOf(':'); if (num > 0 && num < identifier.Length - 1) { return identifier.IndexOf(':', num + 1) < 0; } return false; } private static string NormalizeAlias(string value) { if (string.IsNullOrWhiteSpace(value)) { return string.Empty; } StringBuilder stringBuilder = new StringBuilder(value.Length); foreach (char c in value) { if (char.IsLetterOrDigit(c)) { stringBuilder.Append(char.ToLowerInvariant(c)); } } return stringBuilder.ToString(); } private void Warn(string token, string reason) { _logWarning?.Invoke("[" + _creatureName + "] Ignoring MoonWeightOverrides token '" + token + "': " + reason + "."); } } internal static class DawnMoonWeightOverrides { internal static int Resolve(this MoonWeightOverrides overrides, DawnMoonInfo moon, int authoredWeight) { if (overrides == null || moon == null) { return authoredWeight; } string? canonicalKey = ((object)((DawnBaseInfo<DawnMoonInfo>)(object)moon).TypedKey)?.ToString(); NamespacedKey<DawnMoonInfo> typedKey = ((DawnBaseInfo<DawnMoonInfo>)(object)moon).TypedKey; return overrides.Resolve(canonicalKey, (typedKey != null) ? ((NamespacedKey)typedKey).Key : null, moon.GetConfigName(), moon.GetNumberlessPlanetName(), authoredWeight); } } internal sealed class ServerOwnershipGuard { private ulong _reportedForeignOwner = ulong.MaxValue; internal void Ensure(EnemyAI enemy, ManualLogSource log) { if (!((NetworkBehaviour)enemy).IsServer || !((NetworkBehaviour)enemy).IsSpawned) { return; } ulong ownerClientId = ((NetworkBehaviour)enemy).OwnerClientId; if (ownerClientId == 0L) { _reportedForeignOwner = ulong.MaxValue; } else if (_reportedForeignOwner != ownerClientId) { _reportedForeignOwner = ownerClientId; if (log != null) { log.LogWarning((object)$"[{((object)enemy).GetType().Name}] NetworkObject owner moved to client {ownerClientId}; restoring server ownership."); } ((NetworkBehaviour)enemy).NetworkObject.ChangeOwnership(0uL); if ((Object)(object)StartOfRound.Instance != (Object)null && StartOfRound.Instance.ClientPlayerList.TryGetValue(0uL, out var value)) { enemy.currentOwnershipOnThisClient = value; enemy.ChangeEnemyOwnerClientRpc(value); } } } } internal static class VictimRpc { private static readonly ulong[] SingleTarget = new ulong[1]; internal static ClientRpcParams TargetOnly(PlayerControllerB victim) { //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_0031: Unknown result type (might be due to invalid IL or missing references) SingleTarget[0] = victim.actualClientId; return new ClientRpcParams { Send = new ClientRpcSendParams { TargetClientIds = SingleTarget } }; } internal static bool IsLocalVictim(ulong actualClientId) { PlayerControllerB val = GameNetworkManager.Instance?.localPlayerController; if ((Object)(object)val != (Object)null) { return val.actualClientId == actualClientId; } return false; } internal static PlayerControllerB FromSlot(int playerSlot) { PlayerControllerB[] array = StartOfRound.Instance?.allPlayerScripts; if (array == null || playerSlot < 0 || playerSlot >= array.Length) { return null; } return array[playerSlot]; } internal static PlayerControllerB FromActualClientId(ulong actualClientId) { PlayerControllerB[] array = StartOfRound.Instance?.allPlayerScripts; if (array == null) { return null; } foreach (PlayerControllerB val in array) { if ((Object)(object)val != (Object)null && val.actualClientId == actualClientId && (val.isPlayerControlled || val.isPlayerDead)) { return val; } } return null; } internal static bool IsHostDummy(PlayerControllerB player) { if ((Object)(object)player == (Object)null) { return false; } NetworkManager singleton = NetworkManager.Singleton; if ((Object)(object)singleton == (Object)null || !singleton.IsServer || !((NetworkBehaviour)player).IsOwner || !player.isPlayerControlled) { return false; } GameNetworkManager instance = GameNetworkManager.Instance; if ((Object)(object)instance != (Object)null && (Object)(object)instance.localPlayerController != (Object)null) { return (Object)(object)player != (Object)(object)instance.localPlayerController; } return false; } internal static bool IsVictimLocal(PlayerControllerB player) { if ((Object)(object)player == (Object)null) { return false; } GameNetworkManager instance = GameNetworkManager.Instance; if (!((Object)(object)instance != (Object)null) || !((Object)(object)player == (Object)(object)instance.localPlayerController)) { return IsHostDummy(player); } return true; } internal static ClientRpcParams TargetOwner(PlayerControllerB victim) { //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_0031: Unknown result type (might be due to invalid IL or missing references) SingleTarget[0] = ((NetworkBehaviour)victim).OwnerClientId; return new ClientRpcParams { Send = new ClientRpcSendParams { TargetClientIds = SingleTarget } }; } internal static PlayerControllerB LocalVictimFromSlot(ulong playerSlot) { if (playerSlot > int.MaxValue) { return null; } PlayerControllerB val = FromSlot((int)playerSlot); if (!IsVictimLocal(val)) { return null; } return val; } internal static bool SenderOwnsSlot(ulong senderClientId, PlayerControllerB player) { if ((Object)(object)player != (Object)null) { return ((NetworkBehaviour)player).OwnerClientId == senderClientId; } return false; } } internal static class CreatureAudioSetup { private const string DiegeticGroupName = "Master"; private static AudioMixerGroup _diegeticGroup; internal static bool ConfigureSpatial(AudioSource source, bool occlude = true) { if ((Object)(object)source == (Object)null) { return true; } if (!TryResolveDiegeticGroup(out var group)) { return false; } if ((Object)(object)group != (Object)null) { source.outputAudioMixerGroup = group; } source.dopplerLevel = 0f; if (occlude && (Object)(object)((Component)source).GetComponent<OccludeAudio>() == (Object)null) { OccludeAudio obj = ((Component)source).gameObject.AddComponent<OccludeAudio>(); obj.useReverb = true; obj.overridingLowPass = false; } return true; } internal static void TransmitOneShot(AudioSource source, AudioClip clip, float volume = 1f) { if (!((Object)(object)source == (Object)null) && !((Object)(object)clip == (Object)null)) { source.PlayOneShot(clip, volume); WalkieTalkie.TransmitOneShotAudio(source, clip, volume); } } private static bool TryResolveDiegeticGroup(out AudioMixerGroup group) { if ((Object)(object)_diegeticGroup != (Object)null) { group = _diegeticGroup; return true; } group = null; SoundManager instance = SoundManager.Instance; if ((Object)(object)instance == (Object)null || (Object)(object)instance.diageticMixer == (Object)null) { return false; } AudioMixerGroup[] array = instance.diageticMixer.FindMatchingGroups("Master"); if (array != null && array.Length != 0) { _diegeticGroup = array[0]; } group = _diegeticGroup; return true; } } internal static class VisibleThreatInsanity { private const float InsanityPerSecond = 0.5f; private const float SightWidth = 80f; private const int SightRange = 20; internal static void Tick(EnemyAI enemy, Vector3 sightPoint, float deltaTime) { //IL_00f7: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)enemy == (Object)null || !((NetworkBehaviour)enemy).IsSpawned || !((Behaviour)enemy).isActiveAndEnabled || enemy.isEnemyDead || !(deltaTime > 0f) || float.IsInfinity(deltaTime)) { return; } StartOfRound instance = StartOfRound.Instance; TimeOfDay instance2 = TimeOfDay.Instance; if (!((Object)(object)instance == (Object)null) && !((Object)(object)instance2 == (Object)null) && instance.shipHasLanded && !instance.inShipPhase && !instance.shipIsLeaving && !instance.newGameIsLoading && !instance.allPlayersDead && instance2.currentDayTimeStarted) { GameNetworkManager instance3 = GameNetworkManager.Instance; PlayerControllerB val = (((Object)(object)instance3 != (Object)null) ? instance3.localPlayerController : null); if (!((Object)(object)val == (Object)null) && ((NetworkBehaviour)val).IsOwner && val.isPlayerControlled && !val.isPlayerDead && (!((NetworkBehaviour)val).IsServer || val.isHostPlayerObject) && !((Object)(object)val.playerEye == (Object)null) && val.isInsideFactory != enemy.isOutside && val.insanityLevel < val.maxInsanityLevel && val.HasLineOfSightToPosition(sightPoint, 80f, 20, -1f, -1)) { val.insanityLevel = Mathf.Min(val.maxInsanityLevel, val.insanityLevel + 0.5f * deltaTime); } } } } } namespace Y4NGZCrookedChoir { internal enum ChoirCueClip { SpotPlayer, StrikeWindup, StrikeSlamHit, StrikeSlamMiss, StumbleFall, StumbleRise, Snap1, Snap2, Snap3, Snap4, Gulp, SneezeInhale, Sneeze, Hit, Stun, Death, Chute1, Chute2, Chute3, Chute4 } internal sealed class ChoirAudioClips { internal const int CueCount = 20; internal const string AudioAssetPrefix = "assets/crookedchoir/audio/"; internal static readonly string[] ContractFiles = new string[27] { "choir_chatter_01.ogg", "choir_chatter_02.ogg", "choir_stalk_breath_01.wav", "choir_stalk_breath_02.wav", "choir_spot_player.wav", "choir_strike_windup.wav", "choir_strike_slam_hit.wav", "choir_strike_slam_miss.wav", "choir_stumble_fall.wav", "choir_stumble_rise.wav", "choir_snap_01.wav", "choir_snap_02.wav", "choir_snap_03.wav", "choir_snap_04.wav", "choir_gulp.wav", "choir_sneeze_inhale.wav", "choir_sneeze.wav", "choir_hit.wav", "choir_stun.wav", "choir_death.wav", "choir_blood_chute_01.wav", "choir_blood_chute_02.wav", "choir_blood_chute_03.wav", "choir_blood_chute_04.wav", "choir_footstep_01.wav", "choir_footstep_02.wav", "choir_footstep_03.wav" }; internal static readonly string[] LegacyFiles = new string[1] { "choir_charge.wav" }; private const int ChatterFirst = 0; private const int ChatterCount = 2; private const int BreathFirst = 2; private const int BreathCount = 2; private const int CueFirst = 4; private const int FootstepFirst = 24; private const int FootstepCount = 3; internal readonly AudioClip[] Cues; internal readonly AudioClip[] Chatter; internal readonly AudioClip[] StalkBreath; internal readonly AudioClip[] Footsteps; internal readonly string[] Missing; internal readonly bool FootstepsAuthored; private ChoirAudioClips(AudioClip[] cues, AudioClip[] chatter, AudioClip[] breath, AudioClip[] footsteps, string[] missing, bool footstepsAuthored) { Cues = cues; Chatter = chatter; StalkBreath = breath; Footsteps = footsteps; Missing = missing; FootstepsAuthored = footstepsAuthored; } internal static string FileName(ChoirCueClip clip) { return ContractFiles[(int)(4 + clip)]; } internal static ChoirAudioClips Load(Func<string, AudioClip> load, Action<string> warn) { AudioClip[] array = (AudioClip[])(object)new AudioClip[ContractFiles.Length]; List<string> list = new List<string>(); for (int i = 0; i < ContractFiles.Length; i++) { array[i] = load(ContractFiles[i]); if ((Object)(object)array[i] == (Object)null) { list.Add(ContractFiles[i]); } } AudioClip[] array2 = (AudioClip[])(object)new AudioClip[20]; Array.Copy(array, 4, array2, 0, 20); if ((Object)(object)array2[1] == (Object)null) { array2[1] = load(LegacyFiles[0]); } if (list.Count > 0) { warn($"[CrookedChoir] Optional audio clips missing from the bundle ({list.Count}): " + string.Join(", ", list) + "; those cues fall back or stay silent."); } return new ChoirAudioClips(array2, Present(array, 0, 2), Present(array, 2, 2), Present(array, 24, 3), list.ToArray(), (Object)(object)array[26] != (Object)null); } internal static AudioClip[] SelectFootsteps(AudioClip[] bundle, bool bundleAuthored, AudioClip[] spider) { if (bundleAuthored && bundle != null && bundle.Length != 0) { return bundle; } if (spider != null && spider.Length != 0) { return spider; } return bundle ?? Array.Empty<AudioClip>(); } private static AudioClip[] Present(AudioClip[] loaded, int first, int count) { int num = 0; for (int i = first; i < first + count; i++) { if ((Object)(object)loaded[i] != (Object)null) { num++; } } AudioClip[] array = (AudioClip[])(object)new AudioClip[num]; int num2 = 0; for (int j = first; j < first + count; j++) { if ((Object)(object)loaded[j] != (Object)null) { array[num2++] = loaded[j]; } } return array; } } internal static class ChoirBloodFxBridge { internal delegate bool WoundPose(out Vector3 origin, out Vector3 direction); internal const string PluginGuid = "com.y4ngz.bloodfx"; private const string TypeName = "Y4NGZCompany.Experience.BloodFX.BloodFXCreatureBlood"; private const string PoseTypeName = "Y4NGZCompany.Experience.BloodFX.BloodFXWoundPose"; private static Func<bool> _available; private static Func<int, Vector3, Vector3, Color, int, float, bool> _play; private static Func<int, Transform, WoundPose, float, string, bool> _begin; private static Action<int, float> _pulse; private static Action<int, string> _end; internal static bool StreamsAvailable => _begin != null; internal static bool Bind(Assembly assembly) { Unbind(); Type type = assembly?.GetType("Y4NGZCompany.Experience.BloodFX.BloodFXCreatureBlood", throwOnError: false); if (type == null) { return false; } bool num = BindBleed(type); bool flag = BindStreams(assembly, type); return num || flag; } private static void Unbind() { _available = null; _play = null; _begin = null; _pulse = null; _end = null; } private static bool BindBleed(Type type) { MethodInfo methodInfo = type.GetProperty("IsAvailable", BindingFlags.Static | BindingFlags.Public)?.GetGetMethod(); MethodInfo method = type.GetMethod("PlayCreatureBleed", BindingFlags.Static | BindingFlags.Public, null, new Type[6] { typeof(int), typeof(Vector3), typeof(Vector3), typeof(Color), typeof(int), typeof(float) }, null); if (methodInfo == null || methodInfo.ReturnType != typeof(bool) || method == null || method.ReturnType != typeof(bool)) { return false; } _available = (Func<bool>)Delegate.CreateDelegate(typeof(Func<bool>), methodInfo); _play = (Func<int, Vector3, Vector3, Color, int, float, bool>)Delegate.CreateDelegate(typeof(Func<int, Vector3, Vector3, Color, int, float, bool>), method); return true; } private static bool BindStreams(Assembly assembly, Type type) { Type type2 = assembly.GetType("Y4NGZCompany.Experience.BloodFX.BloodFXWoundPose", throwOnError: false); if (!IsWoundPose(type2)) { return false; } MethodInfo method = type.GetMethod("BeginCreatureStream", BindingFlags.Static | BindingFlags.Public, null, new Type[5] { typeof(int), typeof(Transform), type2, typeof(float), typeof(string) }, null); MethodInfo method2 = type.GetMethod("PulseCreatureStream", BindingFlags.Static | BindingFlags.Public, null, new Type[2] { typeof(int), typeof(float) }, null); MethodInfo method3 = type.GetMethod("EndCreatureStream", BindingFlags.Static | BindingFlags.Public, null, new Type[2] { typeof(int), typeof(string) }, null); if (method == null || method.ReturnType != typeof(bool) || method2 == null || method2.ReturnType != typeof(void) || method3 == null || method3.ReturnType != typeof(void)) { return false; } _begin = (Func<int, Transform, WoundPose, float, string, bool>)typeof(ChoirBloodFxBridge).GetMethod("AdaptBegin", BindingFlags.Static | BindingFlags.NonPublic).MakeGenericMethod(type2).Invoke(null, new object[1] { method }); _pulse = (Action<int, float>)Delegate.CreateDelegate(typeof(Action<int, float>), method2); _end = (Action<int, string>)Delegate.CreateDelegate(typeof(Action<int, string>), method3); return true; } private static bool IsWoundPose(Type poseType) { if (poseType == null || !typeof(Delegate).IsAssignableFrom(poseType)) { return false; } MethodInfo method = poseType.GetMethod("Invoke"); ParameterInfo[] array = method?.GetParameters(); Type type = typeof(Vector3).MakeByRefType(); if (method != null && method.ReturnType == typeof(bool) && array.Length == 2 && array[0].ParameterType == type && array[0].IsOut && array[1].ParameterType == type) { return array[1].IsOut; } return false; } private static Func<int, Transform, WoundPose, float, string, bool> AdaptBegin<TPose>(MethodInfo method) where TPose : Delegate { Func<int, Transform, TPose, float, string, bool> begin = (Func<int, Transform, TPose, float, string, bool>)Delegate.CreateDelegate(typeof(Func<int, Transform, TPose, float, string, bool>), method); return (int key, Transform sourceRoot, WoundPose pose, float scale, string label) => begin(key, sourceRoot, (TPose)Delegate.CreateDelegate(typeof(TPose), pose.Target, pose.Method), scale, label); } internal static void PlayCreatureBleed(int key, Vector3 point, Vector3 direction, float scale) { //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Unknown result type (might be due to invalid IL or missing references) if (_play == null) { return; } try { if (_available()) { _play(key, point, direction, default(Color), 3, scale); } } catch (Exception ex) { _play = null; _available = null; ManualLogSource log = Plugin.Log; if (log != null) { log.LogWarning((object)("[CrookedChoir] Disabled optional BloodFX bridge: " + ex.GetBaseException().Message)); } } } internal static bool BeginCreatureStream(int key, Transform sourceRoot, WoundPose pose, float scale, string label) { if (_begin == null || pose == null) { return false; } try { return _begin(key, sourceRoot, pose, scale, label); } catch (Exception exception) { DisableStreams(exception); return false; } } internal static bool PulseCreatureStream(int key, float intensity) { if (_pulse == null) { return false; } try { _pulse(key, intensity); return true; } catch (Exception exception) { DisableStreams(exception); return false; } } internal static void EndCreatureStream(int key, string reason) { if (_end == null) { return; } try { _end(key, reason); } catch (Exception exception) { DisableStreams(exception); } } private static void DisableStreams(Exception exception) { _begin = null; _pulse = null; _end = null; ManualLogSource log = Plugin.Log; if (log != null) { log.LogWarning((object)("[CrookedChoir] Disabled optional BloodFX creature streams; pipe blood uses bundled cones: " + exception.GetBaseException().Message)); } } internal static void Initialize() { try { if (Bind((Chainloader.PluginInfos.TryGetValue("com.y4ngz.bloodfx", out var value) && (Object)(object)value.Instance != (Object)null) ? ((object)value.Instance).GetType().Assembly : null)) { if (!StreamsAvailable) { ManualLogSource log = Plugin.Log; if (log != null) { log.LogInfo((object)"[CrookedChoir] Optional BloodFX has no creature streams; devour pipe blood uses bundled cones."); } } return; } } catch (Exception) { Unbind(); } ManualLogSource log2 = Plugin.Log; if (log2 != null) { log2.LogInfo((object)"[CrookedChoir] Optional BloodFX unavailable; using bundled pipe spray only."); } } } internal static class ChoirPreyBridge { internal const string PluginGuid = "com.y4ngz.company"; internal const string FacadeType = "Y4NGZCompany.Escalations.BlacksiteRetrieval.BlacksiteMonsterPrey"; private static Func<Type, string, bool> _registerPredator; private static Func<List<EnemyAI>, int> _collectPrey; private static Func<EnemyAI, bool> _isPrey; private static Func<EnemyAI, Transform> _getLookTransform; private static Func<EnemyAI, EnemyAI, bool> _isHeldBy; private static Func<EnemyAI, EnemyAI, bool> _tryBeginCapture; private static Func<EnemyAI, EnemyAI, bool> _kill; private static Func<EnemyAI, EnemyAI, bool> _consume; private static Func<EnemyAI, EnemyAI, bool> _release; private static Func<EnemyAI, EnemyAI, bool> _cleanupRelease; private static Func<EnemyAI, EnemyAI, Vector3, Quaternion, bool> _poseHeld; internal static bool IsBound => _registerPredator != null; internal static bool Bind(Assembly assembly) { return Bind(assembly?.GetType("Y4NGZCompany.Escalations.BlacksiteRetrieval.BlacksiteMonsterPrey", throwOnError: false)); } internal static bool Bind(Type type) { Unbind(); if (type == null) { return false; } try { FieldInfo field = type.GetField("ProtocolVersion", BindingFlags.Static | BindingFlags.Public); if (field == null || field.FieldType != typeof(int) || !field.IsLiteral || (int)field.GetRawConstantValue() != 1) { return false; } _registerPredator = BindMethod<Func<Type, string, bool>>(type, "RegisterPredator"); _collectPrey = BindMethod<Func<List<EnemyAI>, int>>(type, "CollectPrey"); _isPrey = BindMethod<Func<EnemyAI, bool>>(type, "IsPrey"); _getLookTransform = BindMethod<Func<EnemyAI, Transform>>(type, "GetLookTransform"); _isHeldBy = BindMethod<Func<EnemyAI, EnemyAI, bool>>(type, "IsHeldBy"); _tryBeginCapture = BindMethod<Func<EnemyAI, EnemyAI, bool>>(type, "TryBeginCapture"); _kill = BindMethod<Func<EnemyAI, EnemyAI, bool>>(type, "Kill"); _consume = BindMethod<Func<EnemyAI, EnemyAI, bool>>(type, "Consume"); _release = BindMethod<Func<EnemyAI, EnemyAI, bool>>(type, "Release"); _poseHeld = BindMethod<Func<EnemyAI, EnemyAI, Vector3, Quaternion, bool>>(type, "PoseHeld"); if (_registerPredator != null && _collectPrey != null && _isPrey != null && _getLookTransform != null && _isHeldBy != null && _tryBeginCapture != null && _kill != null && _consume != null && _release != null && _poseHeld != null) { return true; } } catch (Exception) { } Unbind(); return false; } private static T BindMethod<T>(Type type, string name) where T : Delegate { MethodInfo method = typeof(T).GetMethod("Invoke"); ParameterInfo[] parameters = method.GetParameters(); Type[] array = new Type[parameters.Length]; for (int i = 0; i < parameters.Length; i++) { array[i] = parameters[i].ParameterType; } MethodInfo method2 = type.GetMethod(name, BindingFlags.Static | BindingFlags.Public, null, array, null); if (method2 == null || method2.ReturnType != method.ReturnType || method2.ContainsGenericParameters) { return null; } ParameterInfo[] parameters2 = method2.GetParameters(); if (parameters2.Length != array.Length) { return null; } for (int j = 0; j < array.Length; j++) { if (parameters2[j].ParameterType != array[j]) { return null; } } return (T)Delegate.CreateDelegate(typeof(T), method2); } private static void Unbind() { _registerPredator = null; _collectPrey = null; _isPrey = null; _getLookTransform = null; _isHeldBy = null; _tryBeginCapture = null; _kill = null; _consume = null; _release = null; _cleanupRelease = null; _poseHeld = null; } internal static bool RegisterPredator(Type predatorType, string displayName) { if (_registerPredator == null) { return false; } try { return _registerPredator(predatorType, displayName); } catch (Exception exception) { Disable(exception); return false; } } internal static int CollectPrey(List<EnemyAI> buffer) { if (_collectPrey == null) { buffer?.Clear(); return 0; } try { return _collectPrey(buffer); } catch (Exception exception) { buffer?.Clear(); Disable(exception); return 0; } } internal static bool IsPrey(EnemyAI enemy) { if (_isPrey == null) { return false; } try { return _isPrey(enemy); } catch (Exception exception) { Disable(exception); return false; } } internal static Transform GetLookTransform(EnemyAI enemy) { if (_getLookTransform == null) { return null; } try { return _getLookTransform(enemy); } catch (Exception exception) { Disable(exception); return null; } } internal static bool IsHeldBy(EnemyAI captor, EnemyAI soldier) { if (_isHeldBy == null) { return false; } try { return _isHeldBy(captor, soldier); } catch (Exception exception) { Disable(exception); return false; } } internal static bool TryBeginCapture(EnemyAI captor, EnemyAI soldier) { if (_tryBeginCapture == null) { return false; } try { return _tryBeginCapture(captor, soldier); } catch (Exception exception) { Disable(exception); Release(captor, soldier); return false; } } internal static bool Kill(EnemyAI captor, EnemyAI soldier) { if (_kill == null) { return false; } try { return _kill(captor, soldier); } catch (Exception exception) { Disable(exception); return false; } } internal static bool Consume(EnemyAI captor, EnemyAI soldier) { if (_consume == null) { return false; } try { return _consume(captor, soldier); } catch (Exception exception) { Disable(exception); return false; } } internal static bool Release(EnemyAI captor, EnemyAI soldier) { Func<EnemyAI, EnemyAI, bool> func = _release ?? _cleanupRelease; if (func == null) { return false; } try { return func(captor, soldier); } catch (Exception exception) { Disable(exception); return false; } } internal static bool PoseHeld(EnemyAI captor, EnemyAI soldier, Vector3 position, Quaternion rotation) { //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Unknown result type (might be due to invalid IL or missing references) if (_poseHeld == null) { return false; } try { return _poseHeld(captor, soldier, position, rotation); } catch (Exception exception) { Disable(exception); return false; } } private static void Disable(Exception exception) { bool isBound = IsBound; Func<EnemyAI, EnemyAI, bool> cleanupRelease = _release ?? _cleanupRelease; Unbind(); _cleanupRelease = cleanupRelease; if (isBound) { ManualLogSource log = Plugin.Log; if (log != null) { log.LogWarning((object)("[CrookedChoir] Optional Company prey bridge failed; soldier prey disabled: " + exception.Message)); } } } internal static void Initialize() { try { if (Bind((Chainloader.PluginInfos.TryGetValue("com.y4ngz.company", out var value) && (Object)(object)value.Instance != (Object)null) ? ((object)value.Instance).GetType().Assembly : null) && RegisterPredator(typeof(CrookedChoirAI), "Crooked Choir")) { return; } } catch (Exception) { } Unbind(); ManualLogSource log = Plugin.Log; if (log != null) { log.LogInfo((object)"[CrookedChoir] Optional Company prey bridge unavailable; hunting players only."); } } } public static class ChoirScale { public const float Factor = 1.15f; } internal static class ChoirVanillaAssets { private static bool _cached; internal static EnemyType Masked { get; private set; } internal static AudioClip[] SpiderSteps { get; private set; } internal static void Cache() { if (_cached) { return; } _cached = true; EnemyType[] array = Resources.FindObjectsOfTypeAll<EnemyType>(); SandSpiderAI val = default(SandSpiderAI); for (int i = 0; i < array.Length; i++) { GameObject enemyPrefab = array[i].enemyPrefab; if (!((Object)(object)enemyPrefab == (Object)null)) { if ((Object)(object)Masked == (Object)null && (Object)(object)enemyPrefab.GetComponent<MaskedPlayerEnemy>() != (Object)null) { Masked = array[i]; } if (SpiderSteps == null && enemyPrefab.TryGetComponent<SandSpiderAI>(ref val) && val.footstepSFX != null && val.footstepSFX.Length != 0) { SpiderSteps = val.footstepSFX; } } } if ((Object)(object)Masked == (Object)null) { ManualLogSource log = Plugin.Log; if (log != null) { log.LogWarning((object)"[CrookedChoir] Vanilla Masked EnemyType not found; sneeze cannot spawn an enemy."); } } } } internal static class CrookedChoirEffectMaterials { internal static GameObject Repair(GameObject prefab, ManualLogSource logger) { //IL_00dc: Unknown result type (might be due to invalid IL or missing references) //IL_00e1: Unknown result type (might be due to invalid IL or missing references) //IL_00e8: Unknown result type (might be due to invalid IL or missing references) //IL_00f7: Expected O, but got Unknown if ((Object)(object)prefab == (Object)null || ((Object)prefab).name != "ChoirPipeBlood") { throw new InvalidOperationException("Required ChoirPipeBlood effect prefab is missing."); } Shader val = Shader.Find("HDRP/Unlit"); if ((Object)(object)val == (Object)null || !val.isSupported) { throw new InvalidOperationException("No supported game HDRP/Unlit shader is available."); } ParticleSystemRenderer[] componentsInChildren = prefab.GetComponentsInChildren<ParticleSystemRenderer>(true); if (componentsInChildren.Length != 6) { throw new InvalidOperationException("ChoirPipeBlood requires six particle renderers."); } Dictionary<Material, Material> dictionary = new Dictionary<Material, Material>(); int num = 0; ParticleSystemRenderer[] array = componentsInChildren; foreach (ParticleSystemRenderer val2 in array) { Material sharedMaterial = ((Renderer)val2).sharedMaterial; if ((Object)(object)sharedMaterial == (Object)null || ((Object)sharedMaterial).name != "ChoirPipeBlood") { throw new InvalidOperationException("Pipe blood renderer lost its authored material identity."); } if ((Object)(object)sharedMaterial.shader == (Object)(object)val && sharedMaterial.shader.isSupported) { continue; } if (!dictionary.TryGetValue(sharedMaterial, out var value)) { value = new Material(sharedMaterial) { shader = val, name = ((Object)sharedMaterial).name }; if ((Object)(object)value.GetTexture("_UnlitColorMap") == (Object)null) { Object.Destroy((Object)(object)value); throw new InvalidOperationException("Pipe blood material lost its authored sprite."); } HDMaterial.ValidateMaterial(value); dictionary.Add(sharedMaterial, value); } ((Renderer)val2).sharedMaterial = value; num++; } logger.LogInfo((object)$"[CrookedChoir] Pipe blood material repair: renderers={componentsInChildren.Length}, repaired={num}, shader={((Object)val).name}."); return prefab; } } internal sealed class CrookedChoirSpawnWeights : ContextualSpawnWeights { internal CrookedChoirSpawnWeights(Func<float> multiplier, Func<string> moonOverrides, Action<string> logWarning) : base(SpawnWeightTable.CrookedChoir, "Crooked Choir", multiplier, moonOverrides, logWarning) { } } internal static class CrookedChoirVisualMaterials { private const string TextureRoot = "assets/crookedchoir/textures/"; internal static void Repair(GameObject prefab, AssetBundle bundle) { //IL_0256: Unknown result type (might be due to invalid IL or missing references) //IL_025b: Unknown result type (might be due to invalid IL or missing references) //IL_0262: Unknown result type (might be due to invalid IL or missing references) //IL_0271: Expected O, but got Unknown Transform obj = prefab.transform.Find("VisualRoot"); if ((Object)(object)obj == (Object)null) { throw new InvalidOperationException("VisualRoot is missing; cannot identify the body/graft/pipe_skin atlases."); } Renderer[] componentsInChildren = ((Component)obj).GetComponentsInChildren<Renderer>(true); if (componentsInChildren.Length == 0) { throw new InvalidOperationException("VisualRoot has no body/graft/pipe_skin renderers."); } Shader val = Shader.Find("HDRP/Lit"); if ((Object)(object)val == (Object)null || !val.isSupported) { throw new InvalidOperationException("No supported game HDRP/Lit shader is available."); } string[] array = new string[3] { "body", "graft", "pipe_skin" }; Texture2D[,] array2 = new Texture2D[array.Length, 3]; string[] array3 = new string[3] { "basecolor", "normal", "mask" }; for (int i = 0; i < array.Length; i++) { for (int j = 0; j < 3; j++) { string text = "assets/crookedchoir/textures/" + array[i] + "_" + array3[j] + ".png"; array2[i, j] = bundle.LoadAsset<Texture2D>(text); if ((Object)(object)array2[i, j] == (Object)null) { throw new InvalidOperationException("Required atlas texture '" + text + "' is missing."); } } } Material[][] array4 = new Material[componentsInChildren.Length][]; bool[] array5 = new bool[array.Length]; for (int k = 0; k < componentsInChildren.Length; k++) { array4[k] = componentsInChildren[k].sharedMaterials; if (array4[k].Length == 0) { throw new InvalidOperationException("Renderer '" + ((Object)componentsInChildren[k]).name + "' has no material slots."); } for (int l = 0; l < array4[k].Length; l++) { Material material = array4[k][l]; array5[AtlasFor(material, ((Object)componentsInChildren[k]).name, l)] = true; } } if (!array5[0] || !array5[1] || !array5[2]) { throw new InvalidOperationException("The prefab does not contain all authored ChoirBody, ChoirGraft and ChoirPipeSkin materials."); } Dictionary<Material, Material> dictionary = new Dictionary<Material, Material>(); HashSet<Material> hashSet = new HashSet<Material>(); int num = 0; for (int m = 0; m < componentsInChildren.Length; m++) { Renderer val2 = componentsInChildren[m]; Material[] array6 = array4[m]; bool flag = false; for (int n = 0; n < array6.Length; n++) { Material val3 = array6[n]; int atlas = AtlasFor(val3, ((Object)val2).name, n); if (ShouldRepairShader(val3.shader, val)) { if (!dictionary.TryGetValue(val3, out var value)) { value = new Material(val3) { shader = val, name = ((Object)val3).name }; Configure(value, array2, atlas); dictionary.Add(val3, value); } array6[n] = value; num++; flag = true; } else if (hashSet.Add(val3)) { Configure(val3, array2, atlas); } } if (flag) { val2.sharedMaterials = array6; } } Plugin.Log.LogInfo((object)$"[CrookedChoir] Visual repair (prefab): renderers={componentsInChildren.Length}, repaired={num}, shader={((Object)val).name}, textures=body_basecolor/body_normal/body_mask,graft_basecolor/graft_normal/graft_mask,pipe_skin_basecolor/pipe_skin_normal/pipe_skin_mask."); } private static int AtlasFor(Material material, string renderer, int slot) { if ((Object)(object)material == (Object)null) { throw new InvalidOperationException($"Renderer '{renderer}' slot {slot} has no material; its body/graft/pipe_skin atlas cannot be identified."); } if (string.Equals(((Object)material).name, "ChoirBody", StringComparison.Ordinal)) { return 0; } if (string.Equals(((Object)material).name, "ChoirGraft", StringComparison.Ordinal)) { return 1; } if (string.Equals(((Object)material).name, "ChoirPipeSkin", StringComparison.Ordinal)) { return 2; } throw new InvalidOperationException($"Renderer '{renderer}' slot {slot} has unknown material '{((Object)material).name}'; its atlas cannot be identified."); } private static bool ShouldRepairShader(Shader shader, Shader gameLit) { if (!((Object)(object)shader != (Object)(object)gameLit) && !((Object)(object)shader == (Object)null) && shader.isSupported) { return ((Object)shader).name.IndexOf("InternalError", StringComparison.OrdinalIgnoreCase) >= 0; } return true; } private static void Configure(Material material, Texture2D[,] maps, int atlas) { //IL_0081: Unknown result type (might be due to invalid IL or missing references) //IL_0091: Unknown result type (might be due to invalid IL or missing references) //IL_00a1: Unknown result type (might be due to invalid IL or missing references) //IL_00b1: Unknown result type (might be due to invalid IL or missing references) //IL_00c1: Unknown result type (might be due to invalid IL or missing references) //IL_00d1: Unknown result type (might be due to invalid IL or missing references) //IL_00e1: Unknown result type (might be due to invalid IL or missing references) if (!material.HasProperty("_BaseColorMap") || !material.HasProperty("_NormalMap") || !material.HasProperty("_MaskMap")) { throw new InvalidOperationException("HDRP/Lit material '" + ((Object)material).name + "' cannot sample the three atlas maps."); } material.SetTexture("_BaseColorMap", (Texture)(object)maps[atlas, 0]); material.SetTexture("_NormalMap", (Texture)(object)maps[atlas, 1]); material.SetTexture("_MaskMap", (Texture)(object)maps[atlas, 2]); material.SetTextureScale("_BaseColorMap", Vector2.one); material.SetTextureOffset("_BaseColorMap", Vector2.zero); material.SetTextureScale("_NormalMap", Vector2.one); material.SetTextureOffset("_NormalMap", Vector2.zero); material.SetTextureScale("_MaskMap", Vector2.one); material.SetTextureOffset("_MaskMap", Vector2.zero); material.SetColor("_BaseColor", Color.white); material.SetFloat("_NormalScale", 1f); material.SetFloat("_NormalMapSpace", 0f); material.SetFloat("_SurfaceType", 0f); material.SetFloat("_Metallic", 0f); material.SetFloat("_Smoothness", 1f); material.SetFloat("_SmoothnessRemapMin", 0f); material.SetFloat("_SmoothnessRemapMax", 1f); material.SetFloat("_MetallicRemapMin", 0f); material.SetFloat("_MetallicRemapMax", 1f); material.SetFloat("_AORemapMin", 0f); material.SetFloat("_AORemapMax", 1f); HDMaterial.ValidateMaterial(material); material.EnableKeyword("_NORMALMAP"); material.EnableKeyword("_NORMALMAP_TANGENT_SPACE"); material.EnableKeyword("_MASKMAP"); if ((Object)(object)material.GetTexture("_BaseColorMap") != (Object)(object)maps[atlas, 0] || (Object)(object)material.GetTexture("_NormalMap") != (Object)(object)maps[atlas, 1] || (Object)(object)material.GetTexture("_MaskMap") != (Object)(object)maps[atlas, 2] || !material.IsKeywordEnabled("_NORMALMAP") || !material.IsKeywordEnabled("_MASKMAP")) { throw new InvalidOperationException("Atlas bindings failed for '" + ((Object)material).name + "'."); } } } internal sealed class CrookedChoirConfig { private static readonly (string Section, string Key, float OldDefault)[] DroppedSettings = new(string, string, float)[21] { ("Combat", "ChargeRange", 8f), ("Combat", "ChargeMaxDuration", 5f), ("Combat", "StalkDuration", 1f), ("Combat", "CooloffDuration", 1f), ("Combat", "CaptureRange", 2.07f), ("Combat", "ChompWindup", 1.1f), ("Combat", "EngulfDuration", 1f), ("Combat", "SwallowDuration", 1.3333334f), ("Combat", "GapeRange", 5f), ("Combat", "LungeRange", 6f), ("Combat", "LungeDuration", 0.7f), ("Movement", "LungeTurnRate", 60f), ("Combat", "GrabRange", 1.2f), ("Combat", "GrabDuration", 23f / 30f), ("Combat", "CarryDuration", 1f), ("Combat", "SwallowInDuration", 1.5f), ("Combat", "MissDeceleration", 1f), ("Combat", "WallBounceDuration", 0.4f), ("Combat", "RecoverDuration", 2f), ("Effects", "BloodDelay", 0.5f), ("Effects", "BloodDuration", 0.5f) }; public ConfigEntry<bool> Enabled { get; } public ConfigEntry<float> SpawnWeightMultiplier { get; } public ConfigEntry<string> MoonWeightOverrides { get; } public ConfigEntry<int> MaxCount { get; } public ConfigEntry<float> PowerLevel { get; } public ConfigEntry<int> HitPoints { get; } public ConfigEntry<float> StunDuration { get; } public ConfigEntry<float> DetectionRange { get; } public ConfigEntry<bool> HuntBlacksiteSoldiers { get; } public ConfigEntry<float> WalkSpeed { get; } public ConfigEntry<float> StalkRunSpeed { get; } public ConfigEntry<float> StrikeRange { get; } public ConfigEntry<float> StrikeCooldown { get; } public ConfigEntry<bool> DebugLogs { get; } public ConfigEntry<bool> LogGait { get; } public ConfigEntry<float> MaskedSpawnChance { get; } public ConfigEntry<float> MaskedSpawnDelayMin { get; } public ConfigEntry<float> MaskedSpawnDelayMax { get; } public ConfigEntry<float> ChatterGapMin { get; } public ConfigEntry<float> ChatterGapMax { get; } public ConfigEntry<float> StalkBreathGapMin { get; } public ConfigEntry<float> StalkBreathGapMax { get; } public CrookedChoirConfig(ConfigFile config) { //IL_0128: Unknown result type (might be due to invalid IL or missing references) //IL_0132: Expected O, but got Unknown //IL_0175: Unknown result type (might be due to invalid IL or missing references) //IL_017f: Expected O, but got Unknown //IL_01ae: Unknown result type (might be due to invalid IL or missing references) //IL_01b8: Expected O, but got Unknown //IL_01dc: Unknown result type (might be due to invalid IL or missing references) //IL_01e6: Expected O, but got Unknown //IL_0215: Unknown result type (might be due to invalid IL or missing references) //IL_021f: Expected O, but got Unknown //IL_024e: Unknown result type (might be due to invalid IL or missing references) //IL_0258: Expected O, but got Unknown //IL_02a3: Unknown result type (might be due to invalid IL or missing references) //IL_02ad: Expected O, but got Unknown using (ConfigPersistence.BeginBinding(config, Plugin.Log, "Crooked Choir")) { (string, string, float)[] droppedSettings = DroppedSettings; for (int i = 0; i < droppedSettings.Length; i++) { (string, string, float) tuple = droppedSettings[i]; Retire(config, tuple.Item1, tuple.Item2, tuple.Item3, null); } float? num = Retire(config, "Movement", "RunSpeed", 3f, "StalkRunSpeed"); float? num2 = Retire(config, "Movement", "LungeSpeed", 9f, "StalkRunSpeed"); float? legacy = Retire(config, "Combat", "LungeCooldown", 2f, "StrikeCooldown"); float? legacy2 = num2 ?? ((num.HasValue && !Same(num.Value, 3f)) ? num : ((float?)null)); Enabled = config.Bind<bool>("General", "Enabled", true, "Enable natural Crooked Choir spawns. Host-only: every install still registers the network prefab and bestiary."); SpawnWeightMultiplier = config.Bind<float>("Spawning", "SpawnWeightMultiplier", 1f, new ConfigDescription("Host-only multiplier for indoor weights: facility 15, manor 20, mineshaft 10; unknown interiors 10. 0 disables natural spawns.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 5f), Array.Empty<object>())); MoonWeightOverrides = config.Bind<string>("Spawning", "MoonWeightOverrides", string.Empty, "Optional host-only comma-separated base moon weights, e.g. Experimentation:8,Offense:15 or namespace:moon=12. These replace the base 15 before interior multipliers; 0 disables that moon."); MaxCount = config.Bind<int>("Spawning", "MaxCount", 1, new ConfigDescription("Maximum living Crooked Choirs. Host-only; requires a restart.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 4), Array.Empty<object>())); PowerLevel = config.Bind<float>("Spawning", "PowerLevel", 2f, new ConfigDescription("Indoor enemy power cost. Host-only; requires a restart.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.1f, 20f), Array.Empty<object>())); HitPoints = config.Bind<int>("Core Stats", "HitPoints", 8, new ConfigDescription("Host-authoritative health of each newly spawned Crooked Choir.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 100), Array.Empty<object>())); StunDuration = config.Bind<float>("Core Stats", "StunDuration", 3f, new ConfigDescription("Host-authoritative stun seconds. A stun during Stalk ends the chase and a stun during Strike makes it miss; Devour, Recover, Stumble, SneezeWait and Sneeze ignore stuns.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.1f, 15f), Array.Empty<object>())); DetectionRange = config.Bind<float>("Detection", "DetectionRange", 20f, new ConfigDescription("Host-only maximum sight range in meters for finding an indoor player.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(2f, 80f), Array.Empty<object>())); HuntBlacksiteSoldiers = config.Bind<bool>("Prey", "HuntBlacksiteSoldiers", true, "Host-only: hunt Blacksite soldiers when Contracted is installed."); WalkSpeed = config.Bind<float>("Movement", "WalkSpeed", 2f, new ConfigDescription("Host-only walking speed in meters per second, bounded by the authored Walk motion envelope.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.1f, 2f), Array.Empty<object>())); StalkRunSpeed = BindReplacement(config, "Movement", "StalkRunSpeed", 9f, 0.1f, 9f, "Host-only Stalk run speed in meters per second within twice StrikeRange of the target, capped by the authored Run envelope.", legacy2, 9f); StrikeRange = BindReplacement(config, "Combat", "StrikeRange", 3f, 1f, 3f, "Host-only nominal strike distance in meters; a Strike begins when the target is within StrikeRange + 0.7 meters or closer, where the lips land at the slam.", null, 0f); StrikeCooldown = BindReplacement(config, "Combat", "StrikeCooldown", 2f, 0f, 10f, "Host-only seconds after Recover, Stumble or Sneeze before another Strike may begin.", legacy, 2f); MaskedSpawnChance = BindReplacement(config, "Eat", "MaskedSpawnChance", 0.25f, 0f, 1f, "Host-only chance after successful consumption to sneeze out the eaten player's Masked. No spawn after all players die.", null, 0f); MaskedSpawnDelayMin = BindReplacement(config, "Eat", "MaskedSpawnDelayMin", 1f, 0f, 10f, "Host-only minimum delay before the three-second sneeze.", null, 0f); MaskedSpawnDelayMax = BindReplacement(config, "Eat", "MaskedSpawnDelayMax", 2f, 0f, 10f, "Host-only maximum sneeze delay; raised to the minimum if reversed.", null, 0f); ChatterGapMin = BindReplacement(config, "Audio", "ChatterGapMin", 2f, 0f, 60f, "Local minimum silence between chatter clips; chatter only in Roam/Stalk.", null, 0f); ChatterGapMax = BindReplacement(config, "Audio", "ChatterGapMax", 7f, 0f, 60f, "Local maximum chatter silence; raised to the minimum if reversed.", null, 0f); StalkBreathGapMin = BindReplacement(config, "Audio", "StalkBreathGapMin", 1.5f, 0f, 60f, "Local minimum silence between StalkRun breath clips; breath only while running in Stalk.", null, 0f); StalkBreathGapMax = BindReplacement(config, "Audio", "StalkBreathGapMax", 3f, 0f, 60f, "Local maximum StalkRun breath silence; raised to the minimum if reversed.", null, 0f); Order(MaskedSpawnDelayMin, MaskedSpawnDelayMax); Order(ChatterGapMin, ChatterGapMax); Order(StalkBreathGapMin, StalkBreathGapMax); MaskedSpawnDelayMin.SettingChanged += delegate { Order(MaskedSpawnDelayMin, MaskedSpawnDelayMax); }; MaskedSpawnDelayMax.SettingChanged += delegate { Order(MaskedSpawnDelayMin, MaskedSpawnDelayMax); }; ChatterGapMin.SettingChanged += delegate { Order(ChatterGapMin, ChatterGapMax); }; ChatterGapMax.SettingChanged += delegate { Order(ChatterGapMin, ChatterGapMax); }; StalkBreathGapMin.SettingChanged += delegate { Order(StalkBreathGapMin, StalkBreathGapMax); }; StalkBreathGapMax.SettingChanged += delegate { Order(StalkBreathGapMin, StalkBreathGapMax); }; DebugLogs = config.Bind<bool>("Debug", "DebugLogs", false, "Log host/client transitions, game time, target distances and capture token events."); LogGait = config.Bind<bool>("Debug", "LogGait", false, "Diagnostic only: log the Choir's gait every 0.5 s while it moves and one line per discontinuity (clip change, motion reseed, planner reset, support fallback, root shift or warp, state revision, long frame)."); } } private static void Order(ConfigEntry<float> minimum, ConfigEntry<float> maximum) { if (maximum.Value < minimum.Value) { maximum.Value = minimum.Value; } } private static float? Retire(ConfigFile config, string section, string key, float oldDefault, string replacement) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Expected O, but got Unknown ConfigDefinition val = new ConfigDefinition(section, key); string value = config.Bind<string>(val, string.Empty, (ConfigDescription)null).Value; config.Remove(val); if (string.IsNullOrEmpty(value)) { return null; } if (!TryFloat(value, out var result)) { ManualLogSource log = Plugin.Log; if (log != null) { log.LogWarning((object)("Crooked Choir: removed invalid retired setting [" + section + "] " + key + ".")); } return null; } if (!Same(result, oldDefault)) { ManualLogSource log2 = Plugin.Log; if (log2 != null) { log2.LogInfo((object)((replacement == null) ? ("Crooked Choir: dropped customized retired [" + section + "] " + key + "=" + value + "; it has no replacement.") : ("Crooked Choir: retired customized [" + section + "] " + key + "=" + value + "; " + replacement + " inherits it unless explicitly configured."))); } } return result; } private static ConfigEntry<float> BindReplacement(ConfigFile config, string section, string key, float authoredDefault, float minimum, float maximum, string description, float? legacy, float legacyDefault) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Expected O, but got Unknown //IL_0040: Unknown result type (might be due to invalid IL or missing references) //IL_004a: Expected O, but got Unknown ConfigDefinition val = new ConfigDefinition(section, key); string value = config.Bind<string>(val, string.Empty, (ConfigDescription)null).Value; config.Remove(val); bool num = !string.IsNullOrEmpty(value); ConfigEntry<float> val2 = config.Bind<float>(section, key, authoredDefault, new ConfigDescription(description, (AcceptableValueBase)(object)new AcceptableValueRange<float>(minimum, maximum), Array.Empty<object>())); float num2 = authoredDefault; if (num) { if (TryFloat(value, out var result)) { num2 = result; } else { ManualLogSource log = Plugin.Log; if (log != null) { log.LogWarning((object)("Crooked Choir: invalid [" + section + "] " + key + "; using authored default.")); } } } else if (legacy.HasValue && !Same(legacy.Value, legacyDefault)) { num2 = legacy.Value; } val2.Value = Math.Max(minimum, Math.Min(maximum, num2)); if (!Same(val2.Value, num2)) { ManualLogSource log2 = Plugin.Log; if (log2 != null) { log2.LogWarning((object)$"Crooked Choir: [{section}] {key}={num2} bounded to {val2.Value} by its supported envelope."); } } return val2; } private static bool Same(float a, float b) { return Math.Abs(a - b) <= 0.0001f; } private static bool TryFloat(string value, out float result) { if (float.TryParse(value, NumberStyles.Float, CultureInfo.InvariantCulture, out result) && !float.IsNaN(result)) { return !float.IsInfinity(result); } return false; } } [BepInPlugin("y4ngz.lethalcompany.crookedchoir", "Y4NGZ Crooked Choir", "2.0.0")] [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInDependency(/*Could not decode attribute arguments.*/)] public sealed class Plugin : BaseUnityPlugin { internal const string BundleFilename = "y4ngzcrookedchoir.bundle"; internal const string PrefabAssetPath = "assets/crookedchoir/y4ngzcrookedchoir.prefab"; internal const string DawnNamespace = "y4ngz_monsters"; internal const string DawnEnemyKey = "crooked_choir"; internal const string BestiaryText = "Crooked Choir\n\nDanger level: high\n\nA many-legged organism found inside abandoned facilities. It stalks workers at a walk, breaks into a run once it is close, then throws its whole body forward and slams its mouth shut. A worker caught between it and the closing lips is devoured.\n\nStep sideways out of its line before the jaws close. A missed strike leaves it stumbling for a moment. A stun spoils a strike in progress, but nothing frees a worker once the mouth has closed.\n\n"; internal static ManualLogSource Log; internal static CrookedChoirConfig ModConfig; internal static AssetBundle ModAssets; internal static EnemyType EnemyType; private static bool _netcodeInitialized; private static bool _loggedScanNodeLayer; private void Awake() { //IL_002f: Unknown result type (might be due to invalid IL or missing references) Log = ((BaseUnityPlugin)this).Logger; try { InitializeNetcodeRPCs(); ModConfig = new CrookedChoirConfig(((BaseUnityPlugin)this).Config); ChoirBloodFxBridge.Initialize(); ChoirPreyBridge.Initialize(); try { new Harmony("y4ngz.lethalcompany.crookedchoir").PatchAll(typeof(Plugin).Assembly); } catch (Exception arg) { Log.LogError((object)$"[CrookedChoir] Harmony patching failed: {arg}"); } if (LoadBundle()) { GameObject prefab = LoadVisualPrefab(); CrookedChoirAI crookedChoirAI = PreparePrefab(prefab); EnemyType = CreateEnemyType(prefab, crookedChoirAI); ((EnemyAI)crookedChoirAI).enemyType = EnemyType; RegisterWithDawn(prefab); if (!ModConfig.Enabled.Value) { Log.LogInfo((object)"Y4NGZ Crooked Choir: registered network prefab; natural spawning disabled by config."); } Log.LogInfo((object)"Y4NGZ Crooked Choir v2.0.0 loaded. Registered as 'Crooked Choir'."); } } catch (Exception arg2) { Log.LogError((object)$"[CrookedChoir] Initialization failed: {arg2}"); } } private void Update() { ChoirMaskedIdentity.Update(); } private static void RegisterWithDawn(GameObject prefab) { CrookedChoirSpawnWeights spawnWeights = new CrookedChoirSpawnWeights(() => (!ModConfig.Enabled.Value) ? 0f : ModConfig.SpawnWeightMultiplier.Value, () => ModConfig.MoonWeightOverrides.Value, delegate(string message) { Log.LogWarning((object)message); }); DawnLib.RegisterNetworkPrefab(prefab); DawnLib.DefineEnemy(NamespacedKey<DawnEnemyInfo>.From("y4ngz_monsters", "crooked_choir"), EnemyType, (Action<EnemyInfoBuilder>)delegate(EnemyInfoBuilder builder) { ((BaseInfoBuilder<DawnEnemyInfo, EnemyType, EnemyInfoBuilder>)(object)builder.DefineInside((Action<EnemyLocationBuilder>)delegate(EnemyLocationBuilder location) { location.SetWeights((Action<WeightTableBuilder<DawnMoonInfo, SpawnWeightContext>>)delegate(WeightTableBuilder<DawnMoonInfo, SpawnWeightContext> table) { table.SetGlobalWeight((IWeighted)(object)spawnWeights); }); }).CreateBestiaryNode("Crooked Choir\n\nDanger level: high\n\nA many-legged organism found inside abandoned facilities. It stalks workers at a walk, breaks into a run once it is close, then throws its whole body forward and slams its mouth shut. A worker caught between it and the closing lips is devoured.\n\nStep sideways out of its line before the jaws close. A missed strike leaves it stumbling for a moment. A stun spoils a strike in progress, but nothing frees a worker once the mouth has closed.\n\n").CreateNameKeyword("crooked_choir")).AddTags((IEnumerable<NamespacedKey>)(object)new NamespacedKey[3] { Tags.Hostile, Tags.Organic, Tags.Medium }); }); } private static void InitializeNetcodeRPCs() { if (_netcodeInitialized) { return; } Type[] types = typeof(Plugin).Assembly.GetTypes(); for (int i = 0; i < types.Length; i++) { MethodInfo[] methods = types[i].GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); foreach (MethodInfo methodInfo in methods) { if (methodInfo.GetCustomAttributes(typeof(RuntimeInitializeOnLoadMethodAttribute), inherit: false).Length != 0) { methodInfo.Invoke(null, null); } } } _netcodeInitialized = true; } private static bool LoadBundle() { string? directoryName = Path.GetDirectoryName(typeof(Plugin).Assembly.Location); if (string.IsNullOrEmpty(directoryName)) { throw new InvalidOperationException("Could not resolve the plugin assembly directory."); } string text = Path.Combine(directoryName, "y4ngzcrookedchoir.bundle"); if (!File.Exists(text)) { Log.LogError((object)("[CrookedChoir] Missing asset bundle: " + text)); return false; } ModAssets = AssetBundle.LoadFromFile(text); if ((Object)(object)ModAssets == (Object)null) { throw new InvalidOperationException("AssetBundle.LoadFromFile returned null for '" + text + "'."); } return true; } internal static GameObject LoadVisualPrefab() { GameObject val = ModAssets.LoadAsset<GameObject>("assets/crookedchoir/y4ngzcrookedchoir.prefab"); if ((Object)(object)val == (Object)null) { throw new InvalidOperationException("Required prefab 'assets/crookedchoir/y4ngzcrookedchoir.prefab' is missing from y4ngzcrookedchoir.bundle."); } try { CrookedChoirVisualMaterials.Repair(val, ModAssets); } catch (Exception ex) { Log.LogError((object)("[CrookedChoir] Visual repair failed: " + ex.GetType().Name + ": " + ex.Message + "; registering the prefab with its current materials.")); } return val; } internal static GameObject LoadPipeBloodPrefab() { try { GameObject val = ModAssets.LoadAsset<GameObject>("assets/crookedchoir/effects/choir_pipe_blood.prefab"); if ((Object)(object)val == (Object)null) { Log.LogWarning((object)"[CrookedChoir] Optional effect 'assets/crookedchoir/effects/choir_pipe_blood.prefab' is missing."); return null; } return CrookedChoirEffectMaterials.Repair(val, Log); } catch (Exception ex) { Log.LogWarning((object)("[CrookedChoir] Optional pipe blood disabled: " + ex.GetType().Name + ": " + ex.Message)); return null; } } private static CrookedChoirAI PreparePrefab(GameObject prefab) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_01e0: Unknown result type (might be due to invalid IL or missing references) //IL_01ea: Unknown result type (might be due to invalid IL or missing references) if (prefab.transform.localScale != Vector3.one) { throw new InvalidOperationException("Crooked Choir requires an unscaled navigation root; scale the authored visual hierarchy instead."); } Transform val = prefab.transform.Find("VisualRoot"); ChoirMotion componentInChildren = prefab.GetComponentInChildren<ChoirMotion>(true); Animator val2 = (((Object)(object)val != (Object)null) ? ((Component)val).GetComponentInChildren<Animator>(true) : null); if ((Object)(object)val == (Object)null || (Object)(object)componentInChildren == (Object)null || (Object)(object)val2 == (Object)null || (Object)(object)val2.runtimeAnimatorController == (Object)null) { throw new InvalidOperationException("Crooked Choir requires a VisualRoot child, serialized ChoirMotion bindings, and an authored Animator controller beneath VisualRoot."); } SetEnemyObject(prefab); Renderer[] componentsInChildren = ((Component)val).GetComponentsInChildren<Renderer>(true); for (int i = 0; i < componentsInChildren.Length; i++) { ((Component)componentsInChildren[i]).gameObject.layer = prefab.layer; } AssignUniqueNetworkHash(prefab); NavMeshAgent val3 = prefab.GetComponent<NavMeshAgent>(); if ((Object)(object)val3 == (Object)null) { val3 = prefab.AddComponent<NavMeshAgent>(); } val3.speed = Mathf.Min(ModConfig.WalkSpeed.Value, componentInChildren.Settings.WalkEnvelope.ForwardSpeed); val3.acceleration = 8f; val3.angularSpeed = 90f; val3.radius = 0.575f; val3.height = 2.3f; val3.baseOffset = 0f; val3.stoppingDistance = 0.23f; val3.autoBraking = true; val3.autoRepath = true; val3.obstacleAvoidanceType = (ObstacleAvoidanceType)4; val3.avoidancePriority = 50; CrookedChoirAI crookedChoirAI = prefab.GetComponent<CrookedChoirAI>(); if ((Object)(object)crookedChoirAI == (Object)null) { crookedChoirAI = prefab.AddComponent<CrookedChoirAI>(); } ((EnemyAI)crookedChoirAI).agent = val3; ((EnemyAI)crookedChoirAI).enemyHP = ModConfig.HitPoints.Value; crookedChoirAI.VisualRoot = val; crookedChoirAI.Motion = componentInChildren; crookedChoirAI.VisualAnimator = val2; ((EnemyAI)crookedChoirAI).creatureAnimator = val2; ((EnemyAI)crookedChoirAI).eye = GetOrCreateChild(prefab.transform, "Eye", new Vector3(0f, 1.75f, 0.35f) * 1.15f); ((EnemyAI)crookedChoirAI).updatePositionThreshold = 0.1f; val2.applyRootMotion = false; val2.cullingMode = (AnimatorCullingMode)0; ((EnemyAI)crookedChoirAI).creatureSFX = GetOrCreateAudioSource(prefab.transform, "CreatureSFX", 1.5f, 15f); ((EnemyAI)crookedChoirAI).creatureVoice = GetOrCreateAudioSource(prefab.transform, "CreatureVoice", 1f, 15f); crookedChoirAI.FootstepSource = GetOrCreateAudioSource(prefab.transform, "CreatureFootsteps", 3f, 42f); ChoirMouthEmitter choirMouthEmitter = prefab.GetComponent<ChoirMouthEmitter>(); if ((Object)(object)choirMouthEmitter == (Object)null) { choirMouthEmitter = prefab.AddComponent<ChoirMouthEmitter>(); } choirMouthEmitter.Configure(val, ((Component)((EnemyAI)crookedChoirAI).creatureVoice).transform, ((Component)((EnemyAI)crookedChoirAI).creatureSFX).transform); ChoirAudioClips choirAudioClips = ChoirAudioClips.Load((string name) => ModAssets.LoadAsset<AudioClip>("assets/crookedchoir/audio/" + name), delegate(string message) { Log.LogWarning((object)message); }); crookedChoirAI.CueClips = choirAudioClips.Cues; crookedChoirAI.ChatterClips = choirAudioClips.Chatter; crookedChoirAI.StalkBreathClips = choirAudioClips.StalkBreath; crookedChoirAI.FootstepClips = choirAudioClips.Footsteps; crookedChoirAI.BundleFootstepsAuthored = choirAudioClips.FootstepsAuthored; crookedChoirAI.PipeBloodPrefab = LoadPipeBloodPrefab(); EnsureCollision(prefab, crookedChoirAI); EnsureScanNode(prefab); return crookedChoirAI; } private static EnemyType CreateEnemyType(GameObject prefab, CrookedChoirAI ai) { //IL_0109: Unknown result type (might be due to invalid IL or missing references) EnemyType val = ScriptableObject.CreateInstance<EnemyType>(); ((Object)val).name = "CrookedChoirEnemy"; val.enemyName = "Crooked Choir"; val.enemyPrefab = prefab; val.PowerLevel = ModConfig.PowerLevel.Value; val.DiversityPowerLevel = 1; val.MaxCount = ModConfig.MaxCount.Value; val.canDie = true; val.canBeStunned = true; val.canBeDestroyed = true; val.destroyOnDeath = false; val.stunTimeMultiplier = 1f; val.stunGameDifficultyMultiplier = 1f; val.doorSpeedMultiplier = 1f; val.isOutsideEnemy = false; val.isDaytimeEnemy = false; val.pushPlayerDistance = 0f; val.pushPlayerForce = 0f; val.normalizedTimeInDayToLeave = 1f; val.probabilityCurve = AnimationCurve.Constant(0f, 1f, 1f); val.numberSpawnedFalloff = AnimationCurve.Linear(0f, 1f, 1f, 0f); val.useNumberSpawnedFalloff = true; val.disableAnimatorWhenFar = false; val.SizeLimit = (NavSizeLimit)1; val.stunSFX = ai.CueClips[14]; val.hitBodySFX = ai.CueClips[13]; val.hitEnemyVoiceSFX = val.hitBodySFX; val.deathSFX = ai.CueClips[15]; ((EnemyAI)ai).dieSFX = val.deathSFX; return val; } private static AudioSource GetOrCreateAudioSource(Transform root, string name, float minDistance, float spread) { //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Unknown result type (might be due to invalid IL or missing references) Transform orCreateChild = GetOrCreateChild(root, name, new Vector3(0f, 1.25f, 0f) * 1.15f); AudioSource val = ((Component)orCreateChild).GetComponent<AudioSource>(); if ((Object)(object)val == (Object)null) { val = ((Component)orCreateChild).gameObject.AddComponent<AudioSource>(); } val.playOnAwake = false; val.loop = false; val.spatialBlend = 1f; val.dopplerLevel = 0f; val.rolloffMode = (AudioRolloffMode)1; val.minDistance = minDistance; val.maxDistance = 15f; val.spread = spread; return val; } private static void EnsureCollision(GameObject prefab, CrookedChoirAI ai) { //IL_0034: Unknown result type (might be due to invalid IL or missing references) CapsuleCollider val = prefab.GetComponent<CapsuleCollider>(); if ((Object)(object)val == (Object)null) { val = prefab.AddComponent<CapsuleCollider>(); } ConfigureCapsule(val, 0.55f, trigger: false); EnsureKinematicBody(prefab); Transform orCreateChild = GetOrCreateChild(prefab.transform, "CollisionDetect", Vector3.zero); SetEnemyObject(((Component)orCreateChild).gameObject); CapsuleCollider val2 = ((Component)orCreateChild).GetComponent<CapsuleCollider>(); if ((Object)(object)val2 == (Object)null) { val2 = ((Component)orCreateChild).gameObject.AddComponent<CapsuleCollider>(); } ConfigureCapsule(val2, 0.65f, trigger: true); EnsureKinematicBody(((Component)orCreateChild).gameObject); EnemyAICollisionDetect val3 = ((Component)orCreateChild).GetComponent<EnemyAICollisionDetect>(); if ((Object)(object)val3 == (Object)null) { val3 = ((Component)orCreateChild).gameObject.AddComponent<EnemyAICollisionDetect>(); } val3.mainScript = (EnemyAI)(object)ai; val3.alwaysAllowHitting = true; val3.canCollideWithEnemies = true; val3.onlyCollideWhenGrounded = false; } private static void ConfigureCapsule(CapsuleCollider collider, float radius, bool trigger) { //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Unknown result type (might be due to invalid IL or missing references) ((Collider)collider).enabled = true; ((Collider)collider).isTrigger = trigger; collider.direction = 1; collider.center = new Vector3(0f, 1.25f, 0f) * 1.15f; collider.height = 2.875f; collider.radius = radius * 1.15f; } internal static void EnsureScanNode(GameObject prefab) { //IL_00f1: Unknown result type (might be due to invalid IL or missing references) //IL_00fb: Unknown result type (might be due to invalid IL or missing references) //IL_01ef: Unknown result type (might be due to invalid IL or missing references) //IL_01f9: Unknown result type (might be due to invalid IL or missing references) //IL_0204: Unknown result type (might be due to invalid IL or missing references) //IL_020f: Unknown result type (might be due to invalid IL or missing references) //IL_02a5: Unknown result type (might be due to invalid IL or missing references) //IL_02c0: Unknown result type (might be due to invalid IL or missing references) //IL_02ca: Unknown result type (might be due to invalid IL or missing references) ScanNodeProperties val = null; ScanNodeProperties[] componentsInChildren = prefab.GetComponentsInChildren<ScanNodeProperties>(true); int num = -1; foreach (ScanNodeProperties val2 in componentsInChildren) { if (val2.creatureScanID >= 0 && num < 0) { num = val2.creatureScanID; } if (!((Object)(object)((Component)val2).gameObject == (Object)(object)prefab)) { bool flag = val2.creatureScanID >= 0; bool flag2 = (Object)(object)val != (Object)null && val.creatureScanID >= 0; bool flag3 = string.Equals(((Object)val2).name, "ScanNode", StringComparison.Ordinal); bool flag4 = (Object)(object)val != (Object)null && string.Equals(((Object)val).name, "ScanNode", StringComparison.Ordinal); if ((Object)(object)val == (Object)null || (flag && !flag2) || (flag == flag2 && flag3 && !flag4)) { val = val2; } } } Transform val3 = (((Object)(object)val != (Object)null) ? ((Component)val).transform : GetOrCreateChild(prefab.transform, "ScanNode", new Vector3(0f, 1.4f, 0f) * 1.15f)); if ((Object)(object)val == (Object)null) { val = ((Component)val3).gameObject.AddComponent<ScanNodeProperties>(); val.creatureScanID = num; } if (componentsInChildren.Length > 1 || (componentsInChildren.Length == 1 && (Object)(object)componentsInChildren[0] != (Object)(object)val)) { Log.LogWarning((object)"[CrookedChoir] Retiring duplicate or root-attached scan nodes."); } foreach (ScanNodeProperties val4 in componentsInChildren) { if (!((Object)(object)val4 == (Object)(object)val)) { if ((Object)(object)((Component)val4).gameObject != (Object)(object)prefab && (Object)(object)((Component)val4).gameObject != (Object)(object)((Component)val3).gameObject && ((Component)val4).transform.childCount == 0) { ((Component)val4).gameObject.SetActive(false); RemoveObject((Object)(object)((Component)val4).gameObject, prefab); } else { RemoveObject((Object)(object)val4, prefab); } } } ((Object)val3).name = "ScanNode"; val3.SetParent(prefab.transform, false); val3.localPosition = new Vector3(0f, 1.4f, 0f) * 1.15f; val3.localRotation = Quaternion.identity; val3.localScale = Vector3.one; ((Component)val3).gameObject.tag = "DoNotSet"; ((Component)val3).gameObject.layer = ResolveLayer("ScanNode", 22); Transform val5 = val3; while ((Object)(object)val5 != (Object)null && (Object)(object)val5 != (Object)(object)prefab.transform) { ((Component)val5).gameObject.SetActive(true); val5 = val5.parent; } BoxCollider val6 = ((Component)val3).GetComponent<BoxCollider>(); if ((Object)(object)val6 == (Object)null) { val6 = ((Component)val3).gameObject.AddComponent<BoxCollider>(); } ((Collider)val6).enabled = true; ((Collider)val6).isTrigger = true; val6.center = Vector3.zero; val6.size = new Vector3(0.75f, 1.35f, 0.75f) * 1.15f; EnsureKinematicBody(((Component)val3).gameObject); val.headerText = "Crooked Choir"; val.subText = string.Empty; val.maxRange = 13; val.minRange = 1; val.requiresLineOfSight = true; val.nodeType = 1; if (!_loggedScanNodeLayer) { _loggedScanNodeLayer = true; Log.LogInfo((object)string.Format("[CrookedChoir] Scan node layer resolved to {0} (NameToLayer={1}, fallback 22).", ((Component)val3).gameObject.layer, LayerMask.NameToLayer("ScanNode"))); } } private static void RemoveObject(Object target, GameObject root) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) Scene scene = root.scene; if (((Scene)(ref scene)).IsValid()) { Object.Destroy(target); } else { Object.DestroyImmediate(target, true); } } private static void EnsureKinematicBody(GameObject target) { Rigidbody val = target.GetComponent<Rigidbody>(); if ((Object)(object)val == (Object)null) { val = target.AddComponent<Rigidbody>(); } val.isKinematic = true; val.useGravity = false; val.detectCollisions = true; } private static Transform GetOrCreateChild(Transform parent, string name, Vector3 localPosition) { //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_0028: Unknown result type (might be due to invalid IL or missing references) Transform val = parent.Find(name); if ((Object)(object)val != (Object)null) { return val; } val = new GameObject(name).transform; val.SetParent(parent, false); val.localPosition = localPosition; return val; } private static void SetEnemyObject(GameObject target) { target.tag = "Enemy"; target.layer = ResolveLayer("Enemies", 19); } private static int ResolveLayer(string name, int vanillaFallback) { int num = LayerMask.NameToLayer(name); if (num < 0) { return vanillaFallback; } return num; } private static void AssignUniqueNetworkHash(GameObject prefab) { NetworkObject val = prefab.GetComponent<NetworkObject>(); if ((Object)(object)val == (Object)null) { val = prefab.AddComponent<NetworkObject>(); } uint num; using (MD5 mD = MD5.Create()) { num = BitConverter.ToUInt32(mD.ComputeHash(Encoding.UTF8.GetBytes("y4ngz.lethalcompany.crookedchoir.Y4NGZCrookedChoir")), 0); } PropertyInfo property = typeof(NetworkObject).GetProperty("GlobalObjectIdHash", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); if (property != null && property.CanWrite) { property.SetValue(val, num); return; } FieldInfo? obj = typeof(NetworkObject).GetField("GlobalObjectIdHash", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic) ?? typeof(NetworkObject).GetField("<GlobalObjectIdHash>k__BackingField", BindingFlags.Instance | BindingFlags.NonPublic); if (obj == null) { throw new MissingMemberException(typeof(NetworkObject).FullName, "GlobalObjectIdHash"); } obj.SetValue(val, num); } } internal static class PluginInfo { public const string PLUGIN_GUID = "y4ngz.lethalcompany.crookedchoir"; public const string PLUGIN_NAME = "Y4NGZ Crooked Choir"; public const string PLUGIN_VERSION = "2.0.0"; } } namespace Y4NGZCrookedChoir.Motion { internal static class ChoirCaptureVolume { internal static bool Contains(Vec3 rootLocal, Vec3 center, Vec3 halfExtents) { if (!(halfExtents.X > 0f) || !(halfExtents.Y > 0f) || !(halfExtents.Z > 0f)) { return false; } float z = halfExtents.Z; if (Math.Abs(rootLocal.X - center.X) <= halfExtents.X && rootLocal.Y >= center.Y - halfExtents.Y - z && rootLocal.Y <= center.Y + halfExtents.Y && rootLocal.Z >= 0f - z) { return rootLocal.Z <= center.Z + halfExtents.Z; } return false; } } [Serializable] public struct ChoirLegBinding { public Transform Hip; public Transform Knee; public Transform Tip; } public struct ChoirFootState { public bool IsStance { get; internal set; } public bool HasContact { get; internal set; } public bool NeedsReplant { get; internal set; } public Vector3 ContactPosition { get; internal set; } public Vector3 TargetPosition { get; internal set; } public uint ContactRevision { get; internal set; } public uint ResetGeneration { get; internal set; } public float MaxReach { get; internal set; } public float ProceduralWeight { get; internal set; } public FootPhase Phase { get; internal set; } public FootRecovery Recovery { get; internal set; } } public enum ChoirMotionResetReason : byte { None, First, Gap, Teleport, Visibility, Handback, Suspension, InvalidPose } public struct ChoirMotionMetrics { public uint ResetGeneration { get; internal set; } public uint TotalReplants { get; internal set; } public uint EnvelopeExceededTicks { get; internal set; } public ChoirMotionResetReason LastResetReason { get; internal set; } public int SupportFallbackCount { get; internal set; } public int RaycastsThisTick { get; internal set; } public int DeferredQueriesThisTick { get; internal set; } public int MissesThisTick { get; internal set; } public int SaturatedQueriesThisTick { get; internal set; } public int SupportCount { get; internal set; } public int SupportPoseCandidates { get; internal set; } public bool SupportUsesPhysicalFallback { get; internal set; } public int AirborneCount { get; internal set; } public int RecoveryCount { get; internal set; } public int ReplantCount { get; internal set; } public int PlannerGlobalResetCount { get; internal set; } public float CurrentCadenceCyclesPerSecond { get; internal set; } public int UrgentLiftCount { get; internal set; } public int ExplicitStanceBreakCount { get; internal set; } public float HitchAnchorDisplacementLimit { get; internal set; } public bool EnvelopeExceeded { get; internal set; } public float MaxProceduralPositionOffset { get; internal set; } public float MaxProceduralRotationDegrees { get; internal set; } public float MaxBodyPositionOffset { get; internal set; } public float MaxBodyRotationDegrees { get; internal set; } public float ProceduralWeight { get; internal set; } } [DefaultExecutionOrder(-10000)] [DisallowMultipleComponent] public sealed class ChoirMotion : MonoBehaviour, IContactQuery { [SerializeField] private Transform _root; [SerializeField] private Transform _visualRoot; [SerializeField] private Transform[] _spine = Array.Empty<Transform>(); [SerializeField] private Transform[] _lobes = Array.Empty<Transform>(); [SerializeField] private Transform[] _mouthBones = Array.Empty<Transform>(); [SerializeField] private ChoirLegBinding[] _legs = Array.Empty<ChoirLegBinding>(); [SerializeField] private Transform[] _twigs = Array.Empty<Transform>(); [SerializeField] private Vector3 _captureCenter; [SerializeField] private Vector3 _captureHalfExtents; [SerializeField] private Renderer[] _visibilityRenderers = Array.Empty<Renderer>(); [SerializeField] private ChoirMotionSettings _settings = ChoirMotionSettings.Default; [SerializeField] [Range(0f, 1f)] private float _captureBlend; private Transform[] _bones; private Vector3[] _authoredPositions; private Quaternion[] _authoredRotations; private Vector3[] _authoredScales; private DampedSpring[] _spineSprings; private DampedSpring[] _lobeSprings; private DampedSpring[] _twigSprings; private Vec3[] _hips; private Vec3[] _supportHips; private Vec3[] _feet; private float[] _maxReach; private float[] _upperLengths; private float[] _lowerLengths; private Transform[] _hipParents; private Transform[] _kneeParents; private Transform _visualRootParent; private Collider[] _ownColliders; private RaycastHit[] _rayHits; private bool[] _rendererEnabled; private bool[] _rendererVisible; private ObservedMotionSampler _sampler; private FootPlanner _planner; private ChoirMotionMetrics _metrics; private int _boneCount; private int _bodyBoneCount; private int _lastPlannerReplants; private bool _awake; private bool _validBindings; private bool _prepared; private bool _applied; private bool _needsReset = true; private ChoirMotionResetReason _resetReason; private bool _suspended = true; private bool _hasSeed; private bool _returningFromCapture; private float _previousCaptureBlend; private float _idlePhase; private float _nominalGroundOffset; private float _supportHeight; private Vector3 _supportNormal = Vector3.up; private float _appliedSupportHeight; private Quaternion _appliedSupportTilt = Quaternion.identity; private Vector3 _supportUp; private Vector3 _supportForward; private float _forwardLeanSlope; public bool ManualTick { get; set; } public bool HasValidBindings => _validBindings; public int LegCount => _legs.Length; public ChoirMotionMetrics Metrics => _metrics; public ChoirMotionSettings Settings => _settings; public Vector3 CaptureCenter => _captureCenter; public Vector3 CaptureHalfExtents => _captureHalfExtents; public GaitProfile ActiveGaitProfile { get { if (_planner == null) { return _settings.WalkProfile; } return _planner.ActiveGaitProfile; } } public float CaptureBlend { get { if (!Finite(_captureBlend)) { return 1f; } return Mathf.Clamp01(_captureBlend); } set { _captureBlend = (Finite(value) ? Mathf.Clamp01(value) : 1f); } } public bool CadenceHeld { get { if (_planner != null) { return _planner.CadenceHeld; } return false; } set { if (_planner == null) { throw new InvalidOperationException("Initialize ChoirMotion bindings before holding cadence."); } _planner.CadenceHeld = value; } } internal bool ContainsCaptureRoot(Vector3 rootLocal) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Unknown result type (might be due to invalid IL or missing references) return ChoirCaptureVolume.Contains(ToCore(rootLocal), ToCore(_captureCenter), ToCore(_captureHalfExtents)); } public void ApplyGaitProfile(GaitProfile profile) { if (_planner == null) { throw new InvalidOperationException("Initialize ChoirMotion bindings before selecting a gait profile."); } profile.MaxBodyForwardLeanDegrees = (Finite(profile.MaxBodyForwardLeanDegrees) ? Mathf.Clamp(profile.MaxBodyForwardLeanDegrees, 0f, _settings.MaxSupportTiltDegrees) : _settings.MaxSupportTiltDegrees); GaitProfile gaitProfile = _planner.ApplyGait(profile); _sampler.EnsureEnvelope(gaitProfile.Envelope); _forwardLeanSlope = Mathf.Tan(gaitProfile.MaxBodyForwardLeanDegrees * (MathF.PI / 180f)); } public void Configure(Transform root, Transform visualRoot, Transform[] spine, Transform[] lobes, Transform[] mouthBones, ChoirLegBinding[] legs, Transform[] twigs, Renderer[] visibilityRenderers, ChoirMotionSettings settings, Vector3 captureCenter, Vector3 captureHalfExtents) { //IL_0076: Unknown result type (might
Y4NGZFlyingTV.dll
Decompiled a day ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.IO.Compression; using System.Net.Http; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security.Cryptography; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using BepInEx; using BepInEx.Configuration; using BepInEx.Logging; using Dawn; using GameNetcodeStuff; using Microsoft.CodeAnalysis; using Unity.Netcode; using Unity.Netcode.Components; using UnityEngine; using UnityEngine.AI; using UnityEngine.Audio; using UnityEngine.Networking; using UnityEngine.SceneManagement; using UnityEngine.Video; using Y4NGZFlyingTV.NetcodePatcher; using Y4NGZMonsters.Shared; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: AssemblyCompany("Y4NGZFlyingTV")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0+3460ec64f0cec4948e51ddb3f02a4b0e414f105e")] [assembly: AssemblyProduct("Y4NGZFlyingTV")] [assembly: AssemblyTitle("Y4NGZFlyingTV")] [assembly: AssemblyVersion("1.0.0.0")] [module: RefSafetyRules(11)] [module: NetcodePatchedAssembly] 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 Y4NGZFlyingTV { public sealed class FlyingTVAi : EnemyAI { private struct ScreenMaterialTarget { public Renderer Renderer; public int MaterialIndex; public ScreenMaterialTarget(Renderer renderer, int materialIndex) { Renderer = renderer; MaterialIndex = materialIndex; } } private struct PlayerMovementSample { public float Timestamp; public Vector3 Position; public PlayerMovementSample(float timestamp, Vector3 position) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_0009: Unknown result type (might be due to invalid IL or missing references) Timestamp = timestamp; Position = position; } } private const int StateRoaming = 0; private const int StateApproach = 1; private const int StateChecking = 2; private const int StateVideo = 3; private const int StateAttack = 4; private const int StateLeave = 5; private const int StateDead = 6; private const float StopSampleIntervalSeconds = 0.1f; private const float AttackDamage = 25f; private const float AttackCooldown = 1.4f; private const float AttackRange = 2.2f; private const int FlyingTVHealth = 6; private const float VoiceToVideoGapSeconds = 0.15f; private const float PlaybackStartLeadSeconds = 0.35f; private const float VideoNoncomplianceGraceSeconds = 5f; private const float VideoMonitorIntervalSeconds = 0.25f; private const float CloseUpFallbackHoldSeconds = 2f; private const float YoutubeResolutionTimeoutSeconds = 90f; private const float VideoPrepareTimeoutSeconds = 20f; private const int StaticTextureWidth = 256; private const int StaticTextureHeight = 144; private const int StaticFrameCount = 12; private const float StaticFrameIntervalSeconds = 1f / 12f; private const float RoamSearchWidth = 70f; private const float RoamSearchPrecision = 4f; private const float RoamSearchRetargetMinSeconds = 3.5f; private const float RoamSearchRetargetMaxSeconds = 7.5f; private const float HoverBobSpeed = 1.2f; private const float HoverBobAmplitude = 0.16f; private const float CeilingClearance = 0.6f; private const float HoverProbeIntervalSeconds = 0.1f; private const float NavMeshRepairIntervalSeconds = 1f; private const float PositionSyncThreshold = 0.3f; private const float TargetStoppingDistance = 0.6f; private const float DamageSlowPerHit = 0.09f; private const float MinDamageSpeedMultiplier = 0.55f; private const float DamageWobblePerHit = 0.2f; private const float MaxDamageWobble = 1.1f; private const float DeathExplosionKnockbackRadius = 10f; private const float DeathExplosionMaxKnockback = 34f; private const float DeathExplosionMinKnockback = 12f; private const float DeathDespawnDelaySeconds = 0.35f; private const float HitFreezeSeconds = 0.3f; private const float DamageFreezeGraceSeconds = 1.5f; private const float AttackVerticalTolerance = 1.6f; private const float ApproachProgressStep = 1f; private const float ApproachKeepUpSlack = 2f; private const float ApproachNoProgressSeconds = 8f; private const float UnreachableGiveUpSeconds = 3f; private const float UnreachableIgnoreDetectionSeconds = 20f; private const float LeaveSightHalfAngle = 70f; private const int LeaveSightRange = 60; private const float LeaveMinStepDistance = 2f; private const float LeaveArrivalDistance = 1.5f; private const float NoiseMinLoudness = 0.5f; private const float NoiseHearingRange = 20f; private const float NoiseMemorySeconds = 3f; private const float NoiseReseedCooldownSeconds = 4f; private const int NoiseMaxRepeatsInOneSpot = 10; private const float NoiseSearchWidth = 35f; private const float HuntArrivalDistance = 1.5f; private const float HuntSearchWidth = 25f; private const float HuntLogRepeatSeconds = 2f; private const int VoiceGreeting = 0; private const int VoiceNoncompliance = 1; private const int VoiceCompliance = 2; private const int VoiceStay = 3; private const int VoiceStayRepeat = 4; private const int NoPlayerSlot = -1; private const string EmbeddedScreenSurfaceName = "FlyingTVEmbeddedScreenSurface"; internal const float BodyColliderRadius = 0.65f; internal const float BodyColliderHeight = 1.35f; private static readonly int MovingHash = Animator.StringToHash("Moving"); private static readonly int DeathHash = Animator.StringToHash("Death"); private static readonly int DamageStageHash = Animator.StringToHash("DamageStage"); private static readonly int HitHash = Animator.StringToHash("Hit"); private static readonly float[] LeaveSampleDistances = new float[3] { 16f, 8f, 4f }; private static readonly string[] VideoExtensions = new string[6] { ".mp4", ".webm", ".mov", ".m4v", ".ogv", ".avi" }; private static readonly int[] ScreenTexturePropertyIds = new int[6] { Shader.PropertyToID("_BaseColorMap"), Shader.PropertyToID("_UnlitColorMap"), Shader.PropertyToID("_EmissiveColorMap"), Shader.PropertyToID("_MainTex"), Shader.PropertyToID("_BaseMap"), Shader.PropertyToID("_EmissionMap") }; private static Texture2D[] s_staticFrames; public Transform visualRoot; public Renderer screenRenderer; public AudioSource videoAudioSource; public AudioClip greetingsClip; public AudioClip noncomplianceClip; public AudioClip complianceClip; public AudioClip propellerLoopClip; public AudioClip stayClip; public AudioClip hitClankClip; public AudioClip smokeLoopClip; public AudioClip idleHumClip; public AudioClip explosionClip; public AISearchRoutine facilitySearch = new AISearchRoutine(); private AudioSource _voiceSource; private AudioSource _propellerSource; private AudioSource _humSource; private AudioSource _smokeSource; private AudioSource _sfxSource; private Coroutine _checkRoutine; private Coroutine _videoRoutine; private Vector3 _leaveDestination; private Vector3 _lastKnownTargetPosition; private Quaternion _videoHoldRotation; private float _leaveDeadline; private float _leaveMovementStartTime; private float _nextAttackTime; private float _serverVideoEndTime; private float _serverNoncomplianceEnableTime = float.PositiveInfinity; private float _lastVoiceStartTime; private float _nextRoamSearchRetargetTime; private float _roamAngle; private int _damageHitCount; private bool _checkActive; private bool _videoActive; private bool _selectedVideoPlaying; private bool _destroying; private bool _leaveMovementStarted; private bool _deathExplosionTriggered; private Coroutine _deathDespawnRoutine; private string _videoName = string.Empty; private float _forcedDurationSeconds; private Vector3 _lastPosition; private Vector3 _visualBaseLocalPosition; private bool _hasVisualBaseLocalPosition; private float _hoverHeight; private float _nextNavMeshRepairTime; private float _attackLostAggroSince = -1f; private float _ignoreDetectionUntil; private float _damageStunUntil; private float _preDamageStunAnimatorSpeed = 1f; private bool _hasMovingParameter; private bool _damageStunFrozen; private AudioClip _lastVoiceClip; private float _videoPresentationStartTime; private bool _hasPendingSearchSeed; private Vector3 _pendingSearchSeed; private float _pendingSearchWidth; private int _assignedPlayerIndex = -1; private readonly ServerOwnershipGuard _ownership = new ServerOwnershipGuard(); private readonly NoiseMemory _noiseMemory = new NoiseMemory(); private float _nextNoiseReseedTime; private bool _audioRouted; private bool _playbackBroadcast; private bool _targetInSight; private float _approachBestDistance = float.PositiveInfinity; private float _approachProgressSince; private float _unreachableSince = -1f; private int _appliedAgentState = -1; private int _appliedAgentHitCount = -1; private float _nextHoverProbeTime; private float _hoverTargetHeight; private float _appliedPropellerVolume = -1f; private float _damageFreezeImmuneUntil; private bool _lethalKillPending; private int _lethalKillFrame; private readonly WardenGreetingGate _greetingGate = new WardenGreetingGate(); private readonly WardenComplianceGate _complianceGate = new WardenComplianceGate(); private float _lastGreetingTickTime = -1f; private float _lastComplianceTickTime = -1f; private readonly WardenHuntMemory _hunt = new WardenHuntMemory(); private float _lastHuntTickTime = -1f; private Vector3 _huntLastSeenPosition; private float _huntLostLogTime = float.NegativeInfinity; private float _huntReacquireLogTime = float.NegativeInfinity; private bool _videoEndHoldLogged; private Vector3 _leaveAwayDirection; private bool _leaveHasDestination; private float _exitRiseOffset; private float? _ceilingHeightAboveFloor; private FlyingTVDamageVisual _damageVisual; private int _appliedDamageStage; private float _currentTilt; private float _tiltSide = 1f; private Quaternion _visualRootBaseLocalRotation = Quaternion.identity; private bool _hasVisualRootBaseLocalRotation; private bool _hasDeathTrigger; private bool _hasDamageStageParameter; private bool _hasHitTrigger; private bool _closeUpActive; private float _closeUpStartTime; private float _closeUpHoldSeconds; private int _closeUpTargetSlot = -1; private bool _staticBurstActive; private bool _smokeSuspendedForCloseUp; private readonly NetworkVariable<int> _networkTargetSlot = new NetworkVariable<int>(-1, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); private readonly NetworkVariable<bool> _networkHumActive = new NetworkVariable<bool>(false, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); private readonly NetworkVariable<int> _networkDamageStage = new NetworkVariable<int>(0, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); private readonly NetworkVariable<float> _networkTiltDegrees = new NetworkVariable<float>(0f, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); private CapsuleCollider _bodyCollider; private Rigidbody _bodyRigidbody; private readonly List<PlayerMovementSample> _playerMovementSamples = new List<PlayerMovementSample>(); private Material _screenMaterial; private Material _screenBlankMaterial; private int _screenMaterialIndex = -1; private readonly List<ScreenMaterialTarget> _screenMaterialTargets = new List<ScreenMaterialTarget>(); private bool _screenTargetsCollected; private bool _screenMaterialApplied; private bool _missingScreenTargetLogged; private VideoPlayer _videoPlayer; private Coroutine _playbackRoutine; private RenderTexture _renderTexture; private Texture2D _fallbackTexture; private bool _staticPlaying; private float _nextStaticFrameTime; private int _staticFrameIndex; private bool _videoPausedForFreeze; private float _videoFreezePausedSeconds; private float _localVideoEndTime; private string _leasedVideoPath; private float FollowDistance => Mathf.Max(1f, FlyingTVConfig.FollowDistance.Value); private float PlayerStopWindowSeconds => Mathf.Max(0.1f, 1f); private float PlayerStopThreshold => 0.35f; private float VideoNoncomplianceDistance => Mathf.Max(FollowDistance, FlyingTVConfig.VideoNoncomplianceDistance.Value); private float TurnAwayAngleThreshold => Mathf.Clamp(FlyingTVConfig.TurnAwayAngleThreshold.Value, 10f, 89f); private float VideoGazeAngleThreshold => Mathf.Clamp(FlyingTVConfig.VideoGazeAngleThreshold.Value, 10f, 89f); private float VideoNoncomplianceSustainSeconds => Mathf.Max(0f, FlyingTVConfig.VideoNoncomplianceSustainSeconds.Value); private float GreetDistance => Mathf.Max(FollowDistance, FlyingTVConfig.GreetDistance.Value); private float GreetApproachSeconds => Mathf.Max(0f, FlyingTVConfig.GreetApproachSeconds.Value); private float WarningGraceSeconds => Mathf.Max(0f, FlyingTVConfig.WarningGraceSeconds.Value); private float AggroPersistSeconds => Mathf.Max(0f, FlyingTVConfig.AggroPersistSeconds.Value); private float StrikeReach => Mathf.Max(0f, FlyingTVConfig.StrikeReach.Value); private float VideoTrackDegreesPerSecond => Mathf.Max(0f, FlyingTVConfig.VideoTrackDegreesPerSecond.Value); private float TiltPerHitDegrees => FlyingTVConfig.TiltPerHitDegrees.Value; private float ExitRiseSpeed => Mathf.Max(0f, FlyingTVConfig.ExitRiseSpeed.Value); private float ExitRiseHeight => Mathf.Max(0f, FlyingTVConfig.ExitRiseHeight.Value); private float ApproachSpeed => Mathf.Max(1f, FlyingTVConfig.ApproachSpeed.Value); private float LeaveSpeed => 7f; private float ChaseLoseAggroSeconds => 4f; private float ApproachLoseAggroDistance => Mathf.Max(FlyingTVConfig.DetectionRange.Value + 5f, 45f); private float ApproachLoseAggroSeconds => 8f; private float ConfiguredHoverHeight => 1.9f; private float RoamSpeed => Mathf.Max(0.1f, FlyingTVConfig.RoamSpeed.Value); private float ChaseSpeed => Mathf.Max(0.1f, FlyingTVConfig.ChaseSpeed.Value); private float DamageSpeedMultiplier => Mathf.Max(0.55f, 1f - (float)_damageHitCount * 0.09f); private float DamageWobbleAmount => Mathf.Min(1.1f, (float)_networkDamageStage.Value * 0.2f); private bool IsFrozen { get { if (!((EnemyAI)(object)this).IsStunned()) { return Time.time < _damageStunUntil; } return true; } } private bool AgentReady { get { if ((Object)(object)base.agent != (Object)null && ((Behaviour)base.agent).enabled) { return base.agent.isOnNavMesh; } return false; } } public override void OnNetworkSpawn() { //IL_01c9: Unknown result type (might be due to invalid IL or missing references) ((NetworkBehaviour)this).OnNetworkSpawn(); _hoverHeight = ConfiguredHoverHeight; _hoverTargetHeight = _hoverHeight; EnsureNavigationAgent(); ResolveReferences(); EnsureBehaviourStates(); ConfigureSearchDefaults(); _voiceSource = EnsureAudioSource(base.creatureVoice, "FlyingTVVoice", 34f); base.creatureVoice = _voiceSource; _propellerSource = EnsureAudioSource(_propellerSource, "FlyingTVPropellerLoop", 38f); _humSource = EnsureAudioSource(_humSource, "FlyingTVHumLoop", 38f); _smokeSource = EnsureAudioSource(_smokeSource, "FlyingTVSmokeLoop", 38f); _sfxSource = EnsureAudioSource(_sfxSource, "FlyingTVSfx", 34f); _audioRouted = RouteAudioSources(); EnsurePropellerLoopPlaying(); _staticFrameIndex = Random.Range(0, 12); StartStaticPlayback(); _damageVisual = ((Component)this).GetComponent<FlyingTVDamageVisual>(); if ((Object)(object)_damageVisual == (Object)null) { _damageVisual = ((Component)this).gameObject.AddComponent<FlyingTVDamageVisual>(); } _damageVisual.Initialize(visualRoot); _tiltSide = ((((NetworkBehaviour)this).NetworkObjectId % 2 == 0L) ? 1f : (-1f)); _roamAngle = Random.Range(0f, 360f); if (((NetworkBehaviour)this).IsServer) { _videoName = FlyingTVConfig.ResolveVideoSource(); _forcedDurationSeconds = ((FlyingTVConfig.PlaybackDurationSeconds != null) ? Mathf.Max(0f, FlyingTVConfig.PlaybackDurationSeconds.Value) : 0f); SnapToNavMesh(logAlways: true); base.currentBehaviourStateIndex = 0; ((EnemyAI)this).SwitchToBehaviourState(0); base.movingTowardsTargetPlayer = false; base.moveTowardsDestination = true; StartFacilitySearch(((Component)this).transform.position, 70f); } } public override void Start() { //IL_0042: Unknown result type (might be due to invalid IL or missing references) //IL_0047: Unknown result type (might be due to invalid IL or missing references) ((EnemyAI)this).Start(); EnsureNavigationAgent(); base.updatePositionThreshold = 0.3f; Plugin.EnsureScanNode(((Component)this).gameObject); EnsureEyeTransform(); EnsureCollisionBody(); ConfigureSearchDefaults(); base.enemyHP = 6; _lastPosition = ((Component)this).transform.position; if (((NetworkBehaviour)this).IsServer) { PrefetchYoutubePlaybackClientRpc(_videoName); } } public override void FinishedCurrentSearchRoutine() { //IL_0023: Unknown result type (might be due to invalid IL or missing references) ((EnemyAI)this).FinishedCurrentSearchRoutine(); if (base.currentSearch == facilitySearch && base.currentBehaviourStateIndex == 0) { StartFacilitySearch(((Component)this).transform.position, 70f); } } private void EnsureNavigationAgent() { if ((Object)(object)base.agent == (Object)null) { base.agent = ((Component)this).GetComponentInChildren<NavMeshAgent>(true); } if ((Object)(object)base.agent == (Object)null) { base.agent = ((Component)this).gameObject.AddComponent<NavMeshAgent>(); } base.agent.updatePosition = true; base.agent.updateRotation = false; base.agent.updateUpAxis = false; ConfigureAgentBody(); if (((NetworkBehaviour)this).IsServer) { ((Behaviour)base.agent).enabled = true; base.agent.baseOffset = _hoverHeight; _appliedAgentState = -1; } } private void ConfigureAgentBody() { base.agent.acceleration = 10f; base.agent.angularSpeed = 360f; base.agent.radius = 0.65f; base.agent.height = 1.35f; base.agent.autoBraking = true; base.agent.autoRepath = true; base.agent.autoTraverseOffMeshLink = true; base.agent.obstacleAvoidanceType = (ObstacleAvoidanceType)4; base.agent.avoidancePriority = 45; if (base.agent.areaMask == 0) { base.agent.areaMask = -1; } if (base.openDoorSpeedMultiplier <= 0f) { base.openDoorSpeedMultiplier = 1f; } } private void ApplyAgentStateSettings() { int currentBehaviourStateIndex = base.currentBehaviourStateIndex; if ((currentBehaviourStateIndex != _appliedAgentState || _damageHitCount != _appliedAgentHitCount) && !((Object)(object)base.agent == (Object)null) && ((Behaviour)base.agent).enabled) { _appliedAgentState = currentBehaviourStateIndex; _appliedAgentHitCount = _damageHitCount; float num; switch (currentBehaviourStateIndex) { case 1: case 2: num = ApproachSpeed; break; case 4: num = ChaseSpeed; break; case 5: num = LeaveSpeed; break; default: num = RoamSpeed; break; } base.agent.speed = Mathf.Max(0.1f, num * DamageSpeedMultiplier); base.agent.stoppingDistance = ((currentBehaviourStateIndex == 0 || currentBehaviourStateIndex == 5) ? 0f : 0.6f); } } private void ApplyHoverHeight() { //IL_0063: Unknown result type (might be due to invalid IL or missing references) //IL_0068: Unknown result type (might be due to invalid IL or missing references) //IL_0078: Unknown result type (might be due to invalid IL or missing references) //IL_007d: Unknown result type (might be due to invalid IL or missing references) //IL_00ae: Unknown result type (might be due to invalid IL or missing references) //IL_00b8: Unknown result type (might be due to invalid IL or missing references) //IL_00bd: Unknown result type (might be due to invalid IL or missing references) //IL_00c2: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)base.agent == (Object)null || !((Behaviour)base.agent).enabled) { return; } float configuredHoverHeight = ConfiguredHoverHeight; float num = 0.675f; bool flag = base.currentBehaviourStateIndex == 5 && _leaveMovementStarted; if (Time.time >= _nextHoverProbeTime) { _nextHoverProbeTime = Time.time + 0.1f; Vector3 val = ((Component)this).transform.position - Vector3.up * base.agent.baseOffset; float num2 = (flag ? (configuredHoverHeight + ExitRiseHeight + num + 0.5f) : (configuredHoverHeight + num + 0.6f)); _ceilingHeightAboveFloor = null; RaycastHit val2 = default(RaycastHit); if (Physics.Raycast(val + Vector3.up * 0.1f, Vector3.up, ref val2, num2, GetWorldCollisionMask(), (QueryTriggerInteraction)1)) { _ceilingHeightAboveFloor = ((RaycastHit)(ref val2)).distance + 0.1f; } } float hoverTargetHeight = configuredHoverHeight; if (_ceilingHeightAboveFloor.HasValue) { hoverTargetHeight = Mathf.Clamp(_ceilingHeightAboveFloor.Value - num - 0.6f, 0f, configuredHoverHeight); } if (flag) { _exitRiseOffset = WardenEncounterMath.ExitRiseStep(_exitRiseOffset, Time.deltaTime, ExitRiseSpeed, ExitRiseHeight, configuredHoverHeight, num, _ceilingHeightAboveFloor, 0.5f); if (_exitRiseOffset > 0f) { hoverTargetHeight = configuredHoverHeight + _exitRiseOffset; } } _hoverTargetHeight = hoverTargetHeight; if (_hoverHeight != _hoverTargetHeight) { float num3 = Mathf.Max(0.5f, _hoverTargetHeight) * 2f; if (flag) { num3 = ((_hoverTargetHeight > _hoverHeight) ? ExitRiseSpeed : Mathf.Max(num3, ExitRiseSpeed)); } _hoverHeight = Mathf.MoveTowards(_hoverHeight, _hoverTargetHeight, num3 * Time.deltaTime); base.agent.baseOffset = _hoverHeight; } } private void RepairOffNavMeshIfNeeded() { if (((NetworkBehaviour)this).IsServer && !((Object)(object)base.agent == (Object)null) && !(Time.time < _nextNavMeshRepairTime) && (!((Behaviour)base.agent).enabled || !base.agent.isOnNavMesh)) { _nextNavMeshRepairTime = Time.time + 1f; SnapToNavMesh(logAlways: false); } } private bool SnapToNavMesh(bool logAlways) { //IL_003a: Unknown result type (might be due to invalid IL or missing references) //IL_003f: Unknown result type (might be due to invalid IL or missing references) //IL_005c: Unknown result type (might be due to invalid IL or missing references) //IL_009a: Unknown result type (might be due to invalid IL or missing references) //IL_00b2: Unknown result type (might be due to invalid IL or missing references) //IL_006d: Unknown result type (might be due to invalid IL or missing references) //IL_0078: 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_00d2: Unknown result type (might be due to invalid IL or missing references) //IL_0109: Unknown result type (might be due to invalid IL or missing references) if (!((NetworkBehaviour)this).IsServer || (Object)(object)base.agent == (Object)null) { return false; } if (((Behaviour)base.agent).enabled && base.agent.isOnNavMesh) { return true; } Vector3 position = ((Component)this).transform.position; int areaMask = ((base.agent.areaMask == 0) ? (-1) : base.agent.areaMask); if (TrySampleNavMesh(position, 14f, areaMask, out var position2) || TrySampleNearestAINode(position, areaMask, out position2) || TrySampleNavMesh(position, 80f, -1, out position2)) { ((Behaviour)base.agent).enabled = false; ((Component)this).transform.position = position2; ((Behaviour)base.agent).enabled = true; bool flag = base.agent.Warp(position2); if (logAlways) { ManualLogSource log = Plugin.Log; if (log != null) { log.LogInfo((object)$"[FlyingTV] Placed on the NavMesh at {position2} (from {position}, warp={flag})."); } } if (!flag) { return base.agent.isOnNavMesh; } return true; } ManualLogSource log2 = Plugin.Log; if (log2 != null) { log2.LogWarning((object)$"[FlyingTV] No NavMesh point found near spawn at {position}; the TV cannot path."); } return false; } private static bool TrySampleNavMesh(Vector3 candidate, float radius, int areaMask, out Vector3 position) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Unknown result type (might be due to invalid IL or missing references) NavMeshHit val = default(NavMeshHit); if (NavMesh.SamplePosition(candidate, ref val, Mathf.Max(0.25f, radius), areaMask)) { position = ((NavMeshHit)(ref val)).position; return true; } position = Vector3.zero; return false; } private bool TrySampleNearestAINode(Vector3 from, int areaMask, out Vector3 position) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_003d: Unknown result type (might be due to invalid IL or missing references) //IL_0042: Unknown result type (might be due to invalid IL or missing references) //IL_0043: Unknown result type (might be due to invalid IL or missing references) //IL_0048: Unknown result type (might be due to invalid IL or missing references) //IL_0077: Unknown result type (might be due to invalid IL or missing references) position = Vector3.zero; GameObject[] allAINodes = base.allAINodes; if (allAINodes == null || allAINodes.Length == 0) { return false; } GameObject val = null; float num = float.PositiveInfinity; foreach (GameObject val2 in allAINodes) { if (!((Object)(object)val2 == (Object)null)) { Vector3 val3 = val2.transform.position - from; float sqrMagnitude = ((Vector3)(ref val3)).sqrMagnitude; if (sqrMagnitude < num) { num = sqrMagnitude; val = val2; } } } if ((Object)(object)val != (Object)null) { return TrySampleNavMesh(val.transform.position, 12f, areaMask, out position); } return false; } private void EnsureEyeTransform() { //IL_0052: Unknown result type (might be due to invalid IL or missing references) //IL_0062: Unknown result type (might be due to invalid IL or missing references) //IL_0067: Unknown result type (might be due to invalid IL or missing references) //IL_006c: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)base.eye == (Object)null) { Transform val = ((Component)this).transform.Find("FlyingTVEye"); if ((Object)(object)val == (Object)null) { val = new GameObject("FlyingTVEye").transform; val.SetParent(((Component)this).transform, false); } base.eye = val; } base.eye.localPosition = Vector3.zero; base.eye.localRotation = Quaternion.LookRotation(FlyingTVManager.GetScreenLocalFacingDirection(), Vector3.up); } private void EnsureCollisionBody() { //IL_0045: Unknown result type (might be due to invalid IL or missing references) _bodyCollider = ((Component)this).GetComponent<CapsuleCollider>() ?? ((Component)this).gameObject.AddComponent<CapsuleCollider>(); ((Collider)_bodyCollider).enabled = true; ((Collider)_bodyCollider).isTrigger = false; _bodyCollider.direction = 1; _bodyCollider.center = Vector3.zero; _bodyCollider.radius = 0.65f; _bodyCollider.height = 1.35f; _bodyRigidbody = ((Component)this).GetComponent<Rigidbody>() ?? ((Component)this).gameObject.AddComponent<Rigidbody>(); _bodyRigidbody.isKinematic = true; _bodyRigidbody.useGravity = false; _bodyRigidbody.detectCollisions = true; _bodyRigidbody.collisionDetectionMode = (CollisionDetectionMode)3; } public override void Update() { _ownership.Ensure((EnemyAI)(object)this, Plugin.Log); if (_lethalKillPending && Time.frameCount > _lethalKillFrame) { if (base.isEnemyDead) { _lethalKillPending = false; } else if (((NetworkBehaviour)this).IsOwner) { _lethalKillPending = false; ((EnemyAI)this).KillEnemyOnOwnerClient(false); } else if (!((NetworkBehaviour)this).IsServer) { _lethalKillPending = false; } } ((EnemyAI)this).Update(); if (!_audioRouted) { _audioRouted = RouteAudioSources(); } UpdateStaticPlayback(); if (base.isEnemyDead) { return; } EnsurePropellerLoopPlaying(); UpdateHumLoop(); ApplyReplicatedDamageStage(); if (((NetworkBehaviour)this).IsServer) { SyncTargetSlot(); } if (ApplyDamageStunFreeze()) { PauseLocalVideoTimers(Time.deltaTime); if (((NetworkBehaviour)this).IsServer) { PauseServerTimers(Time.deltaTime); } return; } UpdateAnimation(); TickVisualHover(); if (((NetworkBehaviour)this).IsServer) { UpdateServerMovement(); } } public override void DoAIInterval() { ((EnemyAI)this).DoAIInterval(); if (((NetworkBehaviour)this).IsServer && !base.isEnemyDead && !((Object)(object)StartOfRound.Instance == (Object)null) && !StartOfRound.Instance.allPlayersDead && !IsFrozen) { int currentBehaviourStateIndex = base.currentBehaviourStateIndex; switch (currentBehaviourStateIndex) { case 0: EvaluateRoaming(); break; case 5: EvaluateLeave(); break; case 1: case 2: case 3: case 4: EvaluateEngagement(currentBehaviourStateIndex); break; } } } public override void DetectNoise(Vector3 noisePosition, float noiseLoudness, int timesPlayedInOneSpot = 0, int noiseID = 0) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0038: Unknown result type (might be due to invalid IL or missing references) //IL_0045: Unknown result type (might be due to invalid IL or missing references) ((EnemyAI)this).DetectNoise(noisePosition, noiseLoudness, timesPlayedInOneSpot, noiseID); if (((NetworkBehaviour)this).IsServer && !base.isEnemyDead && !IsFrozen && timesPlayedInOneSpot <= 10 && base.currentBehaviourStateIndex == 0) { _noiseMemory.Record(noisePosition, noiseLoudness, 0.5f, ((Component)this).transform.position, 20f); } } private void EvaluateRoaming() { if (Time.time >= _ignoreDetectionUntil) { PlayerControllerB val = FindDetectedPlayer(); if ((Object)(object)val != (Object)null) { base.targetPlayer = val; StartApproach(); return; } } TryReseedSearchAtNoise(); } private void TryReseedSearchAtNoise() { //IL_003d: Unknown result type (might be due to invalid IL or missing references) if (!(Time.time < _nextNoiseReseedTime) && CanUseVanillaSearch() && _noiseMemory.TryTake(3f, out var position)) { _nextNoiseReseedTime = Time.time + 4f; StartFacilitySearch(position, 35f, recentre: true); } } private void EvaluateEngagement(int state) { //IL_003f: Unknown result type (might be due to invalid IL or missing references) //IL_0044: Unknown result type (might be due to invalid IL or missing references) PlayerControllerB targetPlayer = base.targetPlayer; if (!FlyingTVManager.IsValidLivingPlayer(targetPlayer) || !((EnemyAI)this).PlayerIsTargetable(targetPlayer, false, false, true)) { if (state == 4 || state == 3) { GiveUpAndLeave(); } else { LoseAttackAggro(ChaseLoseAggroSeconds); } return; } _lastKnownTargetPosition = ((Component)targetPlayer).transform.position; _targetInSight = HasLineOfSightToTarget(targetPlayer); if (state == 1 || state == 2) { TickGreeting(targetPlayer); } switch (state) { case 3: return; case 4: EvaluateHunt(targetPlayer); return; } if (ShouldLoseAggro(targetPlayer, ApproachLoseAggroDistance, ApproachLoseAggroSeconds)) { LoseAttackAggro(ChaseLoseAggroSeconds); } else if (IsApproachStalled(targetPlayer)) { LoseAttackAggro(20f, sweepLastKnown: false); } } private void TickGreeting(PlayerControllerB target) { //IL_003e: Unknown result type (might be due to invalid IL or missing references) //IL_0049: Unknown result type (might be due to invalid IL or missing references) //IL_004e: Unknown result type (might be due to invalid IL or missing references) //IL_0053: Unknown result type (might be due to invalid IL or missing references) if (!_greetingGate.Greeted) { float time = Time.time; float deltaSeconds = ((_lastGreetingTickTime < 0f) ? 0f : (time - _lastGreetingTickTime)); _lastGreetingTickTime = time; Vector3 val = ((Component)target).transform.position - ((Component)this).transform.position; val.y = 0f; if (_greetingGate.Tick(deltaSeconds, ((Vector3)(ref val)).magnitude, _targetInSight, GreetDistance, GreetApproachSeconds)) { PlayVoiceLine(0); } } } private bool IsApproachStalled(PlayerControllerB target) { //IL_005e: Unknown result type (might be due to invalid IL or missing references) //IL_0069: Unknown result type (might be due to invalid IL or missing references) //IL_006e: Unknown result type (might be due to invalid IL or missing references) //IL_0073: Unknown result type (might be due to invalid IL or missing references) float time = Time.time; if (!IsPathEndAwayFrom(target)) { _unreachableSince = -1f; } else if (_unreachableSince < 0f) { _unreachableSince = time; } else if (time - _unreachableSince >= 3f) { ManualLogSource log = Plugin.Log; if (log != null) { log.LogInfo((object)"[FlyingTV] Target is unreachable (path ends away from them); giving up."); } return true; } Vector3 val = ((Component)target).transform.position - ((Component)this).transform.position; val.y = 0f; float magnitude = ((Vector3)(ref val)).magnitude; if (magnitude <= FollowDistance + 2f && _targetInSight) { _approachBestDistance = magnitude; _approachProgressSince = time; return false; } if (magnitude < _approachBestDistance - 1f) { _approachBestDistance = magnitude; _approachProgressSince = time; return false; } if (time - _approachProgressSince < 8f) { return false; } ManualLogSource log2 = Plugin.Log; if (log2 != null) { log2.LogInfo((object)$"[FlyingTV] Approach made no progress for {8f:0} s; giving up."); } return true; } private void ResetApproachProgress() { _approachBestDistance = float.PositiveInfinity; _approachProgressSince = Time.time; _unreachableSince = -1f; } private bool IsPathEndAwayFrom(PlayerControllerB target) { //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Invalid comparison between Unknown and I4 //IL_0031: Unknown result type (might be due to invalid IL or missing references) //IL_0049: Unknown result type (might be due to invalid IL or missing references) //IL_004e: Unknown result type (might be due to invalid IL or missing references) //IL_0055: Unknown result type (might be due to invalid IL or missing references) //IL_005a: Unknown result type (might be due to invalid IL or missing references) //IL_005b: Unknown result type (might be due to invalid IL or missing references) //IL_0061: Unknown result type (might be due to invalid IL or missing references) //IL_0078: Unknown result type (might be due to invalid IL or missing references) //IL_0090: Unknown result type (might be due to invalid IL or missing references) //IL_0091: 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_0097: Unknown result type (might be due to invalid IL or missing references) if (!AgentReady || !base.movingTowardsTargetPlayer || base.agent.pathPending) { return false; } NavMeshPathStatus pathStatus = base.agent.pathStatus; if ((int)pathStatus == 2) { return true; } if ((int)pathStatus == 0 || !base.agent.hasPath) { return false; } Vector3 pathEndPosition = base.agent.pathEndPosition; Vector3 position = ((Component)target).transform.position; if (Mathf.Abs(pathEndPosition.y - position.y) > 1.6f) { return true; } pathEndPosition.y = position.y; float num = FollowDistance + 1f; Vector3 val = pathEndPosition - position; return ((Vector3)(ref val)).sqrMagnitude > num * num; } private void TryStrike(PlayerControllerB target) { //IL_0032: Unknown result type (might be due to invalid IL or missing references) if (!(Time.time < _nextAttackTime) && IsTargetInStrikeReach(target)) { _nextAttackTime = Time.time + 1.4f; ApplyAttackDamageClientRpc(target.actualClientId, 25, VictimRpc.TargetOnly(target)); } } private void EvaluateHunt(PlayerControllerB target) { //IL_006f: Unknown result type (might be due to invalid IL or missing references) //IL_0074: Unknown result type (might be due to invalid IL or missing references) //IL_012a: Unknown result type (might be due to invalid IL or missing references) //IL_010d: Unknown result type (might be due to invalid IL or missing references) float time = Time.time; float deltaSeconds = ((_lastHuntTickTime < 0f) ? 0f : (time - _lastHuntTickTime)); _lastHuntTickTime = time; WardenHuntEvent wardenHuntEvent = _hunt.Tick(deltaSeconds, _targetInSight, _targetInSight && IsTargetInReacquireCone(target), HasReachedHuntLastSeen(), AggroPersistSeconds); if (_hunt.InContact) { _huntLastSeenPosition = ((Component)target).transform.position; } switch (wardenHuntEvent) { case WardenHuntEvent.GiveUp: { ManualLogSource log2 = Plugin.Log; if (log2 != null) { log2.LogInfo((object)$"[FlyingTV] Hunt: no sight of the target for {AggroPersistSeconds:0.#} s; giving up and leaving."); } GiveUpAndLeave(); return; } case WardenHuntEvent.Reacquire: if (ShouldLogHuntLine(ref _huntReacquireLogTime, time)) { ManualLogSource log3 = Plugin.Log; if (log3 != null) { log3.LogInfo((object)"[FlyingTV] Hunt: target back in sight; chasing."); } } ChaseHuntTarget(target); break; case WardenHuntEvent.LoseContact: if (ShouldLogHuntLine(ref _huntLostLogTime, time)) { ManualLogSource log4 = Plugin.Log; if (log4 != null) { log4.LogInfo((object)$"[FlyingTV] Hunt: lost sight of the target; flying to where it was last seen {_huntLastSeenPosition}."); } } base.movingTowardsTargetPlayer = false; ((EnemyAI)this).SetDestinationToPosition(_huntLastSeenPosition, false); ((EnemyAI)(object)this).ReleaseAgent(); break; case WardenHuntEvent.Search: { ManualLogSource log = Plugin.Log; if (log != null) { log.LogInfo((object)"[FlyingTV] Hunt: reached the last-seen spot; searching around it."); } SearchAroundHuntLastSeen(); break; } } TryStrike(target); } private static bool ShouldLogHuntLine(ref float lastLoggedTime, float now) { if (now - lastLoggedTime < 2f) { return false; } lastLoggedTime = now; return true; } private bool IsTargetInReacquireCone(PlayerControllerB target) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_0034: Unknown result type (might be due to invalid IL or missing references) //IL_003f: Unknown result type (might be due to invalid IL or missing references) Vector3 currentScreenSideDirection = GetCurrentScreenSideDirection(); Vector3 val = ((Component)target).transform.position - ((Component)this).transform.position; return WardenEncounterMath.IsWithinCone(currentScreenSideDirection.x, 0f, currentScreenSideDirection.z, val.x, 0f, val.z, 70f); } private void ChaseHuntTarget(PlayerControllerB target) { StopSearchIfNeeded(clear: false); base.movingTowardsTargetPlayer = true; base.moveTowardsDestination = true; ((EnemyAI)this).SetMovingTowardsTargetPlayer(target); ((EnemyAI)(object)this).ReleaseAgent(); } private bool HasReachedHuntLastSeen() { //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_0031: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Unknown result type (might be due to invalid IL or missing references) //IL_003b: Unknown result type (might be due to invalid IL or missing references) if (_hunt.Phase != WardenHuntPhase.Tracking || !AgentReady || base.agent.pathPending) { return false; } Vector3 val = _huntLastSeenPosition - ((Component)this).transform.position; val.y = 0f; if (!(((Vector3)(ref val)).sqrMagnitude <= 2.25f) && base.agent.hasPath) { return base.agent.remainingDistance <= 1.5f; } return true; } private void SearchAroundHuntLastSeen() { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0056: Unknown result type (might be due to invalid IL or missing references) //IL_005c: Unknown result type (might be due to invalid IL or missing references) //IL_0061: Unknown result type (might be due to invalid IL or missing references) //IL_0066: Unknown result type (might be due to invalid IL or missing references) if (!CanUseVanillaSearch()) { return; } StartFacilitySearch(_huntLastSeenPosition, 25f, recentre: true); List<GameObject> unsearchedNodes = facilitySearch.unsearchedNodes; float num = facilitySearch.searchWidth * facilitySearch.searchWidth; for (int num2 = unsearchedNodes.Count - 1; num2 >= 0; num2--) { Vector3 val = unsearchedNodes[num2].transform.position - _huntLastSeenPosition; if (((Vector3)(ref val)).sqrMagnitude > num) { unsearchedNodes.RemoveAt(num2); } } if (unsearchedNodes.Count <= 0) { ((EnemyAI)this).StopSearch(facilitySearch, false); ManualLogSource log = Plugin.Log; if (log != null) { log.LogInfo((object)$"[FlyingTV] Hunt: no AI node within {facilitySearch.searchWidth:0} m of the last-seen spot; holding there."); } } } private void EvaluateLeave() { if (_leaveMovementStarted) { if (Time.time >= _leaveDeadline || !IsInViewOfAudience()) { DespawnSelf(); } else if (HasReachedLeaveDestination()) { PickLeaveDestination(); } } } private bool IsInViewOfAudience() { //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Unknown result type (might be due to invalid IL or missing references) PlayerControllerB[] allPlayerScripts = StartOfRound.Instance.allPlayerScripts; if (allPlayerScripts == null) { return false; } Vector3 position = ((Component)this).transform.position; foreach (PlayerControllerB val in allPlayerScripts) { if (FlyingTVManager.IsValidLivingPlayer(val) && val.HasLineOfSightToPosition(position, 70f, 60, -1f, -1)) { return true; } } return false; } private void DespawnSelf() { if ((Object)(object)((NetworkBehaviour)this).NetworkObject != (Object)null && ((NetworkBehaviour)this).NetworkObject.IsSpawned) { ((NetworkBehaviour)this).NetworkObject.Despawn(true); } } public override void HitEnemy(int force = 1, PlayerControllerB playerWhoHit = null, bool playHitSFX = false, int hitID = -1) { ((EnemyAI)this).HitEnemy(force, playerWhoHit, playHitSFX, hitID); if (base.isEnemyDead) { return; } if (_lethalKillPending) { PlayHitFeedback(); return; } base.enemyHP -= Mathf.Max(1, force); RegisterDamageHit(); BeginDamageStunFreeze(); PlayHitFeedback(); if (base.enemyHP <= 0) { if (((NetworkBehaviour)this).IsServer || ((NetworkBehaviour)this).IsOwner) { _lethalKillPending = true; _lethalKillFrame = Time.frameCount; } return; } if (((NetworkBehaviour)this).IsServer) { PublishDamageStage(); } if (((NetworkBehaviour)this).IsServer && (Object)(object)playerWhoHit != (Object)null) { TriggerNonComplianceFromAttack(playerWhoHit); } } public override void KillEnemy(bool destroy = false) { //IL_007c: Unknown result type (might be due to invalid IL or missing references) if (!base.isEnemyDead) { base.isEnemyDead = true; _destroying = true; if (((NetworkBehaviour)this).IsServer) { _networkHumActive.Value = false; } StopAllServerRoutines(); CleanupVideoResources(); StopPropellerLoop(); ClearDamageStunFreeze(); if ((Object)(object)_voiceSource != (Object)null) { _voiceSource.Stop(); } if ((Object)(object)_damageVisual != (Object)null) { _damageVisual.Explode(); } TriggerDeathExplosionPresentation(((Component)this).transform.position); ((EnemyAI)this).SwitchToBehaviourStateOnLocalClient(6); base.movingTowardsTargetPlayer = false; base.moveTowardsDestination = false; ((EnemyAI)this).KillEnemy(destroy); if (((NetworkBehaviour)this).IsServer && _deathDespawnRoutine == null && (Object)(object)((NetworkBehaviour)this).NetworkObject != (Object)null && ((NetworkBehaviour)this).NetworkObject.IsSpawned) { _deathDespawnRoutine = ((MonoBehaviour)this).StartCoroutine(DeathDespawnRoutine()); } } } public override void OnDestroy() { _destroying = true; CleanupVideoResources(); ((EnemyAI)this).OnDestroy(); } public override void OnNetworkDespawn() { _lethalKillPending = false; StopHumLoop(); StopSmokeLoop(); ((NetworkBehaviour)this).OnNetworkDespawn(); } internal void InitializeServer(int targetPlayerIndex, string videoName, float durationSeconds) { //IL_004d: Unknown result type (might be due to invalid IL or missing references) //IL_0052: Unknown result type (might be due to invalid IL or missing references) //IL_005e: Unknown result type (might be due to invalid IL or missing references) if (((NetworkBehaviour)this).IsServer) { ResolveReferences(); _videoName = videoName ?? string.Empty; _forcedDurationSeconds = Mathf.Max(0f, durationSeconds); PlayerControllerB player = FlyingTVManager.GetPlayer(targetPlayerIndex); if (FlyingTVManager.IsValidLivingPlayer(player)) { _assignedPlayerIndex = targetPlayerIndex; _lastKnownTargetPosition = ((Component)player).transform.position; StartFacilitySearch(((Component)player).transform.position, 70f); } } } internal bool IsEngagedWith(int playerIndex) { if (!((NetworkBehaviour)this).IsSpawned || base.isEnemyDead || base.currentBehaviourStateIndex == 5) { return false; } if (_assignedPlayerIndex != playerIndex) { if ((Object)(object)base.targetPlayer != (Object)null) { return (int)base.targetPlayer.playerClientId == playerIndex; } return false; } return true; } private void SyncTargetSlot() { int num = (((Object)(object)base.targetPlayer != (Object)null) ? ((int)base.targetPlayer.playerClientId) : _assignedPlayerIndex); if (_networkTargetSlot.Value != num) { _networkTargetSlot.Value = num; } } private bool LocalPlayerIsTarget() { PlayerControllerB val = (((Object)(object)GameNetworkManager.Instance != (Object)null) ? GameNetworkManager.Instance.localPlayerController : null); if ((Object)(object)val == (Object)null) { return false; } if (!((NetworkBehaviour)this).IsServer) { return _networkTargetSlot.Value == (int)val.playerClientId; } return (Object)(object)base.targetPlayer == (Object)(object)val; } private void PauseServerTimers(float deltaTime) { _nextAttackTime += deltaTime; if (_attackLostAggroSince >= 0f) { _attackLostAggroSince += deltaTime; } _approachProgressSince += deltaTime; if (_unreachableSince >= 0f) { _unreachableSince += deltaTime; } if (_videoActive) { _videoPresentationStartTime += deltaTime; _serverVideoEndTime += deltaTime; _serverNoncomplianceEnableTime += deltaTime; } if (_lastGreetingTickTime >= 0f) { _lastGreetingTickTime += deltaTime; } if (_lastComplianceTickTime >= 0f) { _lastComplianceTickTime += deltaTime; } if (_lastHuntTickTime >= 0f) { _lastHuntTickTime += deltaTime; } if (base.currentBehaviourStateIndex == 5) { _leaveMovementStartTime += deltaTime; _leaveDeadline += deltaTime; } } private void StartApproach() { if (base.currentBehaviourStateIndex == 0) { StopSearchIfNeeded(clear: false); base.movingTowardsTargetPlayer = true; base.moveTowardsDestination = true; if ((Object)(object)base.targetPlayer != (Object)null) { ((EnemyAI)this).SetMovingTowardsTargetPlayer(base.targetPlayer); } ((EnemyAI)(object)this).ReleaseAgent(); _targetInSight = true; ResetApproachProgress(); ((EnemyAI)this).SwitchToBehaviourState(1); _greetingGate.RestartApproach(); _lastGreetingTickTime = -1f; } } private void StartCheckPhase() { if (!_checkActive) { _checkActive = true; _playerMovementSamples.Clear(); _complianceGate.Reset(); _lastComplianceTickTime = -1f; base.movingTowardsTargetPlayer = false; base.moveTowardsDestination = false; StopAgentForHold(); ((EnemyAI)this).SwitchToBehaviourState(2); _checkRoutine = ((MonoBehaviour)this).StartCoroutine(CheckRoutine()); } } private IEnumerator CheckRoutine() { while (((NetworkBehaviour)this).IsServer && !base.isEnemyDead && _checkActive && base.currentBehaviourStateIndex == 2 && FlyingTVManager.IsValidLivingPlayer(base.targetPlayer)) { if (IsFrozen) { _playerMovementSamples.Clear(); yield return null; continue; } PlayerControllerB targetPlayer = base.targetPlayer; float time = Time.time; float playerStopWindowSeconds = PlayerStopWindowSeconds; Vector3 position = ((Component)targetPlayer).transform.position; _playerMovementSamples.Add(new PlayerMovementSample(time, position)); float num = time - playerStopWindowSeconds; while (_playerMovementSamples.Count > 1 && _playerMovementSamples[1].Timestamp <= num) { _playerMovementSamples.RemoveAt(0); } bool flag = _playerMovementSamples[0].Timestamp <= num; if (flag) { for (int i = 0; i < _playerMovementSamples.Count; i++) { if (Vector3.Distance(position, _playerMovementSamples[i].Position) > PlayerStopThreshold) { flag = false; break; } } } bool flag2 = flag && IsWithinFollowRange(targetPlayer); if (_greetingGate.Greeted) { bool flag3 = flag2 && IsPlayerLookingAwayFromTV(targetPlayer, WardenGazePhase.StopCheck); WardenComplianceEvent verdict = _complianceGate.Tick(TakeComplianceTickSeconds(), flag3, VideoNoncomplianceSustainSeconds, WarningGraceSeconds); bool flag4 = ApplyComplianceEvent(verdict, "Check", Vector3.Distance(position, ((Component)this).transform.position), flag3); if (flag4 || (flag2 && !flag3)) { _checkActive = false; _checkRoutine = null; _playerMovementSamples.Clear(); if (flag4) { StartAttack(); } else { StartVideoPhase(); } yield break; } } yield return (object)new WaitForSeconds(0.1f); } _checkActive = false; _checkRoutine = null; _playerMovementSamples.Clear(); } private void StartVideoPhase() { //IL_003f: Unknown result type (might be due to invalid IL or missing references) //IL_0044: Unknown result type (might be due to invalid IL or missing references) if (!_videoActive) { _videoActive = true; _complianceGate.RestartPhase(); _lastComplianceTickTime = -1f; _videoEndHoldLogged = false; _serverNoncomplianceEnableTime = float.PositiveInfinity; _videoHoldRotation = ((Component)this).transform.rotation; base.movingTowardsTargetPlayer = false; base.moveTowardsDestination = false; StopAgentForHold(); ((EnemyAI)this).SwitchToBehaviourState(3); _networkHumActive.Value = true; float num = ResolveVideoDuration(); float currentVoiceRemainingSeconds = GetCurrentVoiceRemainingSeconds(); _serverVideoEndTime = Time.time + currentVoiceRemainingSeconds + num; if (_videoRoutine != null) { ((MonoBehaviour)this).StopCoroutine(_videoRoutine); } _videoRoutine = ((MonoBehaviour)this).StartCoroutine(VideoStartAndMonitorRoutine(currentVoiceRemainingSeconds, num)); } } private float ResolveVideoDuration() { if (_forcedDurationSeconds > 0f) { return _forcedDurationSeconds; } return 300f; } private IEnumerator VideoStartAndMonitorRoutine(float videoStartDelay, float videoDuration) { _videoPresentationStartTime = Time.time + Mathf.Max(0f, videoStartDelay); while (_videoActive && !base.isEnemyDead && (Object)(object)base.targetPlayer != (Object)null && (IsFrozen || Time.time < _videoPresentationStartTime)) { yield return null; } if (!_videoActive || base.isEnemyDead || (Object)(object)base.targetPlayer == (Object)null) { _videoRoutine = null; yield break; } if (YoutubeVideoResolver.IsYoutubeUrl(_videoName) && LocalPlayerIsTarget()) { Task<YoutubeVideoStreams> localPrefetchTask = YoutubeVideoResolver.ResolveAsync(_videoName); float prefetchDeadline = Time.time + 90f; while (_videoActive && !base.isEnemyDead && (Object)(object)base.targetPlayer != (Object)null && (IsFrozen || (!localPrefetchTask.IsCompleted && Time.time < prefetchDeadline))) { if (IsFrozen) { prefetchDeadline += Time.deltaTime; } yield return null; } if (!_videoActive || base.isEnemyDead || (Object)(object)base.targetPlayer == (Object)null) { _videoRoutine = null; yield break; } if (!localPrefetchTask.IsCompleted) { ManualLogSource log = Plugin.Log; if (log != null) { log.LogWarning((object)"[FlyingTV] YouTube prefetch did not finish before the presentation deadline."); } } } double playbackStartServerTime = GetSynchronizedServerTime() + 0.3499999940395355; _serverVideoEndTime = Time.time + 0.35f + videoDuration; _serverNoncomplianceEnableTime = Time.time + 0.35f + 5f; StartPlaybackClientRpc(_videoName, _forcedDurationSeconds, playbackStartServerTime); _playbackBroadcast = true; while (_videoActive && !base.isEnemyDead && (Object)(object)base.targetPlayer != (Object)null) { if (IsFrozen) { yield return null; continue; } if (TickVideoCompliance(base.targetPlayer)) { _videoActive = false; _videoRoutine = null; StartAttack(); yield break; } if (Time.time >= _serverVideoEndTime && !HoldVideoEndForInfraction()) { CompleteVideoAndLeave(); _videoRoutine = null; yield break; } yield return (object)new WaitForSeconds(0.25f); } CompleteVideoAndLeave(); _videoRoutine = null; } private void StartAttack() { //IL_0045: Unknown result type (might be due to invalid IL or missing references) //IL_004a: Unknown result type (might be due to invalid IL or missing references) //IL_0051: Unknown result type (might be due to invalid IL or missing references) //IL_0056: Unknown result type (might be due to invalid IL or missing references) if (base.currentBehaviourStateIndex != 4) { StopAllServerRoutines(); StopBroadcastPlayback(); StopSearchIfNeeded(clear: false); base.movingTowardsTargetPlayer = true; base.moveTowardsDestination = true; if ((Object)(object)base.targetPlayer != (Object)null) { _lastKnownTargetPosition = ((Component)base.targetPlayer).transform.position; _huntLastSeenPosition = _lastKnownTargetPosition; ((EnemyAI)this).SetMovingTowardsTargetPlayer(base.targetPlayer); } _hunt.Begin(); _lastHuntTickTime = -1f; ((EnemyAI)(object)this).ReleaseAgent(); ((EnemyAI)this).SwitchToBehaviourState(4); _networkHumActive.Value = false; _attackLostAggroSince = -1f; PlayVoiceLine(1); } } private void StartLeave(float movementDelaySeconds = 0f) { //IL_0040: Unknown result type (might be due to invalid IL or missing references) //IL_0045: Unknown result type (might be due to invalid IL or missing references) if (base.currentBehaviourStateIndex != 5) { StopAllServerRoutines(); StopBroadcastPlayback(); StopSearchIfNeeded(clear: false); base.movingTowardsTargetPlayer = false; base.moveTowardsDestination = false; ((EnemyAI)this).SwitchToBehaviourState(5); _networkHumActive.Value = false; _leaveAwayDirection = ResolveLeaveAwayDirection(); _leaveMovementStartTime = Time.time + Mathf.Max(0f, movementDelaySeconds); _leaveDeadline = _leaveMovementStartTime + 10f; _leaveMovementStarted = false; _leaveHasDestination = false; _exitRiseOffset = 0f; StopAgentForHold(); if (movementDelaySeconds <= 0f) { BeginLeaveMovement(); } } } private Vector3 ResolveLeaveAwayDirection() { //IL_0020: 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_0035: Unknown result type (might be due to invalid IL or missing references) //IL_0045: Unknown result type (might be due to invalid IL or missing references) //IL_004a: Unknown result type (might be due to invalid IL or missing references) //IL_004f: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Unknown result type (might be due to invalid IL or missing references) if (!((Object)(object)base.targetPlayer != (Object)null)) { return ((Component)this).transform.forward; } return FlyingTVManager.FlatDirection(((Component)this).transform.position - ((Component)base.targetPlayer).transform.position, -((Component)base.targetPlayer).transform.forward); } private void BeginLeaveMovement() { if (!_leaveMovementStarted) { _leaveMovementStarted = true; ((EnemyAI)(object)this).ReleaseAgent(); PickLeaveDestination(); } } private void PickLeaveDestination() { //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_004d: Unknown result type (might be due to invalid IL or missing references) //IL_0052: Unknown result type (might be due to invalid IL or missing references) //IL_0062: Unknown result type (might be due to invalid IL or missing references) //IL_0067: Unknown result type (might be due to invalid IL or missing references) //IL_006c: Unknown result type (might be due to invalid IL or missing references) //IL_0079: Unknown result type (might be due to invalid IL or missing references) //IL_007b: 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_0096: Unknown result type (might be due to invalid IL or missing references) //IL_0098: Unknown result type (might be due to invalid IL or missing references) //IL_0099: Unknown result type (might be due to invalid IL or missing references) //IL_009e: Unknown result type (might be due to invalid IL or missing references) //IL_00bb: Unknown result type (might be due to invalid IL or missing references) //IL_00c6: Unknown result type (might be due to invalid IL or missing references) //IL_00c8: Unknown result type (might be due to invalid IL or missing references) if (FlyingTVManager.IsValidLivingPlayer(base.targetPlayer)) { _leaveAwayDirection = ResolveLeaveAwayDirection(); } _leaveHasDestination = false; if (AgentReady) { int areaMask = ((base.agent.areaMask != 0) ? base.agent.areaMask : (-1)); Vector3 val = ((Component)this).transform.position - Vector3.up * base.agent.baseOffset; for (int i = 0; i < LeaveSampleDistances.Length; i++) { float num = LeaveSampleDistances[i]; if (TrySampleNavMesh(val + _leaveAwayDirection * num, num, areaMask, out var position)) { Vector3 val2 = position - val; val2.y = 0f; if (!(((Vector3)(ref val2)).sqrMagnitude < 4f) && ((EnemyAI)this).SetDestinationToPosition(position, true)) { _leaveDestination = position; _leaveHasDestination = true; return; } } } } ManualLogSource log = Plugin.Log; if (log != null) { log.LogInfo((object)"[FlyingTV] No path to a leave point; holding here and rising out of sight."); } base.moveTowardsDestination = false; StopAgentForHold(); } private bool HasReachedLeaveDestination() { //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Unknown result type (might be due to invalid IL or missing references) //IL_0035: Unknown result type (might be due to invalid IL or missing references) if (!_leaveHasDestination || !AgentReady || base.agent.pathPending) { return false; } Vector3 val = _leaveDestination - ((Component)this).transform.position; val.y = 0f; if (!(((Vector3)(ref val)).sqrMagnitude <= 2.25f)) { return !base.agent.hasPath; } return true; } private void TriggerDeathExplosionPresentation(Vector3 position) { //IL_0043: Unknown result type (might be due to invalid IL or missing references) //IL_0050: Unknown result type (might be due to invalid IL or missing references) //IL_0057: Unknown result type (might be due to invalid IL or missing references) if (!_deathExplosionTriggered) { _deathExplosionTriggered = true; StopLocalPlayback(resumeStatic: false); StopPropellerLoop(); StopHumLoop(); StopSmokeLoop(); if ((Object)(object)_voiceSource != (Object)null) { _voiceSource.Stop(); } PlayDetachedExplosionAudio(position); HideDeathBody(); SpawnVanillaDeathExplosions(position); ApplyLocalDeathExplosionKnockback(position); } } private void SpawnVanillaDeathExplosions(Vector3 position) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Unknown result type (might be due to invalid IL or missing references) //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_003f: Unknown result type (might be due to invalid IL or missing references) //IL_0044: Unknown result type (might be due to invalid IL or missing references) Vector3 val = position + Vector3.up * 0.7f; SpawnVanillaExplosionVisual(val); SpawnVanillaExplosionVisual(val + Vector3.up * 0.9f); SpawnVanillaExplosionVisual(val - Vector3.up * 0.45f); } private static void SpawnVanillaExplosionVisual(Vector3 position) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) Landmine.SpawnExplosion(position, true, 0f, 0f, 0, 0f, (GameObject)null, false); } private void ApplyLocalDeathExplosionKnockback(Vector3 position) { //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Unknown result type (might be due to invalid IL or missing references) //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_0047: Unknown result type (might be due to invalid IL or missing references) //IL_0048: Unknown result type (might be due to invalid IL or missing references) //IL_0052: Unknown result type (might be due to invalid IL or missing references) //IL_0057: Unknown result type (might be due to invalid IL or missing references) //IL_0062: Unknown result type (might be due to invalid IL or missing references) //IL_0067: Unknown result type (might be due to invalid IL or missing references) //IL_0071: Unknown result type (might be due to invalid IL or missing references) //IL_0076: Unknown result type (might be due to invalid IL or missing references) //IL_00c4: Unknown result type (might be due to invalid IL or missing references) //IL_00d9: Unknown result type (might be due to invalid IL or missing references) //IL_00de: Unknown result type (might be due to invalid IL or missing references) //IL_00f3: Unknown result type (might be due to invalid IL or missing references) //IL_00f8: Unknown result type (might be due to invalid IL or missing references) //IL_00fd: Unknown result type (might be due to invalid IL or missing references) //IL_0101: Unknown result type (might be due to invalid IL or missing references) //IL_0106: Unknown result type (might be due to invalid IL or missing references) //IL_0108: Unknown result type (might be due to invalid IL or missing references) //IL_010d: Unknown result type (might be due to invalid IL or missing references) //IL_00a9: Unknown result type (might be due to invalid IL or missing references) //IL_00ae: Unknown result type (might be due to invalid IL or missing references) PlayerControllerB val = (((Object)(object)GameNetworkManager.Instance != (Object)null) ? GameNetworkManager.Instance.localPlayerController : null); if (!FlyingTVManager.IsValidLivingPlayer(val)) { return; } Vector3 val2 = ((Component)val).transform.position - position; float magnitude = ((Vector3)(ref val2)).magnitude; if (!(magnitude > 10f) && !Physics.Linecast(position + Vector3.up * 0.7f, ((Component)val).transform.position + Vector3.up * 1f, GetWorldCollisionMask(), (QueryTriggerInteraction)1)) { val2.y = 0f; if (((Vector3)(ref val2)).sqrMagnitude < 0.01f) { val2 = ((Component)val).transform.forward; } float num = Mathf.Clamp01(1f - magnitude / 10f); Vector3 val3 = ((Vector3)(ref val2)).normalized * Mathf.Lerp(12f, 34f, num) + Vector3.up * Mathf.Lerp(4f, 9f, num); val.externalForces += val3; if ((Object)(object)val.playerBodyAnimator != (Object)null) { val.playerBodyAnimator.SetTrigger("Damage"); } } } private void HideDeathBody() { Renderer[] componentsInChildren = ((Component)this).GetComponentsInChildren<Renderer>(true); foreach (Renderer val in componentsInChildren) { if (!((Object)(object)val == (Object)null)) { val.enabled = false; val.forceRenderingOff = true; } } Collider[] componentsInChildren2 = ((Component)this).GetComponentsInChildren<Collider>(true); foreach (Collider val2 in componentsInChildren2) { if ((Object)(object)val2 != (Object)null) { val2.enabled = false; } } if ((Object)(object)_bodyRigidbody != (Object)null) { _bodyRigidbody.detectCollisions = false; } } private void PlayDetachedExplosionAudio(Vector3 position) { //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_005c: Expected O, but got Unknown AudioClip val = explosionClip; if (!((Object)(object)val == (Object)null)) { GameObject val2 = new GameObject("FlyingTVExplosionAudio"); val2.transform.position = position; AudioSource source = val2.AddComponent<AudioSource>(); ConfigureAudioSource(source); CreatureAudioSetup.ConfigureSpatial(source); CreatureAudioSetup.TransmitOneShot(source, val); Object.Destroy((Object)val2, val.length + 0.25f); } } private IEnumerator DeathDespawnRoutine() { yield return (object)new WaitForSeconds(0.35f); DespawnSelf(); _deathDespawnRoutine = null; } private void LoseAttackAggro(float ignoreDetectionSeconds, bool sweepLastKnown = true) { //IL_005a: Unknown result type (might be due to invalid IL or missing references) //IL_003b: Unknown result type (might be due to invalid IL or missing references) //IL_0040: Unknown result type (might be due to invalid IL or missing references) //IL_005f: Unknown result type (might be due to invalid IL or missing references) //IL_0083: Unknown result type (might be due to invalid IL or missing references) //IL_004d: Unknown result type (might be due to invalid IL or missing references) StopAllServerRoutines(); StopBroadcastPlayback(); _networkHumActive.Value = false; _attackLostAggroSince = -1f; _targetInSight = false; _ignoreDetectionUntil = Time.time + ignoreDetectionSeconds; Vector3 start = ((!sweepLastKnown || _lastKnownTargetPosition == Vector3.zero) ? ((Component)this).transform.position : _lastKnownTargetPosition); base.targetPlayer = null; base.movingTowardsTargetPlayer = false; base.moveTowardsDestination = true; ((EnemyAI)(object)this).ReleaseAgent(); ((EnemyAI)this).SwitchToBehaviourState(0); StartFacilitySearch(start, 52.5f); } private void GiveUpAndLeave() { _attackLostAggroSince = -1f; _targetInSight = false; StartLeave(); base.targetPlayer = null; } private void StopBroadcastPlayback() { if (_playbackBroadcast) { _playbackBroadcast = false; StopPlaybackClientRpc(); } } private void StopAllServerRoutines() { if (_checkRoutine != null) { ((MonoBehaviour)this).StopCoroutine(_checkRoutine); _checkRoutine = null; } if (_videoRoutine != null) { ((MonoBehaviour)this).StopCoroutine(_videoRoutine); _videoRoutine = null; } _checkActive = false; _videoActive = false; _playerMovementSamples.Clear(); } private void TriggerNonComplianceFromAttack(PlayerControllerB attacker) { //IL_004c: Unknown result type (might be due to invalid IL or missing references) //IL_0051: Unknown result type (might be due to invalid IL or missing references) if (((NetworkBehaviour)this).IsServer && !base.isEnemyDead && FlyingTVManager.IsValidLivingPlayer(attacker)) { bool num = WardenEncounterMath.ShouldReseedHuntOnHit(base.currentBehaviourStateIndex == 4, (Object)(object)attacker == (Object)(object)base.targetPlayer, _hunt.Phase); base.targetPlayer = attacker; _lastKnownTargetPosition = ((Component)attacker).transform.position; if (num) { RetargetHunt(attacker); } else if (base.currentBehaviourStateIndex != 4 && base.currentBehaviourStateIndex != 6 && base.currentBehaviourStateIndex != 5) { StartAttack(); } } } private void RetargetHunt(PlayerControllerB attacker) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) _huntLastSeenPosition = ((Component)attacker).transform.position; _hunt.Begin(); _lastHuntTickTime = -1f; ChaseHuntTarget(attacker); ManualLogSource log = Plugin.Log; if (log != null) { log.LogInfo((object)$"[FlyingTV] Hunt: hit by player index {attacker.playerClientId}; hunting them."); } } private void RegisterDamageHit() { _damageHitCount = Mathf.Clamp(_damageHitCount + 1, 0, 10); _roamAngle += Random.Range(12f, 38f); } private void PublishDamageStage() { int num = WardenEncounterMath.DamageStage(_damageHitCount); _networkDamageStage.Value = num; _networkTiltDegrees.Value = WardenEncounterMath.TiltDegrees(num, TiltPerHitDegrees); } private void PlayHitFeedback() { CreatureAudioSetup.TransmitOneShot(_sfxSource, hitClankClip); if (_hasHitTrigger && (Object)(object)base.creatureAnimator != (Object)null) { base.creatureAnimator.SetTrigger(HitHash); } } private void BeginDamageStunFreeze() { if (!(Time.time < _damageFreezeImmuneUntil)) { _damageStunUntil = Time.time + 0.3f; _damageFreezeImmuneUntil = _damageStunUntil + 1.5f; ApplyDamageStunFreeze(); } } private bool ApplyDamageStunFreeze() { if (!IsFrozen) { bool damageStunFrozen = _damageStunFrozen; ClearDamageStunFreeze(); if (damageStunFrozen) { ResumeVideoAfterFreeze(); if (((NetworkBehaviour)this).IsServer && !IsInStationaryHold()) { ((EnemyAI)(object)this).ReleaseAgent(); } } return false; } ((EnemyAI)(object)this).HoldAgent(); if (!_damageStunFrozen) { _preDamageStunAnimatorSpeed = (((Object)(object)base.creatureAnimator != (Object)null) ? Mathf.Max(0.01f, base.creatureAnimator.speed) : 1f); _damageStunFrozen = true; PauseVideoForFreeze(); } if ((Object)(object)base.creatureAnimator != (Object)null) { base.creatureAnimator.speed = 0f; } return true; } private bool IsInStationaryHold() { return base.currentBehaviourStateIndex switch { 2 => !base.movingTowardsTargetPlayer, 3 => true, 5 => !_leaveMovementStarted, _ => false, }; } private void PauseVideoForFreeze() { if (!((Object)(object)_videoPlayer == (Object)null) && _videoPlayer.isPlaying) { _videoPlayer.Pause(); _videoPausedForFreeze = true; } } private void ResumeVideoAfterFreeze() { if (_videoPausedForFreeze) { _videoPausedForFreeze = false; if ((Object)(object)_videoPlayer != (Object)null && _selectedVideoPlaying && _videoPlayer.isPrepared) { _videoPlayer.Play(); } } } private void PauseLocalVideoTimers(float deltaTime) { if (_selectedVideoPlaying) { _videoFreezePausedSeconds += deltaTime; _localVideoEndTime += deltaTime; } } private void ClearDamageStunFreeze() { if (_damageStunFrozen) { if ((Object)(object)base.creatureAnimator != (Object)null) { base.creatureAnimator.speed = _preDamageStunAnimatorSpeed; } _damageStunFrozen = false; } } private void ConfigureSearchDefaults() { //IL_0009: Unknown result type (might be due to invalid IL or missing references) //IL_0013: Expected O, but got Unknown if (facilitySearch == null) { facilitySearch = new AISearchRoutine(); } facilitySearch.loopSearch = true; facilitySearch.randomized = true; facilitySearch.onlySearchNodesInLOS = false; facilitySearch.searchPrecision = 4f; if (facilitySearch.searchWidth <= 0f) { facilitySearch.searchWidth = 70f; } } private void EnsureRoamingSearch() { //IL_0071: Unknown result type (might be due to invalid IL or missing references) //IL_0058: Unknown result type (might be due to invalid IL or missing references) if (((NetworkBehaviour)this).IsServer && !base.isEnemyDead && base.currentBehaviourStateIndex == 0 && (facilitySearch == null || base.currentSearch != facilitySearch || !facilitySearch.inProgress) && !(Time.time < _nextRoamSearchRetargetTime)) { if (_hasPendingSearchSeed) { StartFacilitySearch(_pendingSearchSeed, _pendingSearchWidth); } else { StartFacilitySearch(((Component)this).transform.position, 70f); } } } private void StartFacilitySearch(Vector3 start, float width, bool recentre = false) { //IL_004b: Unknown result type (might be due to invalid IL or missing references) //IL_004c: Unknown result type (might be due to invalid IL or missing references) //IL_0098: Unknown result type (might be due to invalid IL or missing references) if (!((NetworkBehaviour)this).IsServer || base.isEnemyDead) { return; } ConfigureSearchDefaults(); facilitySearch.searchWidth = Mathf.Clamp(width, 8f, 160f); facilitySearch.searchPrecision = 4f; if (!CanUseVanillaSearch()) { _pendingSearchSeed = start; _pendingSearchWidth = width; _hasPendingSearchSeed = true; _nextRoamSearchRetargetTime = Time.time + 0.5f; return; } _hasPendingSearchSeed = false; if (!facilitySearch.inProgress || recentre) { ((EnemyAI)this).StopSearch(facilitySearch, true); } ((EnemyAI)this).StartSearch(start, facilitySearch); _nextRoamSearchRetargetTime = Time.time + Random.Range(3.5f, 7.5f); } private bool CanUseVanillaSearch() { if (((NetworkBehaviour)this).IsServer && AgentReady && base.allAINodes != null) { return base.allAINodes.Length != 0; } return false; } private void StopSearchIfNeeded(bool clear) { if (((NetworkBehaviour)this).IsServer && base.currentSearch != null && base.currentSearch.inProgress) { ((EnemyAI)this).StopSearch(base.currentSearch, clear); } } private void UpdateRoamingSearch() { EnsureRoamingSearch(); float damageWobbleAmount = DamageWobbleAmount; _roamAngle += Time.deltaTime * (0.6f + damageWobbleAmount * 0.45f); FaceTravelDirection(); } private void FaceTravelDirection() { //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_0028: Unknown result type (might be due to invalid IL or missing references) //IL_007e: Unknown result type (might be due to invalid IL or missing references) //IL_0083: Unknown result type (might be due to invalid IL or missing references) //IL_0088: Unknown result type (might be due to invalid IL or missing references) //IL_004a: Unknown result type (might be due to invalid IL or missing references) //IL_004f: Unknown result type (might be due to invalid IL or missing references) //IL_0054: Unknown result type (might be due to invalid IL or missing references) //IL_0095: Unknown result type (might be due to invalid IL or missing references) //IL_009a: Unknown result type (might be due to invalid IL or missing references) //IL_00ab: Unknown result type (might be due to invalid IL or missing references) Vector3 val = (((Object)(object)base.agent != (Object)null && ((Behaviour)base.agent).enabled) ? base.agent.velocity : Vector3.zero); val.y = 0f; Quaternion val2 = ((!(((Vector3)(ref val)).sqrMagnitude > 0.04f)) ? FlyingTVManager.BuildScreenFacingRotation(new Vector3(Mathf.Cos(_roamAngle * 0.5f), 0f, Mathf.Sin(_roamAngle * 0.5f))) : FlyingTVManager.BuildScreenFacingRotation(((Vector3)(ref val)).normalized)); ((Component)this).transform.rotation = Quaternion.Slerp(((Component)this).transform.rotation, val2, Mathf.Clamp01(Time.deltaTime * 2.5f)); } private PlayerControllerB FindDetectedPlayer() { float num = Mathf.Max(1f, FlyingTVConfig.DetectionRange.Value); float num2 = Mathf.Clamp(FlyingTVConfig.DetectionConeDegrees.Value, 10f, 360f); int num3 = Mathf.RoundToInt(3f); PlayerControllerB val = ((EnemyAI)this).CheckLineOfSightForPlayer(num2 * 0.5f, Mathf.RoundToInt(num), num3); if (!FlyingTVManager.IsValidLivingPlayer(val) || !((EnemyAI)this).PlayerIsTargetable(val, false, false, true)) { return null; } return val; } private void UpdateServerMovement() { //IL_0084: Unknown result type (might be due to invalid IL or missing references) int currentBehaviourStateIndex = base.currentBehaviourStateIndex; if (currentBehaviourStateIndex == 6) { return; } RepairOffNavMeshIfNeeded(); ApplyHoverHeight(); ApplyAgentStateSettings(); switch (currentBehaviourStateIndex) { case 0: UpdateRoamingSearch(); return; case 5: UpdateLeave(); return; } PlayerControllerB targetPlayer = base.targetPlayer; if (!FlyingTVManager.IsValidLivingPlayer(targetPlayer)) { return; } switch (currentBehaviourStateIndex) { case 1: FaceTarget(targetPlayer); if (!_checkActive && IsWithinFollowRange(targetPlayer)) { StartCheckPhase(); } break; case 2: FollowTargetDuringCheck(targetPlayer); break; case 3: TrackTargetDuringVideo(targetPlayer); ((Component)this).transform.rotation = _videoHoldRotation; break; case 4: if (_hunt.Phase == WardenHuntPhase.Chasing) { FaceTarget(targetPlayer); } else { FaceTravelDirection(); } break; } } private void StopAgentForHold() { //IL_002d: Unknown result type (might be due to invalid IL or missing references) StopSearchIfNeeded(clear: false); if (AgentReady) { base.agent.isStopped = true; base.agent.ResetPath(); base.agent.velocity = Vector3.zero; } } private void FollowTargetDuringCheck(PlayerControllerB target) { FaceTarget(target); if (IsWithinFollowRange(target)) { if (base.movingTowardsTargetPlayer || base.moveTowardsDestination || (AgentReady && !base.agent.isStopped)) { base.movingTowardsTargetPlayer = false; base.moveTowardsDestination = false; StopAgentForHold(); } return; } int num; if (base.movingTowardsTargetPlayer) { num = ((!base.moveTowardsDestination) ? 1 : 0); if (num == 0) { goto IL_0076; } } else { num = 1; } base.movingTowardsTargetPlayer = true; base.moveTowardsDestination = true; ((EnemyAI)this).SetMovingTowardsTargetPlayer(target); goto IL_0076; IL_0076: if (num != 0 || (AgentReady && base.agent.isStopped)) { ((EnemyAI)(object)this).ReleaseAgent(); } } private bool IsWithinFollowRange(PlayerControllerB target) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Unknown result type (might be due to invalid IL or missing references) Vector3 val = ((Component)target).transform.position - ((Component)this).transform.position; val.y = 0f; if (((Vector3)(ref val)).sqrMagnitude <= FollowDistance * FollowDistance) { return _targetInSight; } return false; } private void UpdateLeave() { if (FlyingTVManager.IsValidLivingPlayer(base.targetPlayer)) { FaceTarget(base.targetPlayer); } if (!(Time.time < _leaveMovementStartTime)) { BeginLeaveMovement(); } } private bool IsTargetInStrikeReach(PlayerControllerB target) { //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_004e: Unknown result type (might be due to invalid IL or missing references) //IL_004f: Unknown result type (might be due to invalid IL or missing references) //IL_0050: Unknown result type (might be due to invalid IL or missing references) //IL_0055: Unknown result type (might be due to invalid IL or missing references) //IL_0069: Unknown result type (might be due to invalid IL or missing references) //IL_0085: Unknown result type (might be due to invalid IL or missing references) //IL_0086: Unknown result type (might be due to invalid IL or missing references) //IL_0090: Unknown result type (might be due to invalid IL or missing references) //IL_0095: Unknown result type (might be due to invalid IL or missing references) //IL_009a: Unknown result type (might be due to invalid IL or missing references) //IL_009d: Unknown result type (might be due to invalid IL or missing references) //IL_009e: Unknown result type (might be due to invalid IL or missing references) //IL_00a8: Unknown result type (might be due to invalid IL or missing references) //IL_00aa: Unknown result type (might be due to invalid IL or missing references) if (!((EnemyAI)this).PlayerIsTargetable(target, false, false, true)) { return false; } Vector3 position = ((Component)this).transform.position; Vector3 position2 = ((Component)target).transform.position; float num = position.y - (((Object)(object)base.agent != (Object)null) ? base.agent.baseOffset : 0f); Vector3 val = position2 - position; val.y = 0f; if (!WardenEncounterMath.IsWithinStrikeReach(((Vector3)(ref val)).magnitude, position2.y - num, StrikeReach, 1.6f)) { return false; } Vector3 val2 = position2 + Vector3.up * 1.4f; if (!IsSightLineBlocked(position, val2)) { return !IsSightLineBlocked(val2, position); } return false; } [ClientRpc] private void ApplyAttackDamageClientRpc(ulong targetClientId, int damage, ClientRpcParams clientRpcParams = default(ClientRpcParams)) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Invalid comparison between Unknown and I4 //IL_00a6: Unknown result type (might be due to invalid IL or missing references) //IL_00b0: Invalid comparison between Unknown and I4 //IL_005f: Unknown result type (might be due to invalid IL or missing references) //IL_0068: Unknown result type (might be due to invalid IL or missing references) //IL_006d: Unknown result type (might be due to invalid IL or missing references) //IL_0071: Unknown result type (might be due to invalid IL or missing references) //IL_007e: Unknown result type (might be due to invalid IL or missing references) //IL_0096: Unknown result type (might be due to invalid IL or missing references) //IL_00db: Unknown result type (might be due to invalid IL or missing references) //IL_011f: Unknown result type (might be due to invalid IL or missing references) //IL_0125: Unknown result type (might be due to invalid IL or missing references) NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager; if (networkManager == null || !networkManager.IsListening) { return; } if ((int)((NetworkBehaviour)this).__rpc_exec_stage != 1 && (networkManager.IsServer || networkManager.IsHost)) { FastBufferWriter val = ((NetworkBehaviour)this).__beginSendClientRpc(333013693u, clientRpcParams, (RpcDelivery)0); BytePacker.WriteValueBitPacked(val, targetClientId); BytePacker.WriteValueBitPacked(val, damage); ((NetworkBehaviour)this).__endSendClientRpc(ref val, 333013693u, clientRpcParams, (RpcDelivery)0); } if ((int)((NetworkBehaviour)this).__rpc_exec_stage == 1 && (networkManager.IsClient || networkManager.IsHost)) { ((NetworkBehaviour)this).__rpc_exec_stage = (__RpcExecStage)0; PlayerControllerB val2 = (((Object)(object)GameNetworkManager.Instance != (Object)null) ? GameNetworkManager.Instance.localPlayerController : null); if (!((Object)(object)val2 == (Object)null) && !val2.isPlayerDead && VictimRpc.IsLocalVictim(targetClientId)) { val2.DamagePlayer(damage, true, true, (CauseOfDeath)1, 0, false, default(Vector3)); } } } private bool ShouldLoseAggro(PlayerControllerB target, float loseDistance, float loseSeconds) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Unknown result type (might be due to invalid IL or missing references) float num = Vector3.Distance(((Component)this).transform.position, ((Component)target).transform.position); bool flag = num >= loseDistance; bool flag2 = num > 3.2f && !_targetInSight; if (!flag && !flag2) { _attackLostAggroSince = -1f; return false; } if (_attackLostAggroSince < 0f) { _attackLostAggroSince = Time.time; return false; } return Time.time - _attackLostAggroSince >= loseSeconds; } private bool HasLineOfSightToTarget(PlayerControllerB target) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Unknown result type (might be due to invalid IL or missing references) return !IsSightLineBlocked(((Component)this).transform.position, ((Component)target).transform.position + Vector3.up * 1.4f); } private bool IsSightLineBlocked(Vector3 from, Vector3 to) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0001: Unknown result type (might be due to invalid IL or missing references) RaycastHit val = default(RaycastHit); if (Physics.Linecast(from, to, ref val, GetWorldCollisionMask(), (QueryTriggerInteraction)1)) { return !((RaycastHit)(ref val)).transform.IsChildOf(((Component)this).transform); } return false; } private void TickVisualHover() { //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_0098: Unknown result type (might be due to invalid IL or missing references) //IL_00a4: Unknown result type (might be due to invalid IL or missing references) //IL_00a9: Unknown result type (might be due to invalid IL or missing references) //IL_003e: Unknown result type (might be due to invalid IL or missing references) if (!((Object)(object)visualRoot == (Object)null)) { if (!_hasVisualBaseLocalPosition) { _visualBaseLocalPosition = visualRoot.localPosition; _hasVisualBaseLocalPosition = true; } if (base.isEnemyDead) { visualRoot.localPosition = _visualBaseLocalPosition; return; } float damageWobbleAmount = DamageWobbleAmount; float num = Time.time * 1.2f; float num2 = Mathf.Sin(num * 1.3f) * (0.16f + damageWobbleAmount * 0.09f); float num3 = Mathf.Sin(num * 1.7f + _roamAngle) * damageWobbleAmount * 0.11f; visualRoot.localPosition = _visualBaseLocalPosition + new Vector3(num3, num2, 0f); TickTilt(); float num4 = TickCloseUp(); SetStaticBurst(num4 > 0f && !_selectedVideoPlaying); SuspendSmokeForCloseUp(num4 > 0f); } } private void TickTilt() { //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_0047: Unknown result type (might be due to invalid IL or missing references) //IL_004c: Unknown result type (might be due to invalid IL or missing references) float num = _networkTiltDegrees.Value * _tiltSide; _currentTilt = Mathf.MoveTowards(_currentTilt, num, 60f * Time.deltaTime); visualRoot.localRotation = Quaternion.AngleAxis(_currentTilt, Vector3.forward) * _visualRootBaseLocalRotation; } private void BeginCloseUp(int targetSlot, AudioClip greeting) { if (FlyingTVManager.IsValidLivingPlayer(FlyingTVManager.GetPlayer(targetSlot))) { _closeUpActive = true; _closeUpStartTime = Time.time; _closeUpTargetSlot = targetSlot; _closeUpHoldSeconds = (((Object)(object)greeting != (Object)null) ? Mathf.Clamp(greeting.length - 0.35f, 0.5f, 3f) : 2f); } } private void EndCloseUpEarly() { if (_closeUpActive) { float num = 0.35f; float num2 = Time.time - _closeUpStartTime; if (num2 < num) { float num3 = num2 / num; _closeUpHoldSeconds = 0f; _closeUpStartTime = Time.time - (num + (1f - num3) * 0.6f); } else if (num2 < num + _closeUpHoldSeconds) { _closeUpHoldSeconds = num2 - num; } } } private float TickCloseUp() { //IL_0091: Unknown result type (might be due to invalid IL or missing references) //IL_0096: Unknown result type (might be due to invalid IL or missing references) //IL_0098: Unknown result type (might be due to invalid IL or missing references) //IL_00a0: Unknown result type (might be due to invalid IL or missing references) //IL_00a5: Unknown result type (might be due to invalid IL or missing references) //IL_00a7: Unknown result type (might be due to invalid IL or missing references) //IL_00ae: Unknown result type (might be due to invalid IL or missing references) //IL_00b3: Unknown result type (might be due to invalid IL or missing references) //IL_00bd: Unknown result type (might be due to invalid IL or missing references) //IL_00c2: Unknown result type (might be due to invalid IL or missing references) //IL_00c7: Unknown result type (might be due to invalid IL or missing references) //IL_00d5: Unknown result type (might be due to invalid IL or missing references) //IL_00da: Unknown result type (might be due to invalid IL or missing references) //IL_00de: Unknown result type (might be due to invalid IL or missing references) if (!_closeUpActive) { return 0f; } float num = Time.time - _closeUpStartTime; float num2 = 0.35f; float num3 = 0.6f; PlayerControllerB player = FlyingTVManager.GetPlayer(_closeUpTargetSlot); if (num >= num2 + _closeUpHoldSeconds + num3 || !FlyingTVManager.IsValidLivingPlayer(player) || (Object)(object)player.gameplayCamera == (Object)null) { _closeUpActive = false; return 0f; } float num4 = WardenEncounterMath.CloseUpWeight(num, num2, _closeUpHoldSeconds, num3); if (num4 <= 0f) { return 0f; } Transform transform = ((Component)player.gameplayCamera).transform; Vector3 position = transform.position; Vector3 val = position + FlyingTVManager.FlatDirection(((Component)this).transform.position - position, transform.forward) * 0.85f; visualRoot.position = Vector3.Lerp(visualRoot.position, val, num4); return num4; } private void SetStaticBurst(bool active) { if (active != _staticBurstActive) { _staticBurstActive = active; ApplyScreenEmission(); } } private void SuspendSmokeForCloseUp(bool suspend) { if (suspend != _smokeSuspendedForCloseUp) { _smokeSuspendedForCloseUp = suspend; if ((Object)(object)_damageVisual != (Object)null) { _damageVisual.SetStage((!suspend) ? _appliedDamageStage : 0); } } } private void ApplyReplicatedDamageStage() { int value = _networkDamageStage.Value; if (value != _appliedDamageStage) { _appliedDamageStage = value; if ((Object)(object)_damageVisual != (Object)null && !_smokeSuspendedForCloseUp) { _damageVisual.SetStage(value); } if (_hasDamageStageParameter && (Object)(object)base.creatureAnimator != (Object)null) { base.creatureAnimator.SetInteger(DamageStageHash, value); } UpdateSmokeLoop(value); } } private static int GetWorldCollisionMask() { if ((Object)(object)StartOfRound.Instance != (Object)null) { return StartOfRound.Instance.collidersAndRoomMaskAndDefault; } int mask = 1; AddLayerToMask(ref mask, "Room"); AddLayerToMask(ref mask, "MapProps"); AddLayerToMask(ref mask, "Colliders"); return mask; } private static void AddLayerToMask(ref int mask, string layerName) { int num = LayerMask.NameToLayer(layerName); if (num >= 0) { mask |= 1 << num; } } private void FaceTarget(PlayerControllerB target) { //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_0034: Unknown result type (might be due to invalid IL or missing references) //IL_0039: Unknown result type (might be due to invalid IL or missing references) //IL_004e: Unknown result type (might be due to invalid IL or missing references) //IL_0053: Unknown result type (might be due to invalid IL or missing references) //IL_007b: Unknown result type (might be due to invalid IL or missing references) //IL_0080: Unknown result type (might be due to invalid IL or missing references) //IL_0074: Unknown result type (might be due to invalid IL or missing references) //IL_0079: Unknown result type (might be due to invalid IL or missing references) //IL_009d: Unknown result type (might be due to invalid IL or missing references) //IL_00a4: Unknown result type (might be due to invalid IL or missing references) //IL_00a9: Unknown result type (might be due to invalid IL or missing references) //IL_00b4: Unknown result type (might be due to invalid IL or missing references) //IL_00b9: Unknown result type (might be due to invalid IL or missing references) //IL_00be: Unknown result type (might be due to invalid IL or missing references) //IL_00cb: Unknown result type (might be due to invalid IL or missing references) //IL_00d0: Unknown result type (might be due to invalid IL or missing references) //IL_00e1: Unknown result type (might be due to invalid IL or missing references) //IL_0095: Unknown result type (might be due to invalid IL or missing references) //IL_009a: Unknown result type (might be due to invalid IL or missing references) if (!((Object)(object)target == (Object)null)) { Vector3 val = ((Component)target).transform.position + Vector3.up * 1.4f - ((Component)this).transform.position; if (((Vector3)(ref val)).sqrMagnitude < 0.001f) { val = ((Component)this).transform.forward; } val.y = 0f; if (((Vector3)(ref val)).sqrMagnitude < 0.001f) { val = ((Component)this).transform.forward; } Vector3 val2 = GetCurrentScreenSideDirection(); if (((Vector3)(ref val2)).sqrMagnitude < 0.001f) { val2 = ((Component)this)
Y4NGZHarmonic.dll
Decompiled a day ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security.Cryptography; using System.Text; using System.Text.RegularExpressions; using System.Threading; using BepInEx; using BepInEx.Bootstrap; using BepInEx.Configuration; using BepInEx.Logging; using Dawn; using GameNetcodeStuff; using Microsoft.CodeAnalysis; using Unity.Netcode; using Unity.Netcode.Components; using UnityEngine; using UnityEngine.AI; using UnityEngine.Audio; using UnityEngine.Networking; using UnityEngine.Rendering.HighDefinition; using Y4NGZHarmonic.AI; using Y4NGZHarmonic.NetcodePatcher; using Y4NGZMonsters.Shared; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: AssemblyCompany("Y4NGZHarmonic")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0+3460ec64f0cec4948e51ddb3f02a4b0e414f105e")] [assembly: AssemblyProduct("Y4NGZHarmonic")] [assembly: AssemblyTitle("Y4NGZHarmonic")] [assembly: AssemblyVersion("1.0.0.0")] [module: RefSafetyRules(11)] [module: NetcodePatchedAssembly] 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 Y4NGZHarmonic { internal static class HarmonicBloodFxBridge { internal const string PluginGuid = "com.y4ngz.bloodfx"; private const string CreatureBloodTypeName = "Y4NGZCompany.Experience.BloodFX.BloodFXCreatureBlood"; private static bool? _pluginPresent; private static bool _bridgeResolved; private static PropertyInfo _isAvailable; private static MethodInfo _playCreatureBleed; internal static void PlayCreatureBleed(int creatureKey, Vector3 point, Vector3 direction, Color tint, int contacts, float scale) { //IL_0054: Unknown result type (might be due to invalid IL or missing references) //IL_005d: Unknown result type (might be due to invalid IL or missing references) //IL_0066: Unknown result type (might be due to invalid IL or missing references) if (!BloodFxPluginPresent() || !ResolveBridge()) { return; } try { if (_isAvailable != null) { object value = _isAvailable.GetValue(null); if (value is bool && !(bool)value) { return; } } _playCreatureBleed.Invoke(null, new object[6] { creatureKey, point, direction, tint, contacts, scale }); } catch (Exception ex) { ManualLogSource log = Plugin.Log; if (log != null) { log.LogWarning((object)("[Harmonic] Optional BloodFX bridge failed: " + ex.GetBaseException().Message)); } } } private static bool BloodFxPluginPresent() { if (!_pluginPresent.HasValue) { _pluginPresent = Chainloader.PluginInfos.ContainsKey("com.y4ngz.bloodfx"); } return _pluginPresent.Value; } private static bool ResolveBridge() { if (_bridgeResolved) { return _playCreatureBleed != null; } _bridgeResolved = true; if (!Chainloader.PluginInfos.TryGetValue("com.y4ngz.bloodfx", out var value) || (Object)(object)value.Instance == (Object)null) { return false; } Type type = ((object)value.Instance).GetType().Assembly.GetType("Y4NGZCompany.Experience.BloodFX.BloodFXCreatureBlood", throwOnError: false); if (type == null) { return false; } _isAvailable = type.GetProperty("IsAvailable", BindingFlags.Static | BindingFlags.Public); _playCreatureBleed = type.GetMethod("PlayCreatureBleed", BindingFlags.Static | BindingFlags.Public, null, new Type[6] { typeof(int), typeof(Vector3), typeof(Vector3), typeof(Color), typeof(int), typeof(float) }, null); return _playCreatureBleed != null; } } internal static class HarmonicBreath { internal static float AdvancePhase(float phase, float deltaSeconds, float cycleSeconds) { float num = phase + deltaSeconds / cycleSeconds; return num - (float)Math.Floor(num); } internal static float ScaleFactor(float phase) { float num = 0.5f - 0.5f * (float)Math.Cos(Math.PI * 2.0 * (double)phase); return 1f + 0.15f * num; } } internal sealed class HarmonicConfig { public ConfigEntry<bool> Enabled { get; } public ConfigEntry<float> SpawnWeightMultiplier { get; } public ConfigEntry<string> MoonWeightOverrides { get; } public ConfigEntry<int> MaxCount { get; } public ConfigEntry<float> PowerLevel { get; } public ConfigEntry<int> Health { get; } public ConfigEntry<float> MoveSpeed { get; } public ConfigEntry<float> AlarmChance { get; } public ConfigEntry<float> AlarmAttractionRadius { get; } public ConfigEntry<float> MusicVolume { get; } public ConfigEntry<float> SfxVolume { get; } public ConfigEntry<float> MusicMaxDistance { get; } public ConfigEntry<float> SfxMaxDistance { get; } public ConfigEntry<bool> DebugLogs { get; } public HarmonicConfig(ConfigFile config) { //IL_007a: Unknown result type (might be due to invalid IL or missing references) //IL_0084: Expected O, but got Unknown //IL_00c8: Unknown result type (might be due to invalid IL or missing references) //IL_00d2: Expected O, but got Unknown //IL_0101: Unknown result type (might be due to invalid IL or missing references) //IL_010b: Expected O, but got Unknown //IL_012f: Unknown result type (might be due to invalid IL or missing references) //IL_0139: Expected O, but got Unknown //IL_0168: Unknown result type (might be due to invalid IL or missing references) //IL_0172: Expected O, but got Unknown //IL_01a1: Unknown result type (might be due to invalid IL or missing references) //IL_01ab: Expected O, but got Unknown //IL_01da: Unknown result type (might be due to invalid IL or missing references) //IL_01e4: Expected O, but got Unknown //IL_0213: Unknown result type (might be due to invalid IL or missing references) //IL_021d: Expected O, but got Unknown //IL_024c: Unknown result type (might be due to invalid IL or missing references) //IL_0256: Expected O, but got Unknown //IL_0285: Unknown result type (might be due to invalid IL or missing references) //IL_028f: Expected O, but got Unknown //IL_02be: Unknown result type (might be due to invalid IL or missing references) //IL_02c8: Expected O, but got Unknown using (ConfigPersistence.BeginBinding(config, Plugin.Log, "Harmonic")) { HarmonicConfigMigration.TryMigrate(config, Plugin.Log); ConfigSectionNameMigration.TryMigrate(config, Plugin.Log, "Harmonic"); Enabled = config.Bind<bool>("General", "Enabled", true, "Enable the Harmonic encounter. Host-only: the host's value decides whether it spawns; every install still registers the creature so clients stay in sync."); SpawnWeightMultiplier = config.Bind<float>("Spawning", "SpawnWeightMultiplier", 1f, new ConfigDescription("Multiplier applied to Harmonic's contextual moon/interior spawn policy. 0 disables natural spawns.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 5f), Array.Empty<object>())); MoonWeightOverrides = config.Bind<string>("Spawning", "MoonWeightOverrides", string.Empty, "Optional comma-separated base moon weights, e.g. Experimentation:8,Offense:15 or namespace:moon=12. Use 0 to disable a moon; unlisted moons keep authored defaults."); MaxCount = config.Bind<int>("Spawning", "MaxCount", 1, new ConfigDescription("Maximum number of living Harmonics at once.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 20), Array.Empty<object>())); PowerLevel = config.Bind<float>("Spawning", "PowerLevel", 1.1f, new ConfigDescription("Indoor enemy power budget cost for each Harmonic.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.1f, 10f), Array.Empty<object>())); Health = config.Bind<int>("Core Stats", "Health", 4, new ConfigDescription("Hits the Harmonic can take before dying.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 100), Array.Empty<object>())); MoveSpeed = config.Bind<float>("Movement", "MoveSpeed", 1.15f, new ConfigDescription("Passive roaming speed.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.1f, 10f), Array.Empty<object>())); AlarmChance = config.Bind<float>("Abilities", "AlarmChance", 0.2f, new ConfigDescription("Chance that the next selected track will be the alarm.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 1f), Array.Empty<object>())); AlarmAttractionRadius = config.Bind<float>("Abilities", "AlarmAttractionRadius", 30f, new ConfigDescription("Maximum distance in metres at which an alarm attracts other indoor enemies.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 200f), Array.Empty<object>())); MusicVolume = config.Bind<float>("Audio and Presentation", "MusicVolume", 0.95f, new ConfigDescription("Volume for idle music.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 1f), Array.Empty<object>())); SfxVolume = config.Bind<float>("Audio and Presentation", "SfxVolume", 1f, new ConfigDescription("Shared volume for the alarm, hit, and death sounds.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 1f), Array.Empty<object>())); MusicMaxDistance = config.Bind<float>("Audio and Presentation", "MusicMaxDistance", 65f, new ConfigDescription("Maximum audible distance for Harmonic music.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(8f, 65f), Array.Empty<object>())); SfxMaxDistance = config.Bind<float>("Audio and Presentation", "SfxMaxDistance", 42f, new ConfigDescription("Maximum audible distance for alarm, hit, and death sounds.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(8f, 42f), Array.Empty<object>())); DebugLogs = config.Bind<bool>("Diagnostics", "DebugLogs", false, "Write verbose Harmonic diagnostics to the BepInEx log."); } } } internal static class HarmonicConfigMigration { private static readonly ConfigDefinition LegacySpawnWeight = new ConfigDefinition("Spawning", "SpawnWeight"); private static readonly LegacyMigrationSpec Spec = new LegacyMigrationSpec("Harmonic", (IReadOnlyList<ConfigDefinition>)(object)new ConfigDefinition[1] { LegacySpawnWeight }, null, new Dictionary<ConfigDefinition, string> { { new ConfigDefinition("Spawning", "LevelMask"), "-1" }, { new ConfigDefinition("Spawning", "SpawnType"), "Default" }, { new ConfigDefinition("Stats", "ModelScale"), "0.72" }, { new ConfigDefinition("Movement", "Acceleration"), "4.5" }, { new ConfigDefinition("Movement", "AngularSpeed"), "70" }, { new ConfigDefinition("Movement", "HoverHeight"), "0.55" }, { new ConfigDefinition("Movement", "RoamSearchWidth"), "120" }, { new ConfigDefinition("Movement", "RoamSearchPrecision"), "8" }, { new ConfigDefinition("Movement", "RoamStuckRecoverySeconds"), "3.5" }, { new ConfigDefinition("Movement", "MovementBobAmount"), "0.06" }, { new ConfigDefinition("Movement", "MovementTiltDegrees"), "4" }, { new ConfigDefinition("Collision", "BodyColliderRadius"), "0.32" }, { new ConfigDefinition("Collision", "BodyColliderHeight"), "1.25" }, { new ConfigDefinition("Alarm", "RefreshSeconds"), "0.35" }, { new ConfigDefinition("Audio", "AlarmVolume"), "1" }, { new ConfigDefinition("Audio", "DeathVolume"), "1" }, { new ConfigDefinition("Death", "HitInflateAmount"), "0.13" }, { new ConfigDefinition("Death", "DeathEffectScale"), "0.75" }, { new ConfigDefinition("Pulse", "IdlePulseRate"), "0.42" }, { new ConfigDefinition("Pulse", "WarningPulseRate"), "1.55" }, { new ConfigDefinition("Pulse", "PitchPulseAmount"), "0.025" }, { new ConfigDefinition("Pulse", "VolumePulseAmount"), "0.08" }, { new ConfigDefinition("Pulse", "WarningPitchMultiplier"), "1.18" }, { new ConfigDefinition("Pulse", "AnimationPulseAmount"), "0" }, { new ConfigDefinition("Pulse", "HornPulseScale"), "0.06" }, { new ConfigDefinition("Light", "BaseIntensity"), "45" }, { new ConfigDefinition("Light", "PulseIntensity"), "35" }, { new ConfigDefinition("Light", "Range"), "8.5" }, { new ConfigDefinition("Light", "EmissionIntensity"), "0.22" } }, Build); internal static bool TryMigrate(ConfigFile config, ManualLogSource log) { return LegacyConfigMigrator.TryMigrate(config, log, Spec); } private static void Build(LegacyConfigValues values, MigratedConfigWriter output) { //IL_0081: Unknown result type (might be due to invalid IL or missing references) //IL_0087: Expected O, but got Unknown //IL_00be: Unknown result type (might be due to invalid IL or missing references) //IL_00c4: Expected O, but got Unknown //IL_00e6: Unknown result type (might be due to invalid IL or missing references) //IL_00ec: Expected O, but got Unknown //IL_010e: Unknown result type (might be due to invalid IL or missing references) //IL_0114: Expected O, but got Unknown //IL_0136: Unknown result type (might be due to invalid IL or missing references) //IL_013c: Expected O, but got Unknown //IL_015e: Unknown result type (might be due to invalid IL or missing references) //IL_0164: Expected O, but got Unknown //IL_0186: Unknown result type (might be due to invalid IL or missing references) //IL_018c: Expected O, but got Unknown //IL_01ae: Unknown result type (might be due to invalid IL or missing references) //IL_01b4: Expected O, but got Unknown output.Carry("General", "Enabled"); output.CarrySpawnWeightMultiplier(LegacySpawnWeight, 18f); output.Carry("Spawning", "MoonWeightOverrides"); output.Carry("Spawning", "MaxCount"); output.Carry("Spawning", "PowerLevel"); output.Carry("Core Stats", "Health", new ConfigDefinition("Stats", "Health")); output.Carry("Movement", "MoveSpeed"); output.Carry("Abilities", "AlarmChance", new ConfigDefinition("Audio", "AlarmChance")); output.Carry("Abilities", "AlarmAttractionRadius", new ConfigDefinition("Alarm", "AttractionRadius")); output.Carry("Audio and Presentation", "MusicVolume", new ConfigDefinition("Audio", "IdleMusicVolume")); output.Carry("Audio and Presentation", "SfxVolume", new ConfigDefinition("Audio", "HitVolume")); output.Carry("Audio and Presentation", "MusicMaxDistance", new ConfigDefinition("Audio", "MusicMaxDistance")); output.Carry("Audio and Presentation", "SfxMaxDistance", new ConfigDefinition("Audio", "SfxMaxDistance")); output.Carry("Diagnostics", "DebugLogs", new ConfigDefinition("Debug", "DebugLogs")); } } internal enum GatherReissue { None, Arrived, Interval } internal static class HarmonicGather { internal static Vector3 CandidatePoint(Vector3 center, Vector2 unitDisc, float radius) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Unknown result type (might be due to invalid IL or missing references) return new Vector3(center.x + unitDisc.x * radius, center.y, center.z + unitDisc.y * radius); } internal static bool IsInsideArea(Vector3 center, Vector3 point, float radius) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Unknown result type (might be due to invalid IL or missing references) float num = point.x - center.x; float num2 = point.y - center.y; float num3 = point.z - center.z; return num * num + num2 * num2 + num3 * num3 <= radius * radius; } internal static GatherReissue Evaluate(Vector3 enemyPosition, Vector3 gatherPoint, float issuedAt, float now) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_0013: Unknown result type (might be due to invalid IL or missing references) float num = enemyPosition.x - gatherPoint.x; float num2 = enemyPosition.z - gatherPoint.z; float num3 = 2f; if (num * num + num2 * num2 <= num3 * num3) { return GatherReissue.Arrived; } if (now - issuedAt >= 8f) { return GatherReissue.Interval; } return GatherReissue.None; } } internal sealed class HarmonicSpawnWeights : ContextualSpawnWeights { internal HarmonicSpawnWeights(Func<float> multiplier, Func<string> moonOverrides, Action<string> logWarning) : base(SpawnWeightTable.Harmonic, "Harmonic", multiplier, moonOverrides, logWarning) { } } internal static class HarmonicTuning { internal const float ModelScale = 0.72f; internal const float Acceleration = 4.5f; internal const float AngularSpeed = 70f; internal const float HoverHeight = 0.55f; internal const float RoamSearchWidth = 120f; internal const float RoamSearchPrecision = 8f; internal const float RoamStuckRecoverySeconds = 3.5f; internal const float MovementBobAmount = 0.06f; internal const float MovementTiltDegrees = 4f; internal const float BodyColliderRadius = 0.32f; internal const float BodyColliderHeight = 1.25f; internal const float HitboxPadding = 0.06f; internal const float AlarmScanSeconds = 0.35f; internal const float AlarmGatherRadius = 12f; internal const float AlarmGatherInterval = 8f; internal const float AlarmGatherArrivalDistance = 2f; internal const int AlarmGatherPointAttempts = 6; internal const float AlarmGatherSampleDistance = 2.5f; internal const float HitInflateAmount = 0.13f; internal const float DeathEffectScale = 0.75f; internal const float HitFlinchSeconds = 0.45f; internal const float HitFlinchAttackSeconds = 0.05f; internal const float HitFlinchLeanDegrees = 16f; internal const float HitFlinchShoveMetres = 0.12f; internal const float HitFlinchDipMetres = 0.05f; internal const float HitFlinchPunch = 0.15f; internal const float HitLayerPitch = 0.7f; internal const float HitLayerVolume = 0.8f; internal const float IdlePulseRate = 0.42f; internal const float WarningPulseRate = 1.55f; internal const float PitchPulseAmount = 0.025f; internal const float VolumePulseAmount = 0.08f; internal const float WarningPitchMultiplier = 1.18f; internal const float BreathScaleAmplitude = 0.15f; internal const float BreathIdleCycleSeconds = 5f; internal const float BreathWarningCycleSeconds = 2.5f; internal const float BreathAlarmCycleSeconds = 1.25f; internal const string EmissiveColorProperty = "_EmissiveColor"; internal const float EmissionIntensity = 8f; } [BepInPlugin("y4ngz.lethalcompany.harmonic", "Y4NGZ Harmonic", "2.0.0")] [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInDependency(/*Could not decode attribute arguments.*/)] public sealed class Plugin : BaseUnityPlugin { internal const string BundleFilename = "harmonic.bundle"; internal const string PrefabName = "Harmonic"; internal const string DeathEffectName = "DustExplosion"; internal const string AudioFolderName = "Harmonic"; internal const string DawnNamespace = "y4ngz_monsters"; internal const string DawnEnemyKey = "harmonic"; internal const string BestiaryText = "Harmonic\n\nDanger level: ambient\n\nA passive floating organism that wanders facilities while playing warped music. Its alarm call can briefly draw other creatures toward its location.\n\n"; internal const float MusicMaxAudibleDistance = 65f; internal const float SfxMaxAudibleDistance = 42f; internal const float ClearAudioCutoff = 22000f; private const string BundleBuilderPath = "Assets/Y4NGZ/Harmonic/Editor/HarmonicAssetBuilder.cs"; private const int ScanNodeLayerFallback = 22; private const double AudioLoadTimeoutSeconds = 10.0; internal static ManualLogSource Log; internal static HarmonicConfig ModConfig; internal static AssetBundle ModAssets; internal static EnemyType EnemyType; internal static string AssemblyDirectory; private static bool _netcodeInitialized; private static Material _fallbackParticleMaterial; private static Texture2D _runtimeParticleTexture; private static readonly Color RuntimeParticleDustColor = new Color(0.52f, 0.5f, 0.46f, 0.72f); private static readonly Dictionary<Material, Material> RuntimeParticleMaterials = new Dictionary<Material, Material>(); private void Awake() { Log = ((BaseUnityPlugin)this).Logger; try { InitializeNetcodeRPCs(); ModConfig = new HarmonicConfig(((BaseUnityPlugin)this).Config); AssemblyDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); if (!LoadBundle()) { return; } GameObject val = ModAssets.LoadAsset<GameObject>("Harmonic"); if ((Object)(object)val == (Object)null) { Log.LogError((object)"Prefab 'Harmonic' not found in harmonic.bundle. Bundle contents:"); DumpBundleAssets(); return; } GameObject val2 = ModAssets.LoadAsset<GameObject>("DustExplosion"); if ((Object)(object)val2 == (Object)null) { Log.LogWarning((object)"[Harmonic] Death effect 'DustExplosion' not found in harmonic.bundle; death pop will hide the creature without particles."); } ValidateAuthoredPrefab(val); HarmonicAI harmonicAI = PreparePrefab(val, val2); LoadLooseAudio(harmonicAI); EnemyType = CreateEnemyType(val, harmonicAI); ((EnemyAI)harmonicAI).enemyType = EnemyType; RegisterWithDawn(val); if (!ModConfig.Enabled.Value) { Log.LogInfo((object)"Y4NGZ Harmonic: registered network prefab; spawning disabled by config."); } Log.LogInfo((object)"Y4NGZ Harmonic v2.0.0 loaded. Registered as 'Harmonic'."); } catch (Exception arg) { Log.LogError((object)string.Format("[{0}] Initialization failed: {1}", "Y4NGZ Harmonic", arg)); } } private static void RegisterWithDawn(GameObject prefab) { HarmonicSpawnWeights spawnWeights = new HarmonicSpawnWeights(() => (!ModConfig.Enabled.Value) ? 0f : ModConfig.SpawnWeightMultiplier.Value, () => ModConfig.MoonWeightOverrides.Value, delegate(string message) { Log.LogWarning((object)message); }); DawnLib.RegisterNetworkPrefab(prefab); DawnLib.DefineEnemy(NamespacedKey<DawnEnemyInfo>.From("y4ngz_monsters", "harmonic"), EnemyType, (Action<EnemyInfoBuilder>)delegate(EnemyInfoBuilder builder) { ((BaseInfoBuilder<DawnEnemyInfo, EnemyType, EnemyInfoBuilder>)(object)builder.DefineInside((Action<EnemyLocationBuilder>)delegate(EnemyLocationBuilder location) { location.SetWeights((Action<WeightTableBuilder<DawnMoonInfo, SpawnWeightContext>>)delegate(WeightTableBuilder<DawnMoonInfo, SpawnWeightContext> table) { table.SetGlobalWeight((IWeighted)(object)spawnWeights); }); }).CreateBestiaryNode("Harmonic\n\nDanger level: ambient\n\nA passive floating organism that wanders facilities while playing warped music. Its alarm call can briefly draw other creatures toward its location.\n\n").CreateNameKeyword("harmonic")).AddTags((IEnumerable<NamespacedKey>)(object)new NamespacedKey[3] { Tags.Passive, Tags.Organic, Tags.Killable }); }); } private static void InitializeNetcodeRPCs() { if (_netcodeInitialized) { return; } _netcodeInitialized = true; Type[] types = Assembly.GetExecutingAssembly().GetTypes(); foreach (Type type in types) { MethodInfo[] methods; try { methods = type.GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); } catch { continue; } foreach (MethodInfo methodInfo in methods) { if (methodInfo.GetCustomAttributes(typeof(RuntimeInitializeOnLoadMethodAttribute), inherit: false).Length == 0) { continue; } try { methodInfo.Invoke(null, null); } catch (Exception ex) { ManualLogSource log = Log; if (log != null) { log.LogWarning((object)("[NetcodeInit] " + type.Name + "." + methodInfo.Name + " failed: " + ex.Message)); } } } } } private static bool LoadBundle() { if (string.IsNullOrEmpty(AssemblyDirectory)) { Log.LogError((object)"Could not resolve plugin assembly directory."); return false; } string text = Path.Combine(AssemblyDirectory, "harmonic.bundle"); if (!File.Exists(text)) { Log.LogError((object)("Missing asset bundle: " + text)); return false; } ModAssets = AssetBundle.LoadFromFile(text); if ((Object)(object)ModAssets == (Object)null) { Log.LogError((object)("AssetBundle.LoadFromFile returned null for " + text + ".")); return false; } return true; } private static void LoadLooseAudio(HarmonicAI ai) { string text = Path.Combine(AssemblyDirectory ?? string.Empty, "assets", "Harmonic"); if (!Directory.Exists(text)) { Log.LogWarning((object)("[Harmonic] Audio directory not found: " + text)); return; } List<AudioClip> list = new List<AudioClip>(); string path = Path.Combine(text, "idle music"); if (Directory.Exists(path)) { string[] files = Directory.GetFiles(path, "*.mp3", SearchOption.TopDirectoryOnly); Array.Sort(files, (IComparer<string>?)StringComparer.OrdinalIgnoreCase); for (int i = 0; i < files.Length; i++) { AudioClip val = LoadAudioClip(files[i]); if ((Object)(object)val != (Object)null) { list.Add(val); } } } List<AudioClip> list2 = new List<AudioClip>(); string[] array = new string[3] { "hit01.wav", "hit02.wav", "hit03.wav" }; for (int j = 0; j < array.Length; j++) { AudioClip val2 = LoadAudioClip(Path.Combine(text, array[j])); if ((Object)(object)val2 != (Object)null) { list2.Add(val2); } } ai.idleMusicClips = list.ToArray(); ai.alarmClip = LoadAudioClip(Path.Combine(text, "alarm.mp3")); ai.deathClip = LoadAudioClip(Path.Combine(text, "death.wav")); ai.deathPopClip = LoadAudioClip(Path.Combine(text, "pop.mp3")); ai.hitClips = list2.ToArray(); Log.LogInfo((object)$"[Harmonic] Audio loaded. idle={ai.idleMusicClips.Length}, alarm={(Object)(object)ai.alarmClip != (Object)null}, death={(Object)(object)ai.deathClip != (Object)null}, pop={(Object)(object)ai.deathPopClip != (Object)null}, hits={ai.hitClips.Length}."); } private static AudioClip LoadAudioClip(string path) { //IL_0034: 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_00a2: Invalid comparison between Unknown and I4 if (!File.Exists(path)) { Log.LogWarning((object)("[Harmonic] Audio file not found: " + path)); return null; } UnityWebRequest audioClip = UnityWebRequestMultimedia.GetAudioClip("file:///" + path.Replace('\\', '/'), ResolveAudioType(path)); try { UnityWebRequestAsyncOperation val = audioClip.SendWebRequest(); Stopwatch stopwatch = Stopwatch.StartNew(); while (!((AsyncOperation)val).isDone) { if (stopwatch.Elapsed.TotalSeconds > 10.0) { audioClip.Abort(); Log.LogWarning((object)("[Harmonic] Timed out loading audio " + path + ".")); return null; } Thread.Sleep(1); } if ((int)audioClip.result != 1) { Log.LogWarning((object)("[Harmonic] Failed to load audio " + path + ": " + audioClip.error)); return null; } AudioClip content = DownloadHandlerAudioClip.GetContent(audioClip); if ((Object)(object)content != (Object)null) { ((Object)content).name = Path.GetFileNameWithoutExtension(path); } return content; } finally { ((IDisposable)audioClip)?.Dispose(); } } private static AudioType ResolveAudioType(string path) { string extension = Path.GetExtension(path); if (!string.Equals(extension, ".mp3", StringComparison.OrdinalIgnoreCase)) { if (!string.Equals(extension, ".wav", StringComparison.OrdinalIgnoreCase)) { return (AudioType)0; } return (AudioType)20; } return (AudioType)13; } private static void ValidateAuthoredPrefab(GameObject prefab) { if ((Object)(object)prefab.transform.Find("VisualRoot") == (Object)null) { LogBundleError("the VisualRoot child is missing, so the hover visual cannot run"); } if ((Object)(object)prefab.GetComponentInChildren<Animator>(true) == (Object)null) { LogBundleError("no Animator"); } SkinnedMeshRenderer componentInChildren = prefab.GetComponentInChildren<SkinnedMeshRenderer>(true); if ((Object)(object)componentInChildren == (Object)null) { LogBundleError("no SkinnedMeshRenderer"); } else { Material[] sharedMaterials = ((Renderer)componentInChildren).sharedMaterials; for (int i = 0; i < sharedMaterials.Length; i++) { Material val = sharedMaterials[i]; if ((Object)(object)val == (Object)null || (Object)(object)val.shader == (Object)null || !val.shader.isSupported) { LogBundleError(string.Format("model material slot {0} ('{1}') has no supported shader", i, ((Object)(object)val != (Object)null) ? ((Object)val).name : "null")); } } } ScanNodeProperties componentInChildren2 = prefab.GetComponentInChildren<ScanNodeProperties>(true); if ((Object)(object)componentInChildren2 == (Object)null) { LogBundleError("no ScanNode with ScanNodeProperties, so the Harmonic cannot be scanned"); } else { Collider component = ((Component)componentInChildren2).GetComponent<Collider>(); if ((Object)(object)component == (Object)null || !component.isTrigger) { LogBundleError("the ScanNode has no trigger collider"); } int num = LayerMask.NameToLayer("ScanNode"); if (num < 0) { num = 22; } if (((Component)componentInChildren2).gameObject.layer != num) { LogBundleError($"the ScanNode is on layer {((Component)componentInChildren2).gameObject.layer}, not ScanNode ({num})"); } } if ((Object)(object)prefab.GetComponentInChildren<NetworkTransform>(true) != (Object)null) { LogBundleError("the prefab carries a NetworkTransform; remove it in the builder, because EnemyAI already replicates position through serverPosition and two writers jitter clients"); } } private static void LogBundleError(string problem) { Log.LogError((object)("[Harmonic] harmonic.bundle: " + problem + ". Fix it in Assets/Y4NGZ/Harmonic/Editor/HarmonicAssetBuilder.cs and rebuild the bundle; the plugin does not repair authored parts.")); } private static HarmonicAI PreparePrefab(GameObject prefab, GameObject deathEffect) { //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_0031: Unknown result type (might be due to invalid IL or missing references) //IL_00b1: Unknown result type (might be due to invalid IL or missing references) AssignUniqueNetworkHash(prefab, "Harmonic"); TrySetTag(prefab, "Enemy"); TrySetLayer(prefab, "Enemies"); prefab.transform.localScale = Vector3.one * 0.72f; HarmonicAI orAddComponent = GetOrAddComponent<HarmonicAI>(prefab); ((EnemyAI)orAddComponent).updatePositionThreshold = 0.3f; Animator componentInChildren = prefab.GetComponentInChildren<Animator>(true); if ((Object)(object)componentInChildren != (Object)null) { componentInChildren.cullingMode = (AnimatorCullingMode)1; ((EnemyAI)orAddComponent).creatureAnimator = componentInChildren; } NavMeshAgent orAddComponent2 = GetOrAddComponent<NavMeshAgent>(prefab); ConfigureAgent(orAddComponent2); ((EnemyAI)orAddComponent).agent = orAddComponent2; orAddComponent.visualRoot = prefab.transform.Find("VisualRoot"); ((EnemyAI)orAddComponent).eye = GetOrCreateChild(prefab.transform, "EyeTransform", new Vector3(0f, 0.35f, 0.2f)); orAddComponent.musicSource = GetOrCreateAudioSource(prefab.transform, "HarmonicMusic"); orAddComponent.sfxSource = GetOrCreateAudioSource(prefab.transform, "HarmonicSFX"); ApplyAudioDistances(orAddComponent.musicSource, orAddComponent.sfxSource); ((EnemyAI)orAddComponent).creatureVoice = orAddComponent.musicSource; ((EnemyAI)orAddComponent).creatureSFX = orAddComponent.sfxSource; orAddComponent.deathEffectPrefab = deathEffect; PrepareScanNode(prefab); BuildCollision(prefab, orAddComponent); EnsureBehaviourStates(orAddComponent); return orAddComponent; } private static void ConfigureAgent(NavMeshAgent agent) { agent.speed = Mathf.Max(0.1f, ModConfig.MoveSpeed.Value); agent.acceleration = 4.5f; agent.angularSpeed = 70f; agent.stoppingDistance = 0.55f; agent.radius = 0.32f; agent.height = 1.25f; agent.baseOffset = 0f; agent.autoBraking = true; agent.autoRepath = true; agent.obstacleAvoidanceType = (ObstacleAvoidanceType)4; agent.avoidancePriority = 55; } internal static void ApplyAudioDistances(AudioSource music, AudioSource sfx) { if ((Object)(object)music != (Object)null) { music.maxDistance = Mathf.Clamp(ModConfig.MusicMaxDistance.Value, 8f, 65f); } if ((Object)(object)sfx != (Object)null) { sfx.maxDistance = Mathf.Clamp(ModConfig.SfxMaxDistance.Value, 8f, 42f); } } private static void EnsureBehaviourStates(HarmonicAI ai) { //IL_0009: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_001a: Expected O, but got Unknown //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Expected O, but got Unknown //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_0034: Unknown result type (might be due to invalid IL or missing references) //IL_0040: Expected O, but got Unknown ((EnemyAI)ai).enemyBehaviourStates = (EnemyBehaviourState[])(object)new EnemyBehaviourState[3] { new EnemyBehaviourState { name = "Roaming" }, new EnemyBehaviourState { name = "Alarm" }, new EnemyBehaviourState { name = "Dead" } }; ((EnemyAI)ai).currentBehaviourStateIndex = 0; ((EnemyAI)ai).previousBehaviourStateIndex = 0; ((EnemyAI)ai).currentBehaviourState = ((EnemyAI)ai).enemyBehaviourStates[0]; } private static void PrepareScanNode(GameObject prefab) { ScanNodeProperties componentInChildren = prefab.GetComponentInChildren<ScanNodeProperties>(true); if (!((Object)(object)componentInChildren == (Object)null)) { componentInChildren.headerText = "Harmonic"; componentInChildren.subText = string.Empty; Rigidbody orAddComponent = GetOrAddComponent<Rigidbody>(((Component)componentInChildren).gameObject); orAddComponent.isKinematic = true; orAddComponent.useGravity = false; orAddComponent.detectCollisions = true; } } private static void BuildCollision(GameObject prefab, HarmonicAI ai) { //IL_0043: Unknown result type (might be due to invalid IL or missing references) //IL_00b6: Unknown result type (might be due to invalid IL or missing references) //IL_00bb: Unknown result type (might be due to invalid IL or missing references) //IL_00bf: Unknown result type (might be due to invalid IL or missing references) //IL_00cb: Unknown result type (might be due to invalid IL or missing references) //IL_00d0: Unknown result type (might be due to invalid IL or missing references) //IL_00d5: Unknown result type (might be due to invalid IL or missing references) //IL_00dd: Unknown result type (might be due to invalid IL or missing references) //IL_00e2: Unknown result type (might be due to invalid IL or missing references) //IL_00e7: Unknown result type (might be due to invalid IL or missing references) //IL_017d: Unknown result type (might be due to invalid IL or missing references) //IL_0189: Unknown result type (might be due to invalid IL or missing references) //IL_0195: Unknown result type (might be due to invalid IL or missing references) //IL_019f: Unknown result type (might be due to invalid IL or missing references) //IL_01e3: Unknown result type (might be due to invalid IL or missing references) //IL_01f2: Unknown result type (might be due to invalid IL or missing references) //IL_01fe: Unknown result type (might be due to invalid IL or missing references) //IL_0139: Unknown result type (might be due to invalid IL or missing references) //IL_0140: Unknown result type (might be due to invalid IL or missing references) //IL_0145: Unknown result type (might be due to invalid IL or missing references) //IL_0147: Unknown result type (might be due to invalid IL or missing references) //IL_014c: Unknown result type (might be due to invalid IL or missing references) //IL_0151: Unknown result type (might be due to invalid IL or missing references) float num = 0.72f; float radius = 0.32f / num; float height = 1.25f / num; Vector3 center = default(Vector3); ((Vector3)(ref center))..ctor(0f, 1.175f / num, 0f); CapsuleCollider orAddComponent = GetOrAddComponent<CapsuleCollider>(prefab); ((Collider)orAddComponent).isTrigger = false; orAddComponent.direction = 1; orAddComponent.center = center; orAddComponent.radius = radius; orAddComponent.height = height; Rigidbody orAddComponent2 = GetOrAddComponent<Rigidbody>(prefab); orAddComponent2.isKinematic = true; orAddComponent2.useGravity = false; orAddComponent2.detectCollisions = true; Transform visualRoot = ai.visualRoot; SkinnedMeshRenderer componentInChildren = prefab.GetComponentInChildren<SkinnedMeshRenderer>(true); if ((Object)(object)visualRoot == (Object)null || (Object)(object)componentInChildren == (Object)null || (Object)(object)componentInChildren.sharedMesh == (Object)null) { LogBundleError("there is no VisualRoot or model mesh to size the hit trigger from, so the Harmonic cannot be hit"); return; } Bounds bounds = componentInChildren.sharedMesh.bounds; Matrix4x4 val = visualRoot.worldToLocalMatrix * ((Component)componentInChildren).transform.localToWorldMatrix; Bounds val2 = default(Bounds); ((Bounds)(ref val2))..ctor(((Matrix4x4)(ref val)).MultiplyPoint3x4(((Bounds)(ref bounds)).center), Vector3.zero); Vector3 val3 = default(Vector3); for (int i = 0; i < 8; i++) { ((Vector3)(ref val3))..ctor(((i & 1) == 0) ? (-1f) : 1f, ((i & 2) == 0) ? (-1f) : 1f, ((i & 4) == 0) ? (-1f) : 1f); ((Bounds)(ref val2)).Encapsulate(((Matrix4x4)(ref val)).MultiplyPoint3x4(((Bounds)(ref bounds)).center + Vector3.Scale(((Bounds)(ref bounds)).extents, val3))); } ((Bounds)(ref val2)).Expand(0.12f / num); Transform orCreateChild = GetOrCreateChild(visualRoot, "Collision", new Vector3(((Bounds)(ref val2)).center.x, ((Bounds)(ref val2)).min.y, ((Bounds)(ref val2)).center.z)); TrySetTag(((Component)orCreateChild).gameObject, "Enemy"); TrySetLayer(((Component)orCreateChild).gameObject, "Enemies"); BoxCollider orAddComponent3 = GetOrAddComponent<BoxCollider>(((Component)orCreateChild).gameObject); ((Collider)orAddComponent3).isTrigger = true; orAddComponent3.center = new Vector3(0f, ((Bounds)(ref val2)).extents.y, 0f); orAddComponent3.size = ((Bounds)(ref val2)).size; Rigidbody orAddComponent4 = GetOrAddComponent<Rigidbody>(((Component)orCreateChild).gameObject); orAddComponent4.isKinematic = true; orAddComponent4.useGravity = false; orAddComponent4.detectCollisions = true; EnemyAICollisionDetect orAddComponent5 = GetOrAddComponent<EnemyAICollisionDetect>(((Component)orCreateChild).gameObject); orAddComponent5.mainScript = (EnemyAI)(object)ai; orAddComponent5.alwaysAllowHitting = true; orAddComponent5.canCollideWithEnemies = true; orAddComponent5.onlyCollideWhenGrounded = false; } private static EnemyType CreateEnemyType(GameObject prefab, HarmonicAI ai) { //IL_0103: Unknown result type (might be due to invalid IL or missing references) EnemyType obj = ScriptableObject.CreateInstance<EnemyType>(); obj.enemyName = "Harmonic"; obj.enemyPrefab = prefab; obj.PowerLevel = ModConfig.PowerLevel.Value; obj.DiversityPowerLevel = 1; obj.MaxCount = Mathf.Max(1, ModConfig.MaxCount.Value); obj.canDie = true; obj.canBeStunned = true; obj.canBeDestroyed = true; obj.stunTimeMultiplier = 1f; obj.stunGameDifficultyMultiplier = 1f; obj.destroyOnDeath = false; obj.doorSpeedMultiplier = 1f; obj.isOutsideEnemy = false; obj.isDaytimeEnemy = false; obj.pushPlayerDistance = 0f; obj.pushPlayerForce = 0f; obj.normalizedTimeInDayToLeave = 1f; obj.probabilityCurve = AnimationCurve.Constant(0f, 1f, 1f); obj.numberSpawnedFalloff = AnimationCurve.Linear(0f, 1f, 1f, 0f); obj.useNumberSpawnedFalloff = true; obj.disableAnimatorWhenFar = false; obj.SizeLimit = (NavSizeLimit)0; AudioClip stun = ((ai.hitClips != null && ai.hitClips.Length != 0) ? ai.hitClips[0] : null); CreatureSfx.Apply(obj, (EnemyAI)(object)ai, stun); return obj; } private static T GetOrAddComponent<T>(GameObject target) where T : Component { T component = target.GetComponent<T>(); if (!((Object)(object)component != (Object)null)) { return target.AddComponent<T>(); } return component; } private static AudioSource GetOrCreateAudioSource(Transform parent, string childName) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) Transform orCreateChild = GetOrCreateChild(parent, childName, Vector3.zero); AudioSource val = ((Component)orCreateChild).GetComponent<AudioSource>(); if ((Object)(object)val == (Object)null) { val = ((Component)orCreateChild).gameObject.AddComponent<AudioSource>(); val.playOnAwake = false; val.loop = false; val.spatialBlend = 1f; val.rolloffMode = (AudioRolloffMode)0; val.minDistance = 4f; val.dopplerLevel = 0f; val.spread = 55f; } if ((Object)(object)((Component)val).GetComponent<AudioLowPassFilter>() == (Object)null) { AudioLowPassFilter obj = ((Component)val).gameObject.AddComponent<AudioLowPassFilter>(); obj.cutoffFrequency = 22000f; obj.lowpassResonanceQ = 1f; } return val; } private static Transform GetOrCreateChild(Transform parent, string name, Vector3 localPosition) { //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_0028: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_003a: Unknown result type (might be due to invalid IL or missing references) Transform val = parent.Find(name); if ((Object)(object)val != (Object)null) { return val; } val = new GameObject(name).transform; val.SetParent(parent, false); val.localPosition = localPosition; val.localRotation = Quaternion.identity; val.localScale = Vector3.one; return val; } internal static Transform FindChildRecursive(Transform parent, string name) { if ((Object)(object)parent == (Object)null || string.IsNullOrWhiteSpace(name)) { return null; } if (string.Equals(((Object)parent).name, name, StringComparison.OrdinalIgnoreCase)) { return parent; } for (int i = 0; i < parent.childCount; i++) { Transform val = FindChildRecursive(parent.GetChild(i), name); if ((Object)(object)val != (Object)null) { return val; } } return null; } internal static void RepairParticleRenderers(GameObject root) { if ((Object)(object)root == (Object)null) { return; } Renderer[] componentsInChildren = root.GetComponentsInChildren<Renderer>(true); foreach (Renderer val in componentsInChildren) { if ((Object)(object)val == (Object)null) { continue; } Material[] sharedMaterials = val.sharedMaterials; if (sharedMaterials == null || sharedMaterials.Length == 0) { continue; } bool flag = false; for (int j = 0; j < sharedMaterials.Length; j++) { Material val2 = sharedMaterials[j]; if (!((Object)(object)val2 != (Object)null) || ShouldReplaceShader(val2.shader) || !((Object)(object)GetBaseTexture(val2) != (Object)null)) { sharedMaterials[j] = GetOrCreateRuntimeParticleMaterial(val2); flag = true; } } if (flag) { val.sharedMaterials = sharedMaterials; } } } private static Material GetOrCreateRuntimeParticleMaterial(Material source) { //IL_0051: Unknown result type (might be due to invalid IL or missing references) //IL_0057: Expected O, but got Unknown //IL_0082: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)source != (Object)null && RuntimeParticleMaterials.TryGetValue(source, out var value) && (Object)(object)value != (Object)null) { return value; } if ((Object)(object)source == (Object)null && (Object)(object)_fallbackParticleMaterial != (Object)null) { return _fallbackParticleMaterial; } Shader val = FindRuntimeParticleShader(); if ((Object)(object)val == (Object)null) { return source; } Material val2 = new Material(val); ((Object)val2).name = "HarmonicRuntimeParticle"; ((Object)val2).hideFlags = (HideFlags)61; Texture texture = (Texture)(((object)GetBaseTexture(source)) ?? ((object)GetOrCreateRuntimeParticleTexture())); ApplyBaseTexture(val2, texture); ApplyParticleColor(val2, RuntimeParticleDustColor); MakeTransparentUnlit(val2); if ((Object)(object)source != (Object)null) { RuntimeParticleMaterials[source] = val2; } else { _fallbackParticleMaterial = val2; } return val2; } private static Shader FindRuntimeParticleShader() { string[] array = new string[3] { "Particles/Standard Unlit", "Legacy Shaders/Particles/Alpha Blended", "Sprites/Default" }; for (int i = 0; i < array.Length; i++) { Shader val = Shader.Find(array[i]); if ((Object)(object)val != (Object)null && val.isSupported) { return val; } } Shader val2 = Shader.Find("HDRP/Unlit"); if ((Object)(object)val2 != (Object)null && val2.isSupported) { return val2; } return Shader.Find("Unlit/Transparent") ?? FindVisibleShader(); } private static Texture2D GetOrCreateRuntimeParticleTexture() { //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_0031: Unknown result type (might be due to invalid IL or missing references) //IL_0038: Unknown result type (might be due to invalid IL or missing references) //IL_0040: Expected O, but got Unknown //IL_0176: Unknown result type (might be due to invalid IL or missing references) //IL_017b: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)_runtimeParticleTexture != (Object)null) { return _runtimeParticleTexture; } Texture2D val = new Texture2D(64, 64, (TextureFormat)4, true) { name = "HarmonicRuntimeDustSprite", hideFlags = (HideFlags)61, filterMode = (FilterMode)1, wrapMode = (TextureWrapMode)1 }; Color32[] array = (Color32[])(object)new Color32[4096]; for (int i = 0; i < 64; i++) { float num = ((float)i + 0.5f) / 64f * 2f - 1f; for (int j = 0; j < 64; j++) { float num2 = ((float)j + 0.5f) / 64f * 2f - 1f; float num3 = Mathf.Atan2(num, num2); float num4 = Mathf.Sqrt(num2 * num2 + num * num); float num5 = 0.94f + Mathf.Sin(num3 * 3f + 0.45f) * 0.045f + Mathf.Sin(num3 * 7f - 0.8f) * 0.025f; float num6 = Mathf.InverseLerp(0.08f, num5, num4); float num7 = Mathf.SmoothStep(1f, 0f, num6); float num8 = 0.88f + 0.08f * Mathf.Sin(num2 * 8.3f + num * 3.7f) + 0.04f * Mathf.Sin(num * 11.1f - num2 * 2.9f); byte b = (byte)Mathf.RoundToInt(Mathf.Clamp01(num7 * num8) * 255f); array[i * 64 + j] = new Color32(byte.MaxValue, byte.MaxValue, byte.MaxValue, b); } } val.SetPixels32(array); val.Apply(true, true); _runtimeParticleTexture = val; return val; } private static void ApplyParticleColor(Material material, Color color) { //IL_0044: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)material == (Object)null) { return; } string[] array = new string[4] { "_BaseColor", "_Color", "_TintColor", "_UnlitColor" }; for (int i = 0; i < array.Length; i++) { if (material.HasProperty(array[i])) { material.SetColor(array[i], color); } } } private static void MakeTransparentUnlit(Material material) { SetFloatIfPresent(material, "_SurfaceType", 1f); SetFloatIfPresent(material, "_BlendMode", 0f); SetFloatIfPresent(material, "_AlphaCutoffEnable", 0f); SetFloatIfPresent(material, "_SrcBlend", 5f); SetFloatIfPresent(material, "_DstBlend", 10f); SetFloatIfPresent(material, "_AlphaSrcBlend", 5f); SetFloatIfPresent(material, "_AlphaDstBlend", 10f); SetFloatIfPresent(material, "_ZWrite", 0f); SetFloatIfPresent(material, "_TransparentZWrite", 0f); SetFloatIfPresent(material, "_ZTestDepthEqualForOpaque", 4f); SetFloatIfPresent(material, "_CullMode", 0f); SetFloatIfPresent(material, "_TransparentCullMode", 0f); material.SetOverrideTag("RenderType", "Transparent"); material.EnableKeyword("_SURFACE_TYPE_TRANSPARENT"); material.EnableKeyword("_BLENDMODE_ALPHA"); material.EnableKeyword("_ALPHABLEND_ON"); material.EnableKeyword("_ENABLE_FOG_ON_TRANSPARENT"); material.DisableKeyword("_BLENDMODE_ADD"); material.DisableKeyword("_ALPHATEST_ON"); material.DisableKeyword("_ALPHAPREMULTIPLY_ON"); material.renderQueue = 3000; if ((Object)(object)material.shader != (Object)null && ((Object)material.shader).name.StartsWith("HDRP/", StringComparison.OrdinalIgnoreCase)) { HDMaterial.ValidateMaterial(material); } } private static bool ShouldReplaceShader(Shader shader) { if (IsInvalidShader(shader)) { return true; } if (!shader.isSupported) { return true; } string text = ((Object)shader).name ?? string.Empty; if (!string.Equals(text, "Standard", StringComparison.OrdinalIgnoreCase)) { return text.IndexOf("Universal Render Pipeline", StringComparison.OrdinalIgnoreCase) >= 0; } return true; } private static bool IsInvalidShader(Shader shader) { if ((Object)(object)shader == (Object)null) { return true; } return (((Object)shader).name ?? string.Empty).IndexOf("Hidden/InternalErrorShader", StringComparison.OrdinalIgnoreCase) >= 0; } private static Shader FindVisibleShader() { return Shader.Find("HDRP/Lit") ?? Shader.Find("HDRP/Unlit") ?? Shader.Find("Standard") ?? Shader.Find("Universal Render Pipeline/Lit") ?? Shader.Find("Unlit/Texture"); } private static Texture GetBaseTexture(Material material) { if ((Object)(object)material == (Object)null) { return null; } string[] array = new string[4] { "_BaseColorMap", "_UnlitColorMap", "_MainTex", "_BaseMap" }; for (int i = 0; i < array.Length; i++) { if (material.HasProperty(array[i])) { Texture texture = material.GetTexture(array[i]); if ((Object)(object)texture != (Object)null) { return texture; } } } return null; } private static void ApplyBaseTexture(Material material, Texture texture) { if ((Object)(object)material == (Object)null || (Object)(object)texture == (Object)null) { return; } string[] array = new string[4] { "_BaseColorMap", "_UnlitColorMap", "_MainTex", "_BaseMap" }; for (int i = 0; i < array.Length; i++) { if (material.HasProperty(array[i])) { material.SetTexture(array[i], texture); } } } private static void SetFloatIfPresent(Material material, string property, float value) { if ((Object)(object)material != (Object)null && material.HasProperty(property)) { material.SetFloat(property, value); } } private static void AssignUniqueNetworkHash(GameObject prefab, string key) { try { NetworkObject orAddComponent = GetOrAddComponent<NetworkObject>(prefab); uint num = BitConverter.ToUInt32(MD5.Create().ComputeHash(Encoding.UTF8.GetBytes("y4ngz.lethalcompany.harmonic." + key)), 0); PropertyInfo property = typeof(NetworkObject).GetProperty("GlobalObjectIdHash", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); if (property != null && property.CanWrite) { property.SetValue(orAddComponent, num); return; } FieldInfo fieldInfo = typeof(NetworkObject).GetField("GlobalObjectIdHash", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic) ?? typeof(NetworkObject).GetField("<GlobalObjectIdHash>k__BackingField", BindingFlags.Instance | BindingFlags.NonPublic); if (fieldInfo != null) { fieldInfo.SetValue(orAddComponent, num); } } catch (Exception ex) { Log.LogWarning((object)("[Harmonic] Could not assign NetworkObject hash: " + ex.Message)); } } private static void TrySetTag(GameObject obj, string tag) { try { obj.tag = tag; } catch { } } private static void TrySetLayer(GameObject obj, string layerName) { if ((Object)(object)obj == (Object)null) { return; } int num = LayerMask.NameToLayer(layerName); if (num < 0) { num = ResolveLayerFallback(layerName); } if (num >= 0 && num <= 31) { obj.layer = num; return; } ManualLogSource log = Log; if (log != null) { log.LogWarning((object)$"[Harmonic] Layer '{layerName}' unresolved; '{((Object)obj).name}' stays on layer {obj.layer}."); } } private static int ResolveLayerFallback(string layerName) { if (string.Equals(layerName, "ScanNode", StringComparison.OrdinalIgnoreCase)) { return 22; } if (string.Equals(layerName, "Enemies", StringComparison.OrdinalIgnoreCase)) { return 19; } return -1; } private static void DumpBundleAssets() { if (!((Object)(object)ModAssets == (Object)null)) { string[] allAssetNames = ModAssets.GetAllAssetNames(); foreach (string text in allAssetNames) { Log.LogError((object)(" - " + text)); } } } } internal static class PluginInfo { public const string PLUGIN_GUID = "y4ngz.lethalcompany.harmonic"; public const string PLUGIN_NAME = "Y4NGZ Harmonic"; public const string PLUGIN_VERSION = "2.0.0"; } } namespace Y4NGZHarmonic.AI { public sealed class HarmonicAI : EnemyAI { private sealed class HornBreathTarget { public readonly Transform Transform; public readonly Vector3 BaseScale; public HornBreathTarget(Transform transform) { //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Unknown result type (might be due to invalid IL or missing references) Transform = transform; BaseScale = (((Object)(object)transform != (Object)null) ? transform.localScale : Vector3.one); } } private struct AlarmedEnemyState { public PlayerControllerB TargetPlayer; public bool MovingTowardsTargetPlayer; public bool MoveTowardsDestination; public Vector3 Destination; public AISearchRoutine Search; public Vector3 ForcedDestination; public Vector3 GatherPoint; public float GatherIssuedAt; } public const int StateRoaming = 0; public const int StateAlarm = 1; public const int StateDead = 2; private const int LocalTrackNone = 0; private const int LocalTrackIdle = 1; private const int LocalTrackAlarm = 2; private const float DistantAudioCutoff = 6500f; private const float ObstructedAudioCutoff = 2400f; private const float AudioOcclusionInterval = 0.15f; private const float CeilingProbeInterval = 0.2f; private const float CeilingProbeDistance = 5.5f; private const float DamageStunFreezeSeconds = 1f; private const float DeathPopDelaySeconds = 0.08f; private const float MovingSpeedThreshold = 0.1f; private const float MovementAmountSharpness = 6f; private const float NoiseMinLoudness = 0.5f; private const float NoiseHearingRange = 20f; private const float NoiseMemorySeconds = 3f; private const float NoiseReseedCooldown = 4f; private const int NoiseMaxRepeatsInOneSpot = 10; private static readonly string[] IdleAnimationStates = new string[4] { "Idle_1", "Idle_2", "Idle_3", "Idle_4" }; private static readonly int EmissiveColorId = Shader.PropertyToID("_EmissiveColor"); private static readonly string[] HornBreathBoneNames = new string[6] { "JNT_Trumpet_a4", "JNT_Trumpet_b4", "JNT_Trumpet_c4", "JNT_Trumpet_d4", "JNT_Trumpet_e4", "JNT_Trumpet_f4" }; public AISearchRoutine facilitySearch = new AISearchRoutine(); public Transform visualRoot; public AudioSource musicSource; public AudioSource sfxSource; public AudioClip[] idleMusicClips; public AudioClip alarmClip; public AudioClip deathClip; public AudioClip deathPopClip; public AudioClip[] hitClips; public GameObject deathEffectPrefab; private readonly ServerOwnershipGuard _ownership = new ServerOwnershipGuard(); private readonly NoiseMemory _noiseMemory = new NoiseMemory(); private readonly Dictionary<EnemyAI, AlarmedEnemyState> _alarmedEnemies = new Dictionary<EnemyAI, AlarmedEnemyState>(); private readonly NetworkVariable<int> _networkState = new NetworkVariable<int>(0, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); private readonly NetworkVariable<int> _networkTrackKind = new NetworkVariable<int>(0, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); private readonly NetworkVariable<int> _networkTrackClipIndex = new NetworkVariable<int>(-1, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); private readonly NetworkVariable<bool> _networkTrackWarningRamp = new NetworkVariable<bool>(false, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); private readonly NetworkVariable<float> _networkTrackPhase = new NetworkVariable<float>(0f, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); private readonly NetworkVariable<double> _networkTrackStart = new NetworkVariable<double>(0.0, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); private readonly NetworkVariable<bool> _networkDead = new NetworkVariable<bool>(false, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); private readonly List<Material> _runtimeMaterials = new List<Material>(); private readonly List<HornBreathTarget> _hornBreathTargets = new List<HornBreathTarget>(); private readonly RaycastHit[] _audioOcclusionHits = (RaycastHit[])(object)new RaycastHit[8]; private readonly RaycastHit[] _ceilingHits = (RaycastHit[])(object)new RaycastHit[8]; private Coroutine _serverMusicRoutine; private Coroutine _deathPresentationRoutine; private Vector3 _visualBaseLocalPosition; private Vector3 _visualBaseLocalScale = Vector3.one; private Quaternion _visualBaseLocalRotation = Quaternion.identity; private Vector3 _lastFramePosition; private float _planarSpeed; private float _movementAmount; private float _visualLocalMinY; private float _visualLocalMaxY; private float _visualHoverVelocity; private float _hoverLocalY; private Quaternion _hoverLocalRotation = Quaternion.identity; private float _flinchStartedAt = float.NegativeInfinity; private Vector3 _flinchDirection; private float _breathPhase; private float _targetHitInflateAmount; private float _hitInflateAmount; private float _hitInflateVelocity; private float _pulsePhase; private float _localClipStartedAt; private float _localClipDuration; private float _stuckTimer; private float _nextSearchRepairTime; private float _nextAlarmScanTime; private float _nextAudioOcclusionUpdateTime; private float _nextCeilingProbeTime; private float _ceilingClearanceLocal; private float _nextNavMeshRepairTime; private float _nextNoiseReseedTime; private float _damageStunUntil; private float _preDamageStunAnimatorSpeed = 1f; private int _lastIdleIndex = -1; private int _localTrackKind; private string _currentAnimationState; private AudioLowPassFilter _musicLowPass; private AudioLowPassFilter _sfxLowPass; private AudioSource _hitLayerSource; private AudioLowPassFilter _hitLayerLowPass; private NavMeshPath _gatherPath; private bool _hasCapturedVisualBase; private bool _hasVisualBounds; private bool _hornBreathTargetsScanned; private bool _hasCeilingClearance; private bool _localWarningRamp; private bool _musicRpcReceived; private bool _serverAlarmActive; private bool _deathPresentationStarted; private bool _deathBodyHidden; private bool _damageStunFrozen; private bool _wasStunned; private bool _audioRouted; private bool _configSubscribed; private int Health => Plugin.ModConfig?.Health.Value ?? 4; private float MoveSpeed => Mathf.Max(0.1f, Plugin.ModConfig?.MoveSpeed.Value ?? 1.15f); private float AlarmChance => Mathf.Clamp01(Plugin.ModConfig?.AlarmChance.Value ?? 0.2f); private float AlarmScanSeconds => 0.35f; private float AlarmGatherRadius => 12f; private float AlarmAttractionRadius => Mathf.Max(0f, Plugin.ModConfig?.AlarmAttractionRadius.Value ?? 30f); private float IdleVolume => Mathf.Clamp01(Plugin.ModConfig?.MusicVolume.Value ?? 0.95f); private float SfxVolume => Mathf.Clamp01(Plugin.ModConfig?.SfxVolume.Value ?? 1f); private float PulseRate => 0.42f; private float WarningPulseRate => 1.55f; private float PitchPulseAmount => 0.025f; private float VolumePulseAmount => 0.08f; private float WarningPitchMultiplier => 1.18f; private float HoverHeight => 0.55f; private float MaxHitInflateAmount => 0.13f; private float DeathEffectScale => 0.75f; private float RoamSearchWidth => 120f; private float RoamSearchPrecision => 8f; private float RoamStuckRecoverySeconds => 3.5f; private float MovementBobAmount => 0.06f; private float MovementTiltDegrees => 4f; private float EmissionIntensity => 8f; private bool DebugLogs => Plugin.ModConfig?.DebugLogs.Value ?? false; private bool IsFrozen { get { if (!((EnemyAI)(object)this).IsStunned()) { return Time.time < _damageStunUntil; } return true; } } public override void Awake() { try { ((EnemyAI)this).Awake(); ConfigureSearchDefaults(); _musicLowPass = (((Object)(object)musicSource != (Object)null) ? ((Component)musicSource).GetComponent<AudioLowPassFilter>() : null); _sfxLowPass = (((Object)(object)sfxSource != (Object)null) ? ((Component)sfxSource).GetComponent<AudioLowPassFilter>() : null); if ((Object)(object)sfxSource != (Object)null) { _hitLayerSource = Object.Instantiate<AudioSource>(sfxSource, ((Component)sfxSource).transform.parent); ((Object)_hitLayerSource).name = "HarmonicHitLayer"; _hitLayerLowPass = ((Component)_hitLayerSource).GetComponent<AudioLowPassFilter>(); } } catch (Exception arg) { ManualLogSource log = Plugin.Log; if (log != null) { log.LogError((object)$"[HarmonicAI] Awake failed: {arg}"); } } } public override void Start() { //IL_0056: Unknown result type (might be due to invalid IL or missing references) //IL_005b: Unknown result type (might be due to invalid IL or missing references) try { CaptureRuntimeMaterials(); SubscribeConfig(); ApplyMoveSpeed(); ApplyAudioDistances(); if (((NetworkBehaviour)this).IsServer) { SnapToInteriorNavMeshIfNeeded(logAlways: true); } ((EnemyAI)this).Start(); base.enemyHP = Health; _pulsePhase = Random.Range(0f, 1000f); _lastFramePosition = ((Component)this).transform.position; _audioRouted = RouteAudioSources(); if (((NetworkBehaviour)this).IsServer) { SwitchState(0); EnsureRoamingSearch(); RestartMusicLoop(); } else { ApplySpawnSnapshot(); } } catch (Exception arg) { ManualLogSource log = Plugin.Log; if (log != null) { log.LogError((object)$"[HarmonicAI] Start failed: {arg}"); } } } public override void OnNetworkSpawn() { ((NetworkBehaviour)this).OnNetworkSpawn(); if (!((NetworkBehaviour)this).IsServer) { int value = _networkState.Value; if (base.enemyBehaviourStates != null && value >= 0 && value < base.enemyBehaviourStates.Length && value != base.currentBehaviourStateIndex) { ((EnemyAI)this).SwitchToBehaviourStateOnLocalClient(value); } return; } try { _networkState.Value = base.currentBehaviourStateIndex; _networkDead.Value = base.isEnemyDead; WriteTrackSnapshot(0, -1, warningRamp: false, 0f); } catch (Exception arg) { ManualLogSource log = Plugin.Log; if (log != null) { log.LogError((object)$"[HarmonicAI] OnNetworkSpawn failed: {arg}"); } } } public override void Update() { try { _ownership.Ensure((EnemyAI)(object)this, Plugin.Log); ((EnemyAI)this).Update(); if (!_audioRouted) { _audioRouted = RouteAudioSources(); } if (base.isEnemyDead) { return; } ((EnemyAI)(object)this).TrackStun(ref _wasStunned); TrackMovement(Time.deltaTime); if (ApplyDamageStunFreeze()) { TickVisualPose(Time.deltaTime); return; } if (((NetworkBehaviour)this).IsServer) { RepairOffNavMeshIfNeeded(); TickRoamingSearch(Time.deltaTime); TickAlarmAttraction(); } TickLocalPulse(); } catch (Exception arg) { ManualLogSource log = Plugin.Log; if (log != null) { log.LogError((object)$"[HarmonicAI] Update failed: {arg}"); } } } private void LateUpdate() { try { if (!_damageStunFrozen && !_deathBodyHidden) { ApplyHornBreathing(); } } catch (Exception arg) { ManualLogSource log = Plugin.Log; if (log != null) { log.LogError((object)$"[HarmonicAI] LateUpdate failed: {arg}"); } } } public override void DoAIInterval() { try { if (!((NetworkBehaviour)this).IsServer || base.isEnemyDead) { return; } if (IsFrozen) { ((EnemyAI)(object)this).HoldAgent(); ((EnemyAI)this).SyncPositionToClients(); return; } RepairOffNavMeshIfNeeded(); if (!((Object)(object)base.agent == (Object)null) && ((Behaviour)base.agent).enabled && base.agent.isOnNavMesh) { ((EnemyAI)this).DoAIInterval(); if (!((Object)(object)StartOfRound.Instance == (Object)null) && !StartOfRound.Instance.allPlayersDead && (base.currentBehaviourStateIndex == 0 || base.currentBehaviourStateIndex == 1) && !TryReseedSearchAtNoise()) { EnsureRoamingSearch(); } } } catch (Exception arg) { ManualLogSource log = Plugin.Log; if (log != null) { log.LogError((object)$"[HarmonicAI] DoAIInterval failed: {arg}"); } } } public override void HitEnemy(int force = 1, PlayerControllerB playerWhoHit = null, bool playHitSFX = false, int hitID = -1) { //IL_006a: Unknown result type (might be due to invalid IL or missing references) //IL_0075: Unknown result type (might be due to invalid IL or missing references) //IL_007a: Unknown result type (might be due to invalid IL or missing references) //IL_007f: Unknown result type (might be due to invalid IL or missing references) //IL_0084: Unknown result type (might be due to invalid IL or missing references) //IL_0089: Unknown result type (might be due to invalid IL or missing references) //IL_008c: Unknown result type (might be due to invalid IL or missing references) //IL_005d: Unknown result type (might be due to invalid IL or missing references) //IL_0091: Unknown result type (might be due to invalid IL or missing references) //IL_00b4: Unknown result type (might be due to invalid IL or missing references) try { ((EnemyAI)this).HitEnemy(force, playerWhoHit, playHitSFX, hitID); if (base.isEnemyDead) { return; } BeginDamageStunFreeze(); if (!((NetworkBehaviour)this).IsServer) { return; } base.enemyHP -= Mathf.Max(1, force); if (base.enemyHP <= 0) { ((EnemyAI)this).KillEnemyOnOwnerClient(false); return; } Vector3 val; if (!((Object)(object)playerWhoHit != (Object)null)) { val = Vector3.zero; } else { Vector3 val2 = Vector3.ProjectOnPlane(((Component)this).transform.position - ((Component)playerWhoHit).transform.position, Vector3.up); val = ((Vector3)(ref val2)).normalized; } Vector3 recoilDirection = val; PlayHitClientRpc(PickHitClipIndex(), Random.Range(0.92f, 1.08f), CalculateHitInflateAmount(base.enemyHP), recoilDirection); RestartMusicLoop(); } catch (Exception arg) { ManualLogSource log = Plugin.Log; if (log != null) { log.LogError((object)$"[HarmonicAI] HitEnemy failed: {arg}"); } } } public override void DetectNoise(Vector3 noisePosition, float noiseLoudness, int timesPlayedInOneSpot = 0, int noiseID = 0) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0038: Unknown result type (might be due to invalid IL or missing references) //IL_0045: Unknown result type (might be due to invalid IL or missing references) ((EnemyAI)this).DetectNoise(noisePosition, noiseLoudness, timesPlayedInOneSpot, noiseID); if (((NetworkBehaviour)this).IsServer && !base.isEnemyDead && !IsFrozen && timesPlayedInOneSpot <= 10 && base.currentBehaviourStateIndex == 0) { _noiseMemory.Record(noisePosition, noiseLoudness, 0.5f, ((Component)this).transform.position, 20f); } } public override void KillEnemy(bool destroy = false) { StopServerMusicLoop(); if (((NetworkBehaviour)this).IsServer) { EndAlarmAttraction(returnToRoaming: false, "death"); } StopLocalMusic(); EndDamageStunFreeze(); ((EnemyAI)this).KillEnemy(destroy); if (base.isEnemyDead) { if (((NetworkBehaviour)this).IsServer) { SwitchState(2); WriteTrackSnapshot(0, -1, warningRamp: false, 0f); _networkDead.Value = true; } BeginDeathPresentation(); } } public override void OnDestroy() { try { UnsubscribeConfig(); StopServerMusicLoop(); _serverAlarmActive = false; ReleaseAllAlarmedEnemies("destroy"); if (_deathPresentationRoutine != null) { ((MonoBehaviour)this).StopCoroutine(_deathPresentationRoutine); _deathPresentationRoutine = null; } DestroyRuntimeMaterials(); } finally { ((EnemyAI)this).OnDestroy(); } } private void SubscribeConfig() { HarmonicConfig modConfig = Plugin.ModConfig; if (!_configSubscribed && modConfig != null) { modConfig.MoveSpeed.SettingChanged += OnMoveSpeedChanged; modConfig.MusicMaxDistance.SettingChanged += OnAudioDistanceChanged; modConfig.SfxMaxDistance.SettingChanged += OnAudioDistanceChanged; _configSubscribed = true; } } private void UnsubscribeConfig() { HarmonicConfig modConfig = Plugin.ModConfig; if (_configSubscribed && modConfig != null) { modConfig.MoveSpeed.SettingChanged -= OnMoveSpeedChanged; modConfig.MusicMaxDistance.SettingChanged -= OnAudioDistanceChanged; modConfig.SfxMaxDistance.SettingChanged -= OnAudioDistanceChanged; _configSubscribed = false; } } private void OnMoveSpeedChanged(object sender, EventArgs e) { ApplyMoveSpeed(); } private void OnAudioDistanceChanged(object sender, EventArgs e) { ApplyAudioDistances(); } private void ApplyAudioDistances() { Plugin.ApplyAudioDistances(musicSource, sfxSource); if ((Object)(object)_hitLayerSource != (Object)null) { _hitLayerSource.maxDistance = sfxSource.maxDistance; } } private void ApplyMoveSpeed() { if ((Object)(object)base.agent != (Object)null) { base.agent.speed = MoveSpeed; } } private bool RouteAudioSources() { bool num = CreatureAudioSetup.ConfigureSpatial(musicSource, occlude: false); bool flag = CreatureAudioSetup.ConfigureSpatial(sfxSource, occlude: false); bool flag2 = CreatureAudioSetup.ConfigureSpatial(_hitLayerSource, occlude: false); return num && flag && flag2; } private void RestartMusicLoop() { if (((NetworkBehaviour)this).IsServer && !base.isEnemyDead) { StopServerMusicLoop(); EndAlarmAttraction(returnToRoaming: true, "music-restart"); WriteTrackSnapshot(0, -1, warningRamp: false, 0f); StopMusicClientRpc(); _serverMusicRoutine = ((MonoBehaviour)this).StartCoroutine(ServerMusicLoop()); } } private void StopServerMusicLoop() { if (_serverMusicRoutine != null) { ((MonoBehaviour)this).StopCoroutine(_serverMusicRoutine); _serverMusicRoutine = null; } } private IEnumerator ServerMusicLoop() { yield return (object)new WaitForSeconds(0.05f); if (!HasIdleMusic()) { yield break; } bool nextWillAlarm = RollAlarm(); while (!base.isEnemyDead) { int num = PickIdleClipIndex(); if (num < 0) { break; } SwitchState(0); float phase = Random.Range(0f, 1000f); WriteTrackSnapshot(1, num, nextWillAlarm, phase); PlayIdleClientRpc(num, nextWillAlarm, phase); yield return (object)new WaitForSeconds(GetIdleClipLength(num)); if (base.isEnemyDead) { break; } if (nextWillAlarm && (Object)(object)alarmClip != (Object)null) { SwitchState(1); float phase2 = Random.Range(0f, 1000f); WriteTrackSnapshot(2, -1, warningRamp: false, phase2); PlayAlarmClientRpc(phase2); BeginAlarmAttraction(); yield return (object)new WaitForSeconds(Mathf.Max(0.5f, alarmClip.length)); EndAlarmAttraction(returnToRoaming: true, "alarm-end"); if (base.isEnemyDead) { break; } } nextWillAlarm = RollAlarm(); } } private bool HasIdleMusic() { if (idleMusicClips == null) { return false; } for (int i = 0; i < idleMusicClips.Length; i++) { if ((Object)(object)idleMusicClips[i] != (Object)null) { return true; } } return false; } private bool RollAlarm() { if ((Object)(object)alarmClip != (Object)null) { return Random.value < AlarmChance; } return false; } private int PickIdleClipIndex() { if (idleMusicClips == null || idleMusicClips.Length == 0) { return -1; } int num = Random.Range(0, idleMusicClips.Length); for (int i = 0; i < idleMusicClips.Length; i++) { int num2 = (num + i) % idleMusicClips.Length; if (!((Object)(object)idleMusicClips[num2] == (Object)null) && (idleMusicClips.Length <= 1 || num2 != _lastIdleIndex)) { _lastIdleIndex = num2; return num2; } } for (int j = 0; j < idleMusicClips.Length; j++) { if ((Object)(object)idleMusicClips[j] != (Object)null) { _lastIdleIndex = j; return j; } } return -1; } private float GetIdleClipLength(int index) { AudioClip val = ((idleMusicClips != null && index >= 0 && index < idleMusicClips.Length) ? idleMusicClips[index] : null); return Mathf.Max(0.5f, ((Object)(object)val != (Object)null) ? val.length : 5f); } private int PickHitClipIndex() { if (hitClips == null || hitClips.Length == 0) { return -1; } int num = Random.Range(0, hitClips.Length); for (int i = 0; i < hitClips.Length; i++) { int num2 = (num + i) % hitClips.Length; if ((Object)(object)hitClips[num2] != (Object)null) { return num2; } } return -1; } private float CalculateHitInflateAmount(int hpAfterDamage) { int num = Mathf.Max(1, Health); float num2 = Mathf.Clamp01((float)(num - Mathf.Max(0, hpAfterDamage)) / (float)num); return MaxHitInflateAmount * num2; } private Vector3 ResolveDeathEffectPosition() { //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_0031: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Unknown result type (might be due to invalid IL or missing references) if (TryGetRendererBounds(((Component)this).gameObject, out var bounds)) { return ((Bounds)(ref bounds)).center; } return ((Component)this).transform.position + Vector3.up * 1.15f; } private void BeginAlarmAttraction() { if (((NetworkBehaviour)this).IsServer) { _serverAlarmActive = true; _nextAlarmScanTime = 0f; ScanAlarmAttraction(); } } private void TickAlarmAttraction() { if (_serverAlarmActive && !(Time.time < _nextAlarmScanTime)) { ScanAlarmAttraction(); } } private void ScanAlarmAttraction() { //IL_003d: Unknown result type (might be due to invalid IL or missing references) //IL_0042: Unknown result type (might be due to invalid IL or missing references) //IL_00ba: Unknown result type (might be due to invalid IL or missing references) //IL_00bf: Unknown result type (might be due to invalid IL or missing references) //IL_00c1: Unknown result type (might be due to invalid IL or missing references) //IL_00c2: Unknown result type (might be due to invalid IL or missing references) //IL_00fd: Unknown result type (might be due to invalid IL or missing references) //IL_0101: Unknown result type (might be due to invalid IL or missing references) //IL_00e3: Unknown result type (might be due to invalid IL or missing references) //IL_00e4: Unknown result type (might be due to invalid IL or missing references) if (!_serverAlarmActive || (Object)(object)RoundManager.Instance == (Object)null) { return; } _nextAlarmScanTime = Time.time + AlarmScanSeconds; List<EnemyAI> spawnedEnemies = RoundManager.Instance.SpawnedEnemies; if (spawnedEnemies == null) { return; } Vector3 position = ((Component)this).transform.position; float alarmAttractionRadius = AlarmAttractionRadius; for (int i = 0; i < spawnedEnemies.Count; i++) { EnemyAI val = spawnedEnemies[i]; if ((Object)(object)val == (Object)null || (Object)(object)val == (Object)(object)this || val is HarmonicAI) { continue; } AlarmedEnemyState value; bool flag = _alarmedEnemies.TryGetValue(val, out value); if (!CanPull(val)) { if (flag) { ReleaseAlarmedEnemy(val, "lost-pull"); } continue; } Vector3 position2 = ((Component)val).transform.position; if (!HarmonicGather.IsInsideArea(position, position2, alarmAttractionRadius)) { if (flag) { ReleaseAlarmedEnemy(val, "out-of-range"); } continue; } if (!flag) { if (!HarmonicGather.IsInsideArea(position, position2, AlarmGatherRadius)) { AttractEnemy(val); } continue; } switch (HarmonicGather.Evaluate(position2, value.GatherPoint, value.GatherIssuedAt, Time.time)) { case GatherReissue.Arrived: IssueGatherPoint(val, value, "arrived"); break; case GatherReissue.Interval: IssueGatherPoint(val, value, "interval"); break; } } } private static bool CanPull(EnemyAI enemy) { if (!enemy.isEnemyDead && !enemy.isOutside && ((NetworkBehaviour)enemy).IsSpawned && ((NetworkBehaviour)enemy).IsOwner && !enemy.inSpecialAnimation && !enemy.IsStunned() && (Object)(object)enemy.agent != (Object)null && ((Behaviour)enemy.agent).enabled) { return enemy.agent.isOnNavMesh; } return false; } private void AttractEnemy(EnemyAI enemy) { //IL_0051: Unknown result type (might be due to invalid IL or missing references) //IL_0056: Unknown result type (might be due to invalid IL or missing references) AISearchRoutine val = ((enemy.currentSearch != null && enemy.currentSearch.inProgress) ? enemy.currentSearch : null); AlarmedEnemyState state = new AlarmedEnemyState { TargetPlayer = enemy.targetPlayer, MovingTowardsTargetPlayer = enemy.movingTowardsTargetPlayer, MoveTowardsDestination = enemy.moveTowardsDestination, Destination = enemy.destination, Search = val }; if (val != null) { enemy.StopSearch(val, false); } IssueGatherPoint(enemy, state, "first"); } private void IssueGatherPoint(EnemyAI enemy, AlarmedEnemyState state, string reason) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Unknown result type (might be due to invalid IL or missing references) //IL_0041: Unknown result type (might be due to invalid IL or missing references) //IL_0046: Unknown result type (might be due to invalid IL or missing references) //IL_004d: Unknown result type (might be due to invalid IL or missing references) //IL_004e: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_0077: 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_00a4: Unknown result type (might be due to invalid IL or missing references) //IL_00b2: Unknown result type (might be due to invalid IL or missing references) //IL_00c0: Unknown result type (might be due to invalid IL or missing references) Vector3 position = ((Component)this).transform.position; Vector3 point; int attempts; bool flag = !TryPickGatherPoint(enemy, position, out point, out attempts); if (flag) { point = ResolveAlarmDestinationFor(enemy); } enemy.targetPlayer = null; enemy.movingTowardsTargetPlayer = false; enemy.SetDestinationToPosition(point, false); state.ForcedDestination = enemy.destination; state.GatherPoint = point; state.GatherIssuedAt = Time.time; _alarmedEnemies[enemy] = state; if (DebugLogs) { float num = Vector3.Distance(position, point); ManualLogSource log = Plugin.Log; if (log != null) { log.LogInfo((object)FormattableString.Invariant(FormattableStringFactory.Create("[HarmonicAI] Harmonic alarm gather: {0} reason={1} point=({2:F2},{3:F2},{4:F2}) fromHarmonic={5:F2} attempts={6} fallback={7}", DescribeEnemy(enemy), reason, point.x, point.y, point.z, num, attempts, flag ? "true" : "false"))); } } } private bool TryPickGatherPoint(EnemyAI enemy, Vector3 center, out Vector3 point, out int attempts) { //IL_0009: Unknown result type (might be due to invalid IL or missing references) //IL_0013: Expected O, but got Unknown //IL_0020: 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_002c: Unknown result type (might be due to invalid IL or missing references) //IL_009e: Unknown result type (might be due to invalid IL or missing references) //IL_00a3: 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_0043: Unknown result type (might be due to invalid IL or missing references) //IL_005d: Unknown result type (might be due to invalid IL or missing references) //IL_0075: Unknown result type (might be due to invalid IL or missing references) //IL_007f: Unknown result type (might be due to invalid IL or missing references) //IL_0084: Unknown result type (might be due to invalid IL or missing references) if (_gatherPath == null) { _gatherPath = new NavMeshPath(); } int num = ResolveAlarmAreaMask(enemy); NavMeshHit val = default(NavMeshHit); for (attempts = 1; attempts <= 6; attempts++) { if (NavMesh.SamplePosition(HarmonicGather.CandidatePoint(center, Random.insideUnitCircle, AlarmGatherRadius), ref val, 2.5f, num) && HarmonicGather.IsInsideArea(center, ((NavMeshHit)(ref val)).position, AlarmGatherRadius) && enemy.agent.CalculatePath(((NavMeshHit)(ref val)).position, _gatherPath) && (int)_gatherPath.status == 0) { point = ((NavMeshHit)(ref val)).position; return true; } } attempts = 6; point = Vector3.zero; return false; } private Vector3 ResolveAlarmDestinationFor(EnemyAI enemy) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Unknown result type (might be due to invalid IL or missing references) Vector3 position = ((Component)this).transform.position; NavMeshHit val = default(NavMeshHit); if (NavMesh.SamplePosition(position, ref val, 8f, ResolveAlarmAreaMask(enemy))) { return ((NavMeshHit)(ref val)).position; } return position; } private static int ResolveAlarmAreaMask(EnemyAI enemy) { if (!((Object)(object)enemy.agent != (Object)null)) { return -1; } return enemy.agent.areaMask; } private void ReleaseAlarmedEnemy(EnemyAI enemy, string reason) { if (_alarmedEnemies.TryGetValue(enemy, out var value)) { _alarmedEnemies.Remove(enemy); RestoreAlarmedEnemy(enemy, value); LogAlarmRelease(enemy, reason); } } private void EndAlarmAttraction(bool returnToRoaming, string reason) { if (_serverAlarmActive || _alarmedEnemies.Count != 0) { _serverAlarmActive = false; ReleaseAllAlarmedEnemies(reason); if (returnToRoaming && !base.isEnemyDead) { SwitchState(0); } } } private void ReleaseAllAlarmedEnemies(string reason) { foreach (KeyValuePair<EnemyAI, AlarmedEnemyState> alarmedEnemy in _alarmedEnemies) { RestoreAlarmedEnemy(alarmedEnemy.Key, alarmedEnemy.Value); LogAlarmRelease(alarmedEnemy.Key, reason); } _alarmedEnemies.Clear(); } private void LogAlarmRelease(EnemyAI enemy, string reason) { if (DebugLogs) { ManualLogSource log = Plugin.Log; if (log != null) { log.LogInfo((object)("[HarmonicAI] Harmonic alarm release: " + DescribeEnemy(enemy) + " reason=" + reason)); } } } private static string DescribeEnemy(EnemyAI enemy) { if ((Object)(object)enemy == (Object)null) { return "<destroyed>"; } string arg = (((Object)(object)enemy.enemyType != (Object)null) ? enemy.enemyType.enemyName : ((Object)enemy).name); return $"{arg}#{((NetworkBehaviour)enemy).NetworkObjectId}"; } private static void RestoreAlarmedEnemy(EnemyAI enemy, AlarmedEnemyState state) { //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_005e: Unknown result type (might be due to invalid IL or missing references) if (CanRestore(enemy)) { if (enemy.destination == state.ForcedDestination) { enemy.moveTowardsDestination = state.MoveTowardsDestination; enemy.destination = state.Destination; } if (state.Search != null && enemy.currentSearch == state.Search && !state.Search.inProgress) { enemy.StartSearch(state.Search.currentSearchStartPosition, state.Search); } if ((Object)(object)enemy.targetPlayer == (Object)null && (Object)(object)state.TargetPlayer != (Object)null && enemy.PlayerIsTargetable(state.TargetPlayer, false, false, true)) { enemy.targetPlayer = state.TargetPlayer; enemy.movingTowardsTargetPlayer = state.MovingTowardsTargetPlayer; } } } private static bool CanRestore(EnemyAI enemy) { NetworkManager singleton = NetworkManager.Singleton; if ((Object)(object)enemy != (Object)null && (Object)(object)singleton != (Object)null && !singleton.ShutdownInProgress && ((NetworkBehaviour)enemy).IsSpawned && ((NetworkBehaviour)enemy).IsOwner && ((Behaviour)enemy).isActiveAndEnabled) { return !enemy.isEnemyDead; } return false; } [ClientRpc] private void PlayIdleClientRpc(int clipIndex, bool warningRamp, float phase) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Invalid comparison between Unknown and I4 //IL_00cf: Unknown result type (might be due to invalid IL or missing references) //IL_00d9: Invalid comparison between Unknown and I4 //IL_005f: Unknown result type (might be due to invalid IL or missing references) //IL_0068: Unknown result type (might be due to invalid IL or missing references) //IL_006d: Unknown result type (might be due to invalid IL or missing references) //IL_0071: Unknown result type (might be due to invalid IL or missing references) //IL_008a: Unknown result type (might be due to invalid IL or missing references) //IL_0090: Unknown result type (might be due to invalid IL or missing references) //IL_00a5: Unknown result type (might be due to invalid IL or missing references) //IL_00ab: Unknown result type (might be due to invalid IL or missing references) //IL_00bf: Unknown result type (might be due to invalid IL or missing references) //IL_0104: Unknown result type (might be due to invalid IL or missing references) NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager; if (networkManager != null && networkManager.IsListening) { if ((int)((NetworkBehaviour)this).__rpc_exec_stage != 1 && (networkManager.IsServer || networkManager.IsHost)) { ClientRpcParams val2 = default(ClientRpcParams); FastBufferWriter val = ((NetworkBehaviour)this).__beginSendClientRpc(2294735284u, val2, (RpcDelivery)0); BytePacker.WriteValueBitPacked(val, clipIndex); ((FastBufferWriter)(ref val)).WriteValueSafe<bool>(ref warningRamp, default(ForPrimitives)); ((FastBufferWriter)(ref val)).WriteValueSafe<float>(ref phase, default(ForPrimitives)); ((NetworkBehaviour)this).__endSendClientRpc(ref val, 2294735284u, val2, (RpcDelivery)0); } if ((int)((NetworkBehaviour)this).__rpc_exec_stage == 1 && (networkManager.IsClient || networkManager.IsHost)) { ((NetworkBehaviour)this).__rpc_exec_stage = (__RpcExecStage)0; _musicRpcReceived = true; PlayLocalMusicClip(1, clipIndex, ResolveIdleClip(clipIndex), warningRamp, phase); } } } [ClientRpc] private void PlayAlarmClientRpc(float phase) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Invalid comparison between Unknown and I4 //IL_00a7: Unknown result type (might be due to invalid IL or missing references) //IL_00b1: Invalid comparison between Unknown and I4 //IL_005f: Unknown result type (might be due to invalid IL or missing references) //IL_0068: Unknown result type (might be due to invalid IL or missing references) //IL_006d: Unknown result type (might be due to invalid IL or missing references) //IL_007d: Unknown result type (might be due to invalid IL or missing references) //IL_0083: Unknown result type (might be due to invalid IL or missing references) //IL_0097: Unknown result type (might be due to invalid IL or missing references) //IL_00dc: Unknown result type (might be due to invalid IL or missing references) NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager; if (networkManager != null && networkManager.IsListening) { if ((int)((NetworkBehaviour)this).__rpc_exec_stage != 1 && (networkManager.IsServer || networkManager.IsHost)) { ClientRpcParams val2 = default(ClientRpcParams); FastBufferWriter val = ((NetworkBehaviour)this).__beginSendClientRpc(643380925u, val2, (RpcDelivery)0); ((FastBufferWriter)(ref val)).WriteValueSafe<float>(ref phase, default(ForPrimitives)); ((NetworkBehaviour)this).__endSendClientRpc(ref val, 643380925u, val2, (RpcDelivery)0); } if ((int)((NetworkBehaviour)this).__rpc_exec_stage == 1 && (networkManager.IsClient || networkManager.IsHost)) { ((NetworkBehaviour)this).__rpc_exec_stage = (__RpcExecStage)0; _musicRpcReceived = true; PlayLocalMusicClip(2, -1, alarmClip, warningRamp: false, phase); } } } [ClientRpc] private void StopMusicClientRpc() { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Invalid comparison between Unknown and I4 //IL_008c: Unknown result type (might be due to invalid IL or missing references) //IL_0096: Invalid comparison between Unknown and I4 //IL_005f: Unknown result type (might be due to invalid IL or missing references) //IL_0068: Unknown result type (might be due to invalid IL or missing references) //IL_006d: Unknown result type (might be due to invalid IL or missing references) //IL_007c: Unknown result type (might be due to invalid IL or missing references) //IL_00c1: Unknown result type (might be due to invalid IL or missing references) NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager; if (networkManager != null && networkManager.IsListening) { if ((int)((NetworkBehaviour)this).__rpc_exec_stage != 1 && (networkManager.IsServer || networkManager.IsHost)) { ClientRpcParams val2 = default(ClientRpcParams); FastBufferWriter val = ((NetworkBehaviour)this).__beginSendClientRpc(4194604744u, val2, (RpcDelivery)0); ((NetworkBehaviour)this).__endSendClientRpc(ref val, 4194604744u, val2, (RpcDelivery)0); } if ((int)((NetworkBehaviour)this).__rpc_exec_stage == 1 && (networkManager.IsClient || networkManager.IsHost)) { ((NetworkBehaviour)this).__rpc_exec_stage = (__RpcExecStage)0; _musicRpcReceived = true; StopLocalMusic(); } } } [ClientRpc] private void PlayHitClientRpc(int clipIndex, float pitch, float inflateAmount, Vector3 recoilDirection) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Invalid comparison between Unknown and I4 //IL_00dc: Unknown result type (might be due to invalid IL or missing references) //IL_00e6: Invalid comparison between Unknown and I4 //IL_005f: Unknown result type (might be due to invalid IL or missing references) //IL_0068: Unknown result type (might be due to invalid IL or missing references) //IL_006d: Unknown result type (might be due to invalid IL or missing references) //IL_0071: Unknown result type (might be due to invalid IL or missing references) //IL_008a: Unknown result type (might be due to invalid IL or missing references) //IL_0090: Unknown result type (might be due to invalid IL or missing references) //IL_00a5: Unknown result type (might be due to invalid IL or missing references) //IL_00ab: Unknown result type (might be due to invalid IL or missing references) //IL_00cc: 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_0129: Unknown result type (might be due to invalid IL or missing references) //IL_012b: Unknown result type (might be due to invalid IL or missing references) NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager; if (networkManager == null || !networkManager.IsListening) { return; } if ((int)((NetworkBehaviour)this).__rpc_exec_stage != 1 && (networkManager.IsServer || networkManager.IsHost)) { ClientRpcParams val2 = default(ClientRpcParams); FastBufferWriter val = ((NetworkBehaviour)this).__beginSendClientRpc(874231898u, val2, (RpcDelivery)0); BytePacker.WriteValueBitPacked(val, clipIndex); ((FastBufferWriter)(ref val)).WriteValueSafe<float>(ref pitch, default(ForPrimitives)); ((FastBufferWriter)(ref val)).WriteValueSafe<float>(ref inflateAmount, default(ForPrimitives)); ((FastBufferWriter)(ref val)).WriteValueSafe(ref recoilDirection); ((NetworkBehaviour)this).__endSendClientRpc(ref val, 874231898u, val2, (RpcDelivery)0); } if ((int)((NetworkBehaviour)this).__rpc_exec_stage != 1 || (!networkManager.IsClient && !networkManager.IsHost)) { return; } ((NetworkBehaviour)this).__rpc_exec_stage = (__RpcExecStage)0; SetInflationTarget(inflateAmount); _flinchStartedAt = Time.time; _flinchDirection = recoilDirection; AudioClip val3 = ((hitClips != null && clipIndex >= 0 && clipIndex < hitClips.Length) ? hitClips[clipIndex] : null); if (!((Object)(object)val3 == (Object)null) && !((Object)(object)sfxSource == (Object)null)) { sfxSource.pitch = Mathf.Clamp(pitch, 0.75f, 1.3f); CreatureAudioSetup.TransmitOneShot(sfxSource, val3, SfxVolume); if (!((Object)(object)_hitLayerSource == (Object)null)) { _hitLayerSource.pitch = sfxSource.pitch * 0.7f; CreatureAudioSetup.TransmitOneShot(_hitLayerSource, val3, SfxVolume * 0.8f); } } } private AudioClip ResolveIdleClip(int clipIndex) { if (idleMusicClips == null || clipIndex < 0 || clipIndex >= idleMusicClips.Length) { return null; } return idleMusicClips[clipIndex]; } private void PlayLocalMusicClip(int kind, int clipIndex, AudioClip clip, bool warningRamp, float phase, float elapsed = 0f) { if (!((Object)(object)musicSource == (Object)null) && !((Object)(object)clip == (Object)null) && !base.isEnemyDead) { CrossFadeAnimationForTrack(kind, clipIndex, warningRamp); bool flag = kind == 2; musicSource.Stop(); musicSource.clip = clip; musicSource.loop = false; musicSource.pitch = 1f; musicSource.volume = ResolveEffectiveMusicVolume(flag); musicSource.Play(); if (elapsed > 0f) { musicSource.time = elapsed; } if (flag && elapsed <= 0f) { WalkieTalkie.TransmitOneShotAudio(musicSource, clip, musicSource.volume); } _pulsePhase = phase; _localTrackKind = kind; _localWarningRamp = warningRamp; _localClipStartedAt = Time.time - elapsed; _localClipDuration = Mathf.Max(0.1f, clip.length); } } private void WriteTrackSnapshot(int kind, int clipIndex, bool warningRamp, float phase) { //IL_0056: Unknown result type (might be due to invalid IL or missing references) //IL_005b: Unknown result type (might be due to invalid IL or missing references) _networkTrackKind.Value = kind; _networkTrackClipIndex.Value = clipIndex; _networkTrackWarningRamp.Valu
Y4NGZLocust.dll
Decompiled a day ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Reflection; using System.Reflection.Emit; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security.Cryptography; using System.Text; using System.Text.RegularExpressions; using BepInEx; using BepInEx.Bootstrap; using BepInEx.Configuration; using BepInEx.Logging; using Dawn; using DunGen; using GameNetcodeStuff; using HarmonyLib; using Microsoft.CodeAnalysis; using Unity.Netcode; using UnityEngine; using UnityEngine.AI; using UnityEngine.Audio; using UnityEngine.Events; using UnityEngine.Rendering; using Y4NGZCompany.Facility.Interior.Placement; using Y4NGZCore.Modules.Monitor; using Y4NGZCore.Modules.ShipSystems; using Y4NGZLocust; using Y4NGZLocust.Broadcast; using Y4NGZLocust.Emergence; using Y4NGZLocust.NetcodePatcher; using Y4NGZLocust.ShipDoor; using Y4NGZMonsters.Shared; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: AssemblyCompany("Y4NGZLocust")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0+3460ec64f0cec4948e51ddb3f02a4b0e414f105e")] [assembly: AssemblyProduct("Y4NGZLocust")] [assembly: AssemblyTitle("Y4NGZLocust")] [assembly: AssemblyVersion("1.0.0.0")] [module: RefSafetyRules(11)] [module: NetcodePatchedAssembly] 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 Y4NGZLocust { internal static class HuntAudio { private const string Folder = "assets/y4ngz/locust/audio/"; private const int StepCount = 4; internal static readonly AudioClip[] Steps = (AudioClip[])(object)new AudioClip[4]; internal static readonly AudioClip[] Speech = (AudioClip[])(object)new AudioClip[7]; internal static AudioClip Kill { get; private set; } internal static AudioClip IdleLoop { get; private set; } internal static AudioClip Emerge { get; private set; } internal static void Load(AssetBundle bundle) { for (int i = 0; i < Steps.Length; i++) { Steps[i] = LoadClip(bundle, "locust_body_step" + (i + 1)); } for (int j = 0; j < Speech.Length; j++) { Speech[j] = LoadClip(bundle, "locust_speech" + (j + 1)); } Kill = LoadClip(bundle, "locust_killsfx"); IdleLoop = LoadClip(bundle, "locust_idleloop"); Emerge = LoadClip(bundle, "locust_emerge"); } private static AudioClip LoadClip(AssetBundle bundle, string name) { string text = "assets/y4ngz/locust/audio/" + name + ".wav"; AudioClip obj = bundle.LoadAsset<AudioClip>(text); if ((Object)(object)obj == (Object)null) { Plugin.Log.LogWarning((object)("[Locust] y4ngzlocust.bundle has no " + text + "; the hunt plays without it.")); } return obj; } } internal readonly struct HuntBody { internal const float SourceStandHeight = 2.772f; internal const float SourceCrouchHeight = 1.5953126f; internal const float SourceBodyRadius = 0.4f; internal const float SourceCollisionHalfWidth = 0.5f; internal const float SourceHeadroomMargin = 0.1f; internal const float SourceWalkSpeed = 2.1f; internal const float SourceRunSpeed = 7.81f; internal const float SourceCrouchWalkSpeed = 1.52f; internal const float SourceMoveStartSpeed = 0.35f; internal const float SourceMoveStopSpeed = 0.12f; internal const float CatchReachPastBody = 2.4f; internal const float CrouchLeadSeconds = 0.35f; internal float Scale { get; } internal float StandHeight => 2.772f * Scale; internal float CrouchHeight => 1.5953126f * Scale; internal float BodyRadius => 0.4f * Scale; internal float StandClearance => 2.872f * Scale; internal float CatchReach => 0.5f * Scale + 2.4f; internal float MoveStartSpeed => 0.35f * Scale; internal float MoveStopSpeed => 0.12f * Scale; internal HuntBody(float scale) { Scale = ((scale > 0f) ? scale : 1f); } internal float NativeSpeed(HuntClip clip) { return clip switch { HuntClip.Walk => 2.1f * Scale, HuntClip.Run => 7.81f * Scale, HuntClip.CrouchWalk => 1.52f * Scale, _ => 0f, }; } internal float ProbeLookahead(float speed) { return BodyRadius + Math.Max(0f, speed) * 0.35f; } } internal struct HuntSighting { internal int Slot; internal float Distance; internal HuntSighting(int slot, float distance) { Slot = slot; Distance = distance; } } internal sealed class HuntBrain { internal const float AcquireSeconds = 0.2f; internal const float RetargetBuffer = 1.5f; private bool _noticing; internal int TargetSlot { get; private set; } = -1; internal float SecondsUnseen { get; private set; } internal float SecondsNoticing { get; private set; } internal void Reset() { TargetSlot = -1; SecondsUnseen = 0f; SecondsNoticing = 0f; _noticing = false; } internal LocustState Tick(LocustState state, bool stunned, HuntSighting[] visible, int visibleCount, bool targetTargetable, float deltaTime, float loseSeconds) { if (stunned) { return state; } return state switch { LocustState.Roam => TickRoam(visible, visibleCount, deltaTime), LocustState.Chase => TickChase(visible, visibleCount, targetTargetable, deltaTime, loseSeconds), _ => state, }; } private LocustState TickRoam(HuntSighting[] visible, int visibleCount, float deltaTime) { int num = Closest(visible, visibleCount); if (num < 0) { SecondsNoticing = 0f; _noticing = false; return LocustState.Roam; } if (!_noticing) { _noticing = true; SecondsNoticing = 0f; } else { SecondsNoticing += deltaTime; } if (SecondsNoticing < 0.2f) { return LocustState.Roam; } TargetSlot = visible[num].Slot; SecondsUnseen = 0f; SecondsNoticing = 0f; _noticing = false; return LocustState.Chase; } private LocustState TickChase(HuntSighting[] visible, int visibleCount, bool targetTargetable, float deltaTime, float loseSeconds) { if (TargetSlot < 0 || !targetTargetable) { Reset(); return LocustState.Roam; } int num = Closest(visible, visibleCount); if (num >= 0) { SecondsUnseen = 0f; int num2 = IndexOf(visible, visibleCount, TargetSlot); if (num2 < 0 || (visible[num].Slot != TargetSlot && visible[num].Distance < visible[num2].Distance - 1.5f)) { TargetSlot = visible[num].Slot; } return LocustState.Chase; } SecondsUnseen += deltaTime; if (SecondsUnseen < loseSeconds) { return LocustState.Chase; } Reset(); return LocustState.Roam; } private static int Closest(HuntSighting[] visible, int visibleCount) { int num = -1; for (int i = 0; i < visibleCount; i++) { if (num < 0 || visible[i].Distance < visible[num].Distance) { num = i; } } return num; } private static int IndexOf(HuntSighting[] visible, int visibleCount, int slot) { for (int i = 0; i < visibleCount; i++) { if (visible[i].Slot == slot) { return i; } } return -1; } } internal static class HuntCatchRules { internal const float ReleaseSeconds = 0.3f; internal const float RecatchGraceSeconds = 2f; internal static float JumpscareSeconds => HuntGait.ClipLength(HuntClip.Jumpscare); internal static bool CanBegin(LocustState state, bool stunned, bool catchInProgress, bool victimAlive, bool victimJustReleased, bool victimTargetable, float horizontalDistance, float verticalDistance, in HuntBody body) { if ((state == LocustState.Roam || state == LocustState.Chase) && !stunned && !catchInProgress && victimAlive && !victimJustReleased && victimTargetable && horizontalDistance <= body.CatchReach) { return verticalDistance <= body.StandHeight; } return false; } internal static bool VictimLeft(bool isPlayerControlled, bool isPlayerDead) { if (!isPlayerControlled) { return !isPlayerDead; } return false; } } internal enum HuntClip { None, Idle, Walk, Run, CrouchIdle, CrouchWalk, Jumpscare } internal static class HuntGait { internal const float MinPlayback = 0.3f; internal const float MaxPlayback = 2.5f; private const float Fps = 60f; private static readonly float[] NoSteps = Array.Empty<float>(); private static readonly float[] WalkSteps = Frames(40f, 80f, 120f, 160f, 200f, 240f, 280f, 320f); private static readonly float[] RunSteps = Frames(2f, 22f); private static readonly float[] CrouchWalkSteps = Frames(55f, 110f); internal static string StateName(HuntClip clip) { return clip switch { HuntClip.Idle => "Idle", HuntClip.Walk => "Walk", HuntClip.Run => "Run", HuntClip.CrouchIdle => "CrouchIdle", HuntClip.CrouchWalk => "CrouchWalk", HuntClip.Jumpscare => "Jumpscare", _ => null, }; } internal static HuntClip Choose(LocustState state, bool crouched, bool moving, bool stunned) { if (!LocustStates.IsHunt(state)) { return HuntClip.None; } if (state == LocustState.Catch) { return HuntClip.Jumpscare; } if (stunned || !moving) { if (!crouched) { return HuntClip.Idle; } return HuntClip.CrouchIdle; } if (crouched) { return HuntClip.CrouchWalk; } if (state != LocustState.Chase) { return HuntClip.Walk; } return HuntClip.Run; } internal static bool UpdateMoving(bool wasMoving, float speed, in HuntBody body) { if (!wasMoving) { return speed > body.MoveStartSpeed; } return !(speed < body.MoveStopSpeed); } internal static float PlaybackSpeed(HuntClip clip, float moveSpeed, in HuntBody body) { float num = body.NativeSpeed(clip); if (!(num > 0f)) { return 1f; } return Math.Clamp(moveSpeed / num, 0.3f, 2.5f); } internal static float ClipLength(HuntClip clip) { return clip switch { HuntClip.Idle => 10f, HuntClip.Walk => 5.3333335f, HuntClip.Run => 2f / 3f, HuntClip.CrouchIdle => 12.4f, HuntClip.CrouchWalk => 1.8333334f, HuntClip.Jumpscare => 1.7f, _ => 0f, }; } internal static float[] StepTimes(HuntClip clip) { return clip switch { HuntClip.Walk => WalkSteps, HuntClip.Run => RunSteps, HuntClip.CrouchWalk => CrouchWalkSteps, _ => NoSteps, }; } private static float[] Frames(params float[] frames) { float[] array = new float[frames.Length]; for (int i = 0; i < frames.Length; i++) { array[i] = frames[i] / 60f; } return array; } } internal static class HuntHeadroom { internal static int FirstLowSpan(in HuntBody body, float floor, float[] bottoms, float[] tops, int count) { float num = floor + body.CrouchHeight; float num2 = floor + body.StandClearance; for (int i = 0; i < count; i++) { if (bottoms[i] < num2 && tops[i] > num) { return i; } } return -1; } } internal sealed class HuntPosture { internal const float StandUpDelay = 0.4f; private float _clearSeconds; internal bool Crouched { get; private set; } internal bool Update(bool lowSpace, float deltaTime) { if (lowSpace) { _clearSeconds = 0f; if (Crouched) { return false; } Crouched = true; return true; } if (!Crouched) { return false; } _clearSeconds += deltaTime; if (_clearSeconds < 0.4f) { return false; } Crouched = false; _clearSeconds = 0f; return true; } internal void Reset() { Crouched = false; _clearSeconds = 0f; } } internal sealed class HuntRecatchGuard { private readonly float[] _deadlines; private readonly ulong[] _occupants; internal int Slots => _deadlines.Length; internal HuntRecatchGuard(int slots) { _deadlines = new float[Math.Max(0, slots)]; _occupants = new ulong[_deadlines.Length]; ClearAll(); } internal void Release(int slot, float now, ulong occupant) { if (Has(slot)) { _deadlines[slot] = now + 2f; _occupants[slot] = occupant; } } internal bool Blocks(int slot, float now, ulong occupant) { if (!Has(slot)) { return false; } if (now < _deadlines[slot] && _occupants[slot] == occupant) { return true; } Clear(slot); return false; } internal bool Pending(int slot, float now) { if (Has(slot)) { return now < _deadlines[slot]; } return false; } internal void Refresh(int slot, bool aliveAndControlled, ulong occupant) { if (Has(slot) && (!aliveAndControlled || _occupants[slot] != occupant)) { Clear(slot); } } internal void Clear(int slot) { if (Has(slot)) { _deadlines[slot] = float.NegativeInfinity; } } internal void ClearAll() { for (int i = 0; i < _deadlines.Length; i++) { _deadlines[i] = float.NegativeInfinity; } } private bool Has(int slot) { if (slot >= 0) { return slot < _deadlines.Length; } return false; } } internal static class HuntSight { internal const float Range = 40f; internal const float HalfAngle = 60f; private const float RadToDeg = 57.29578f; internal static bool InView(float headX, float headY, float headZ, float forwardX, float forwardZ, float viewX, float viewY, float viewZ, float proximity, out float distance) { float num = viewX - headX; float num2 = viewY - headY; float num3 = viewZ - headZ; float num4 = num * num + num2 * num2 + num3 * num3; distance = (float)Math.Sqrt(num4); if (distance >= 40f) { return false; } if (!(distance < proximity)) { return Angle(forwardX * forwardX + forwardZ * forwardZ, num4, forwardX * num + forwardZ * num3) < 60f; } return true; } private static float Angle(float fromSquared, float toSquared, float dot) { float num = (float)Math.Sqrt(fromSquared * toSquared); if (num < 1E-15f) { return 0f; } return (float)Math.Acos(Math.Clamp(dot / num, -1f, 1f)) * 57.29578f; } } internal struct HuntSnapshot : INetworkSerializable, IEquatable<HuntSnapshot> { internal static readonly HuntSnapshot Initial = new HuntSnapshot { VictimSlot = -1 }; internal byte State; internal bool Crouched; internal bool Moving; internal ushort MoveSpeedCm; internal short VictimSlot; internal byte CatchSeq; internal byte SpeechLine; internal byte SpeechSeq; public unsafe void NetworkSerialize<T>(BufferSerializer<T> serializer) where T : IReaderWriter { //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Unknown result type (might be due to invalid IL or missing references) //IL_0043: Unknown result type (might be due to invalid IL or missing references) //IL_0049: Unknown result type (might be due to invalid IL or missing references) //IL_0059: Unknown result type (might be due to invalid IL or missing references) //IL_005f: Unknown result type (might be due to invalid IL or missing references) serializer.SerializeValue(ref State); ((BufferSerializer<bool>*)(&serializer))->SerializeValue<bool>(ref Crouched, default(ForPrimitives)); ((BufferSerializer<bool>*)(&serializer))->SerializeValue<bool>(ref Moving, default(ForPrimitives)); ((BufferSerializer<ushort>*)(&serializer))->SerializeValue<ushort>(ref MoveSpeedCm, default(ForPrimitives)); ((BufferSerializer<short>*)(&serializer))->SerializeValue<short>(ref VictimSlot, default(ForPrimitives)); serializer.SerializeValue(ref CatchSeq); serializer.SerializeValue(ref SpeechLine); serializer.SerializeValue(ref SpeechSeq); } public bool Equals(HuntSnapshot other) { if (State == other.State && Crouched == other.Crouched && Moving == other.Moving && MoveSpeedCm == other.MoveSpeedCm && VictimSlot == other.VictimSlot && CatchSeq == other.CatchSeq && SpeechLine == other.SpeechLine) { return SpeechSeq == other.SpeechSeq; } return false; } } internal sealed class HuntSpeech { internal const int LineCount = 7; private readonly Random _random; internal int LastLine { get; private set; } internal double NextAt { get; private set; } internal HuntSpeech(Random random) { _random = random; } internal void Schedule(double now, float minSeconds, float maxSeconds) { NextAt = now + (double)Interval(_random.NextDouble(), minSeconds, maxSeconds); } internal int Tick(double now, bool canSpeak, float minSeconds, float maxSeconds) { if (!canSpeak || now < NextAt) { return 0; } int num = _random.Next((LastLine > 0) ? 6 : 7) + 1; if (LastLine > 0 && num >= LastLine) { num++; } LastLine = num; Schedule(now, minSeconds, maxSeconds); return num; } internal static float Interval(double unit, float minSeconds, float maxSeconds) { double num = Math.Max(0.0, Math.Min(minSeconds, maxSeconds)); double num2 = Math.Max(0.0, Math.Max(minSeconds, maxSeconds)); return (float)(num + unit * (num2 - num)); } } internal sealed class HuntStepTimer { internal HuntClip Clip { get; private set; } internal float Phase { get; private set; } internal int Advance(HuntClip clip, float deltaTime, float playbackSpeed) { if (clip != Clip) { Clip = clip; Phase = 0f; } float num = HuntGait.ClipLength(clip); if (num <= 0f || !(deltaTime > 0f) || !(playbackSpeed > 0f)) { return 0; } float phase = Phase; float num2 = phase + deltaTime * playbackSpeed; Phase = num2 % num; float[] array = HuntGait.StepTimes(clip); int num3 = 0; for (int i = 0; i < array.Length; i++) { num3 += StepsUpTo(num2, array[i], num) - StepsUpTo(phase, array[i], num); } return num3; } internal void Reset() { Clip = HuntClip.None; Phase = 0f; } private static int StepsUpTo(float phase, float t, float length) { return Math.Max(0, (int)MathF.Floor((phase - t) / length) + 1); } } public sealed class LocustAI : EnemyAI { private const string InputLockHolder = "Y4NGZLocust"; private const float CatchRequestCooldown = 0.5f; private const float FacingSeconds = 0.25f; private const float MaxVictimPitch = 60f; private PlayerControllerB _huntCatchVictim; private float _huntCatchStartTime; private bool _huntKillSent; private string _huntLastRefusal; private HuntRecatchGuard _huntRecatch; private float _huntNextCatchRequestTime; private PlayerControllerB _huntHeldVictim; private int _huntHeldSlot = -1; private bool _huntLocalHold; private float _huntHoldStartTime; private float _huntHoldStartYaw; private float _huntHoldStartPitch; private const float GaitCrossFade = 0.2f; private const float JumpscareCrossFade = 0.1f; private const float SpeakCrossFade = 0.1f; private const float FearSightWidth = 80f; private const int FearSightRange = 25; private const float FearProximity = 5f; private const float FearRate = 0.8f; private const float RoamFearCap = 0.5f; private const string SpeakLayerName = "Speak"; private const string SpeakEmptyState = "Empty"; private static readonly int CrouchedHash = Animator.StringToHash("Crouched"); private static readonly string[] SpeakStates = new string[7] { "Speak1", "Speak2", "Speak3", "Speak4", "Speak5", "Speak6", "Speak7" }; private readonly HuntStepTimer _huntSteps = new HuntStepTimer(); private HuntSnapshot _huntApplied = HuntSnapshot.Initial; private bool _huntHasApplied; private bool _huntPresenting; private bool _huntPresentStunned; private HuntClip _huntClip; private int _huntSpeakLayer = -1; private bool _huntSpeaking; private const float WatchIntervalSeconds = 0.2f; private const int WatchRangeMeters = 20; private const float WatchPointDepth = 0.05f; private const float SwitchOffReachMeters = 6f; private const float ChargePublishStep = 0.01f; private readonly NetworkVariable<BroadcastSnapshot> _broadcast = new NetworkVariable<BroadcastSnapshot>(default(BroadcastSnapshot), (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); private Renderer[] _bodyRenderers; private Collider[] _bodyColliders; private bool[] _bodyCollidersEnabled; private LocustTvView _tv; private bool _warnedClientManifest; private BroadcastSettings _broadcastSettings; private TvPlacementJob _placement; private BroadcastState _broadcastState; private float _publishedCharge; private Vector3 _watchPoint; private Vector3 _tvForward; private float _watchTimer; private bool _watched; internal const string AnimCrouched = "Crouched"; private readonly ServerOwnershipGuard _ownership = new ServerOwnershipGuard(); private const string EmergenceVisualPath = "VisualRoot"; private static readonly int TvExitHash = Animator.StringToHash("TvExit"); private readonly NetworkVariable<EmergenceSnapshot> _emergence = new NetworkVariable<EmergenceSnapshot>(default(EmergenceSnapshot), (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); private bool _warnedClientEmergence; private Vector3 _emergenceStandPoint; private StandResult _emergenceStand; private bool _emergenceBound; private Transform _emergenceVisual; private SkinnedMeshRenderer _emergenceBody; private Transform[] _emergenceBones; private int[] _emergenceGroup; private Transform[] _emergenceStandIns; private Transform[] _emergenceWorking; private Vector3 _emergenceVisualLocalPosition; private Quaternion _emergenceVisualLocalRotation; private Vector3 _emergencePinStart; private Vector3 _emergencePinPosition; private Quaternion _emergencePinRotation; private bool _emergencePresenting; private float _emergenceClock; private int _emergenceSteps; private int _emergenceShown; private bool _emergenceSoundHeld; private Vector3 _emergenceSoundLocalPosition; private Vector3 _emergenceSoundPoint; private const float ProximityAwarenessPerScale = 4f; private const float AgentAcceleration = 35f; private const float AgentAngularSpeed = 600f; private const float ProbeInterval = 0.1f; private const float ProbeRadiusScale = 0.75f; private const float ProbeSpacingRadii = 1.5f; private const int MaxProbeSamples = 12; private const float MaxProbeSlope = 1f; private const int MiscLevelGeometryLayer = 24; private const int ProbeIgnoredLayers = 1572872; private const int ProbeHitCapacity = 16; private const int MaxStateEdgesPerFrame = 3; private readonly NetworkVariable<HuntSnapshot> _huntSnapshot = new NetworkVariable<HuntSnapshot>(HuntSnapshot.Initial, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); private readonly HuntBrain _huntBrain = new HuntBrain(); private readonly HuntPosture _huntPosture = new HuntPosture(); private readonly HuntSpeech _huntSpeech = new HuntSpeech(new Random()); private readonly AISearchRoutine _huntSearch = new AISearchRoutine(); private HuntBody _huntBody = new HuntBody(1f); private HuntSighting[] _huntSightings = Array.Empty<HuntSighting>(); private bool _huntAudioReady; private LocustState _huntServerState; private HuntSnapshot _huntServerSnapshot = HuntSnapshot.Initial; private bool _huntServerStunned; private bool _huntMoving; private float _huntProbeElapsed; private readonly Collider[] _huntProbeColliders = (Collider[])(object)new Collider[16]; private readonly RaycastHit[] _huntProbeHits = (RaycastHit[])(object)new RaycastHit[16]; private readonly float[] _huntProbeBottoms = new float[16]; private readonly float[] _huntProbeTops = new float[16]; private readonly Collider[] _huntProbeSpanColliders = (Collider[])(object)new Collider[16]; private int _huntLowSample; private int _huntLowSamples; private Vector3 _huntLowFloor; private string _huntLowKind; private Collider _huntLowCollider; private float _huntLowBottom; private float _huntLowTop; private Transform _huntHead; private bool _huntHeadSearched; private bool _huntHeadWarned; private readonly NetworkVariable<ShipDoorSnapshot> _shipDoor = new NetworkVariable<ShipDoorSnapshot>(default(ShipDoorSnapshot), (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); private static LocustAI s_shipDoorHolder; private ShipDoorSettings _shipDoorSettings; private ShipDoorClock _shipDoorClock; private bool _shipDoorFailed; private bool _shipDoorLoggedGi; private ShipMonitorView _shipMonitors; private bool _shipMonitorsRefused; private bool _shipDoorOutsideApplied; private double BroadcastNow { get { //IL_001a: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Unknown result type (might be due to invalid IL or missing references) if (!((Object)(object)((NetworkBehaviour)this).NetworkManager != (Object)null)) { return Time.timeAsDouble; } NetworkTime serverTime = ((NetworkBehaviour)this).NetworkManager.ServerTime; return ((NetworkTime)(ref serverTime)).Time; } } internal bool BroadcastUnplaced => _broadcast.Value.CurrentPhase == BroadcastPhase.Unplaced; [ServerRpc(RequireOwnership = false)] private void HuntCatchServerRpc(int slot, ServerRpcParams rpcParams = default(ServerRpcParams)) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Invalid comparison between Unknown and I4 //IL_0099: Unknown result type (might be due to invalid IL or missing references) //IL_00a3: Invalid comparison between Unknown and I4 //IL_005f: Unknown result type (might be due to invalid IL or missing references) //IL_0068: Unknown result type (might be due to invalid IL or missing references) //IL_006d: Unknown result type (might be due to invalid IL or missing references) //IL_0071: Unknown result type (might be due to invalid IL or missing references) //IL_0089: Unknown result type (might be due to invalid IL or missing references) //IL_00ce: Unknown result type (might be due to invalid IL or missing references) //IL_00dd: Unknown result type (might be due to invalid IL or missing references) //IL_00de: Unknown result type (might be due to invalid IL or missing references) NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager; if (networkManager == null || !networkManager.IsListening) { return; } if ((int)((NetworkBehaviour)this).__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost)) { FastBufferWriter val = ((NetworkBehaviour)this).__beginSendServerRpc(2734622522u, rpcParams, (RpcDelivery)0); BytePacker.WriteValueBitPacked(val, slot); ((NetworkBehaviour)this).__endSendServerRpc(ref val, 2734622522u, rpcParams, (RpcDelivery)0); } if ((int)((NetworkBehaviour)this).__rpc_exec_stage != 1 || (!networkManager.IsServer && !networkManager.IsHost)) { return; } ((NetworkBehaviour)this).__rpc_exec_stage = (__RpcExecStage)0; PlayerControllerB val2 = VictimRpc.FromSlot(slot); string text = HuntCatchRefusal(slot, val2, rpcParams.Receive.SenderClientId); if (text != null) { if ((object)text != _huntLastRefusal) { _huntLastRefusal = text; Plugin.Log.LogInfo((object)$"[Locust] catch refused slot {slot}: {text}"); } return; } _huntLastRefusal = null; _huntCatchVictim = val2; _huntCatchStartTime = Time.time; _huntKillSent = false; ((EnemyAI)this).StopSearch(base.currentSearch, false); base.movingTowardsTargetPlayer = false; ((EnemyAI)(object)this).HoldAgent(); _huntMoving = false; val2.inAnimationWithEnemy = (EnemyAI)(object)this; base.inSpecialAnimationWithPlayer = val2; _huntServerSnapshot.CatchSeq++; _huntServerSnapshot.VictimSlot = (short)slot; _huntServerSnapshot.State = 4; _huntServerSnapshot.Moving = false; ((EnemyAI)this).SwitchToBehaviourState(4); HuntPublish(); Plugin.Log.LogInfo((object)$"[Locust] catch accepted slot {slot}"); } private string HuntCatchRefusal(int slot, PlayerControllerB victim, ulong senderClientId) { //IL_0084: Unknown result type (might be due to invalid IL or missing references) //IL_008f: Unknown result type (might be due to invalid IL or missing references) //IL_0094: Unknown result type (might be due to invalid IL or missing references) //IL_0099: Unknown result type (might be due to invalid IL or missing references) //IL_009b: Unknown result type (might be due to invalid IL or missing references) //IL_0135: Unknown result type (might be due to invalid IL or missing references) //IL_013a: Unknown result type (might be due to invalid IL or missing references) //IL_0150: Unknown result type (might be due to invalid IL or missing references) //IL_0155: Unknown result type (might be due to invalid IL or missing references) //IL_0180: Unknown result type (might be due to invalid IL or missing references) //IL_0173: Unknown result type (might be due to invalid IL or missing references) //IL_0185: Unknown result type (might be due to invalid IL or missing references) //IL_0187: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)victim == (Object)null) { return "no such player"; } if (!VictimRpc.SenderOwnsSlot(senderClientId, victim)) { return "the sender does not control that player"; } LocustState currentBehaviourStateIndex = (LocustState)base.currentBehaviourStateIndex; bool flag = ((EnemyAI)(object)this).IsStunned(); bool flag2 = (Object)(object)_huntCatchVictim != (Object)null; bool flag3 = victim.isPlayerControlled && !victim.isPlayerDead; bool flag4 = _huntRecatch != null && _huntRecatch.Blocks(slot, Time.time, victim.actualClientId); bool flag5 = ((EnemyAI)this).PlayerIsTargetable(victim, false, false, true); Vector3 val = ((Component)victim).transform.position - ((Component)this).transform.position; float verticalDistance = Mathf.Abs(val.y); val.y = 0f; float magnitude = ((Vector3)(ref val)).magnitude; if (!HuntCatchRules.CanBegin(currentBehaviourStateIndex, flag, flag2, flag3, flag4, flag5, magnitude, verticalDistance, in _huntBody)) { if (currentBehaviourStateIndex == LocustState.Roam || currentBehaviourStateIndex == LocustState.Chase) { if (!flag) { if (!flag2) { if (flag3) { if (!flag4) { if (flag5) { if (!(magnitude > _huntBody.CatchReach)) { return "too far above or below"; } return "out of reach"; } return "player not targetable"; } return "just released"; } return "player not alive"; } return "already catching"; } return "stunned"; } return "not roaming or chasing"; } Vector3 val2 = ((Component)this).transform.position + Vector3.up * (_huntBody.CrouchHeight * 0.5f); Vector3 val3 = (((Object)(object)victim.upperSpine != (Object)null) ? victim.upperSpine.position : ((Component)victim.gameplayCamera).transform.position); if (Physics.Linecast(val2, val3, StartOfRound.Instance.collidersAndRoomMask, (QueryTriggerInteraction)1)) { return "no line of sight"; } return null; } private void HuntServerCatchTick(bool stunned) { //IL_00b3: Unknown result type (might be due to invalid IL or missing references) //IL_00fe: Unknown result type (might be due to invalid IL or missing references) ((EnemyAI)(object)this).HoldAgent(); PlayerControllerB huntCatchVictim = _huntCatchVictim; if ((Object)(object)huntCatchVictim == (Object)null) { HuntEndCatch("aborted (player gone)", switchToRoam: true); return; } if (stunned) { HuntEndCatch(_huntKillSent ? "ended (stunned after the kill)" : "aborted (stunned), player released alive", switchToRoam: true); return; } if (HuntCatchRules.VictimLeft(huntCatchVictim.isPlayerControlled, huntCatchVictim.isPlayerDead)) { HuntEndCatch("aborted (player disconnected)", switchToRoam: true); return; } float num = Time.time - _huntCatchStartTime; if (!_huntKillSent) { string text = (huntCatchVictim.isPlayerDead ? "aborted (player died first)" : (((Object)(object)huntCatchVictim.inAnimationWithEnemy != (Object)(object)this) ? "aborted (hold cancelled), player released alive" : null)); if (text != null) { HuntEndCatch(text, switchToRoam: true); return; } HuntTurnToward(((Component)huntCatchVictim).transform.position); if (num >= HuntCatchRules.JumpscareSeconds) { _huntKillSent = true; Plugin.Log.LogInfo((object)$"[Locust] catch kill sent slot {_huntServerSnapshot.VictimSlot}"); HuntKillClientRpc((ulong)_huntServerSnapshot.VictimSlot, VictimRpc.TargetOwner(huntCatchVictim)); } } else if (num >= HuntCatchRules.JumpscareSeconds + 0.3f) { HuntEndCatch("finished", switchToRoam: true); } } private void HuntEndCatch(string outcome, bool switchToRoam) { PlayerControllerB huntCatchVictim = _huntCatchVictim; int victimSlot = _huntServerSnapshot.VictimSlot; Plugin.Log.LogInfo((object)$"[Locust] catch {outcome} slot {victimSlot}"); _huntCatchVictim = null; _huntKillSent = false; _huntServerSnapshot.VictimSlot = -1; if ((Object)(object)huntCatchVictim != (Object)null) { HuntUnmark(huntCatchVictim); if (_huntRecatch != null && huntCatchVictim.isPlayerControlled && !huntCatchVictim.isPlayerDead) { _huntRecatch.Release(victimSlot, Time.time, huntCatchVictim.actualClientId); Plugin.Log.LogInfo((object)$"[Locust] slot {victimSlot} let go alive: no re-catch for {2f:0.0} s"); } } if (switchToRoam && base.currentBehaviourStateIndex == 4) { ((EnemyAI)this).SwitchToBehaviourState(2); _huntServerSnapshot.State = 2; } HuntPublish(); } private void HuntServerRefreshRecatch() { HuntRecatchGuard huntRecatch = _huntRecatch; if (huntRecatch == null) { return; } float time = Time.time; for (int i = 0; i < huntRecatch.Slots; i++) { if (huntRecatch.Pending(i, time)) { PlayerControllerB val = VictimRpc.FromSlot(i); if ((Object)(object)val == (Object)null) { huntRecatch.Clear(i); } else { huntRecatch.Refresh(i, val.isPlayerControlled && !val.isPlayerDead, val.actualClientId); } } } } private void HuntTurnToward(Vector3 point) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Unknown result type (might be due to invalid IL or missing references) //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_0041: Unknown result type (might be due to invalid IL or missing references) //IL_0047: Unknown result type (might be due to invalid IL or missing references) //IL_004d: Unknown result type (might be due to invalid IL or missing references) //IL_0075: Unknown result type (might be due to invalid IL or missing references) //IL_007c: Unknown result type (might be due to invalid IL or missing references) //IL_0082: Unknown result type (might be due to invalid IL or missing references) Vector3 val = point - ((Component)this).transform.position; if (!(val.x * val.x + val.z * val.z < 0.0001f)) { Vector3 eulerAngles = ((Component)this).transform.eulerAngles; float num = Mathf.MoveTowardsAngle(eulerAngles.y, Mathf.Atan2(val.x, val.z) * 57.29578f, 600f * Time.deltaTime); ((Component)this).transform.eulerAngles = new Vector3(eulerAngles.x, num, eulerAngles.z); } } [ClientRpc] private void HuntKillClientRpc(ulong slot, ClientRpcParams clientRpcParams = default(ClientRpcParams)) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Invalid comparison between Unknown and I4 //IL_0099: Unknown result type (might be due to invalid IL or missing references) //IL_00a3: Invalid comparison between Unknown and I4 //IL_005f: Unknown result type (might be due to invalid IL or missing references) //IL_0068: Unknown result type (might be due to invalid IL or missing references) //IL_006d: Unknown result type (might be due to invalid IL or missing references) //IL_0071: Unknown result type (might be due to invalid IL or missing references) //IL_0089: Unknown result type (might be due to invalid IL or missing references) //IL_00ce: Unknown result type (might be due to invalid IL or missing references) //IL_0122: 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_0132: Unknown result type (might be due to invalid IL or missing references) NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager; if (networkManager == null || !networkManager.IsListening) { return; } if ((int)((NetworkBehaviour)this).__rpc_exec_stage != 1 && (networkManager.IsServer || networkManager.IsHost)) { FastBufferWriter val = ((NetworkBehaviour)this).__beginSendClientRpc(2094350016u, clientRpcParams, (RpcDelivery)0); BytePacker.WriteValueBitPacked(val, slot); ((NetworkBehaviour)this).__endSendClientRpc(ref val, 2094350016u, clientRpcParams, (RpcDelivery)0); } if ((int)((NetworkBehaviour)this).__rpc_exec_stage != 1 || (!networkManager.IsClient && !networkManager.IsHost)) { return; } ((NetworkBehaviour)this).__rpc_exec_stage = (__RpcExecStage)0; HuntApplyLatest(); PlayerControllerB val2 = VictimRpc.LocalVictimFromSlot(slot); if (!((Object)(object)val2 == (Object)null) && !val2.isPlayerDead) { if ((Object)(object)val2 != (Object)(object)_huntHeldVictim) { Plugin.Log.LogInfo((object)$"[Locust] catch kill skipped slot {slot}: not held here"); return; } HuntReleaseHold(); val2.KillPlayer(Vector3.zero, true, (CauseOfDeath)0, 0, default(Vector3), false); Plugin.Log.LogInfo((object)$"[Locust] catch killed slot {slot}"); } } private void HuntPresentHold(int slot) { //IL_00bb: Unknown result type (might be due to invalid IL or missing references) //IL_00d6: Unknown result type (might be due to invalid IL or missing references) HuntReleaseHold(); PlayerControllerB val = VictimRpc.FromSlot(slot); if ((Object)(object)val == (Object)null || val.isPlayerDead) { return; } _huntHeldVictim = val; _huntHeldSlot = slot; val.inAnimationWithEnemy = (EnemyAI)(object)this; base.inSpecialAnimationWithPlayer = val; if (VictimRpc.IsVictimLocal(val)) { GameNetworkManager instance = GameNetworkManager.Instance; if ((Object)(object)instance != (Object)null && (Object)(object)val == (Object)(object)instance.localPlayerController) { val.CancelSpecialTriggerAnimations(); val.JumpToFearLevel(1f, true); } if (!PlayerInputLock.Acquire(val, "Y4NGZLocust")) { Plugin.Log.LogInfo((object)$"[Locust] slot {slot} is held by something else; the catch plays without turning the view"); return; } _huntLocalHold = true; val.inSpecialInteractAnimation = true; _huntHoldStartTime = Time.time; _huntHoldStartYaw = ((Component)val).transform.eulerAngles.y; _huntHoldStartPitch = ((Component)val.gameplayCamera).transform.localEulerAngles.x; } } private void HuntCheckHold() { PlayerControllerB huntHeldVictim = _huntHeldVictim; if (!((Object)(object)huntHeldVictim == (Object)null) && (_huntApplied.State != 4 || _huntApplied.VictimSlot != _huntHeldSlot || huntHeldVictim.isPlayerDead || !((Object)(object)huntHeldVictim.inAnimationWithEnemy == (Object)(object)this))) { HuntReleaseHold(); } } private void HuntReleaseHold() { PlayerControllerB huntHeldVictim = _huntHeldVictim; _huntHeldVictim = null; _huntHeldSlot = -1; if (huntHeldVictim != null) { if (_huntLocalHold) { _huntLocalHold = false; PlayerInputLock.Release(huntHeldVictim, "Y4NGZLocust"); huntHeldVictim.inSpecialInteractAnimation = false; } HuntUnmark(huntHeldVictim); } } private void HuntUnmark(PlayerControllerB player) { if ((Object)(object)player.inAnimationWithEnemy == (Object)(object)this) { player.inAnimationWithEnemy = null; } if ((Object)(object)base.inSpecialAnimationWithPlayer == (Object)(object)player) { base.inSpecialAnimationWithPlayer = null; } } private void HuntDropCatch() { HuntReleaseHold(); PlayerControllerB huntCatchVictim = _huntCatchVictim; _huntCatchVictim = null; if (huntCatchVictim != null) { HuntUnmark(huntCatchVictim); } _huntRecatch?.ClearAll(); } private void HuntPresent() { HuntApplyLatest(); HuntCheckHold(); LocustState state = (LocustState)_huntApplied.State; if (!LocustStates.IsHunt(state)) { if (_huntPresenting) { HuntLeavePresentation(); } return; } _huntPresenting = true; bool stunned = ((EnemyAI)(object)this).IsStunned(); if (((EnemyAI)(object)this).TrackStun(ref _huntPresentStunned) == StunEdge.Started) { HuntStopSpeech(); } HuntAnimate(state, stunned); HuntVoice(state); HuntFear(state); } private void HuntApplyLatest() { HuntSnapshot snapshot = _huntSnapshot.Value; if (!_huntHasApplied || !snapshot.Equals(_huntApplied)) { HuntApply(in snapshot); } } private void HuntApply(in HuntSnapshot snapshot) { bool flag = !_huntHasApplied; HuntSnapshot huntApplied = _huntApplied; _huntApplied = snapshot; _huntHasApplied = true; if (!((NetworkBehaviour)this).IsServer && snapshot.State != base.currentBehaviourStateIndex && snapshot.State < base.enemyBehaviourStates.Length) { ((EnemyAI)this).SwitchToBehaviourStateOnLocalClient((int)snapshot.State); } LocustState state = (LocustState)snapshot.State; if (state == LocustState.Catch && snapshot.VictimSlot >= 0 && (flag || snapshot.CatchSeq != huntApplied.CatchSeq)) { HuntPresentCatch(snapshot.VictimSlot, flag); } else if (!flag && snapshot.SpeechSeq != huntApplied.SpeechSeq && (state == LocustState.Roam || state == LocustState.Chase)) { HuntPresentSpeech(snapshot.SpeechLine); } } private void HuntPresentCatch(int slot, bool first) { _huntClip = HuntClip.None; if ((Object)(object)base.creatureVoice != (Object)null) { base.creatureVoice.Stop(); } HuntEndSpeak(); if (!first) { CreatureAudioSetup.TransmitOneShot(base.creatureSFX, HuntAudio.Kill); } HuntPresentHold(slot); } private void HuntPresentSpeech(byte line) { if (line >= 1 && line <= 7) { AudioClip val = HuntAudio.Speech[line - 1]; if ((Object)(object)val != (Object)null && (Object)(object)base.creatureVoice != (Object)null) { base.creatureVoice.Stop(); base.creatureVoice.clip = val; base.creatureVoice.loop = false; base.creatureVoice.Play(); } if (_huntSpeakLayer >= 0) { base.creatureAnimator.CrossFadeInFixedTime(SpeakStates[line - 1], 0.1f, _huntSpeakLayer, 0f); } _huntSpeaking = true; Plugin.Log.LogInfo((object)$"[Locust] speaks line {line} (locust_speech{line})"); } } private void HuntStopSpeech() { if (_huntSpeaking) { AudioSource creatureVoice = base.creatureVoice; if ((Object)(object)creatureVoice != (Object)null && (Object)(object)creatureVoice.clip != (Object)(object)HuntAudio.IdleLoop) { creatureVoice.Stop(); } HuntEndSpeak(); } } private void HuntEndSpeak() { if (_huntSpeaking) { _huntSpeaking = false; if (_huntSpeakLayer >= 0 && (Object)(object)base.creatureAnimator != (Object)null) { base.creatureAnimator.CrossFadeInFixedTime("Empty", 0.1f, _huntSpeakLayer, 0f); } } } private void HuntAnimate(LocustState state, bool stunned) { Animator creatureAnimator = base.creatureAnimator; if ((Object)(object)creatureAnimator == (Object)null) { return; } creatureAnimator.SetBool(CrouchedHash, _huntApplied.Crouched); HuntClip huntClip = HuntGait.Choose(state, _huntApplied.Crouched, _huntApplied.Moving, stunned); if (huntClip != _huntClip) { _huntClip = huntClip; creatureAnimator.CrossFadeInFixedTime(HuntGait.StateName(huntClip), (huntClip == HuntClip.Jumpscare) ? 0.1f : 0.2f, 0, 0f); } float playbackSpeed = (creatureAnimator.speed = HuntGait.PlaybackSpeed(huntClip, (float)(int)_huntApplied.MoveSpeedCm / 100f, in _huntBody)); if (_huntSteps.Advance(huntClip, Time.deltaTime, playbackSpeed) > 0 && (Object)(object)base.creatureSFX != (Object)null) { AudioClip val = HuntAudio.Steps[Random.Range(0, HuntAudio.Steps.Length)]; if ((Object)(object)val != (Object)null) { base.creatureSFX.PlayOneShot(val); } } } private void HuntVoice(LocustState state) { AudioSource creatureVoice = base.creatureVoice; if (_huntSpeaking && ((Object)(object)creatureVoice == (Object)null || !creatureVoice.isPlaying || (Object)(object)creatureVoice.clip == (Object)(object)HuntAudio.IdleLoop)) { HuntEndSpeak(); } if ((Object)(object)creatureVoice == (Object)null) { return; } if (state == LocustState.Catch) { if (creatureVoice.isPlaying) { creatureVoice.Stop(); } } else if (!creatureVoice.isPlaying && !((Object)(object)HuntAudio.IdleLoop == (Object)null)) { creatureVoice.clip = HuntAudio.IdleLoop; creatureVoice.loop = true; creatureVoice.Play(); } } private void HuntFear(LocustState state) { //IL_003a: Unknown result type (might be due to invalid IL or missing references) if (state == LocustState.Catch) { return; } GameNetworkManager instance = GameNetworkManager.Instance; PlayerControllerB val = (((Object)(object)instance != (Object)null) ? instance.localPlayerController : null); if (!((Object)(object)val == (Object)null) && !val.isPlayerDead && HuntTryHeadPoint(out var point) && val.HasLineOfSightToPosition(point, 80f, 25, 5f, -1)) { if (state == LocustState.Chase) { val.IncreaseFearLevelOverTime(0.8f, 1f); } else { val.IncreaseFearLevelOverTime(0.8f, 0.5f); } } } private void HuntLeavePresentation() { _huntPresenting = false; _huntPresentStunned = false; _huntClip = HuntClip.None; _huntSteps.Reset(); if ((Object)(object)base.creatureAnimator != (Object)null) { base.creatureAnimator.speed = 1f; ((EnemyAI)this).PlayAnimationOfCurrentState(); HuntClip clip = ((base.currentBehaviourStateIndex != 1) ? HuntClip.Idle : HuntClip.CrouchIdle); base.creatureAnimator.CrossFadeInFixedTime(HuntGait.StateName(clip), 0.2f, 0, 0f); } if ((Object)(object)base.creatureVoice != (Object)null) { base.creatureVoice.Stop(); } HuntEndSpeak(); HuntReleaseHold(); } internal void SetManifested(bool shown) { if (!((NetworkBehaviour)this).IsServer) { if (!_warnedClientManifest) { _warnedClientManifest = true; Plugin.Log.LogWarning((object)"Locust: SetManifested is server only; ignored on this client."); } } else { BroadcastSnapshot value = _broadcast.Value; value.Manifested = shown; _broadcast.Value = value; } } private bool TickBroadcastServer(double now) { if (_broadcastState.Phase == BroadcastPhase.Unplaced) { if (_placement == null) { RemoveUnplaced("no usable TV prefab Assets/Y4NGZ/Locust/Prefabs/LocustTV.prefab, removing the Locust"); return false; } switch (_placement.Tick(now)) { case TvPlacementStatus.Placed: PlaceTv(now); break; case TvPlacementStatus.GaveUp: RemoveUnplaced("no valid room, removing the Locust: " + _placement.Summary); return false; } return true; } if (_broadcastState.Phase == BroadcastPhase.On || _broadcastState.Phase == BroadcastPhase.Off) { _watchTimer -= Time.deltaTime; if (_watchTimer <= 0f) { _watchTimer = 0.2f; _watched = AnyPlayerWatching(); } } BroadcastState to = BroadcastRules.Advance(_broadcastState, now, Time.deltaTime, _watched, _broadcastSettings); if (to.Phase != _broadcastState.Phase) { LogPhaseChange(in _broadcastState, in to, null); } to = ((to.Phase != BroadcastPhase.Ready) ? ShipDoorDecide(in to, now) : BroadcastHandOver(in to, now)); bool num = to.Phase != _broadcastState.Phase; _broadcastState = to; if (num && to.Phase == BroadcastPhase.On) { _watchTimer = 0f; } if (num || Mathf.Abs(to.Charge - _publishedCharge) >= 0.01f) { PublishBroadcast(); } return true; } private BroadcastState BroadcastHandOver(in BroadcastState ready, double now) { //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Unknown result type (might be due to invalid IL or missing references) TvPose pose = _broadcast.Value.Pose; BeginEmergence(pose.Position, pose.Yaw, Vector3.zero, requireStand: false); BroadcastState to = BroadcastRules.Break(ready, now); LogPhaseChange(in ready, in to, null); return to; } private void PlaceTv(double now) { //IL_004e: Unknown result type (might be due to invalid IL or missing references) //IL_006e: Unknown result type (might be due to invalid IL or missing references) //IL_0085: Unknown result type (might be due to invalid IL or missing references) //IL_008a: Unknown result type (might be due to invalid IL or missing references) //IL_0096: Unknown result type (might be due to invalid IL or missing references) //IL_009b: Unknown result type (might be due to invalid IL or missing references) //IL_00fc: Unknown result type (might be due to invalid IL or missing references) //IL_0101: Unknown result type (might be due to invalid IL or missing references) //IL_003b: Unknown result type (might be due to invalid IL or missing references) TvPose pose = _placement.Pose; if (!((Object)(object)base.agent != (Object)null) || !((Behaviour)base.agent).enabled || !base.agent.isOnNavMesh || !base.agent.Warp(pose.Position)) { ((Component)this).transform.position = pose.Position; } ((Component)this).transform.rotation = Quaternion.Euler(0f, pose.Yaw, 0f); ((EnemyAI)this).SyncPositionToClients(); _watchPoint = LocustTvView.ScreenPoint(pose, 0.05f); _tvForward = ((Component)this).transform.forward; _watchTimer = 0f; BroadcastState to = BroadcastRules.Begin(now, _broadcastSettings); Plugin.Log.LogInfo((object)("Locust TV placed: " + _placement.Summary)); LogPhaseChange(in _broadcastState, in to, null); _broadcastState = to; BroadcastSnapshot value = _broadcast.Value; value.TvPosition = pose.Position; value.TvYaw = pose.Yaw; _broadcast.Value = value.With(in _broadcastState); _publishedCharge = _broadcastState.Charge; ApplyManifested(_broadcast.Value.Manifested); } private void RemoveUnplaced(string reason) { Plugin.Log.LogWarning((object)("Locust TV: " + reason)); base.enemyType.numberSpawned = Mathf.Max(base.enemyType.numberSpawned, base.enemyType.MaxCount); ((NetworkBehaviour)this).NetworkObject.Despawn(true); } private bool AnyPlayerWatching() { //IL_0048: Unknown result type (might be due to invalid IL or missing references) //IL_0053: Unknown result type (might be due to invalid IL or missing references) //IL_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_0071: Unknown result type (might be due to invalid IL or missing references) StartOfRound instance = StartOfRound.Instance; if ((Object)(object)instance == (Object)null) { return false; } PlayerControllerB[] allPlayerScripts = instance.allPlayerScripts; foreach (PlayerControllerB val in allPlayerScripts) { if (!((Object)(object)val == (Object)null) && val.isPlayerControlled && !val.isPlayerDead && !((Object)(object)val.playerEye == (Object)null) && Vector3.Dot(_tvForward, val.playerEye.position - _watchPoint) > 0f && val.HasLineOfSightToPosition(_watchPoint, 45f, 20, -1f, -1)) { return true; } } return false; } private void PublishBroadcast() { _broadcast.Value = _broadcast.Value.With(in _broadcastState); _publishedCharge = _broadcastState.Charge; } private void LogPhaseChange(in BroadcastState from, in BroadcastState to, string byPlayer) { Plugin.Log.LogInfo((object)($"Locust broadcast: {from.Phase} -> {to.Phase} (switch-offs {to.SwitchOffs}/{to.SwitchOffLimit}, " + $"dark {to.OffSeconds:0.#}s, charge {to.Charge:0.00})" + ((byPlayer != null) ? (" by " + byPlayer) : string.Empty))); } private void OnBroadcastChanged(BroadcastSnapshot previous, BroadcastSnapshot current) { if (previous.Manifested != current.Manifested) { ApplyManifested(current.Manifested); } EnsureTv(in current); } private void EnsureTv(in BroadcastSnapshot snapshot) { if (_tv == null && snapshot.CurrentPhase != BroadcastPhase.Unplaced) { _tv = LocustTvView.Create(snapshot.Pose, RequestSwitchOff); } } private void ApplyManifested(bool shown) { if (_bodyRenderers == null) { return; } for (int i = 0; i < _bodyRenderers.Length; i++) { if ((Object)(object)_bodyRenderers[i] != (Object)null) { _bodyRenderers[i].forceRenderingOff = !shown; } } for (int j = 0; j < _bodyColliders.Length; j++) { if ((Object)(object)_bodyColliders[j] != (Object)null) { _bodyColliders[j].enabled = shown && _bodyCollidersEnabled[j]; } } if (((NetworkBehaviour)this).IsServer && (Object)(object)base.agent != (Object)null && ((Behaviour)base.agent).enabled && base.agent.isOnNavMesh) { base.agent.isStopped = !shown; } if (!shown) { if ((Object)(object)base.creatureSFX != (Object)null) { base.creatureSFX.Stop(); } if ((Object)(object)base.creatureVoice != (Object)null) { base.creatureVoice.Stop(); } } } private void RequestSwitchOff() { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Unknown result type (might be due to invalid IL or missing references) if (((NetworkBehaviour)this).IsSpawned) { BroadcastSwitchOffServerRpc(); } } [ServerRpc(RequireOwnership = false)] private void BroadcastSwitchOffServerRpc(ServerRpcParams rpcParams = default(ServerRpcParams)) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Invalid comparison between Unknown and I4 //IL_008c: Unknown result type (might be due to invalid IL or missing references) //IL_0096: Invalid comparison between Unknown and I4 //IL_005f: Unknown result type (might be due to invalid IL or missing references) //IL_0068: Unknown result type (might be due to invalid IL or missing references) //IL_006d: Unknown result type (might be due to invalid IL or missing references) //IL_007c: Unknown result type (might be due to invalid IL or missing references) //IL_00c1: Unknown result type (might be due to invalid IL or missing references) //IL_00c6: Unknown result type (might be due to invalid IL or missing references) //IL_00c7: Unknown result type (might be due to invalid IL or missing references) //IL_0133: Unknown result type (might be due to invalid IL or missing references) //IL_0144: Unknown result type (might be due to invalid IL or missing references) NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager; if (networkManager == null || !networkManager.IsListening) { return; } if ((int)((NetworkBehaviour)this).__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost)) { FastBufferWriter val = ((NetworkBehaviour)this).__beginSendServerRpc(1578454682u, rpcParams, (RpcDelivery)0); ((NetworkBehaviour)this).__endSendServerRpc(ref val, 1578454682u, rpcParams, (RpcDelivery)0); } if ((int)((NetworkBehaviour)this).__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost)) { ((NetworkBehaviour)this).__rpc_exec_stage = (__RpcExecStage)0; ulong senderClientId = rpcParams.Receive.SenderClientId; PlayerControllerB val2 = SenderPlayer(senderClientId); BroadcastSnapshot value = _broadcast.Value; string text = (((Object)(object)val2 == (Object)null) ? "no player for this client" : ((!val2.isPlayerControlled || val2.isPlayerDead || (Object)(object)val2.playerEye == (Object)null) ? "player not alive" : (value.Manifested ? "the Locust is out" : ((!BroadcastRules.CanSwitchOff(in _broadcastState)) ? $"phase {_broadcastState.Phase}, switch-offs {_broadcastState.SwitchOffs}/{_broadcastState.SwitchOffLimit}" : ((Vector3.Distance(val2.playerEye.position, LocustTvView.ScreenPoint(value.Pose, 0f)) > 6f) ? "out of reach" : null))))); if (text != null) { Plugin.Log.LogDebug((object)$"Locust TV switch-off refused for client {senderClientId}: {text}."); return; } BroadcastState to = BroadcastRules.SwitchOff(_broadcastState, BroadcastNow, _broadcastSettings); LogPhaseChange(in _broadcastState, in to, val2.playerUsername); _broadcastState = to; PublishBroadcast(); } } private static PlayerControllerB SenderPlayer(ulong clientId) { StartOfRound instance = StartOfRound.Instance; if ((Object)(object)instance == (Object)null || !instance.ClientPlayerList.TryGetValue(clientId, out var value) || value < 0 || value >= instance.allPlayerScripts.Length) { return null; } return instance.allPlayerScripts[value]; } private void ReleaseBroadcast() { NetworkVariable<BroadcastSnapshot> broadcast = _broadcast; broadcast.OnValueChanged = (OnValueChangedDelegate<BroadcastSnapshot>)(object)Delegate.Remove((Delegate?)(object)broadcast.OnValueChanged, (Delegate?)(object)new OnValueChangedDelegate<BroadcastSnapshot>(OnBroadcastChanged)); if (_tv != null) { _tv.Dispose(); _tv = null; } if (_placement != null) { _placement.Dispose(); _placement = null; } } private void BroadcastStart() { ApplyManifested(_broadcast.Value.Manifested); } private void BroadcastNetworkSpawn() { //IL_00df: Unknown result type (might be due to invalid IL or missing references) _bodyRenderers = ((Component)this).GetComponentsInChildren<Renderer>(true); _bodyColliders = ((Component)this).GetComponentsInChildren<Collider>(true); _bodyCollidersEnabled = new bool[_bodyColliders.Length]; for (int i = 0; i < _bodyColliders.Length; i++) { _bodyCollidersEnabled[i] = _bodyColliders[i].enabled; } NetworkVariable<BroadcastSnapshot> broadcast = _broadcast; broadcast.OnValueChanged = (OnValueChangedDelegate<BroadcastSnapshot>)(object)Delegate.Combine((Delegate?)(object)broadcast.OnValueChanged, (Delegate?)(object)new OnValueChangedDelegate<BroadcastSnapshot>(OnBroadcastChanged)); if (((NetworkBehaviour)this).IsServer && _broadcast.Value.CurrentPhase == BroadcastPhase.Unplaced && (Object)(object)Plugin.LocustTvPrefab != (Object)null) { LocustConfig modConfig = Plugin.ModConfig; _broadcastSettings = BroadcastSettings.Create(modConfig.EmergeSeconds.Value, modConfig.WatchedMultiplier.Value, modConfig.SwitchOffSeconds.Value); _placement = new TvPlacementJob(((Component)this).transform.position, LocustPickInterception.TakeSpawningPick()); } ApplyManifested(_broadcast.Value.Manifested); EnsureTv(_broadcast.Value); } private void BroadcastNetworkDespawn() { ReleaseBroadcast(); } private void BroadcastUpdate() { double broadcastNow = BroadcastNow; if (!((NetworkBehaviour)this).IsServer || !((NetworkBehaviour)this).IsSpawned || base.isEnemyDead || TickBroadcastServer(broadcastNow)) { _tv?.Tick(_broadcast.Value, broadcastNow); } } private void BroadcastDestroy() { ReleaseBroadcast(); } private void ShipDoorNetworkSpawn() { if (((NetworkBehaviour)this).IsServer) { LocustConfig modConfig = Plugin.ModConfig; _shipDoorSettings = ShipDoorSettings.Create(modConfig.ShipDoorEnabled.Value, modConfig.NobodyNearTvSeconds.Value, modConfig.NobodyInsideSeconds.Value); } } private void ShipDoorUpdate() { if (!((NetworkBehaviour)this).IsSpawned) { return; } StartOfRound instance = StartOfRound.Instance; bool landed = (Object)(object)instance != (Object)null && ShipDoorRules.Landed(instance.shipHasLanded, instance.shipIsLeaving, instance.inShipPhase); double broadcastNow = BroadcastNow; if (((NetworkBehaviour)this).IsServer && _shipDoor.Value.CurrentStage == ShipDoorStage.Sequence && _emergence.Value.CurrentStage == EmergenceStage.None) { ShipDoorTickServer(instance, landed, broadcastNow); } ShipDoorSnapshot value = _shipDoor.Value; EmergenceSnapshot emergence = _emergence.Value; if (!_shipDoorOutsideApplied && ShipDoorRules.Outside(value.CurrentStage, emergence.CurrentStage)) { ShipDoorApplyOutside(instance, in emergence); } MonitorStage monitorStage = ShipDoorTimeline.Stage(value.CurrentStage, landed, broadcastNow - value.Start, emergence.CurrentStage); if (monitorStage == MonitorStage.None) { ShipDoorReleaseMonitors(); if (((NetworkBehaviour)this).IsServer && value.CurrentStage != ShipDoorStage.None && (Object)(object)s_shipDoorHolder == (Object)(object)this) { s_shipDoorHolder = null; } return; } if (_shipMonitors == null && !_shipMonitorsRefused) { _shipMonitors = ShipMonitorView.TryCreate($"Y4NGZLocust.ShipDoor.{((NetworkBehaviour)this).NetworkObjectId}", out var refusal); if (_shipMonitors == null) { _shipMonitorsRefused = true; Plugin.Log.LogInfo((object)("Locust ship monitors: not shown on this machine, " + refusal)); } } _shipMonitors?.Tick(monitorStage, value.Start, broadcastNow); } private void ShipDoorNetworkDespawn() { ShipDoorRelease(); } private void ShipDoorDestroy() { ShipDoorRelease(); } private void EmergenceUpdate() { if (!((NetworkBehaviour)this).IsSpawned) { return; } EmergenceSnapshot snapshot = _emergence.Value; if (EmergenceRules.Presents(snapshot.CurrentStage)) { EmergencePresent(in snapshot); if (((NetworkBehaviour)this).IsServer && EmergenceTimeline.Finished(_emergenceClock)) { EmergenceServerFinish(); } } else if (_emergencePresenting) { EmergenceEndPresentation(EmergenceRules.CutShort(snapshot.CurrentStage)); } } private void EmergenceLateUpdate() { //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_0050: Unknown result type (might be due to invalid IL or missing references) if (_emergencePresenting) { if ((Object)(object)_emergenceVisual != (Object)null) { _emergenceVisual.SetPositionAndRotation(_emergencePinPosition, _emergencePinRotation); } if (_emergenceSoundHeld && (Object)(object)base.creatureSFX != (Object)null) { ((Component)base.creatureSFX).transform.position = _emergenceSoundPoint; } } } private void EmergenceNetworkDespawn() { EmergenceEndPresentation(cutShort: true); } private void EmergenceDestroy() { EmergenceEndPresentation(cutShort: true); } private void HuntStart() { //IL_001d: Unknown result type (might be due to invalid IL or missing references) CapsuleCollider component = ((Component)this).GetComponent<CapsuleCollider>(); if ((Object)(object)component != (Object)null) { _huntBody = new HuntBody(component.height * ((Component)this).transform.lossyScale.y / 2.772f); } if ((Object)(object)base.creatureAnimator != (Object)null) { _huntSpeakLayer = base.creatureAnimator.GetLayerIndex("Speak"); } HuntConfigureAudio(); StartOfRound instance = StartOfRound.Instance; _huntRecatch = new HuntRecatchGuard(((Object)(object)instance != (Object)null) ? instance.allPlayerScripts.Length : 0); } private void HuntNetworkDespawn() { HuntDropCatch(); HuntDropHead(); } private void HuntUpdate() { if (!_huntAudioReady) { HuntConfigureAudio(); } if (((NetworkBehaviour)this).IsSpawned) { if (((NetworkBehaviour)this).IsServer) { HuntServerTick(); } HuntPresent(); } } private void HuntLateUpdate() { //IL_004a: Unknown result type (might be due to invalid IL or missing references) //IL_0055: Unknown result type (might be due to invalid IL or missing references) //IL_005a: Unknown result type (might be due to invalid IL or missing references) //IL_005f: Unknown result type (might be due to invalid IL or missing references) //IL_0060: Unknown result type (might be due to invalid IL or missing references) //IL_0066: Unknown result type (might be due to invalid IL or missing references) //IL_006d: Unknown result type (might be due to invalid IL or missing references) //IL_0073: Unknown result type (might be due to invalid IL or missing references) //IL_00e1: Unknown result type (might be due to invalid IL or missing references) //IL_00e4: Unknown result type (might be due to invalid IL or missing references) //IL_00e9: Unknown result type (might be due to invalid IL or missing references) //IL_00ee: Unknown result type (might be due to invalid IL or missing references) //IL_00f0: Unknown result type (might be due to invalid IL or missing references) //IL_00f7: Unknown result type (might be due to invalid IL or missing references) //IL_00ff: Unknown result type (might be due to invalid IL or missing references) //IL_0106: Unknown result type (might be due to invalid IL or missing references) //IL_0116: Unknown result type (might be due to invalid IL or missing references) //IL_013e: 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_0155: Unknown result type (might be due to invalid IL or missing references) //IL_015c: Unknown result type (might be due to invalid IL or missing references) //IL_0163: Unknown result type (might be due to invalid IL or missing references) //IL_0088: Unknown result type (might be due to invalid IL or missing references) //IL_008e: Unknown result type (might be due to invalid IL or missing references) //IL_00ad: Unknown result type (might be due to invalid IL or missing references) //IL_00b2: 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_00c3: Unknown result type (might be due to invalid IL or missing references) //IL_00ca: Unknown result type (might be due to invalid IL or missing references) if (!_huntLocalHold) { return; } PlayerControllerB huntHeldVictim = _huntHeldVictim; if (!((Object)(object)huntHeldVictim == (Object)null) && !huntHeldVictim.isPlayerDead && HuntTryHeadPoint(out var point)) { float num = Mathf.Clamp01((Time.time - _huntHoldStartTime) / 0.25f); Vector3 val = ((Component)this).transform.position - ((Component)huntHeldVictim).transform.position; if (val.x * val.x + val.z * val.z > 0.0001f) { float num2 = Mathf.LerpAngle(_huntHoldStartYaw, Mathf.Atan2(val.x, val.z) * 57.29578f, num); Vector3 eulerAngles = ((Component)huntHeldVictim).transform.eulerAngles; ((Component)huntHeldVictim).transform.eulerAngles = new Vector3(eulerAngles.x, num2, eulerAngles.z); } Transform transform = ((Component)huntHeldVictim.gameplayCamera).transform; Vector3 val2 = point - transform.position; float num3 = Mathf.Sqrt(val2.x * val2.x + val2.z * val2.z); float num4 = Mathf.Clamp((0f - Mathf.Atan2(val2.y, num3)) * 57.29578f, -60f, 60f); Vector3 localEulerAngles = transform.localEulerAngles; transform.localEulerAngles = new Vector3(Mathf.LerpAngle(_huntHoldStartPitch, num4, num), localEulerAngles.y, localEulerAngles.z); } } private void HuntAIInterval() { //IL_00c5: Unknown result type (might be due to invalid IL or missing references) LocustState huntServerState = _huntServerState; if (!((NetworkBehaviour)this).IsServer || base.currentBehaviourStateIndex != (int)huntServerState || (huntServerState != LocustState.Roam && huntServerState != LocustState.Chase) || ((EnemyAI)(object)this).IsStunned()) { return; } StartOfRound instance = StartOfRound.Instance; if ((Object)(object)instance == (Object)null) { return; } int visibleCount = HuntCollectSightings(instance); PlayerControllerB val = VictimRpc.FromSlot(_huntBrain.TargetSlot); bool targetTargetable = (Object)(object)val != (Object)null && ((EnemyAI)this).PlayerIsTargetable(val, false, false, true); LocustState locustState = _huntBrain.Tick(huntServerState, stunned: false, _huntSightings, visibleCount, targetTargetable, base.AIIntervalTime, Plugin.ModConfig.LoseTargetSeconds.Value); if (locustState != huntServerState) { ((EnemyAI)this).SwitchToBehaviourState((int)locustState); return; } if (huntServerState == LocustState.Roam) { if (base.currentSearch == null || !base.currentSearch.inProgress) { ((EnemyAI)this).StartSearch(((Component)this).transform.position, _huntSearch); } return; } val = VictimRpc.FromSlot(_huntBrain.TargetSlot); if (!((Object)(object)val == (Object)null) && (!((Object)(object)val == (Object)(object)base.targetPlayer) || !base.movingTowardsTargetPlayer)) { if ((Object)(object)val != (Object)(object)base.targetPlayer) { Plugin.Log.LogInfo((object)$"[Locust] chase retargets to slot {_huntBrain.TargetSlot}"); } ((EnemyAI)this).SetMovingTowardsTargetPlayer(val); } } private void HuntCollideWithPlayer(Collider other) { //IL_0054: Unknown result type (might be due to invalid IL or missing references) //IL_005a: Unknown result type (might be due to invalid IL or missing references) LocustState currentBehaviourStateIndex = (LocustState)base.currentBehaviourStateIndex; if ((currentBehaviourStateIndex == LocustState.Roam || currentBehaviourStateIndex == LocustState.Chase) && !((EnemyAI)(object)this).IsStunned() && !(Time.time < _huntNextCatchRequestTime)) { PlayerControllerB val = ((EnemyAI)this).MeetsStandardPlayerCollisionConditions(other, false, false); if (!((Object)(object)val == (Object)null)) { _huntNextCatchRequestTime = Time.time + 0.5f; HuntCatchServerRpc((int)val.playerClientId); } } } private void HuntDestroy() { HuntDropCatch(); HuntDropHead(); } public override void Start() { ((EnemyAI)this).Start(); base.moveTowardsDestination = false; base.movingTowardsTargetPlayer = false; if ((Object)(object)base.agent != (Object)null && ((Behaviour)base.agent).enabled && base.agent.isOnNavMesh) { base.agent.isStopped = true; } BroadcastStart(); HuntStart(); } public override void OnNetworkSpawn() { ((NetworkBehaviour)this).OnNetworkSpawn(); BroadcastNetworkSpawn(); ShipDoorNetworkSpawn(); } public override void OnNetworkDespawn() { ((NetworkBehaviour)this).OnNetworkDespawn(); BroadcastNetworkDespawn(); ShipDoorNetworkDespawn(); EmergenceNetworkDespawn(); HuntNetworkDespawn(); } public override void Update() { _ownership.Ensure((EnemyAI)(object)this, Plugin.Log); ((EnemyAI)this).Update(); BroadcastUpdate(); ShipDoorUpdate(); EmergenceUpdate(); HuntUpdate(); } private void LateUpdate() { EmergenceLateUpdate(); HuntLateUpdate(); } public override void DoAIInterval() { ((EnemyAI)this).DoAIInterval(); HuntAIInterval(); } public override void OnCollideWithPlayer(Collider other) { ((EnemyAI)this).OnCollideWithPlayer(other); HuntCollideWithPlayer(other); } public override void HitEnemy(int force = 1, PlayerControllerB playerWhoHit = null, bool playHitSFX = false, int hitID = -1) { ((EnemyAI)this).HitEnemy(force, playerWhoHit, playHitSFX, hitID); } public override void SetEnemyStunned(bool setToStunned, float setToStunTime = 1f, PlayerControllerB setStunnedByPlayer = null) { ((EnemyAI)this).SetEnemyStunned(setToStunned, setToStunTime, setStunnedByPlayer); } public override void DetectNoise(Vector3 noisePosition, float noiseLoudness, int timesPlayedInOneSpot = 0, int noiseID = 0) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) ((EnemyAI)this).DetectNoise(noisePosition, noiseLoudness, timesPlayedInOneSpot, noiseID); } public override void OnDestroy() { ((EnemyAI)this).OnDestroy(); BroadcastDestroy(); ShipDoorDestroy(); EmergenceDestroy(); HuntDestroy(); } internal bool BeginEmergence(Vector3 position, float yaw, Vector3 drop, bool requireStand) { //IL_0073: Unknown result type (might be due to invalid IL or missing references) //IL_0075: Unknown result type (might be due to invalid IL or missing references) //IL_0078: Unknown result type (might be due to invalid IL or missing references) //IL_007e: Unknown result type (might be due to invalid IL or missing references) //IL_0080: Unknown result type (might be due to invalid IL or missing references) //IL_0085: Unknown result type (might be due to invalid IL or missing references) //IL_0088: Unknown result type (might be due to invalid IL or missing references) //IL_00aa: Unknown result type (might be due to invalid IL or missing references) //IL_00d6: Unknown result type (might be due to invalid IL or missing references) //IL_00db: Unknown result type (might be due to invalid IL or missing references) //IL_00bc: Unknown result type (might be due to invalid IL or missing references) //IL_011d: Unknown result type (might be due to invalid IL or missing references) //IL_011e: 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_01a5: Unknown result type (might be due to invalid IL or missing references) //IL_01a6: Unknown result type (might be due to invalid IL or missing references) //IL_01b5: Unknown result type (might be due to invalid IL or missing references) //IL_01b6: Unknown result type (might be due to invalid IL or missing references) //IL_01cc: Unknown result type (might be due to invalid IL or missing references) //IL_01dd: Unknown result type (might be due to invalid IL or missing references) //IL_01de: Unknown result type (might be due to invalid IL or missing references) //IL_010a: Unknown result type (might be due to invalid IL or missing references) //IL_01f6: Unknown result type (might be due to invalid IL or missing references) //IL_0206: Unknown result type (might be due to invalid IL or missing references) //IL_0253: Unknown result type (might be due to invalid IL or missing references) //IL_027e: Unknown result type (might be due to invalid IL or missing references) if (!((NetworkBehaviour)this).IsServer) { if (!_warnedClientEmergence) { _warnedClientEmergence = true; Plugin.Log.LogWarning((object)"Locust: BeginEmergence is server only; ignored on this client."); } return false; } string text = EmergenceRules.BeginRefusal(_emergence.Value.CurrentStage, ((NetworkBehaviour)this).IsSpawned, base.isEnemyDead, LocustStates.IsHunt((LocustState)base.currentBehaviourStateIndex)); if (text != null) { Plugin.Log.LogWarning((object)("Locust emergence refused: " + text)); return false; } Vector3 val = EmergenceStandPoint(position, yaw, drop); NavMeshHit hit = default(NavMeshHit); bool flag = (Object)(object)base.agent != (Object)null && ((Behaviour)base.agent).enabled && SampleEmergenceStand(val, out hit) && base.agent.Warp(((NavMeshHit)(ref hit)).position); float num = (flag ? Vector3.Distance(((NavMeshHit)(ref hit)).position, val) : float.PositiveInfinity); StandResult standResult = EmergenceRules.Stand(flag, num); if (requireStand && standResult == StandResult.NoNavMesh) { Plugin.Log.LogWarning((object)$"Locust emergence refused: the agent cannot be placed within {1.5f} m of stand point {val}"); return false; } _emergenceStandPoint = val; _emergenceStand = standResult; if ((Object)(object)base.agent != (Object)null && ((Behaviour)base.agent).enabled && base.agent.isOnNavMesh) { base.agent.isStopped = true; } ((Component)this).transform.rotation = Quaternion.Euler(0f, yaw, 0f); ((EnemyAI)this).SyncPositionToClients(); _emergence.Value = new EmergenceSnapshot { Stage = 1, Start = BroadcastNow, Position = position, Yaw = yaw, Drop = drop }; Plugin.Log.LogInfo((object)($"Locust emergence: start at {position} yaw {yaw:0.#}" + ((drop != Vector3.zero) ? $" drop {drop}" : string.Empty) + $"; stand point {val}: {standResult}" + (flag ? $" {num:0.00} m" : string.Empty))); switch (standResult) { case StandResult.Snapped: Plugin.Log.LogWarning((object)$"Locust emergence: NavMesh {num:0.00} m from stand point {val}; the body steps that far at the end"); break; case StandResult.NoNavMesh: Plugin.Log.LogWarning((object)$"Locust emergence: no NavMesh within {1.5f} m of stand point {val}; the Locust will stand shown and inert"); break; } return true; } private static Vector3 EmergenceStandPoint(Vector3 position, float yaw, Vector3 drop, Vector3 localOffset = default(Vector3)) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Unknown result type (might be due to invalid IL or missing references) //IL_0031: Unknown result type (might be due to invalid IL or missing references) //IL_0045: Unknown result type (might be due to invalid IL or missing references) EmergenceTimeline.PointAtStand(position.x, position.y, position.z, drop.x, drop.y, drop.z, yaw, localOffset.x, localOffset.y, localOffset.z, out var pointX, out var pointY, out var pointZ); return new Vector3(pointX, pointY, pointZ); } private bool SampleEmergenceStand(Vector3 stand, out NavMeshHit hit) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0048: Unknown result type (might be due to invalid IL or missing references) hit = default(NavMeshHit); if ((Object)(object)base.agent != (Object)null) { NavMeshQueryFilter val = default(NavMeshQueryFilter); ((NavMeshQueryFilter)(ref val)).agentTypeID = base.agent.agentTypeID; ((NavMeshQueryFilter)(ref val)).areaMask = base.agent.areaMask; return NavMesh.SamplePosition(stand, ref hit, 1.5f, val); } return false; } private void EmergencePresent(in EmergenceSnapshot snapshot) { //IL_0090: Unknown result type (might be due to invalid IL or missing references) //IL_0096: Unknown result type (might be due to invalid IL or missing references) //IL_00a6: Unknown result type (might be due to invalid IL or missing references) //IL_00ab: Unknown result type (might be due to invalid IL or missing references) //IL_00b0: Unknown result type (might be due to invalid IL or missing references) if (_emergencePresenting) { _emergenceClock += Time.deltaTime; if (!((NetworkBehaviour)this).IsServer) { double elapsedServerSeconds = BroadcastNow - snapshot.Start; if (EmergenceTimeline.Behind(_emergenceClock, elapsedServerSeconds)) { _emergenceClock = EmergenceTimeline.ClockAtJoin(elapsedServerSeconds); _emergenceSteps = EmergenceTimeline.StepsPassed(_emergenceClock); if ((Object)(object)base.creatureAnimator != (Object)null) { base.creatureAnimator.Play(TvExitHash, 0, EmergenceTimeline.NormalizedTime(_emergenceClock)); } } } } else { EmergenceStartPresentation(in snapshot); } _emergencePinPosition = _emergencePinStart + snapshot.Drop * EmergenceTimeline.DescentFraction(_emergenceClock); SkinnedMeshRenderer emergenceBody = _emergenceBody; if ((Object)(object)emergenceBody != (Object)null) { if (((Renderer)emergenceBody).forceRenderingOff) { ((Renderer)emergenceBody).forceRenderingOff = false; } int num = EmergenceTimeline.ShownGroups(_emergenceClock); if (num != _emergenceShown) { _emergenceShown = num; for (int i = 0; i < _emergenceWorking.Length; i++) { Transform val = _emergenceStandIns[i]; _emergenceWorking[i] = ((EmergenceTimeline.IsShown(num, _emergenceGroup[i]) || (Object)(object)val == (Object)null) ? _emergenceBones[i] : val); } emergenceBody.bones = _emergenceWorking; } } int num2 = EmergenceTimeline.StepsPassed(_emergenceClock); while (_emergenceSteps < num2) { _emergenceSteps++; AudioClip val2 = HuntAudio.Steps[Random.Range(0, HuntAudio.Steps.Length)]; if ((Object)(object)val2 != (Object)null && (Object)(object)base.creatureSFX != (Object)null) { base.creatureSFX.PlayOneShot(val2); } } } private void EmergenceStartPresentation(in EmergenceSnapshot snapshot) { //IL_00a0: Unknown result type (might be due to invalid IL or missing references) //IL_00a5: Unknown result type (might be due to invalid IL or missing references) //IL_00b1: Unknown result type (might be due to invalid IL or missing references) //IL_00b6: Unknown result type (might be due to invalid IL or missing references) //IL_00cb: Unknown result type (might be due to invalid IL or missing references) //IL_00d0: Unknown result type (might be due to invalid IL or missing references) //IL_00d4: Unknown result type (might be due to invalid IL or missing references) //IL_00d9: Unknown result type (might be due to invalid IL or missing references) //IL_00dc: Unknown result type (might be due to invalid IL or missing references) //IL_00e1: Unknown result type (might be due to invalid IL or missing references) //IL_00e6: Unknown result type (might be due to invalid IL or missing references) //IL_00eb: Unknown result type (might be due to invalid IL or missing references) //IL_00f1: Unknown result type (might be due to invalid IL or missing references) //IL_00f4: Unknown result type (might be due to invalid IL or missing references) //IL_00f9: Unknown result type (might be due to invalid IL or missing references) //IL_00fe: Unknown result type (might be due to invalid IL or missing references) //IL_012e: Unknown result type (might be due to invalid IL or missing references) //IL_0133: Unknown result type (might be due to invalid IL or missing references) //IL_013a: Unknown result type (might be due to invalid IL or missing references) //IL_0146: Unknown result type (might be due to invalid IL or missing references) //IL_014c: Unknown result type (might be due to invalid IL or missing references) //IL_0151: Unknown result type (might be due to invalid IL or missing references) //IL_0156: Unknown result type (might be due to invalid IL or missing references) //IL_015e: Unknown result type (might be due to invalid IL or missing references) //IL_0058: Unknown result type (might be due to invalid IL or missing references) //IL_006f: Unknown result type (might be due to invalid IL or missing references) if (!_emergenceBound) { EmergenceBindRig(); } if ((Object)(object)_emergenceBody != (Object)null) { int num = _emergenceBones.Length; _emergenceStandIns = (Transform[])(object)new Transform[num]; _emergenceWorking = (Transform[])(object)new Transform[num]; for (int i = 0; i < num; i++) { Transform val = _emergenceBones[i]; if (!((Object)(object)val == (Object)null)) { Transform transform = new GameObject("EmergenceStandIn").transform; transform.SetParent(val, false); transform.localScale = Vector3.zero; _emergenceStandIns[i] = transform; } } } if ((Object)(object)_emergenceVisual != (Object)null) { _emergenceVisualLocalPosition = _emergenceVisual.localPosition; _emergenceVisualLocalRotation = _emergenceVisual.localRotation; Quaternion val2 = Quaternion.Euler(0f, snapshot.Yaw, 0f); _emergencePinStart = snapshot.Position + val2 * _emergenceVisualLocalPosition; _emergencePinRotation = val2 * _emergenceVisualLocalRotation; } if (EmergenceRules.HoldsSound(((NetworkBehaviour)this).IsServer) && (Object)(object)base.creatureSFX != (Object)null) { Transform transform2 = ((Component)base.creatureSFX).transform; _emergenceSoundLocalPosition = transform2.localPosition; _emergenceSoundPoint = EmergenceStandPoint(snapshot.Position, snapshot.Yaw, snapshot.Drop, _emergenceSoundLocalPosition); transform2.position = _emergenceSoundPoint; _emergenceSoundHeld = true; } _emergenceClock = EmergenceTimeline.ClockAtJoin(BroadcastNow - snapshot.Start); AudioClip emerge = HuntAudio.Emerge; if ((Object)(object)emerge != (Object)null && (Object)(object)base.creatureSFX != (Object)null && EmergenceTimeline.SoundJoins(_emergenceClock, emerge.length)) { base.creatureSFX.clip = emerge; base.creatureSFX.loop = false; base.creatureSFX.Play(); base.creatureSFX.time = ScreenAudio.Seek(emerge, _emergenceClock); } _emergenceSteps = EmergenceTimeline.StepsPassed(_emergenceClock); _emergenceShown = -1; _emergencePresenting = true; if ((Object)(object)base.creatureAnimator != (Object)null) { base.creatureAnimator.speed = 1f; base.creatureAnimator.Play(TvExitHash, 0, EmergenceTimeline.NormalizedTime(_emergenceClock)); } Plugin.Log.LogInfo((object)$"Locust emergence: playing TvExit from {_emergenceClock:0.00} s"); } private void EmergenceBindRig() { _emergenceBound = true; _emergenceVisual = ((Component)this).transform.Find("VisualRoot"); _emergenceBody = (((Object)(object)_emergenceVisual != (Object)null) ? ((Component)_emergenceVisual).GetComponentInChildren<SkinnedMeshRenderer>(true) : null); if ((Object)(object)_emergenceVisual == (Object)null) { Plugin.Log.LogWarning((object)"Locust emergence: no VisualRoot; the model is neither shown nor pinned during the clip"); } else if ((Object)(object)_emergenceBody == (Object)null) { Plugin.Log.LogWarning((object)"Locust emergence: no SkinnedMeshRenderer under VisualRoot; the body stays hidden during the clip"); } if ((Object)(object)base.creatureAnimator == (Object)null) { Plugin.Log.LogWarning((object)"Locust emergence: no Animator; TvExit does not play"); } if ((Object)(object)_emergenceBody == (Object)null) { return; } _emergenceBones = _emergenceBody.bones; _emergenceGroup = new int[_emergenceBones.Length]; int num = 0; for (int i = 0; i < _emergenceBones.Length; i++) { Transform val = _emergenceBones[i]; _emergenceGroup[i] = EmergenceTimeline.GroupOf(((Object)(object)val != (Object)null) ? ((Object)val).name : null); num |= 1 << _emergenceGroup[i]; } for (int j = 0; j < 8; j++) { if (!EmergenceTimeline.IsShown(num, j)) { Plugin.Log.LogWarning((object)$"Locust emergence: no skinned bone of reveal group {j} ({EmergenceTimeline.GroupBoneNames(j)})"); } } } private void EmergenceEndPresentation(bool cutShort) { //IL_008c: Unknown result type (might be due to invalid IL or missing references) //IL_009d: Unknown result type (might be due to invalid IL or missing references) //IL_00d0: Unknown result type (might be due to invalid IL or missing references) if (!_emergencePresenting) { return; } _emergencePresenting = false; SkinnedMeshRenderer emergenceBody = _emergenceBody; if ((Object)(object)emergenceBody != (Object)null) { emergenceBody.bones = _emergenceBones; } if (_emergenceStandIns != null) { for (int i = 0; i < _emergenceStandIns.Length; i++) { if ((Object)(object)_emergenceStandIns[i] != (Object)null) { Object.Destroy((Object)(object)((Component)_emergenceStandIns[i]).gameObject); } } } _emergenceStandIns = null; _emergenceWorking = null; if ((Object)(object)_emergenceVisual != (Object)null) { _emergenceVisual.localPosition = _emergenceVisualLocalPosition; _emergenceVisual.localRotation = _emergenceVisualLocalRotation; } if (_emergenceSoundHeld) { _emergenceSoundHeld = false; if ((Object)(object)base.creatureSFX != (Object)null) { ((Component)base.creatureSFX).transform.localPosition = _emergenceSoundLocalPosition; } } if ((Object)(object)emergenceBody != (Object)null) { ((Renderer)emergenceBody).forceRenderingOff = !_broadcast.Value.Manifested; } if (cutShort) { if ((Object)(object)base.creatureSFX != (Object)null) { base.creatureSFX.Stop(); base.creatureSFX.clip = null; } Plugin.Log.LogInfo((object)$"Locust emergence: cut short at {_emergenceClock:0.00} s, bones restored"); } else { if ((Object)(object)base.creatureAnimator != (Object)null) { base.creatureAnimator.Play(HuntGait.StateName(HuntClip.Idle), 0, 0f); base.creatureAnimator.Update(0f); } Plugin.Log.LogInfo((object)"Locust emergence: bones restored, body at the root"); } } private void EmergenceServerFinish() { //IL_005a: Unknown result type (might be due to invalid IL or missing references) //IL_007c: Unknown result type (might be due to invalid IL or missing references) //IL_0082: Unknown result type (might be due to invalid IL or missing references) //IL_0095: Unknown result type (might be due to invalid IL or missing references) //IL_0117: Unknown result type (might be due to invalid IL or missing references) //IL_0136: Unknown result type (might be due to invalid IL or missing references) EmergenceSnapshot value = _emergence.Value; value.Stage = 2; _emergence.Value = value; bool flag = (Object)(object)base.agent != (Object)null && ((Behaviour)base.agent).enabled && base.agent.isOnNavMesh; Plugin.Log.LogInfo((object)($"Locust emergence: clip done; root {((Component)this).transform.position} is " + $"{Vector3.Distance(((Component)this).transform.position, _emergenceStandPoint):0.00} m from stand point {_emergenceStandPoint}, stand {_emergenceStand}, on NavMesh {flag}")); EmergenceEndPresentation(cutShort: false); SetManifested(shown: true); Plugin.Log.LogInfo((object)"Locust emergence: shown"); if (EmergenceRules.HuntsAtEnd(_emergenceStand, flag)) { Plugin.Log.LogInfo((object)"Locust emergence: hunt begins"); BeginHunt(); } else { Plugin.Log.LogWarning((object)($"Locust emergence: no hunt at {((Component)this).transform.position} (searched {1.5f} m " + $"round stand point {_emergenceStandPoint}); stand {_emergenceStand}, on NavMesh {flag}; it stays shown and inert")); } } internal void BeginHunt() { if (((NetworkBehaviour)this).IsServer && !LocustStates.IsHunt((LocustState)base.currentBehaviourStateIndex)) { ((EnemyAI)this).SwitchToBehaviourState(2); } } private bool HuntTryHeadPoint(out Vector3 point) { //IL_0077: Unknown result type (might be due to invalid IL or missing references) //IL_007c: Unknown result type (might be due to invalid IL or missing references) //IL_0068: Unknown result type (might be due to invalid IL or missing references) if (!_huntHeadSearched || ((Object)(object)_huntHead == (Object)null && _huntHead != null)) { _huntHeadSearched = true; _huntHead = FindHuntChild(((Component)this).transform, "Head"); } if ((Object)(object)_huntHead == (Object)null) { if (!_huntHeadWarned) { _huntHeadWarned = true; Plugin.Log.LogWarning((object)"[Locust] Head bone missing: the hunt sees no one, its sight-based fear does not rise and no caught player's view turns"); } point = default(Vector3); return false; } point = _huntHead.position; return true; } private void HuntDropHead() { _huntHead = null; _huntHeadSearched = false; } private static Transform FindHuntChild(Transform parent, string name) { if (((Object)parent).name == name) { return parent; } for (int i = 0; i < parent.childCount; i++) { Transform val = FindHuntChild(parent.GetChild(i), name); if ((Object)(object)val != (Object)null) { return val; } } return null; } private void HuntConfigureAudio() { _huntAudioReady = CreatureAudioSetup.ConfigureSpatial(base.creatureSFX) & CreatureAudioSetup.ConfigureSpatial(base.creatureVoice); } private void HuntServerTick() { HuntServerFollowState(); LocustState huntServerState = _huntServerState; if (!LocustStates.IsHunt(huntServerState)) { return; } HuntServerRefreshRecatch(); bool flag = ((EnemyAI)(object)this).IsStunned(); StunEdge stunEdge = ((EnemyAI)(object)this).TrackStun(ref _huntServerStunned); if (stunEdge == StunEdge.Started) { HuntServerStopMoving(); } if (flag) { ((EnemyAI)(object)this).HoldAgent(); } else if (stunEdge == StunEdge.Ended && huntServerState != LocustState.Catch) { HuntResumeAgent(); HuntServerStartMoving(huntServerState); } if (huntServerState == LocustState.Catch) { HuntServerCatchTick(flag); if (base.currentBehaviourStateIndex != (int)huntServerState) { return; } } HuntServerProbe(huntServerState, Time.deltaTime); bool flag2 = flag || huntServerState == LocustState.Catch; float num = HuntTargetSpeed(huntServerState); if (!flag2 && (Object)(object)base.agent != (Object)null) { base.agent.speed = num; } _huntMoving = !flag2 && HuntGait.UpdateMoving(_huntMoving, HuntAgentGroundSpeed(), in _huntBody); LocustConfig modConfig = Plugin.ModConfig; int num2 = _huntSpeech.Tick(Time.timeAsDouble, !flag2, modConfig.SpeechIntervalMin.Value, modConfig.SpeechIntervalMax.Value); if (num2 > 0) { _huntServerSnapshot.SpeechLine = (byte)num2; _huntServerSnapshot.SpeechSeq++; } _huntServerSnapshot.State = (byte)huntServerState; _huntServerSnapshot.Crouched = _huntPosture.Crouched; _huntServerSnapshot.Moving = _huntMoving; _huntServerSnapshot.MoveSpeedCm = (ushort)Mathf.RoundToInt(num * 100f); HuntPublish(); } private void HuntServerFollowState() { for (int i = 0; i < 3; i++) { if (base.currentBehaviourStateIndex == (int)_huntServerState) { break; } LocustState huntServerState = _huntServerState; _huntServerState = (LocustState)base.currentBehaviourStateIndex; HuntServerEnter(huntServerState, _huntServerState); } } private void HuntServerEnter(LocustState from, LocustState to) { int num = to switch { LocustState.Catch => _huntServerSnapshot.VictimSlot, LocustState.Chase => _huntBrain.TargetSlot, _ => -1, }; Plugin.Log.LogInfo((object)$"[Locust] state {from} -> {to} (target {num})"); if ((Object)(object)_huntCatchVictim != (Object)null && to != LocustState.Catch) { HuntEndCatch(_huntKillSent ? "ended (left the catch after the kill)" : "aborted (left the catch), player released alive", switchToRoam: false); } if (!LocustStates.IsHunt(to)) { if (LocustStates.IsHunt(from)) { HuntServerStop(); } byte catchSeq = _huntServerSnapshot.CatchSeq; byte speechSeq = _huntServerSnapshot.SpeechSeq; _huntServerSnapshot = HuntSnapshot.Initial; _huntServerSnapshot.State = (byte)to; _huntServerSnapshot.CatchSeq = catchSeq; _huntServerSnapshot.SpeechSeq = speechSeq; HuntPublish(); return; } if (!LocustStates.IsHunt(from)) { _huntServerStunned = false; _huntProbeElapsed = 0f; LocustConfig modConfig = Plugin.ModConfig; _huntSpeech.Schedule(Time.timeAsDouble, modConfig.SpeechIntervalMin.Value, modConfig.SpeechIntervalMax.Value); } switch (to) { case LocustState.Roam: HuntResumeAgent(); _huntBrain.Reset(); base.movingTowardsTargetPlayer = false; base.targetPlayer = null; HuntServerStartMoving(LocustState.Roam); break; case LocustState.Chase: if ((Object)(object)VictimRpc.FromSlot(_huntBrain.TargetSlot) == (Object)null) { Plugin.Log.LogInfo((object)"[Locust] chase has no target; back to Roam"); ((EnemyAI)this).SwitchToBehaviourState(2); } else { HuntResumeAgent(); HuntServerStartMoving(LocustState.Chase); } break; case LocustState.Catch: if ((Object)(object)_huntCatchVictim == (Object)null) { Plugin.Log.LogInfo((object)"[Locust] catch has no victim; back to Roam"); ((EnemyAI)this).SwitchToBehaviourState(2); } break; } } private void HuntServerStop() { HuntServerStopMoving(); base.targetPlayer = null; if ((Object)(object)base.agent != (Object)null) { base.agent.speed = 0f; } ((EnemyAI)(object)this).HoldAgent(); _huntBrain.Reset(); _huntPosture.Reset(); _huntRecatch?.ClearAll(); _huntMoving = false; _huntServerStunned = false; } private void HuntServerStartMoving(LocustState state) { //IL_001b: Unknown result type (might be due to invalid IL or missing references) if (((EnemyAI)(object)this).IsStunned()) { return; } if (state == LocustState.Roam) { base.moveTowardsDestination = true; ((EnemyAI)this).StartSearch(((Component)this).transform.position, _huntSearch); return; } PlayerControllerB val = VictimRpc.FromSlot(_huntBrain.TargetSlot); if (state == LocustState.Chase && !((Object)(object)val == (Object)null)) { base.moveTowardsDestination = true; ((EnemyAI)this).StopSearch(base.currentSearch, false); ((EnemyAI)this).SetMovingTowardsTargetPlayer(val); } } private void HuntServerStopMoving() { ((EnemyAI)this).StopSearch(base.currentSearch, false); base.movingTowardsTargetPlayer = false; base.moveTowardsDestination = false; } private void HuntResumeAgent() { if (!((Object)(object)base.agent == (Object)null)) { base.agent.acceleration = 35f; base.agent.angularSpeed = 600f; if (!((EnemyAI)(object)this).IsStunned()) { ((EnemyAI)(object)this).ReleaseAgent(); } } } private static float HuntStandingSpeed(LocustState state) { LocustConfig modConfig = Plugin.ModConfig; if (state != LocustState.Chase) { return modConfig.RoamSpeed.Value; } return modConfig.ChaseSpeed.Value; } private float HuntTargetSpeed(Lo
Y4NGZModer.dll
Decompiled a day ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security.Cryptography; using System.Text; using System.Text.RegularExpressions; using BepInEx; using BepInEx.Bootstrap; using BepInEx.Configuration; using BepInEx.Logging; using Dawn; using GameNetcodeStuff; using Microsoft.CodeAnalysis; using Unity.Netcode; using UnityEngine; using UnityEngine.AI; using UnityEngine.Audio; using UnityEngine.Events; using Y4NGZModer.AI; using Y4NGZModer.NetcodePatcher; using Y4NGZModer.World; using Y4NGZMonsters.Shared; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: AssemblyCompany("Y4NGZModer")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0+3460ec64f0cec4948e51ddb3f02a4b0e414f105e")] [assembly: AssemblyProduct("Y4NGZModer")] [assembly: AssemblyTitle("Y4NGZModer")] [assembly: AssemblyVersion("1.0.0.0")] [module: RefSafetyRules(11)] [module: NetcodePatchedAssembly] 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 Y4NGZModer { [Serializable] public sealed class ModerAudio { [Tooltip("creatureVoice: entering Stalk or Hunt with no target, then every 25-40 s.")] public AudioClip CallDistant; [Tooltip("Optional second variant, picked at random.")] public AudioClip CallDistant2; [Tooltip("creatureVoice: Chase start, Charge start.")] public AudioClip RoarClose; [Tooltip("Optional second variant, picked at random.")] public AudioClip RoarClose2; [Tooltip("creatureSFX loop at low volume while wandering.")] public AudioClip BreathLoop; [Tooltip("creatureSFX loop while the stare holds.")] public AudioClip StareDrone; [Tooltip("footsteps: up to four OnStep variants in Walk/Prowl, without immediate repeats.")] public AudioClip[] StepWalk = Array.Empty<AudioClip>(); [Tooltip("footsteps: up to four OnStep variants in Run/Charge, without immediate repeats.")] public AudioClip[] StepRun = Array.Empty<AudioClip>(); [Tooltip("footstepBass: run plants at or above nominal clip pace (MoveSpeed >= 1).")] public AudioClip StepRunBass; [Tooltip("creatureSFX: OnGrabContact.")] public AudioClip Grab; [Tooltip("creatureSFX: OnCrush.")] public AudioClip Crush; [Tooltip("creatureVoice: OnThrowRelease.")] public AudioClip Throw; [Tooltip("creatureSFX: OnAntlerPin.")] public AudioClip AntlerHit; [Tooltip("creatureSFX: OnDoorStart bed; only DoorStrain and DoorOpen may layer over it.")] public AudioClip DoorRip; [Tooltip("creatureSFX: each OnDoorStrain contact.")] public AudioClip DoorStrain; [Tooltip("creatureSFX: OnDoorOpen.")] public AudioClip DoorOpen; [Tooltip("creatureVoice: first Chase/Charge entry in a Hunt/Stalk encounter, replacing the entry roar.")] public AudioClip Alert; [Tooltip("creatureVoice: a hit accepted while vulnerable.")] public AudioClip Hurt; [Tooltip("creatureVoice: after all other audio stops on death.")] public AudioClip Death; [Tooltip("creatureVoice: entering Flee.")] public AudioClip FleeSnort; } internal static class ModerBestiary { internal const string Text = "Moder\n\nDanger level: high\n\nEmployees have reported a towering, antlered creature watching them from the edge of the forest. Its resemblance to a deer is superficial. Witnesses describe a second pair of arms beneath the head, and human remains caught in its antlers.\n\nThe creature follows at a distance, sometimes standing motionless and staring for several minutes. This is not evidence of a peaceful temperament. Survivors have referred to it as a 'deer-god'; the Company does not recognize this classification.\n\nKeep your distance. A closed ship door has not always prevented entry.\n\n"; } internal static class ModerBloodFxBridge { internal const string PluginGuid = "com.y4ngz.bloodfx"; internal const string SourceKeyCrush = "ModerCrush"; internal const int GibKindSplit = 3; private const string GibApiTypeName = "Y4NGZCompany.Experience.BloodFX.BloodFXGibApi"; private static bool _resolved; private static Func<bool> _isAvailable; private static Func<PlayerControllerB, string, int, bool> _requestGib; internal static bool RequestGib(PlayerControllerB victim, string sourceKey, int kind) { try { if (!_resolved) { Resolve(); } if (_requestGib == null || !_isAvailable()) { return false; } return _requestGib(victim, sourceKey, kind); } catch (Exception ex) { _isAvailable = null; _requestGib = null; ManualLogSource log = Plugin.Log; if (log != null) { log.LogWarning((object)("[Moder] Disabled optional BloodFX gib bridge: " + ex.GetBaseException().Message)); } return false; } } private static void Resolve() { _resolved = true; if (!Chainloader.PluginInfos.TryGetValue("com.y4ngz.bloodfx", out var value) || (Object)(object)value.Instance == (Object)null) { return; } Type? type = ((object)value.Instance).GetType().Assembly.GetType("Y4NGZCompany.Experience.BloodFX.BloodFXGibApi", throwOnError: false); PropertyInfo propertyInfo = type?.GetProperty("IsAvailable", BindingFlags.Static | BindingFlags.Public); MethodInfo methodInfo = ((propertyInfo != null && propertyInfo.PropertyType == typeof(bool)) ? propertyInfo.GetGetMethod() : null); MethodInfo methodInfo2 = type?.GetMethod("RequestGib", BindingFlags.Static | BindingFlags.Public, null, new Type[3] { typeof(PlayerControllerB), typeof(string), typeof(int) }, null); if (methodInfo == null || methodInfo2 == null || methodInfo2.ReturnType != typeof(bool)) { ManualLogSource log = Plugin.Log; if (log != null) { log.LogWarning((object)"[Moder] BloodFX is installed but Y4NGZCompany.Experience.BloodFX.BloodFXGibApi is missing or incompatible; the crush keeps the vanilla death."); } return; } _isAvailable = (Func<bool>)Delegate.CreateDelegate(typeof(Func<bool>), methodInfo); _requestGib = (Func<PlayerControllerB, string, int, bool>)Delegate.CreateDelegate(typeof(Func<PlayerControllerB, string, int, bool>), methodInfo2); ManualLogSource log2 = Plugin.Log; if (log2 != null) { log2.LogInfo((object)"[Moder] BloodFX gib bridge bound (Y4NGZCompany.Experience.BloodFX.BloodFXGibApi)."); } } } public sealed class ModerConfig { private const string SectionGeneral = "General"; private const string SectionSpawning = "Spawning"; private const string SectionMoods = "Moods"; private const string SectionMovement = "Movement"; private const string SectionCombat = "Combat"; private const string SectionPatrol = "Patrol"; private const string SectionSiege = "Siege"; private const string SectionPresentation = "Presentation"; private const string SectionDiagnostics = "Diagnostics"; public ConfigEntry<bool> Enabled { get; } public ConfigEntry<float> SpawnWeightMultiplier { get; } public ConfigEntry<string> MoonOverrides { get; } public ConfigEntry<int> HuntWeight { get; } public ConfigEntry<int> StalkWeight { get; } public ConfigEntry<int> StareWeight { get; } public ConfigEntry<int> SiegeWeight { get; } public ConfigEntry<float> MoodCooldownSeconds { get; } public ConfigEntry<float> WalkSpeed { get; } public ConfigEntry<float> ProwlSpeed { get; } public ConfigEntry<float> RunSpeed { get; } public ConfigEntry<float> ChargeSpeed { get; } public ConfigEntry<bool> Invulnerable { get; } public ConfigEntry<int> Health { get; } public ConfigEntry<float> GrabReach { get; } public ConfigEntry<float> CrushChance { get; } public ConfigEntry<float> ThrowSpeed { get; } public ConfigEntry<float> ChargeMinRange { get; } public ConfigEntry<float> ChargeMaxRange { get; } public ConfigEntry<float> StareHoldMin { get; } public ConfigEntry<float> StareHoldMax { get; } public ConfigEntry<float> StareFleeChance { get; } public ConfigEntry<float> CloseAttackRange { get; } public ConfigEntry<float> StareChargeRange { get; } public ConfigEntry<int> ThreatLevel { get; } public ConfigEntry<float> TerritoryRadius { get; } public ConfigEntry<float> NightApproachStart { get; } public ConfigEntry<bool> SiegeEnabled { get; } public ConfigEntry<float> ShipEntrySeconds { get; } public ConfigEntry<float> EyeEmission { get; } public ConfigEntry<bool> VerboseLogging { get; } public ModerConfig(ConfigFile config) { //IL_0068: Unknown result type (might be due to invalid IL or missing references) //IL_0072: Expected O, but got Unknown //IL_00b7: Unknown result type (might be due to invalid IL or missing references) //IL_00c1: Expected O, but got Unknown //IL_00e6: Unknown result type (might be due to invalid IL or missing references) //IL_00f0: Expected O, but got Unknown //IL_0115: Unknown result type (might be due to invalid IL or missing references) //IL_011f: Expected O, but got Unknown //IL_0143: Unknown result type (might be due to invalid IL or missing references) //IL_014d: Expected O, but got Unknown //IL_017c: Unknown result type (might be due to invalid IL or missing references) //IL_0186: Expected O, but got Unknown //IL_01b5: Unknown result type (might be due to invalid IL or missing references) //IL_01bf: Expected O, but got Unknown //IL_01ee: Unknown result type (might be due to invalid IL or missing references) //IL_01f8: Expected O, but got Unknown //IL_0227: Unknown result type (might be due to invalid IL or missing references) //IL_0231: Expected O, but got Unknown //IL_0260: Unknown result type (might be due to invalid IL or missing references) //IL_026a: Expected O, but got Unknown //IL_02ae: Unknown result type (might be due to invalid IL or missing references) //IL_02b8: Expected O, but got Unknown //IL_02e7: Unknown result type (might be due to invalid IL or missing references) //IL_02f1: Expected O, but got Unknown //IL_0320: Unknown result type (might be due to invalid IL or missing references) //IL_032a: Expected O, but got Unknown //IL_0359: Unknown result type (might be due to invalid IL or missing references) //IL_0363: Expected O, but got Unknown //IL_0392: Unknown result type (might be due to invalid IL or missing references) //IL_039c: Expected O, but got Unknown //IL_03cb: Unknown result type (might be due to invalid IL or missing references) //IL_03d5: Expected O, but got Unknown //IL_0404: Unknown result type (might be due to invalid IL or missing references) //IL_040e: Expected O, but got Unknown //IL_043d: Unknown result type (might be due to invalid IL or missing references) //IL_0447: Expected O, but got Unknown //IL_0476: Unknown result type (might be due to invalid IL or missing references) //IL_0480: Expected O, but got Unknown //IL_04af: Unknown result type (might be due to invalid IL or missing references) //IL_04b9: Expected O, but got Unknown //IL_04e8: Unknown result type (might be due to invalid IL or missing references) //IL_04f2: Expected O, but got Unknown //IL_0517: Unknown result type (might be due to invalid IL or missing references) //IL_0521: Expected O, but got Unknown //IL_0550: Unknown result type (might be due to invalid IL or missing references) //IL_055a: Expected O, but got Unknown //IL_0589: Unknown result type (might be due to invalid IL or missing references) //IL_0593: Expected O, but got Unknown //IL_05de: Unknown result type (might be due to invalid IL or missing references) //IL_05e8: Expected O, but got Unknown //IL_0617: Unknown result type (might be due to invalid IL or missing references) //IL_0621: Expected O, but got Unknown using (ConfigPersistence.BeginBinding(config, Plugin.Log, "Moder")) { ModerConfigMigration.RetuneUntouchedDefaults(config, Plugin.Log); Enabled = config.Bind<bool>("General", "Enabled", true, "Enable natural Moder spawns. Host-only: every install still registers the creature so host and clients stay in sync."); SpawnWeightMultiplier = config.Bind<float>("Spawning", "SpawnWeightMultiplier", 1f, new ConfigDescription("Host-only multiplier applied to Moder's outdoor moon weights. 0 disables natural spawns.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 5f), Array.Empty<object>())); MoonOverrides = config.Bind<string>("Spawning", "MoonOverrides", string.Empty, "Host-only comma-separated base moon weights, e.g. Experimentation:20,Offense:30 or namespace:moon=20. Weights are clamped to 0-100; 0 disables a moon. Unlisted normal moons use weight 20."); HuntWeight = config.Bind<int>("Moods", "HuntWeight", 60, new ConfigDescription("Host-only relative weight of the Hunt mood. 0 excludes it from the mood roll.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 100), Array.Empty<object>())); StalkWeight = config.Bind<int>("Moods", "StalkWeight", 20, new ConfigDescription("Host-only relative weight of the Stalk mood. 0 excludes it from the mood roll.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 100), Array.Empty<object>())); StareWeight = config.Bind<int>("Moods", "StareWeight", 15, new ConfigDescription("Host-only relative weight of the Stare mood. 0 excludes it from the mood roll.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 100), Array.Empty<object>())); SiegeWeight = config.Bind<int>("Moods", "SiegeWeight", 5, new ConfigDescription("Host-only relative weight of the Siege mood when siege is enabled and a player is inside the closed ship. 0 excludes it from the mood roll.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 100), Array.Empty<object>())); MoodCooldownSeconds = config.Bind<float>("Moods", "MoodCooldownSeconds", 60f, new ConfigDescription("Host-only minimum seconds between mood rolls.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 600f), Array.Empty<object>())); WalkSpeed = config.Bind<float>("Movement", "WalkSpeed", 1.6f, new ConfigDescription("Host-only wandering speed in metres per second.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.1f, 30f), Array.Empty<object>())); ProwlSpeed = config.Bind<float>("Movement", "ProwlSpeed", 1f, new ConfigDescription("Host-only stalking speed in metres per second.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.1f, 30f), Array.Empty<object>())); RunSpeed = config.Bind<float>("Movement", "RunSpeed", 8.5f, new ConfigDescription("Host-only chase speed in metres per second.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.1f, 30f), Array.Empty<object>())); ChargeSpeed = config.Bind<float>("Movement", "ChargeSpeed", 10f, new ConfigDescription("Host-only charge speed in metres per second.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.1f, 30f), Array.Empty<object>())); Invulnerable = config.Bind<bool>("Combat", "Invulnerable", true, "Ignore damage to Moder. Restart after changing so EnemyType.canDie and Dawn tags agree; keep this value identical on every install."); Health = config.Bind<int>("Combat", "Health", 40, new ConfigDescription("Host-authoritative hit points when Invulnerable is false. Applied to newly spawned Moder instances.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 1000), Array.Empty<object>())); GrabReach = config.Bind<float>("Combat", "GrabReach", 2.6f, new ConfigDescription("Host-only maximum grab distance in metres from the torso's right hand; line of sight is still required.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.1f, 10f), Array.Empty<object>())); CrushChance = config.Bind<float>("Combat", "CrushChance", 0.6f, new ConfigDescription("Host-only chance to crush a grabbed player rather than throw them.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 1f), Array.Empty<object>())); ThrowSpeed = config.Bind<float>("Combat", "ThrowSpeed", 28f, new ConfigDescription("Launch speed in metres per second at 35 degrees above the ground. Keep this value identical on every install; the victim applies the throw force.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 100f), Array.Empty<object>())); ChargeMinRange = config.Bind<float>("Combat", "ChargeMinRange", 12f, new ConfigDescription("Host-only minimum target distance in metres to begin a charge. Keep at or below ChargeMaxRange.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 100f), Array.Empty<object>())); ChargeMaxRange = config.Bind<float>("Combat", "ChargeMaxRange", 25f, new ConfigDescription("Host-only maximum target distance in metres to begin a charge. Keep at or above ChargeMinRange.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 100f), Array.Empty<object>())); StareHoldMin = config.Bind<float>("Combat", "StareHoldMin", 6f, new ConfigDescription("Host-only minimum stare-hold duration in seconds. Keep at or below StareHoldMax.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 60f), Array.Empty<object>())); StareHoldMax = config.Bind<float>("Combat", "StareHoldMax", 12f, new ConfigDescription("Host-only maximum stare-hold duration in seconds. Keep at or above StareHoldMin.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 60f), Array.Empty<object>())); StareFleeChance = config.Bind<float>("Combat", "StareFleeChance", 0.7f, new ConfigDescription("Host-only chance to flee after a stare rather than attack.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 1f), Array.Empty<object>())); CloseAttackRange = config.Bind<float>("Combat", "CloseAttackRange", 4f, new ConfigDescription("Host-only horizontal distance in metres within which Moder attacks a player it can see, whatever its mood or stare (the Siege doorway stare keeps its own rules). 0 turns the rule off.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 10f), Array.Empty<object>())); StareChargeRange = config.Bind<float>("Combat", "StareChargeRange", 10f, new ConfigDescription("Host-only target distance in metres within which a finished stare always attacks (a charge inside the charge range, otherwise a chase) rather than flees; not at the Siege doorway. 0 turns the rule off.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 30f), Array.Empty<object>())); ThreatLevel = config.Bind<int>("Combat", "ThreatLevel", 18, new ConfigDescription("Threat level other monsters see in the Moder (a Forest Giant is 18): Old Birds target him and Baboon Hawks keep away. 0 hides him from them. Read where the other monster's AI runs, normally the host.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 30), Array.Empty<object>())); TerritoryRadius = config.Bind<float>("Patrol", "TerritoryRadius", 60f, new ConfigDescription("Host-only radius in metres of the landmark ring the Moder patrols around its spawn point when it has no target.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(30f, 150f), Array.Empty<object>())); NightApproachStart = config.Bind<float>("Patrol", "NightApproachStart", 0.55f, new ConfigDescription("Host-only day fraction (0 = landing, 1 = midnight) after which the idle patrol drifts toward the ship every second landmark; 1 effectively disables it.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.1f, 1f), Array.Empty<object>())); SiegeEnabled = config.Bind<bool>("Siege", "SiegeEnabled", true, "Host-only: allow the Siege mood and the ship-door rip attack."); ShipEntrySeconds = config.Bind<float>("Siege", "ShipEntrySeconds", 30f, new ConfigDescription("Host-only ship pursuit window in seconds, starting when Moder opens the doors. Open doors also allow ship-room targets; a pursuit still ends when its window expires.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 300f), Array.Empty<object>())); EyeEmission = config.Bind<float>("Presentation", "EyeEmission", 6f, new ConfigDescription("Local eye emission intensity scale; 0 disables both the eye glow and the small eye point light (the light itself is not scaled).", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 20f), Array.Empty<object>())); VerboseLogging = config.Bind<bool>("Diagnostics", "VerboseLogging", false, "Write verbose Moder state, attack and animation-event diagnostics on this install."); } } } internal static class ModerConfigMigration { private const string CreatureName = "Moder"; private const string DefaultValueComment = "# Default value:"; private static readonly KeyValuePair<ConfigDefinition, float>[] RetunedDefaults = new KeyValuePair<ConfigDefinition, float>[7] { new KeyValuePair<ConfigDefinition, float>(new ConfigDefinition("Movement", "RunSpeed"), 7f), new KeyValuePair<ConfigDefinition, float>(new ConfigDefinition("Movement", "ChargeSpeed"), 8f), new KeyValuePair<ConfigDefinition, float>(new ConfigDefinition("Presentation", "EyeEmission"), 3f), new KeyValuePair<ConfigDefinition, float>(new ConfigDefinition("Moods", "HuntWeight"), 40f), new KeyValuePair<ConfigDefinition, float>(new ConfigDefinition("Moods", "StalkWeight"), 30f), new KeyValuePair<ConfigDefinition, float>(new ConfigDefinition("Moods", "StareWeight"), 20f), new KeyValuePair<ConfigDefinition, float>(new ConfigDefinition("Moods", "SiegeWeight"), 10f) }; internal static void RetuneUntouchedDefaults(ConfigFile config, ManualLogSource log) { string configFilePath = config.ConfigFilePath; if (!File.Exists(configFilePath)) { return; } string[] lines; try { lines = File.ReadAllLines(configFilePath); } catch (Exception ex) { if (log != null) { log.LogWarning((object)("[Moder] Could not read the config to apply changed defaults: " + ex.Message + " Stored values are kept.")); } return; } KeyValuePair<ConfigDefinition, float>[] retunedDefaults = RetunedDefaults; for (int i = 0; i < retunedDefaults.Length; i++) { KeyValuePair<ConfigDefinition, float> keyValuePair = retunedDefaults[i]; if (TryReadStoredEntry(lines, keyValuePair.Key, out var value, out var recordedDefault) && IsExactly(value, keyValuePair.Value) && IsExactly(recordedDefault, keyValuePair.Value)) { config.Bind<string>(keyValuePair.Key, value, (ConfigDescription)null); config.Remove(keyValuePair.Key); if (log != null) { log.LogInfo((object)("[Moder] " + keyValuePair.Key.Section + "." + keyValuePair.Key.Key + " was still at the old default " + value + " and now uses the current default.")); } } } } private static bool TryReadStoredEntry(string[] lines, ConfigDefinition definition, out string value, out string recordedDefault) { value = null; recordedDefault = null; bool result = false; string a = string.Empty; string text = null; for (int i = 0; i < lines.Length; i++) { string text2 = lines[i].Trim(); if (text2.StartsWith("#", StringComparison.Ordinal)) { if (text2.StartsWith("# Default value:", StringComparison.Ordinal)) { text = text2.Substring("# Default value:".Length).Trim(); } continue; } if (text2.StartsWith("[", StringComparison.Ordinal) && text2.EndsWith("]", StringComparison.Ordinal)) { a = text2.Substring(1, text2.Length - 2); text = null; continue; } int num = text2.IndexOf('='); if (num >= 0 && string.Equals(a, definition.Section, StringComparison.Ordinal) && string.Equals(text2.Substring(0, num).Trim(), definition.Key, StringComparison.Ordinal)) { value = text2.Substring(num + 1).Trim(); recordedDefault = text; result = true; } text = null; } return result; } private static bool IsExactly(string value, float expected) { if (float.TryParse(value, NumberStyles.Float, CultureInfo.InvariantCulture, out var result)) { return result == expected; } return false; } } internal sealed class ModerSpawnWeights : IWeighted, IContextualWeighted<SpawnWeightContext> { private const int DefaultWeight = 20; private readonly Func<float> _multiplier; private readonly MoonWeightOverrides _moonOverrides; internal ModerSpawnWeights(Func<float> multiplier, Func<string> moonOverrides, Action<string> logWarning) { _multiplier = multiplier ?? throw new ArgumentNullException("multiplier"); _moonOverrides = new MoonWeightOverrides(moonOverrides, logWarning, "Moder"); } public int GetWeight() { return SpawnWeightTable.Scale(20, 1f, _multiplier()); } public int GetWeight(SpawnWeightContext context) { DawnMoonInfo moon = ((SpawnWeightContext)(ref context)).Moon; int authoredWeight = 20; if (moon != null && (((DawnBaseInfo<DawnMoonInfo>)(object)moon).HasTag(Tags.Company) || ((DawnBaseInfo<DawnMoonInfo>)(object)moon).HasTag(Tags.Unimplemented) || (((DawnBaseInfo<DawnMoonInfo>)(object)moon).TypedKey != null && ((object)((DawnBaseInfo<DawnMoonInfo>)(object)moon).TypedKey).Equals((object?)MoonKeys.Test)))) { authoredWeight = 0; } authoredWeight = _moonOverrides.Resolve(moon, authoredWeight); return SpawnWeightTable.Scale(authoredWeight, 1f, _multiplier()); } } [BepInPlugin("y4ngz.lethalcompany.moder", "Y4NGZ Moder", "2.0.0")] [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInDependency(/*Could not decode attribute arguments.*/)] public sealed class Plugin : BaseUnityPlugin { internal const string BundleFilename = "y4ngzmoder.bundle"; internal const string ModerPrefabName = "LGUModer"; internal const string ModerPrefabPath = "Assets/Y4NGZ/Moder/Prefabs/LGUModer.prefab"; internal const string DawnNamespace = "y4ngz_monsters"; internal const string DawnEnemyKey = "moder"; internal static ManualLogSource Log; internal static AssetBundle ModAssets; internal static GameObject ModerPrefab; internal static EnemyType ModerEnemyType; internal static ModerSpawnWeights SpawnWeights; private static bool _netcodeInitialized; public static Plugin Instance { get; private set; } public static ModerConfig ModerConfig { get; private set; } private void Awake() { Instance = this; Log = ((BaseUnityPlugin)this).Logger; try { InitializeNetcodeRPCs(); ModerConfig = new ModerConfig(((BaseUnityPlugin)this).Config); if (!LoadBundle()) { return; } ModerPrefab = ModAssets.LoadAsset<GameObject>("Assets/Y4NGZ/Moder/Prefabs/LGUModer.prefab"); if ((Object)(object)ModerPrefab == (Object)null) { Log.LogError((object)"Moder bundle did not contain the required prefab: Assets/Y4NGZ/Moder/Prefabs/LGUModer.prefab."); return; } ModerAI moderAI = PreparePrefab(ModerPrefab); ModerEnemyType = CreateEnemyType(ModerPrefab, moderAI); ((EnemyAI)moderAI).enemyType = ModerEnemyType; RegisterWithDawn(); if (!ModerConfig.Enabled.Value) { Log.LogInfo((object)"Y4NGZ Moder: registered network prefab; spawning disabled by config."); } Log.LogInfo((object)"Y4NGZ Moder v2.0.0 loaded. Registered as 'y4ngz_monsters:moder'."); } catch (Exception arg) { Log.LogError((object)string.Format("[{0}] Initialization failed: {1}", "Y4NGZ Moder", arg)); } } private static void RegisterWithDawn() { SpawnWeights = new ModerSpawnWeights(() => (!ModerConfig.Enabled.Value) ? 0f : ModerConfig.SpawnWeightMultiplier.Value, () => ModerConfig.MoonOverrides.Value, delegate(string message) { Log.LogWarning((object)message); }); DawnLib.RegisterNetworkPrefab(ModerPrefab); DawnLib.DefineEnemy(NamespacedKey<DawnEnemyInfo>.From("y4ngz_monsters", "moder"), ModerEnemyType, (Action<EnemyInfoBuilder>)delegate(EnemyInfoBuilder builder) { ((BaseInfoBuilder<DawnEnemyInfo, EnemyType, EnemyInfoBuilder>)(object)builder.DefineOutside((Action<EnemyLocationBuilder>)delegate(EnemyLocationBuilder location) { location.SetWeights((Action<WeightTableBuilder<DawnMoonInfo, SpawnWeightContext>>)delegate(WeightTableBuilder<DawnMoonInfo, SpawnWeightContext> table) { table.SetGlobalWeight((IWeighted)(object)SpawnWeights); }); }).CreateBestiaryNode("Moder\n\nDanger level: high\n\nEmployees have reported a towering, antlered creature watching them from the edge of the forest. Its resemblance to a deer is superficial. Witnesses describe a second pair of arms beneath the head, and human remains caught in its antlers.\n\nThe creature follows at a distance, sometimes standing motionless and staring for several minutes. This is not evidence of a peaceful temperament. Survivors have referred to it as a 'deer-god'; the Company does not recognize this classification.\n\nKeep your distance. A closed ship door has not always prevented entry.\n\n").CreateNameKeyword("moder")).AddTags((IEnumerable<NamespacedKey>)(object)new NamespacedKey[4] { Tags.Hostile, Tags.Organic, Tags.Large, Tags.Quadruped }); if (!ModerConfig.Invulnerable.Value) { ((BaseInfoBuilder<DawnEnemyInfo, EnemyType, EnemyInfoBuilder>)(object)builder).AddTags((IEnumerable<NamespacedKey>)(object)new NamespacedKey[1] { Tags.Killable }); } }); } private static void InitializeNetcodeRPCs() { if (_netcodeInitialized) { return; } _netcodeInitialized = true; Type[] types = Assembly.GetExecutingAssembly().GetTypes(); foreach (Type type in types) { MethodInfo[] methods; try { methods = type.GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); } catch { continue; } foreach (MethodInfo methodInfo in methods) { if (methodInfo.GetCustomAttributes(typeof(RuntimeInitializeOnLoadMethodAttribute), inherit: false).Length != 0) { try { methodInfo.Invoke(null, null); } catch (Exception ex) { Log.LogWarning((object)("[NetcodeInit] " + type.Name + "." + methodInfo.Name + " failed: " + ex.Message)); } } } } } private static bool LoadBundle() { string directoryName = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); if (string.IsNullOrEmpty(directoryName)) { Log.LogError((object)"Could not resolve plugin assembly directory."); return false; } string text = Path.Combine(directoryName, "y4ngzmoder.bundle"); if (!File.Exists(text)) { Log.LogError((object)("Missing asset bundle: " + text)); return false; } ModAssets = AssetBundle.LoadFromFile(text); if ((Object)(object)ModAssets == (Object)null) { Log.LogError((object)("AssetBundle.LoadFromFile returned null for " + text + ".")); return false; } return true; } private static ModerAI PreparePrefab(GameObject prefab) { //IL_0159: Unknown result type (might be due to invalid IL or missing references) //IL_015e: Unknown result type (might be due to invalid IL or missing references) //IL_0169: Unknown result type (might be due to invalid IL or missing references) //IL_0174: Unknown result type (might be due to invalid IL or missing references) //IL_017c: Expected O, but got Unknown //IL_017e: Unknown result type (might be due to invalid IL or missing references) //IL_0183: Unknown result type (might be due to invalid IL or missing references) //IL_018e: Unknown result type (might be due to invalid IL or missing references) //IL_0199: Unknown result type (might be due to invalid IL or missing references) //IL_01a1: Expected O, but got Unknown //IL_01a3: Unknown result type (might be due to invalid IL or missing references) //IL_01a8: Unknown result type (might be due to invalid IL or missing references) //IL_01b3: Unknown result type (might be due to invalid IL or missing references) //IL_01be: Unknown result type (might be due to invalid IL or missing references) //IL_01c6: Expected O, but got Unknown //IL_01c8: Unknown result type (might be due to invalid IL or missing references) //IL_01cd: Unknown result type (might be due to invalid IL or missing references) //IL_01d8: Unknown result type (might be due to invalid IL or missing references) //IL_01e3: Unknown result type (might be due to invalid IL or missing references) //IL_01eb: Expected O, but got Unknown //IL_01ed: Unknown result type (might be due to invalid IL or missing references) //IL_01f2: Unknown result type (might be due to invalid IL or missing references) //IL_01fd: Unknown result type (might be due to invalid IL or missing references) //IL_0208: Unknown result type (might be due to invalid IL or missing references) //IL_0210: Expected O, but got Unknown //IL_0212: Unknown result type (might be due to invalid IL or missing references) //IL_0217: Unknown result type (might be due to invalid IL or missing references) //IL_0222: Unknown result type (might be due to invalid IL or missing references) //IL_022d: Unknown result type (might be due to invalid IL or missing references) //IL_0235: Expected O, but got Unknown //IL_0237: Unknown result type (might be due to invalid IL or missing references) //IL_023c: Unknown result type (might be due to invalid IL or missing references) //IL_0247: Unknown result type (might be due to invalid IL or missing references) //IL_0252: Unknown result type (might be due to invalid IL or missing references) //IL_025a: Expected O, but got Unknown //IL_025c: Unknown result type (might be due to invalid IL or missing references) //IL_0261: Unknown result type (might be due to invalid IL or missing references) //IL_026c: Unknown result type (might be due to invalid IL or missing references) //IL_0277: Unknown result type (might be due to invalid IL or missing references) //IL_027f: Expected O, but got Unknown AssignUniqueNetworkHash(prefab); ModerAI moderAI = prefab.GetComponent<ModerAI>(); if ((Object)(object)moderAI == (Object)null) { moderAI = prefab.AddComponent<ModerAI>(); } NavMeshAgent val = prefab.GetComponent<NavMeshAgent>(); if ((Object)(object)val == (Object)null) { val = prefab.AddComponent<NavMeshAgent>(); } val.radius = 1.6f; val.height = 5.9f; val.baseOffset = 0f; val.angularSpeed = 70f; val.acceleration = 12f; ((EnemyAI)moderAI).agent = val; ((EnemyAI)moderAI).enemyHP = ModerConfig.Health.Value; if ((Object)(object)((EnemyAI)moderAI).creatureAnimator == (Object)null) { ((EnemyAI)moderAI).creatureAnimator = prefab.GetComponentInChildren<Animator>(true); } if ((Object)(object)((EnemyAI)moderAI).creatureAnimator != (Object)null) { ((EnemyAI)moderAI).creatureAnimator.applyRootMotion = false; ((EnemyAI)moderAI).creatureAnimator.cullingMode = (AnimatorCullingMode)0; } ((EnemyAI)moderAI).skinnedMeshRenderers = prefab.GetComponentsInChildren<SkinnedMeshRenderer>(true); ((EnemyAI)moderAI).meshRenderers = prefab.GetComponentsInChildren<MeshRenderer>(true); EnemyAICollisionDetect[] componentsInChildren = prefab.GetComponentsInChildren<EnemyAICollisionDetect>(true); for (int i = 0; i < componentsInChildren.Length; i++) { componentsInChildren[i].mainScript = (EnemyAI)(object)moderAI; } ScanNodeProperties[] componentsInChildren2 = prefab.GetComponentsInChildren<ScanNodeProperties>(true); for (int j = 0; j < componentsInChildren2.Length; j++) { componentsInChildren2[j].headerText = "Moder"; componentsInChildren2[j].subText = string.Empty; componentsInChildren2[j].nodeType = 1; componentsInChildren2[j].creatureScanID = -1; } ((EnemyAI)moderAI).enemyBehaviourStates = (EnemyBehaviourState[])(object)new EnemyBehaviourState[8] { new EnemyBehaviourState { name = "Wander", parameterString = "StareHold", boolValue = false }, new EnemyBehaviourState { name = "Stalk", parameterString = "StareHold", boolValue = false }, new EnemyBehaviourState { name = "Stare", parameterString = "StareHold", boolValue = true }, new EnemyBehaviourState { name = "Chase", parameterString = "StareHold", boolValue = false }, new EnemyBehaviourState { name = "Charge", parameterString = "StareHold", boolValue = false }, new EnemyBehaviourState { name = "Grab", parameterString = "StareHold", boolValue = false }, new EnemyBehaviourState { name = "Siege", parameterString = "StareHold", boolValue = false }, new EnemyBehaviourState { name = "Flee", parameterString = "StareHold", boolValue = false } }; ((EnemyAI)moderAI).currentBehaviourStateIndex = 0; ((EnemyAI)moderAI).previousBehaviourStateIndex = 0; ((EnemyAI)moderAI).currentBehaviourState = ((EnemyAI)moderAI).enemyBehaviourStates[0]; return moderAI; } private static EnemyType CreateEnemyType(GameObject prefab, ModerAI ai) { //IL_00f1: Unknown result type (might be due to invalid IL or missing references) //IL_00f8: Unknown result type (might be due to invalid IL or missing references) EnemyType obj = ScriptableObject.CreateInstance<EnemyType>(); obj.enemyName = "Moder"; obj.enemyPrefab = prefab; obj.PowerLevel = 3f; obj.DiversityPowerLevel = 1; obj.MaxCount = 1; obj.canDie = !ModerConfig.Invulnerable.Value; obj.canBeStunned = false; obj.canBeDestroyed = !ModerConfig.Invulnerable.Value; obj.stunTimeMultiplier = 1f; obj.stunGameDifficultyMultiplier = 0f; obj.destroyOnDeath = false; obj.doorSpeedMultiplier = 0f; obj.isOutsideEnemy = true; obj.isDaytimeEnemy = false; obj.normalizedTimeInDayToLeave = 1f; obj.probabilityCurve = AnimationCurve.Constant(0f, 1f, 1f); obj.numberSpawnedFalloff = AnimationCurve.Linear(0f, 1f, 1f, 0.25f); obj.useNumberSpawnedFalloff = true; obj.disableAnimatorWhenFar = false; obj.SizeLimit = (NavSizeLimit)1; obj.EnemySize = (EnemySize)1; CreatureSfx.Apply(obj, (EnemyAI)(object)ai); return obj; } private static void AssignUniqueNetworkHash(GameObject prefab) { NetworkObject val = prefab.GetComponent<NetworkObject>(); if ((Object)(object)val == (Object)null) { val = prefab.AddComponent<NetworkObject>(); } uint num; using (MD5 mD = MD5.Create()) { num = BitConverter.ToUInt32(mD.ComputeHash(Encoding.UTF8.GetBytes("y4ngz.lethalcompany.moder.LGUModer")), 0); } PropertyInfo property = typeof(NetworkObject).GetProperty("GlobalObjectIdHash", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); if (property != null && property.CanWrite) { property.SetValue(val, num); return; } FieldInfo? obj = typeof(NetworkObject).GetField("GlobalObjectIdHash", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic) ?? typeof(NetworkObject).GetField("<GlobalObjectIdHash>k__BackingField", BindingFlags.Instance | BindingFlags.NonPublic); if (obj == null) { throw new MissingFieldException(typeof(NetworkObject).FullName, "GlobalObjectIdHash"); } obj.SetValue(val, num); } } internal static class PluginInfo { public const string PLUGIN_GUID = "y4ngz.lethalcompany.moder"; public const string PLUGIN_NAME = "Y4NGZ Moder"; public const string PLUGIN_VERSION = "2.0.0"; } } namespace Y4NGZModer.World { [DisallowMultipleComponent] [DefaultExecutionOrder(-1000)] public sealed class ModerVictimLock : MonoBehaviour { private const string InputLockHolder = "Y4NGZModer"; private PlayerControllerB _player; private ModerAI _ai; private bool _holding; private bool _controlsApplied; private bool _inputLocked; private bool _savedInSpecialInteractAnimation; private bool _savedSnapToServerPosition; private bool _savedDisableInteract; private bool _savedDisableSyncInAnimation; private EnemyAI _savedInAnimationWithEnemy; private ModerVictimPresentation _presentation; internal static void Hold(PlayerControllerB player, ModerAI ai) { if (!((Object)(object)player == (Object)null) && !((Object)(object)ai == (Object)null)) { ModerVictimLock moderVictimLock = ((Component)player).GetComponent<ModerVictimLock>(); if ((Object)(object)moderVictimLock == (Object)null) { moderVictimLock = ((Component)player).gameObject.AddComponent<ModerVictimLock>(); } moderVictimLock.Configure(player, ai); } } internal static void Release(PlayerControllerB player, ModerAI ai) { if (!((Object)(object)player == (Object)null)) { ModerVictimLock component = ((Component)player).GetComponent<ModerVictimLock>(); if ((Object)(object)component != (Object)null && component._holding && (Object)(object)component._ai == (Object)(object)ai) { component.ReleaseNow(); } } } private void Configure(PlayerControllerB player, ModerAI ai) { if (_holding) { ReleaseNow(); } _player = player; _ai = ai; _holding = true; ((Behaviour)this).enabled = true; if (VictimRpc.IsVictimLocal(player)) { ApplyLocalControls(); } } private void LateUpdate() { //IL_0122: Unknown result type (might be due to invalid IL or missing references) //IL_0127: Unknown result type (might be due to invalid IL or missing references) if (!_holding) { ((Behaviour)this).enabled = false; return; } if ((Object)(object)_player == (Object)null || (Object)(object)_ai == (Object)null || !_ai.IsHolding(_player) || _player.isPlayerDead || !_player.isPlayerControlled) { ReleaseNow(); return; } if (_controlsApplied) { _player.inSpecialInteractAnimation = true; _player.snapToServerPosition = false; _player.disableInteract = true; _player.disableSyncInAnimation = true; _player.inAnimationWithEnemy = (EnemyAI)(object)_ai; if (_inputLocked) { PlayerInputLock.Acquire(_player, "Y4NGZModer"); } } if ((Object)(object)_presentation == (Object)null) { _presentation = ModerVictimPresentation.For(_player); } _presentation.Present((MonoBehaviour)(object)this, _player, _ai.VictimSocket, _ai.VictimYaw); if (_controlsApplied) { _player.serverPlayerPosition = ((Component)_player).transform.localPosition; _player.ResetFallGravity(); } } private void ReleaseNow() { if ((Object)(object)_presentation != (Object)null) { _presentation.Release((MonoBehaviour)(object)this); } RestoreLocalControls(); _holding = false; _ai = null; ((Behaviour)this).enabled = false; } private void OnEnable() { StartOfRound instance = StartOfRound.Instance; if ((Object)(object)instance != (Object)null && instance.playerTeleportedEvent != null) { ((UnityEvent<PlayerControllerB>)(object)instance.playerTeleportedEvent).AddListener((UnityAction<PlayerControllerB>)OnPlayerTeleported); } } private void OnDisable() { StartOfRound instance = StartOfRound.Instance; if ((Object)(object)instance != (Object)null && instance.playerTeleportedEvent != null) { ((UnityEvent<PlayerControllerB>)(object)instance.playerTeleportedEvent).RemoveListener((UnityAction<PlayerControllerB>)OnPlayerTeleported); } if (_holding) { ReleaseNow(); } } private void OnPlayerTeleported(PlayerControllerB player) { if (_holding && _controlsApplied && !((Object)(object)player == (Object)null) && !((Object)(object)player != (Object)(object)_player)) { ModerAI ai = _ai; ReleaseNow(); if ((Object)(object)ai != (Object)null) { ai.RequestReleaseHeld(player); } } } private void OnDestroy() { if (_holding) { ReleaseNow(); } } private void ApplyLocalControls() { _player.CancelSpecialTriggerAnimations(); if (_player.performingEmote) { _player.StopPerformingEmoteServerRpc(); } _savedInSpecialInteractAnimation = _player.inSpecialInteractAnimation; _savedSnapToServerPosition = _player.snapToServerPosition; _savedDisableInteract = _player.disableInteract; _savedDisableSyncInAnimation = _player.disableSyncInAnimation; _savedInAnimationWithEnemy = _player.inAnimationWithEnemy; _controlsApplied = true; _inputLocked = PlayerInputLock.Acquire(_player, "Y4NGZModer"); } private void RestoreLocalControls() { //IL_00bb: Unknown result type (might be due to invalid IL or missing references) //IL_00c0: Unknown result type (might be due to invalid IL or missing references) if (!_controlsApplied || (Object)(object)_player == (Object)null) { _controlsApplied = false; _inputLocked = false; return; } _player.inSpecialInteractAnimation = _savedInSpecialInteractAnimation; _player.snapToServerPosition = _savedSnapToServerPosition; _player.disableInteract = _savedDisableInteract; _player.disableSyncInAnimation = _savedDisableSyncInAnimation; if ((Object)(object)_player.inAnimationWithEnemy == (Object)(object)_ai) { _player.inAnimationWithEnemy = _savedInAnimationWithEnemy; } if (_inputLocked) { PlayerInputLock.Release(_player, "Y4NGZModer"); } _player.serverPlayerPosition = ((Component)_player).transform.localPosition; _player.ResetFallGravity(); _controlsApplied = false; _inputLocked = false; } } [DisallowMultipleComponent] public sealed class ModerVictimPresentation : MonoBehaviour { private const float BlendSeconds = 0.2f; private const float FallbackHipsHeight = 0.9f; private PlayerControllerB _player; private MonoBehaviour _owner; private bool _active; private int _lastPresentFrame; private Vector3 _hipsOffset; private float _blendStartTime; private Vector3 _blendFromPosition; private Quaternion _blendFromRotation; internal static ModerVictimPresentation For(PlayerControllerB player) { ModerVictimPresentation component = ((Component)player).GetComponent<ModerVictimPresentation>(); if (!((Object)(object)component != (Object)null)) { return ((Component)player).gameObject.AddComponent<ModerVictimPresentation>(); } return component; } internal void Present(MonoBehaviour owner, PlayerControllerB player, Transform socket, float yaw) { //IL_0073: Unknown result type (might be due to invalid IL or missing references) //IL_0078: Unknown result type (might be due to invalid IL or missing references) //IL_007a: Unknown result type (might be due to invalid IL or missing references) //IL_007f: Unknown result type (might be due to invalid IL or missing references) //IL_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_008b: Unknown result type (might be due to invalid IL or missing references) //IL_0090: Unknown result type (might be due to invalid IL or missing references) //IL_00b4: Unknown result type (might be due to invalid IL or missing references) //IL_00b9: Unknown result type (might be due to invalid IL or missing references) //IL_00bb: Unknown result type (might be due to invalid IL or missing references) //IL_00c1: Unknown result type (might be due to invalid IL or missing references) //IL_00c6: Unknown result type (might be due to invalid IL or missing references) //IL_00c8: Unknown result type (might be due to invalid IL or missing references) if (!((Object)(object)owner == (Object)null) && !((Object)(object)player == (Object)null) && !((Object)(object)socket == (Object)null)) { if (_active && ((Object)(object)player != (Object)(object)_player || owner != _owner)) { Restore(); } if (!_active) { Begin(owner, player); } _lastPresentFrame = Time.frameCount; Transform transform = ((Component)_player).transform; Quaternion val = Quaternion.Euler(0f, yaw, 0f); Vector3 val2 = socket.position - val * _hipsOffset; float num = Mathf.SmoothStep(0f, 1f, (Time.time - _blendStartTime) / 0.2f); transform.SetPositionAndRotation(Vector3.Lerp(_blendFromPosition, val2, num), Quaternion.Slerp(_blendFromRotation, val, num)); } } internal void Release(MonoBehaviour owner) { if (_active && owner == _owner) { Restore(); } } private void LateUpdate() { if (_active && ((Object)(object)_owner == (Object)null || Time.frameCount - _lastPresentFrame > 1)) { Restore(); } } private void OnDisable() { Restore(); } private void Begin(MonoBehaviour owner, PlayerControllerB player) { //IL_003f: Unknown result type (might be due to invalid IL or missing references) //IL_0044: Unknown result type (might be due to invalid IL or missing references) //IL_004a: Unknown result type (might be due to invalid IL or missing references) //IL_0050: Unknown result type (might be due to invalid IL or missing references) //IL_0055: Unknown result type (might be due to invalid IL or missing references) //IL_005a: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_005f: Unknown result type (might be due to invalid IL or missing references) //IL_0066: 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_0072: Unknown result type (might be due to invalid IL or missing references) //IL_0077: Unknown result type (might be due to invalid IL or missing references) _player = player; _owner = owner; _active = true; Transform transform = ((Component)player).transform; Transform lowerSpine = player.lowerSpine; _hipsOffset = (((Object)(object)lowerSpine != (Object)null) ? (Quaternion.Inverse(transform.rotation) * (lowerSpine.position - transform.position)) : (Vector3.up * 0.9f)); _blendFromPosition = transform.position; _blendFromRotation = transform.rotation; _blendStartTime = Time.time; } private void Restore() { _active = false; _owner = null; } } } namespace Y4NGZModer.AI { public sealed class ModerAI : EnemyAI, IVisibleThreat { private const float ClipFrameRate = 60f; private const int GrabFrames = 72; private const int GrabContactFrame = 36; private const int LiftCrushFrames = 270; private const int CrushFrame = 210; private const int DropFrame = 216; private const int ThrowFrames = 96; private const int ThrowPickupFrame = 14; private const int ThrowReleaseFrame = 60; private const int AntlerHitFrames = 36; private const float EventSlackSeconds = 0.5f; private const float GrabServerSlack = 0.65f; private const float GrabBodyHeight = 1.8f; private const float ThrowElevationDegrees = 35f; private const float PinServerReach = 8f; private const float PinAttachWindowSeconds = 2f; private const float PinRequestCooldownSeconds = 0.5f; private const int DeadBodyLimbIndex = 5; private bool _victimOnHand; private float _pinRequestBlockedUntil; private readonly int[] _pinSlot = new int[2] { -1, -1 }; private readonly DeadBodyInfo[] _pinBody = (DeadBodyInfo[])(object)new DeadBodyInfo[2]; private readonly Transform[] _pinSocket = (Transform[])(object)new Transform[2]; private readonly bool[] _pinAttached = new bool[2]; private readonly bool[] _pinClosed = new bool[2]; private readonly float[] _pinDeadline = new float[2]; private const float SightRange = 60f; private const float SightHalfAngle = 70f; private const float ProximityAwareness = 12f; private const float LookConeDegrees = 15f; private const int LookRange = 120; private const float TurnDegreesPerSecond = 120f; private const float DefaultAcceleration = 12f; private const float ChargeAcceleration = 40f; private const float ChargeOvershoot = 8f; private const float ChargeAheadDegrees = 35f; private const float ChargeCooldownSeconds = 8f; private const float ChargeArriveDistance = 2f; private const float ChargeSlackSeconds = 1.5f; private const float FleeArriveDistance = 6f; private const float FleeTimeoutSeconds = 40f; private const float FleeFallbackDistance = 60f; private const float StalkRepathSeconds = 6f; private const float StalkCircleMinStep = 8f; private const float StalkSeenPenalty = 30f; private const float StalkNodeEyeHeight = 3f; private const float CallMinSeconds = 25f; private const float CallMaxSeconds = 40f; private const float FallbackEyeHeight = 4.5f; private const float FallbackAimHeight = 1.45f; private const float PlayerEyeHeight = 1.6f; private const float StareApproachExtraSeconds = 10f; private const float StareApproachPathCheckSeconds = 1f; [SerializeField] private Animator animator; [SerializeField] private AudioSource footsteps; [SerializeField] private Transform grabPoint; [SerializeField] private Transform scanPoint; [SerializeField] private Transform antlerSocketL; [SerializeField] private Transform antlerSocketR; [SerializeField] private Transform eyeL; [SerializeField] private Transform eyeR; [SerializeField] private Transform torsoHandR; [SerializeField] private Transform torsoSpine3; [SerializeField] private Collider antlerTriggerL; [SerializeField] private Collider antlerTriggerR; [SerializeField] private Transform doorReach; [SerializeField] private Collider torsoHitbox; [SerializeField] private ModerAnimEvents animEvents; [SerializeField] private ModerAudio audio = new ModerAudio(); internal readonly NetworkVariable<int> Mood = new NetworkVariable<int>(0, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); internal readonly NetworkVariable<int> HeldPlayerIndex = new NetworkVariable<int>(-1, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); internal readonly NetworkVariable<int> PinnedBodiesMask = new NetworkVariable<int>(0, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); private readonly NetworkVariable<int> _pinnedPlayerLeft = new NetworkVariable<int>(-1, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); private readonly NetworkVariable<int> _pinnedPlayerRight = new NetworkVariable<int>(-1, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); private readonly NetworkVariable<int> _behaviourIndex = new NetworkVariable<int>(0, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); private readonly NetworkVariable<int> _activeAction = new NetworkVariable<int>(-1, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); private readonly NetworkVariable<double> _activeActionStart = new NetworkVariable<double>(0.0, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); private readonly NetworkVariable<int> _stareLookSlot = new NetworkVariable<int>(-1, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); private readonly ServerOwnershipGuard _ownership = new ServerOwnershipGuard(); private Coroutine _actionRoutine; private PlayerControllerB _senseTarget; private PlayerControllerB _stalkNearest; private PlayerControllerB _looker; private PlayerControllerB _faceTarget; private PlayerControllerB _closeTarget; private ModerPlayer _approachPlayer = ModerPlayer.None; private Vector3 _approachPosition; private float _approachTime; private bool _rollPending; private float _lastRollTime = float.NegativeInfinity; private float _lastTargetTime; private float _lastSeenTime; private float _lastIntervalTime; private float _lookedAtSeconds; private ModerStareStage _stareStage; private double _stareRoll; private float _stareStageDeadline; private float _stareNextPathCheck; private int _stareUpMark; private Vector3 _chargeEnd; private float _chargeDeadline; private bool _chargeHit; private float _chargeHitTime; private float _nextChargeTime; private bool _actionDone; private bool _threw; private ModerPlayer _thrown = ModerPlayer.None; private double _throwRoll; private Vector3 _stalkDestination; private float _nextStalkRepathTime; private Vector3 _fleeDestination; private float _fleeDeadline; private float _nextCallTime; private float _lastCallTime = float.NegativeInfinity; private bool _siegeDoorway; private ModerQuarry _quarry = ModerQuarry.None; private const int NoLandmark = -1; private const int ShipEdgeLandmark = -2; private const int NoiseLandmark = -3; private const float RingRetrySeconds = 10f; private const float RingNodeMinDistance = 5f; private const float LandmarkSampleRadius = 1.75f; private const float NoiseSampleRadius = 5f; private const float NoiseEnemyRadius = 3f; private const int NoiseOcclusionMask = 256; private Vector3 _territoryAnchor; private bool _ringBuilt; private float _nextRingBuildTime; private Vector3[] _ringPoints = Array.Empty<Vector3>(); private ModerFlatPoint[] _ringFlat = Array.Empty<ModerFlatPoint>(); private int _ringIndex = -1; private bool _shipEdgeKnown; private Vector3 _shipEdgePoint; private float _shipEdgeFromAnchor; private int _pickNumber; private int _lastVigilLandmark = -1; private float _lastNoiseInvestigation = float.NegativeInfinity; private bool _legActive; private int _legLandmark = -1; private Vector3 _legTarget; private ModerLeg _leg; private bool _vigilActive; private float _vigilStart; private float _vigilDuration; private bool _vigilTurned; private float _vigilYaw; private int _vigilNext = -1; private bool _noisePending; private Vector3 _pendingNoise; private Vector3 _investigatedNoise; private const int StareUpFrames = 180; private const int StareUpEventFrame = 90; private const int StareDownFrames = 36; private const float MovingSpeedThreshold = 0.3f; private const float MaxObservedSpeed = 30f; private const float RemoteSpeedSmoothing = 8f; private const float PivotYawRate = 15f; private const float PivotMoveSpeed = 0.6f; private const float YawRateSmoothing = 12f; private const float MaxObservedYawRate = 720f; private const float StepPitchMin = 0.92f; private const float StepPitchMax = 1.08f; private const float StepWalkVolume = 0.8f; private const float StepRunVolume = 1f; private const float StepMinPace = 0.5f; private const int MaxStepVariants = 4; private const float StepRunBassThreshold = 1f; private const float BreathLoopVolume = 0.35f; private const string EyeMaterialName = "M_DeerGod_Eyes"; private const string StepKindRun = "run"; private const int NoAction = -1; private const float ActionCancelFadeSeconds = 0.2f; private static readonly int LocomotionHash = Animator.StringToHash("Locomotion"); private static readonly int MoveSpeedHash = Animator.StringToHash("MoveSpeed"); private static readonly int StareHoldHash = Animator.StringToHash("StareHold"); private static readonly int[] ActionTriggers = new int[7] { Animator.StringToHash("Grab"), Animator.StringToHash("LiftCrush"), Animator.StringToHash("Throw"), Animator.StringToHash("AntlerHit"), Animator.StringToHash("DoorRip"), Animator.StringToHash("Stare"), Animator.StringToHash("Hit") }; private static readonly int[] ActionStateHashes = new int[7] { Animator.StringToHash("Base Layer.Grab"), Animator.StringToHash("Base Layer.LiftCrush"), Animator.StringToHash("Base Layer.Throw"), Animator.StringToHash("Base Layer.AntlerHit"), Animator.StringToHash("Base Layer.DoorRip"), Animator.StringToHash("Base Layer.StareUp"), Animator.StringToHash("Base Layer.Hit") }; private static readonly int[] ActionFrames = new int[7] { 72, 270, 96, 36, 300, 180, 30 }; private static readonly int StareHoldStateHash = Animator.StringToHash("Base Layer.StareHold"); private static readonly int IdleStateHash = Animator.StringToHash("Base Layer.Locomotion.Idle"); public AudioSource footstepBass; [SerializeField] private Light eyeLight; private readonly int[] _eventMarks = new int[12]; private int _seenState = -1; private Vector3 _lastLocomotionPosition; private bool _hasLocomotionPosition; private float _remoteSpeed; private float _lastYaw; private bool _hasLastYaw; private float _yawRate; private bool _audioRouted; private bool _stareDroneLocal; private AudioClip _lastWalkStep; private AudioClip _lastRunStep; private int _audioAction = -1; private float _audioActionUntil = float.NegativeInfinity; private int _seenAudioMood = int.MinValue; private bool _alertPlayed; private PlayerControllerB _lookPlayer; private float _stareLowerStart = float.NegativeInfinity; private const int DoorRipFrames = 300; private const int DoorOpenFrame = 252; private const float SiegeTimeoutSeconds = 180f; private const float DoorAlignmentSeconds = 0.2f; private const float DoorReachFallbackDistance = 2.4f; private const float ShipDoorSearchInterval = 5f; private const float DoorPoseTolerance = 1f; private const float PathClearanceSkin = 0.05f; private const string ShipDoorClosedBool = "Closed"; private const string ShipDoorPryBool = "PryingOpenDoor"; private const string ShipDoorPryFloat = "pryOpenDoor"; private HangarShipDoor _shipDoor; private float _shipDoorSearchedAt = float.NegativeInfinity; private float _siegeDeadline; private bool _siegeMoving; private float _siegeApproachStarted; private bool _siegeRecoveryUsed; private bool _siegeFailed; private bool _siegeBackingOut; private Vector3 _siegeBackoutRoot; private Vector3 _siegeRoot; private float _siegeYaw; private float _shipEntryUntil; private bool _siegeOpenedDoor; private bool _shipPursuing; private bool _shipExiting; private ModerPlayer _shipQuarry = ModerPlayer.None; private readonly NetworkVariable<Vector3> _doorRipSnapshotRoot = new NetworkVariable<Vector3>(default(Vector3), (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); private readonly NetworkVariable<float> _doorRipSnapshotYaw = new NetworkVariable<float>(0f, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); private readonly NetworkVariable<int> _doorRipSnapshotId = new NetworkVariable<int>(0, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); private bool _doorRipLocal; private int _doorRipLocalId; private int _doorRipFinishedId; private int _doorRipLastId; private float _doorRipStartLocal; private Vector3 _doorRipRoot; private float _doorRipYaw; private Vector3 _doorRipAlignFrom; private Quaternion _doorRipRotationFrom; private bool _doorRipAligned; private float _nextSiegeTime; private bool[] _sheltered; private static readonly int StareUpStateHash = Animator.StringToHash("Base Layer.StareUp"); private static readonly int StareDownStateHash = Animator.StringToHash("Base Layer.StareDown"); private float _lastEnemyHitTime = float.NegativeInfinity; private float _lastEnemyHitVoiceTime = float.NegativeInfinity; private readonly Dictionary<int, float> _retaliationTimes = new Dictionary<int, float>(); private EnemyAI _retaliationFaceEnemy; private PlayerControllerB _retaliationFacePlayer; private float _lastFlinchTime = float.NegativeInfinity; private float _retaliationFaceUntil; private static readonly int TurnLTrigger = Animator.StringToHash("TurnL"); private static readonly int TurnRTrigger = Animator.StringToHash("TurnR"); private static readonly int TurnStopTrigger = Animator.StringToHash("TurnStop"); private static readonly int TurnLStateHash = Animator.StringToHash("Base Layer.TurnL"); private static readonly int TurnRStateHash = Animator.StringToHash("Base Layer.TurnR"); private readonly ModerTurnPresenter _turn = new ModerTurnPresenter(); private bool _turnModelPosed; private byte _turnSerial; private ModerState _turnStartState; private float _turnStartWantedYaw; private float _turnWantedYaw; internal Transform VictimSocket { get { if (_victimOnHand && (Object)(object)torsoHandR != (Object)null) { return torsoHandR; } if (!((Object)(object)grabPoint != (Object)null)) { return ((Component)this).transform; } return grabPoint; } } internal float VictimYaw => ((Component)this).transform.eulerAngles.y + 180f; private PlayerControllerB HeldPlayer { get { if (HeldPlayerIndex.Value < 0) { return null; } return VictimRpc.FromSlot(HeldPlayerIndex.Value); } } private Vector3 GrabHandPosition { get { //IL_003a: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Unknown result type (might be due to invalid IL or missing references) if (!((Object)(object)torsoHandR != (Object)null)) { return ((Component)this).transform.position + ((Component)this).transform.forward * 3f; } return torsoHandR.position; } } private ModerState State => (ModerState)base.currentBehaviourStateIndex; private static ModerConfig Config => Plugin.ModerConfig; private static bool Verbose { get { if (Plugin.ModerConfig != null) { return Plugin.ModerConfig.VerboseLogging.Value; } return false; } } private ModerTuning Tuning => new ModerTuning(Config.ChargeMinRange.Value, Config.ChargeMaxRange.Value, Config.StareFleeChance.Value, Config.CloseAttackRange.Value, Config.StareChargeRange.Value); private Vector3 EyePosition { get { //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_0062: Unknown result type (might be due to invalid IL or missing references) //IL_0067: Unknown result type (might be due to invalid IL or missing references) //IL_0071: Unknown result type (might be due to invalid IL or missing references) //IL_0076: Unknown result type (might be due to invalid IL or missing references) //IL_003c: Unknown result type (might be due to invalid IL or missing references) //IL_0047: Unknown result type (might be due to invalid IL or missing references) //IL_004c: Unknown result type (might be due to invalid IL or missing references) //IL_0056: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)base.eye != (Object)null) { return base.eye.position; } if ((Object)(object)eyeL != (Object)null && (Object)(object)eyeR != (Object)null) { return (eyeL.position + eyeR.position) * 0.5f; } return ((Component)this).transform.position + Vector3.up * 4.5f; } } private Vector3 LookedAtPoint { get { //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Unknown result type (might be due to invalid IL or missing references) if (!((Object)(object)scanPoint != (Object)null)) { return EyePosition; } return scanPoint.position; } } private float PatrolSpeed { get { if (State != ModerState.Stalk) { return Config.WalkSpeed.Value; } return Config.ProwlSpeed.Value; } } private static bool PatrolShipLanded { get { StartOfRound instance = StartOfRound.Instance; if ((Object)(object)instance != (Object)null && instance.shipHasLanded) { return !instance.shipIsLeaving; } return false; } } private bool PatrolNight { get { if ((Object)(object)TimeOfDay.Instance != (Object)null) { return ModerPatrolLogic.IsNight(TimeOfDay.Instance.normalizedTimeOfDay, Config.NightApproachStart.Value); } return false; } } private ModerIdleActivity IdleActivity { get { if (_noisePending || (_legActive && _legLandmark == -3)) { return ModerIdleActivity.Investigate; } if (_vigilActive) { return ModerIdleActivity.Vigil; } if (!_legActive) { return ModerIdleActivity.None; } return ModerIdleActivity.Patrol; } } internal Transform LookTarget { get { if ((Object)(object)_lookPlayer == (Object)null || base.isEnemyDead || State != ModerState.Stare || _lookPlayer.isPlayerDead) { return null; } if (!((Object)(object)_lookPlayer.gameplayCamera != (Object)null)) { return ((Component)_lookPlayer).transform; } return ((Component)_lookPlayer.gameplayCamera).transform; } } internal float StareLowerStart => _stareLowerStart; internal static float StareDownSeconds => Seconds(36); internal Transform TorsoSpine3 => torsoSpine3; private Animator Anim { get { if (!((Object)(object)animator != (Object)null)) { return base.creatureAnimator; } return animator; } } private int AudioAction { get { //IL_005e: Unknown result type (might be due to invalid IL or missing references) //IL_0063: Unknown result type (might be due to invalid IL or missing references) if (_doorRipLocal) { return 4; } if (_stareDroneLocal) { return 5; } if (Time.time < _audioActionUntil) { return _audioAction; } int value = _activeAction.Value; if (value < 0 || value >= ActionFrames.Length || (Object)(object)((NetworkBehaviour)this).NetworkManager == (Object)null) { return -1; } if (value == 5) { return value; } NetworkTime serverTime = ((NetworkBehaviour)this).NetworkManager.ServerTime; if (!(((NetworkTime)(ref serverTime)).Time - _activeActionStart.Value < (double)Seconds(ActionFrames[value]))) { return -1; } return value; } } private HangarShipDoor ShipDoor { get { if ((Object)(object)_shipDoor == (Object)null && Time.time >= _shipDoorSearchedAt + 5f) { _shipDoorSearchedAt = Time.time; _shipDoor = Object.FindObjectOfType<HangarShipDoor>(); } return _shipDoor; } } private int CurrentThreatLevel => ModerThreatLogic.ThreatLevel((Config != null) ? Config.ThreatLevel.Value : 18); private bool RetaliationBlocked { get { if (_actionRoutine == null && _activeAction.Value == -1 && !_doorRipLocal && State != ModerState.Siege && !_siegeDoorway && !_shipPursuing && (State != ModerState.Stare || !ModerMoodLogic.StareClipCancelNeeded(_stareStage))) { return AnimatorInStareClip(); } return true; } } private bool FacingRetaliationTarget { get { if (Time.time <= _retaliationFaceUntil) { if (!((Object)(object)_retaliationFaceEnemy != (Object)null)) { return (Object)(object)_retaliationFacePlayer != (Object)null; } return true; } return false; } } ThreatType IVisibleThreat.type => (ThreatType)4; internal bool IsHolding(PlayerControllerB player) { if ((Object)(object)player != (Object)null && !base.isEnemyDead && HeldPlayerIndex.Value >= 0) { return (Object)(object)VictimRpc.FromSlot(HeldPlayerIndex.Value) == (Object)(object)player; } return false; } private static float Seconds(int frames) { return (float)frames / 60f; } private bool IsHeldSlot(PlayerControllerB player) { if (HeldPlayerIndex.Value >= 0) { return (Object)(object)VictimRpc.FromSlot(HeldPlayerIndex.Value) == (Object)(object)player; } return false; } private void BeginGrab(PlayerControllerB target) { _actionDone = false; _threw = false; _throwRoll = 0.0; _thrown = ModerPlayer.None; Halt(); base.targetPlayer = target; _actionRoutine = ((MonoBehaviour)this).StartCoroutine(GrabRoutine(target)); } private IEnumerator GrabRoutine(PlayerControllerB target) { float start = Time.time; int contactMark = EventMark(ModerAnimEvent.GrabContact); _faceTarget = target; PlayActionServer(ModerAction.Grab); float contactDeadline = start + Seconds(36) + 0.5f; while (!base.isEnemyDead && EventMark(ModerAnimEvent.GrabContact) == contactMark && Time.time < contactDeadline) { yield return null; } _faceTarget = null; if (!base.isEnemyDead) { PlayerControllerB val = ResolveGrabVictim(); if ((Object)(object)val != (Object)null) { RequestGrabServerRpc(SlotOf(val)); } } float grabEnd = start + Seconds(72); while (!base.isEnemyDead && Time.time < grabEnd) { yield return null; } if (!base.isEnemyDead && (Object)(object)HeldPlayer != (Object)null) { if (ModerMoodLogic.ChooseCrush(Random.value, Config.CrushChance.Value)) { float crushStart = Time.time; int crushMark = EventMark(ModerAnimEvent.Crush); int dropMark = EventMark(ModerAnimEvent.Drop); PlayActionServer(ModerAction.LiftCrush); float crushDeadline = crushStart + Seconds(210) + 0.5f; while (!base.isEnemyDead && EventMark(ModerAnimEvent.Crush) == crushMark && Time.time < crushDeadline) { yield return null; } PlayerControllerB heldPlayer = HeldPlayer; if (!base.isEnemyDead && (Object)(object)heldPlayer != (Object)null) { CrushVictimClientRpc((ulong)HeldPlayerIndex.Value, VictimRpc.TargetOwner(heldPlayer)); } float dropDeadline = crushStart + Seconds(216) + 0.5f; while (!base.isEnemyDead && EventMark(ModerAnimEvent.Drop) == dropMark && Time.time < dropDeadline) { yield return null; } if (!base.isEnemyDead) { HeldPlayerIndex.Value = -1; } float crushEnd = crushStart + Seconds(270); while (!base.isEnemyDead && Time.time < crushEnd) { yield return null; } } else { float crushEnd = Time.time; int dropMark = EventMark(ModerAnimEvent.ThrowRelease); PlayActionServer(ModerAction.Throw); float dropDeadline = crushEnd + Seconds(60) + 0.5f; while (!base.isEnemyDead && EventMark(ModerAnimEvent.ThrowRelease) == dropMark && Time.time < dropDeadline) { yield return null; } PlayerControllerB heldPlayer2 = HeldPlayer; if (!base.isEnemyDead && (Object)(object)heldPlayer2 != (Object)null) { int value = HeldPlayerIndex.Value; _thrown = new ModerPlayer(value, heldPlayer2.actualClientId); Vector3 launch = ThrowLaunch(); HeldPlayerIndex.Value = -1; ThrowVictimClientRpc((ulong)value, launch, VictimRpc.TargetOwner(heldPlayer2)); } else if (!base.isEnemyDead) { HeldPlayerIndex.Value = -1; } _threw = true; float crushDeadline = crushEnd + Seconds(96); while (!base.isEnemyDead && Time.time < crushDeadline) { yield return null; } } } _throwRoll = Random.value; _actionDone = true; _actionRoutine = null; } private PlayerControllerB ResolveGrabVictim() { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0039: Unknown result type (might be due to invalid IL or missing references) Vector3 grabHandPosition = GrabHandPosition; float num = Config.GrabReach.Value; PlayerControllerB result = null; PlayerControllerB[] allPlayerScripts = StartOfRound.Instance.allPlayerScripts; foreach (PlayerControllerB val in allPlayerScripts) { if (IsGrabbable(val)) { float num2 = DistanceToBody(grabHandPosition, val); if (!(num2 > num) && HasLineOfSight(val)) { result = val; num = num2; } } } return result; } private static float DistanceToBody(Vector3 point, PlayerControllerB player) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_0038: Unknown result type (might be due to invalid IL or missing references) Vector3 position = ((Component)player).transform.position; float num = Mathf.Clamp(point.y, position.y, position.y + 1.8f); return Vector3.Distance(point, new Vector3(position.x, num, position.z)); } private Vector3 ThrowLaunch() { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_0034: Unknown result type (might be due to invalid IL or missing references) //IL_004c: Unknown result type (might be due to invalid IL or missing references) //IL_0043: Unknown result type (might be due to invalid IL or missing references) //IL_0051: Unknown result type (might be due to invalid IL or missing references) //IL_0080: 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_006e: Unknown result type (might be due to invalid IL or missing references) //IL_0073: Unknown result type (might be due to invalid IL or missing references) //IL_00a1: Unknown result type (might be due to invalid IL or missing references) //IL_00aa: Unknown result type (might be due to invalid IL or missing references) //IL_00af: Unknown result type (might be due to invalid IL or missing references) //IL_00bc: Unknown result type (might be due to invalid IL or missing references) //IL_00c1: Unknown result type (might be due to invalid IL or missing references) Vector3 val = ((Component)this).transform.forward; val.y = 0f; val = ((((Vector3)(ref val)).sqrMagnitude > 0.0001f) ? ((Vector3)(ref val)).normalized : Vector3.forward); Vector3 val2 = (((Object)(object)torsoHandR != (Object)null) ? torsoHandR.forward : val); val2.y = 0f; if (((Vector3)(ref val2)).sqrMagnitude < 0.0001f || Vector3.Dot(((Vector3)(ref val2)).normalized, val) < 0f) { val2 = val; } else { ((Vector3)(ref val2)).Normalize(); } float value = Config.ThrowSpeed.Value; float num = 0.61086524f; return val2 * (value * Mathf.Cos(num)) + Vector3.up * (value * Mathf.Sin(num)); } private bool IsGrabbable(PlayerControllerB player) { if (IsTargetable(player)) { return !player.isClimbingLadder; } return false; } private bool CanServerGrab(PlayerControllerB player) { //IL_0035: Unknown result type (might be due to invalid IL or missing references) if (!((NetworkBehaviour)this).IsServer || base.isEnemyDead || State != ModerState.Grab || HeldPlayerIndex.Value >= 0) { return false; } if (!IsGrabbable(player)) { return false; } if (DistanceToBody(GrabHandPosition, player) <= Config.GrabReach.Value + 0.65f) { return HasLineOfSight(player); } return false; } [ServerRpc(RequireOwnership = false)] private void RequestGrabServerRpc(int playerIndex, ServerRpcParams rpcParams = default(ServerRpcParams)) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Invalid comparison between Unknown and I4 //IL_0099: Unknown result type (might be due to invalid IL or missing references) //IL_00a3: Invalid comparison between Unknown and I4 //IL_005f: Unknown result type (might be due to invalid IL or missing references) //IL_0068: Unknown result type (might be due to invalid IL or missing references) //IL_006d: Unknown result type (might be due to invalid IL or missing references) //IL_0071: Unknown result type (might be due to invalid IL or missing references) //IL_0089: Unknown result type (might be due to invalid IL or missing references) //IL_00ce: Unknown result type (might be due to invalid IL or missing references) //IL_00db: Unknown result type (might be due to invalid IL or missing references) //IL_00dc: Unknown result type (might be due to invalid IL or missing references) NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager; if (networkManager == null || !networkManager.IsListening) { return; } if ((int)((NetworkBehaviour)this).__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost)) { FastBufferWriter val = ((NetworkBehaviour)this).__beginSendServerRpc(588868421u, rpcParams, (RpcDelivery)0); BytePacker.WriteValueBitPacked(val, playerIndex); ((NetworkBehaviour)this).__endSendServerRpc(ref val, 588868421u, rpcParams, (RpcDelivery)0); } if ((int)((NetworkBehaviour)this).__rpc_exec_stage != 1 || (!networkManager.IsServer && !networkManager.IsHost)) { return; } ((NetworkBehaviour)this).__rpc_exec_stage = (__RpcExecStage)0; if (!((NetworkBehaviour)this).IsServer || rpcParams.Receive.SenderClientId != 0L) { return; } PlayerControllerB player = VictimRpc.FromSlot(playerIndex); if (!CanServerGrab(player)) { return; } HeldPlayerIndex.Value = playerIndex; if (Verbose) { ManualLogSource log = Plugin.Log; if (log != null) { log.LogInfo((object)("[ModerAI] Grabbed " + PlayerName(player) + ".")); } } } internal void RequestReleaseHeld(PlayerControllerB player) { //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Unknown result type (might be due to invalid IL or missing references) int num = SlotOf(player); if (num >= 0 && ((NetworkBehaviour)this).IsSpawned && !base.isEnemyDead) { ReleaseHeldServerRpc(num); } } [ServerRpc(RequireOwnership = false)] private void ReleaseHeldServerRpc(int playerIndex, ServerRpcParams rpcParams = default(ServerRpcParams)) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Invalid comparison between Unknown and I4 //IL_0099: Unknown result type (might be due to invalid IL or missing references) //IL_00a3: Invalid comparison between Unknown and I4 //IL_005f: Unknown result type (might be due to invalid IL or missing references) //IL_0068: Unknown result type (might be due to invalid IL or missing references) //IL_006d: Unknown result type (might be due to invalid IL or missing references) //IL_0071: Unknown result type (might be due to invalid IL or missing references) //IL_0089: Unknown result type (might be due to invalid IL or missing references) //IL_00ce: Unknown result type (might be due to invalid IL or missing references) //IL_00fd: Unknown result type (might be due to invalid IL or missing references) //IL_00fe: Unknown result type (might be due to invalid IL or missing references) NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager; if (networkManager == null || !networkManager.IsListening) { return; } if ((int)((NetworkBehaviour)this).__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost)) { FastBufferWriter val = ((NetworkBehaviour)this).__beginSendServerRpc(3645515045u, rpcParams, (RpcDelivery)0); BytePacker.WriteValueBitPacked(val, playerIndex); ((NetworkBehaviour)this).__endSendServerRpc(ref val, 3645515045u, rpcParams, (RpcDelivery)0); } if ((int)((NetworkBehaviour)this).__rpc_exec_stage != 1 || (!networkManager.IsServer && !networkManager.IsHost)) { return; } ((NetworkBehaviour)this).__rpc_exec_stage = (__RpcExecStage)0; if (!((NetworkBehaviour)this).IsServer || base.isEnemyDead || playerIndex < 0 || HeldPlayerIndex.Value != playerIndex) { return; } PlayerControllerB player = VictimRpc.FromSlot(playerIndex); if (!VictimRpc.SenderOwnsSlot(rpcParams.Receive.SenderClientId, player)) { return; } HeldPlayerIndex.Value = -1; if (Verbose) { ManualLogSource log = Plugin.Log; if (log != null) { log.LogInfo((object)("[ModerAI] " + PlayerName(player) + " was teleported out of the hand.")); } } if (State == ModerState.Grab) { StopActionRoutine(); CancelActionClientRpc(); _senseTarget = FollowUpTarget(); EnterState(ModerMoodLogic.ReleasedGrabOutcome((ModerMood)Mood.Value)); } } [ClientRpc] private void CrushVictimClientRpc(ulong playerSlot, ClientRpcParams clientRpcParams = default(ClientRpcParams)) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Invalid comparison between Unknown and I4 //IL_0099: Unknown result type (might be due to invalid IL or missing references) //IL_00a3: Invalid comparison between Unknown and I4 //IL_005f: Unknown result type (might be due to invalid IL or missing references) //IL_0068: Unknown result type (might be due to invalid IL or missing references) //IL_006d: Unknown result type (might be due to invalid IL or missing references) //IL_0071: Unknown result type (might be due to invalid IL or missing references) //IL_0089: Unknown result type (might be due to invalid IL or missing references) //IL_00ce: Unknown result type (might be due to invalid IL or missing references) //IL_00fa: Unknown result type (might be due to invalid IL or missing references) //IL_0104: Unknown result type (might be due to invalid IL or missing references) //IL_010a: Unknown result type (might be due to invalid IL or missing references) NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager; if (networkManager == null || !networkManager.IsListening) { return; } if ((int)((NetworkBehaviour)this).__rpc_exec_stage != 1 && (networkManager.IsServer || networkManager.IsHost)) { FastBufferWriter val = ((NetworkBehaviour)this).__beginSendClientRpc(4149200445u, clientRpcParams, (RpcDelivery)0); BytePacker.WriteValueBitPacked(val, playerSlot); ((NetworkBehaviour)this).__endSendClientRpc(ref val, 4149200445u, clientRpcParams, (RpcDelivery)0); } if ((int)((NetworkBehaviour)this).__rpc_exec_stage == 1 && (networkManager.IsClient || networkManager.IsHost)) { ((NetworkBehaviour)this).__rpc_exec_stage = (__RpcExecStage)0; PlayerControllerB val2 = VictimRpc.LocalVictimFromSlot(playerSlot); if (!((Object)(object)val2 == (Object)null) && !val2.isPlayerDead) { ModerBloodFxBridge.RequestGib(val2, "ModerCrush", 3); val2.KillPlayer(Vector3.zero, true, (CauseOfDeath)8, 0, default(Vector3), false); } } } [ClientRpc] private void ThrowVictimClientRpc(ulong playerSlot, Vector3 launch, ClientRpcParams clientRpcParams = default(ClientRpcParams)) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Invalid comparison between Unknown and I4 //IL_00a6: Unknown result type (might be due to invalid IL or missing references) //IL_00b0: Invalid comparison between Unknown and I4 //IL_005f: Unknown result type (might be due to invalid IL or missing references) //IL_0068: Unknown result type (might be due to invalid IL or missing references) //IL_006d: Unknown result type (might be due to invalid IL or missing references) //IL_0071: Unknown result type (might be due to invalid IL or missing references) //IL_0096: Unknown result type (might be due to invalid IL or missing references) //IL_00db: Unknown result type (might be due to invalid IL or missing references) //IL_0101: Unknown result type (might be due to invalid IL or missing references) //IL_0102: Unknown result type (might be due to invalid IL or missing references) NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager; if (networkManager == null || !networkManager.IsListening) { return; } if ((int)((NetworkBehaviour)this).__rpc_exec_stage != 1 && (networkManager.IsServer || networkManager.IsHost)) { FastBufferWriter val = ((NetworkBehaviour)this).__beginSendClientRpc(375480040u, clientRpcParams, (RpcDelivery)0); BytePacker.WriteValueBitPacked(val, playerSlot); ((FastBufferWriter)(ref val)).WriteValueSafe(ref launch); ((NetworkBehaviour)this).__endSendClientRpc(ref val, 375480040u, clientRpcParams, (RpcDelivery)0); } if ((int)((NetworkBehaviour)this).__rpc_exec_stage == 1 && (networkManager.IsClient || networkManager.IsHost)) { ((NetworkBehaviour)this).__rpc_exec_stage = (__RpcExecStage)0; PlayerControllerB val2 = VictimRpc.LocalVictimFromSlot(playerSlot); if (!((Object)(object)val2 == (Object)null) && !val2.isPlayerDead) { ModerVictimLock.Release(val2, this); val2.externalForceAutoFade = launch; } } } private void ValidateHeldPlayer() { int value = HeldPlayerIndex.Value; if (value >= 0) { PlayerControllerB val = VictimRpc.FromSlot(value); if ((Object)(object)val == (Object)null || !val.isPlayerControlled || val.isPlayerDead || State != ModerState.Grab) { HeldPlayerIndex.Value = -1; } } } private void OnHeldPlayerIndexChanged(int previous, int next) { ApplyHeldPlayerIndexLocal(previous, next); } private void ApplyHeldPlayerIndexLocal(int previous, int next) { if (previous >= 0 && previous != next) { ReleaseHeldLocal(previous); } _victimOnHand = false; if (next >= 0 && !base.isEnemyDead) { PlayerControllerB val = VictimRpc.FromSlot(next); if ((Object)(object)val != (Object)null) { ModerVictimLock.Hold(val, this); } } } private void ReleaseHeldLocal(int playerIndex) { if (playerIndex >= 0) { PlayerControllerB val = VictimRpc.FromSlot(playerIndex); if ((Object)(object)val != (Object)null) { ModerVictimLock.Release(val, this); } } } internal void OnAntlerTouch(PlayerControllerB player, int side) { //IL_0063: Unknown result type (might be due to invalid IL or missing references) //IL_0069: Unknown result type (might be due to invalid IL or missing references) if (!base.isEnemyDead && State == ModerState.Charge && !((Object)(object)player == (Object)null) && !player.isPlayerDead && player.isPlayerControlled && VictimRpc.IsVictimLocal(player) && !(Time.time < _pinRequestBlockedUntil)) { int num = SlotOf(player); if (num >= 0) { _pinRequestBlockedUntil = Time.time + 0.5f; RequestAntlerPinServerRpc(num, side); } } } [ServerRpc(RequireOwnership = false)] private void RequestAntlerPinServerRpc(int playerIndex, int side, ServerRpcParams rpcParams = default(ServerRpcParams)) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Invalid comparison between Unknown and I4 //IL_00a6: Unknown result type (might be due to invalid IL or missing references) //IL_00b0: Invalid comparison between Unknown and I4 //IL_005f: Unknown result type (might be due to invalid IL or missing references) //IL_0068: Unknown result type (might be due to invalid IL or missing references) //IL_006d: Unknown result type (might be due to invalid IL or missing references) //IL_0071: Unknown result type (might be due to invalid IL or missing references) //IL_007e: Unknown result type (might be due to invalid IL or missing references) //IL_0096: Unknown result type (might be due to invalid IL or missing references) //IL_00db: Unknown result type (might be due to invalid IL or missing references) //IL_00ea: Unknown result type (might be due to invalid IL or missing references) //IL_00eb: Unknown result type (might be due to invalid IL or missing references) //IL_0113: Unknown result type (might be due to invalid IL or missing references) NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager; if (networkManager == null || !networkManager.IsListening) { return; } if ((int)((NetworkBehaviour)this).__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost)) { FastBufferWriter val = ((NetworkBehaviour)this).__beginSendServerRpc(756574841u, rpcParams, (RpcDelivery)0); BytePacker.WriteValueBitPacked(val, playerIndex); BytePacker.WriteValueBitPacked(val, side); ((NetworkBehaviour)this).__endSendServerRpc(ref val, 756574841u, rpcParams, (RpcDelivery)0); } if ((int)((NetworkBehaviour)this).__rpc_exec_stage != 1 || (!networkManager.IsServer && !networkManager.IsHost)) { return; } ((NetworkBehaviour)this).__rpc_exec_stage = (__RpcExecStage)0; PlayerControllerB val2 = VictimRpc.FromSlot(playerIndex); if (!CanServerPin(val2, playerIndex, rpcParams.Receive.SenderClientId)) { return; } int num = ModerMoodLogic.ChoosePinSide(PinnedBodiesMask.Value, side); KillPinnedVictimClientRpc((ulong)playerIndex, VictimRpc.TargetOwner(val2)); if (num >= 0) { SetPinnedPlayer(num, playerIndex); PinnedBodiesMask.Value = ModerMoodLogic.WithPin(PinnedBodiesMask.Value, num); } if (!_chargeHit) { _chargeHit = true; _chargeHitTime = Time.time; Halt(); PlayActionServer(ModerAction.AntlerHit); } if (Verbose) { ManualLogSource log = Plugin.Log; if (log != null) { log.LogInfo((object)$"[ModerAI] Antler hit {PlayerName(val2)} (touched side {side}, pinned side {num})."); } } } private bool CanServerPin(PlayerControllerB player, int playerIndex, ulong senderClientId) { //IL_0049: Unknown result type (might be due to invalid IL or missing references) //IL_0054: Unknown result type (might be due to invalid IL or missing references) if (!((NetworkBehaviour)this).IsServer || base.isEnemyDead || State != ModerState.Charge || (Object)(object)player == (Object)null) { return false; } if (!VictimRpc.SenderOwnsSlot(senderClientId, player) || !IsTargetable(player)) { return false; } if (IsPinnedSlot(playerIndex)) { return false; } return Vector3.Distance(((Component)player).transform.position, ((Component)this).transform.position) <= 8f; } [ClientRpc] private void KillPinnedVictimClientRpc(ulong playerSlot, ClientRpcParams clientRpcParams = default(ClientRpcParams)) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Invalid comparison between Unknown and I4 //IL_0099: Unknown result type (might be due to invalid IL or missing references) //IL_00a3: Invalid comparison between Unknown and I4 //IL_005f: Unknown result type (might be due to invalid IL or missing references) //IL_0068: Unknown result type (might be due to invalid IL or missing references) //IL_006d: Unknown result type (might be due to invalid IL or missing references) //IL_0071: Unknown result type (might be due to invalid IL or missing references) //IL_0089: Unknown result type (might be due to invalid IL or missing references) //IL_00ce: Unknown result type (might be due to invalid IL or missing references) //IL_00ed: Unknown result type (might be due to invalid IL or missing references) //IL_00f8: Unknown result type (might be due to invalid IL or missing references) //IL_00fe: Unknown result type (might be due to invalid IL or missing references) NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager; if (networkManager == null || !networkManager.IsListening) { return; } if ((int)((NetworkBehaviour)this).__rpc_exec_stage != 1 && (networkManager.IsServer || networkManager.IsHost)) { FastBufferWriter val = ((NetworkBehaviour)this).__beginSendClientRpc(3080373461u, clientRpcParams, (RpcDelivery)0); BytePacker.WriteValueBitPacked(val, playerSlot); ((NetworkBehaviour)this).__endSendClientRpc(ref val, 3080373461u, clientRpcParams, (RpcDelivery)0); } if ((int)((NetworkBehaviour)this).__rpc_exec_stage == 1 && (networkManager.IsClient || networkManager.IsHost)) { ((NetworkBehaviour)this).__rpc_exec_stage = (__RpcExecStage)0; PlayerControllerB val2 = VictimRpc.LocalVictimFromSlot(playerSlot); if (!((Object)(object)val2 == (Object)null) && !val2.isPlayerDead) { val2.KillPlayer(Vector3.zero, true, (CauseOfDeath)14, 0, default(Vector3), false); } } } private int PinnedPlayer(int side) { if (side != 0) { return _pinnedPlayerRight.Value; } return _pinnedPlayerLeft.Value; } private void SetPinnedPlayer(int side, int playerIndex) { if (side == 0) { _pinnedPlayerLeft.Value = playerIndex; } else { _pinnedPlayerRight.Value = playerIndex; } } private Transform PinSocket(int side) { if (side != 0) { return antlerSocketR; } return antlerSocketL; } private bool IsPinnedSlot(int playerIndex) { int value = PinnedBodiesMask.Value; for (int i = 0; i <= 1; i++) { if (ModerMoodLogic.IsPinned(value, i) && PinnedPlayer(i) == playerIndex) { return true; } } return false; } private void ServerClearPin(int side) { if (((NetworkBehaviour)this).IsServer) { PinnedBodiesMask.Value = ModerMoodLogic.WithoutPin(PinnedBodiesMask.Value, side); SetPinnedPlayer(side, -1); } } private void ReconcilePins() { int value = PinnedBodiesMask.Value; for (int i = 0; i <= 1; i++) { int num = (ModerMoodLogic.IsPinned(value, i) ? PinnedPlayer(i) : (-1)); if (num != _pinSlot[i]) { DetachPin(i); _pinSlot[i] = num; _pinClosed[i] = num < 0; _pinDeadline[i] = Time.time + 2f; } if (num < 0) { continue; } if (_pinAttached[i]) { DeadBodyInfo val = _pinBody[i]; if (!((Object)(object)val != (Object)null) || val.deactivated || val.attachedTo != _pinSocket[i]) { _pinAttached[i] = false; _pinBody[i] = null; _pinSocket[i] = null; _pinClosed[i] = true; ServerClearPin(i); } } else if (!_pinClosed[i]) { PlayerControllerB val2 = VictimRpc.FromSlot(num); Transform val3 = PinSocket(i); if ((Object)(object)val3 != (Object)null && IsAttachable(val2)) { AttachPin(i, val2.deadBody, val3); } else if (Time.time >= _pinDeadline[i]) { _pinClosed[i] = true; ServerClearPin(i); } } } } private static bool IsAttachable(PlayerControllerB player) { if ((Object)(object)player == (Object)null || !player.isPlayerDead) { return false; } DeadBodyInfo deadBody = player.deadBody; if ((Object)(object)deadBody != (Object)null && !deadBody.deactivated && ((Component)deadBody).gameObject.activeSelf && (Object)(object)deadBody.attachedTo == (Object)null && deadBody.bodyParts != null && deadBody.bodyParts.Length > 5) { return (Object)(object)deadBody.bodyParts[5] != (Object)null; } return false; } private void AttachPin(int side, DeadBodyInfo body, Transform socket) { body.attachedLimb = body.bodyParts[5]; body.attachedTo = socket; body.matchPositionExactly = true; body.canBeGrabbedBackByPlayers = false; _pinBody[side] = body; _pinSocket[side] = socket; _pinAttached[side] = true; } private void DetachPin(int side) { DeadBodyInfo val = _pinBody[side]; if (_pinAttached[side] && (Object)(object)val != (Object)null && val.attachedTo == _pinSocket[side]) { val.attachedTo = null; val.attach
Y4NGZPoltergeist.dll
Decompiled a day ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security.Cryptography; using System.Text; using System.Text.RegularExpressions; using System.Threading; using BepInEx; using BepInEx.Configuration; using BepInEx.Logging; using Dawn; using GameNetcodeStuff; using HarmonyLib; using Microsoft.CodeAnalysis; using Unity.Netcode; using Unity.Netcode.Components; using UnityEngine; using UnityEngine.AI; using UnityEngine.Animations; using UnityEngine.Audio; using UnityEngine.Events; using UnityEngine.Networking; using UnityEngine.Playables; using UnityEngine.Rendering; using UnityEngine.Rendering.HighDefinition; using UnityEngine.SceneManagement; using Y4NGZMonsters.Shared; using Y4NGZPoltergeist.AI; using Y4NGZPoltergeist.AI.Voice; using Y4NGZPoltergeist.NetcodePatcher; using Y4NGZPoltergeist.Patches; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: AssemblyCompany("Y4NGZPoltergeist")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0+3460ec64f0cec4948e51ddb3f02a4b0e414f105e")] [assembly: AssemblyProduct("Y4NGZPoltergeist")] [assembly: AssemblyTitle("Y4NGZPoltergeist")] [assembly: AssemblyVersion("1.0.0.0")] [module: RefSafetyRules(11)] [module: NetcodePatchedAssembly] 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 Y4NGZPoltergeist { internal static class PassengerContract { internal const string DisplayName = "Passenger"; internal const int ScanNodeMaxRange = 18; internal const int ScanNodeMinRange = 1; internal const float DefaultPowerLevel = 2.5f; internal const int DefaultMaxCount = 1; internal const int DefaultHealth = 5; internal static void RepairScanNode(bool created, ref string header, ref string subtitle, ref int maxRange, ref int minRange) { header = "Passenger"; subtitle = string.Empty; if (created || maxRange <= 0) { maxRange = 18; minRange = 1; } } } internal static class PassengerLooseCues { private static readonly AudioClip[][] Pools = CreateEmptyPools(); private static readonly bool[] BundleCovered = new bool[15]; private static readonly PassengerCueWarnOnce WarnOnce = new PassengerCueWarnOnce(); internal static AudioClip[] Pool(PassengerCue cue) { return Pools[(uint)cue]; } internal static void RecordBundleCoverage(PassengerCue cue, bool covered) { BundleCovered[(uint)cue] = covered; } internal static IEnumerator Load(string audioDir) { yield return null; string[] fileNames = ListFileNames(audioDir); int[] found = new int[15]; PassengerCueTable.CountTakes(fileNames, found); AudioClip[][] takes = new AudioClip[15][]; for (int i = 0; i < fileNames.Length; i++) { if (!PassengerCueTable.TryParseTakeFile(fileNames[i], out var cue, out var take)) { continue; } AudioClip[] slots = takes[(uint)cue] ?? (takes[(uint)cue] = (AudioClip[])(object)new AudioClip[32]); if (!((Object)(object)slots[take - 1] != (Object)null)) { AudioClip loaded = null; yield return Plugin.LoadLooseClip(Path.Combine(audioDir, fileNames[i]), delegate(AudioClip clip) { loaded = clip; }); slots[take - 1] = loaded; } } StringBuilder stringBuilder = new StringBuilder("[PoltergeistAudio] Loose cue pools:"); for (int num = 0; num < 15; num++) { PassengerCue cue2 = (PassengerCue)num; AudioClip[] array = InTakeOrder(takes[num]); Pools[num] = array; stringBuilder.Append((num == 0) ? " " : ", ").Append(cue2.ToString()).Append(' ') .Append(array.Length); if (array.Length != found[num]) { stringBuilder.Append('/').Append(found[num]); } if (BundleCovered[num]) { stringBuilder.Append(" (bundle)"); } if (PassengerCueTable.NeedsMissingWarning(array.Length, BundleCovered[num]) && WarnOnce.ShouldWarn(cue2)) { Plugin.Log.LogWarning((object)("[PoltergeistAudio] " + PassengerCueTable.MissingWarning(cue2))); } } Plugin.Log.LogInfo((object)stringBuilder.Append('.').ToString()); } private static string[] ListFileNames(string audioDir) { if (string.IsNullOrEmpty(audioDir) || !Directory.Exists(audioDir)) { return Array.Empty<string>(); } try { string[] files = Directory.GetFiles(audioDir); List<string> list = new List<string>(files.Length); for (int i = 0; i < files.Length; i++) { string fileName = Path.GetFileName(files[i]); if (PassengerCueTable.AcceptedExtensionLength(fileName) > 0) { list.Add(fileName); } } return list.ToArray(); } catch (Exception ex) when (ex is IOException || ex is UnauthorizedAccessException) { Plugin.Log.LogWarning((object)("[PoltergeistAudio] Could not list " + audioDir + ": " + ex.Message)); return Array.Empty<string>(); } } private static AudioClip[] InTakeOrder(AudioClip[] slots) { int num = 0; if (slots != null) { for (int i = 0; i < slots.Length; i++) { if ((Object)(object)slots[i] != (Object)null) { num++; } } } if (num == 0) { return Array.Empty<AudioClip>(); } AudioClip[] array = (AudioClip[])(object)new AudioClip[num]; num = 0; for (int j = 0; j < slots.Length; j++) { if ((Object)(object)slots[j] != (Object)null) { array[num++] = slots[j]; } } return array; } private static AudioClip[][] CreateEmptyPools() { AudioClip[][] array = new AudioClip[15][]; for (int i = 0; i < array.Length; i++) { array[i] = Array.Empty<AudioClip>(); } return array; } } [BepInPlugin("y4ngz.lethalcompany.poltergeist", "Y4NGZ Poltergeist", "2.0.0")] [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInDependency(/*Could not decode attribute arguments.*/)] public sealed class Plugin : BaseUnityPlugin { internal const string BundleFilename = "y4ngzpoltergeist.bundle"; internal const string PrefabName = "Poltergeist"; internal const string AlternatePrefabName = "thc3"; internal const string DawnNamespace = "y4ngz_monsters"; internal const string DawnEnemyKey = "passenger"; internal const string BestiaryText = "Passenger\n\nDanger level: high\n\nAn intangible facility resident that ignores walls entirely, drifting through them to reach a worker it has chosen. It does not claw. What it wants is worse: a wounded or unaware worker can be worn like a coat, and will turn on their own crew for as long as the thing keeps its grip. It does not enjoy being shot at, and leaves when it is.\n\n"; internal static ManualLogSource Log; private static bool _loggedScanNodeLayer; internal static PoltergeistConfig ModConfig; internal static AssetBundle ModAssets; internal static EnemyType PoltergeistEnemyType; internal static Material PhaseMaterial; internal static Material TransitBodyMaterial; internal static Material WallDisturbanceMaterial; internal static Material PhaseDissolveMaterial; internal static AudioClip PossessedLoopClip; internal const string LooseAudioFolderName = "Poltergeist"; private static AudioMixerGroup _diegeticMaster; private static bool _netcodeInitialized; private void Awake() { //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_004f: Expected O, but got Unknown Log = ((BaseUnityPlugin)this).Logger; try { InitializeNetcodeRPCs(); ModConfig = new PoltergeistConfig(((BaseUnityPlugin)this).Config); Harmony val = new Harmony("y4ngz.lethalcompany.poltergeist"); val.PatchAll(typeof(Plugin).Assembly); PossessedVoiceSender.ResetSession(); DissonanceEncoderPatch.TryInstall(val); if (!LoadBundle()) { return; } PassengerVictimClipLayer.ResolveFromBundle(ModAssets); PoltergeistAI.PossessionImpact += PassengerPossessionScene.OnPossessionImpact; LoadPresentationMaterials(); ((MonoBehaviour)this).StartCoroutine(LoadLoosePossessionAudio()); GameObject val2 = LoadBundlePrefab(); if ((Object)(object)val2 == (Object)null) { Log.LogError((object)"Prefab 'Poltergeist' not found in y4ngzpoltergeist.bundle."); DumpBundleAssets(); return; } PreparePrefab(val2); PoltergeistEnemyType = CreateEnemyType(val2); PoltergeistAI component = val2.GetComponent<PoltergeistAI>(); if ((Object)(object)component != (Object)null) { ((EnemyAI)component).enemyType = PoltergeistEnemyType; } PoltergeistSpawnWeights spawnWeights = new PoltergeistSpawnWeights(() => (!ModConfig.Enabled.Value) ? 0f : ModConfig.SpawnWeightMultiplier.Value, () => ModConfig.MoonWeightOverrides.Value, delegate(string message) { Log.LogWarning((object)message); }); DawnLib.RegisterNetworkPrefab(val2); DawnLib.DefineEnemy(NamespacedKey<DawnEnemyInfo>.From("y4ngz_monsters", "passenger"), PoltergeistEnemyType, (Action<EnemyInfoBuilder>)delegate(EnemyInfoBuilder builder) { ((BaseInfoBuilder<DawnEnemyInfo, EnemyType, EnemyInfoBuilder>)(object)builder.DefineInside((Action<EnemyLocationBuilder>)delegate(EnemyLocationBuilder location) { location.SetWeights((Action<WeightTableBuilder<DawnMoonInfo, SpawnWeightContext>>)delegate(WeightTableBuilder<DawnMoonInfo, SpawnWeightContext> table) { table.SetGlobalWeight((IWeighted)(object)spawnWeights); }); }).CreateBestiaryNode("Passenger\n\nDanger level: high\n\nAn intangible facility resident that ignores walls entirely, drifting through them to reach a worker it has chosen. It does not claw. What it wants is worse: a wounded or unaware worker can be worn like a coat, and will turn on their own crew for as long as the thing keeps its grip. It does not enjoy being shot at, and leaves when it is.\n\n").CreateNameKeyword("passenger")).AddTags((IEnumerable<NamespacedKey>)(object)new NamespacedKey[5] { Tags.Hostile, Tags.Organic, Tags.Biped, Tags.Killable, Tags.Medium }); }); if (!ModConfig.Enabled.Value) { Log.LogInfo((object)"Y4NGZ Poltergeist: registered network prefab; spawning disabled by config."); } Log.LogInfo((object)"Y4NGZ Poltergeist v2.0.0 loaded. Registered as 'Passenger'."); } catch (Exception arg) { Log.LogError((object)string.Format("[{0}] Initialization failed: {1}", "Y4NGZ Poltergeist", arg)); } } private static void InitializeNetcodeRPCs() { if (_netcodeInitialized) { return; } _netcodeInitialized = true; Type[] types = Assembly.GetExecutingAssembly().GetTypes(); foreach (Type type in types) { MethodInfo[] methods; try { methods = type.GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); } catch { continue; } foreach (MethodInfo methodInfo in methods) { if (methodInfo.GetCustomAttributes(typeof(RuntimeInitializeOnLoadMethodAttribute), inherit: false).Length == 0) { continue; } try { methodInfo.Invoke(null, null); } catch (Exception ex) { ManualLogSource log = Log; if (log != null) { log.LogWarning((object)("[NetcodeInit] " + type.Name + "." + methodInfo.Name + " failed: " + ex.Message)); } } } } } private static bool LoadBundle() { string directoryName = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); if (string.IsNullOrEmpty(directoryName)) { Log.LogError((object)"Could not resolve plugin assembly directory."); return false; } string text = Path.Combine(directoryName, "y4ngzpoltergeist.bundle"); if (!File.Exists(text)) { Log.LogError((object)("Missing asset bundle: " + text)); return false; } ModAssets = AssetBundle.LoadFromFile(text); if ((Object)(object)ModAssets == (Object)null) { Log.LogError((object)("AssetBundle.LoadFromFile returned null for " + text + ".")); return false; } return true; } private IEnumerator LoadLoosePossessionAudio() { string directoryName = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); string audioDir = Path.Combine(directoryName ?? string.Empty, "assets", "Poltergeist"); if (Directory.Exists(audioDir)) { yield return LoadLooseClip(Path.Combine(audioDir, "plt_possession_loop_01.ogg"), delegate(AudioClip clip) { PossessedLoopClip = clip; }); Log.LogInfo((object)$"[PoltergeistAudio] Local possession loop loaded: {(Object)(object)PossessedLoopClip != (Object)null}."); } else { Log.LogWarning((object)("[PoltergeistAudio] Loose audio folder not found: " + audioDir + ". The local possession loop will be silent and the loose Passenger cues have no takes.")); } yield return PassengerLooseCues.Load(audioDir); RefreshDeathFallback(); } internal static IEnumerator LoadLooseClip(string path, Action<AudioClip> onLoaded) { if (!File.Exists(path)) { Log.LogWarning((object)("[PoltergeistAudio] Audio file not found: " + path)); yield break; } string text = "file:///" + path.Replace('\\', '/'); string extension = Path.GetExtension(path); AudioType val; if (string.Equals(extension, ".ogg", StringComparison.OrdinalIgnoreCase)) { val = (AudioType)14; } else if (string.Equals(extension, ".wav", StringComparison.OrdinalIgnoreCase)) { val = (AudioType)20; } else { if (!string.Equals(extension, ".mp3", StringComparison.OrdinalIgnoreCase)) { Log.LogWarning((object)("[PoltergeistAudio] Unsupported audio extension '" + extension + "', not loaded: " + path)); yield break; } val = (AudioType)13; } UnityWebRequest request = UnityWebRequestMultimedia.GetAudioClip(text, val); try { yield return request.SendWebRequest(); if ((int)request.result != 1) { Log.LogWarning((object)("[PoltergeistAudio] Failed to load " + path + ": " + request.error)); yield break; } AudioClip content = DownloadHandlerAudioClip.GetContent(request); if ((Object)(object)content == (Object)null) { yield break; } ((Object)content).name = Path.GetFileNameWithoutExtension(path); onLoaded(content); } finally { ((IDisposable)request)?.Dispose(); } } private static GameObject LoadBundlePrefab() { GameObject val = ModAssets.LoadAsset<GameObject>("Poltergeist") ?? ModAssets.LoadAsset<GameObject>("thc3"); if ((Object)(object)val != (Object)null) { return val; } string[] allAssetNames = ModAssets.GetAllAssetNames(); foreach (string text in allAssetNames) { string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(text.Replace('\\', '/')); if (string.Equals(fileNameWithoutExtension, "Poltergeist", StringComparison.OrdinalIgnoreCase) || string.Equals(fileNameWithoutExtension, "thc3", StringComparison.OrdinalIgnoreCase)) { val = ModAssets.LoadAsset<GameObject>(text); if ((Object)(object)val != (Object)null) { return val; } } } return null; } private static void LoadPresentationMaterials() { PhaseMaterial = LoadBundleMaterial("Poltergeist_Phase"); TransitBodyMaterial = LoadBundleMaterial("PassengerTransitBody"); WallDisturbanceMaterial = LoadBundleMaterial("PassengerWallDisturbance"); PhaseDissolveMaterial = LoadBundleMaterial("Poltergeist_PhaseDissolve"); if ((Object)(object)PhaseMaterial == (Object)null) { ManualLogSource log = Log; if (log != null) { log.LogError((object)"[PoltergeistMaterial] Poltergeist_Phase is missing from the bundle: phasing and the death fade lose their translucency."); } } if ((Object)(object)WallDisturbanceMaterial == (Object)null) { ManualLogSource log2 = Log; if (log2 != null) { log2.LogError((object)"[PoltergeistMaterial] PassengerWallDisturbance is missing: install the matching wall-combat-v3 bundle."); } } if ((Object)(object)PhaseDissolveMaterial == (Object)null) { ManualLogSource log3 = Log; if (log3 != null) { log3.LogInfo((object)"[Passenger] Bundle has no Poltergeist_PhaseDissolve; the vanish uses the alpha fallback."); } } } private static Material LoadBundleMaterial(string materialName) { if ((Object)(object)ModAssets == (Object)null) { return null; } Material val = ModAssets.LoadAsset<Material>(materialName); if ((Object)(object)val != (Object)null) { return val; } Material[] array = ModAssets.LoadAllAssets<Material>(); for (int i = 0; i < array.Length; i++) { if ((Object)(object)array[i] != (Object)null && string.Equals(((Object)array[i]).name, materialName, StringComparison.OrdinalIgnoreCase)) { return array[i]; } } for (int j = 0; j < array.Length; j++) { if ((Object)(object)array[j] != (Object)null && ((Object)array[j]).name.IndexOf(materialName, StringComparison.OrdinalIgnoreCase) >= 0) { return array[j]; } } return null; } internal static Color ResolvePhaseLightColor() { //IL_0029: 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_003a: Unknown result type (might be due to invalid IL or missing references) Color result = default(Color); ((Color)(ref result))..ctor(0.44f, 0.66f, 1f, 1f); string text = "#6FA8FF"; if (string.IsNullOrWhiteSpace(text)) { return result; } Color result2 = default(Color); if (!ColorUtility.TryParseHtmlString(text.Trim(), ref result2)) { return result; } return result2; } private static void PreparePrefab(GameObject prefab) { //IL_0029: 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_0150: Unknown result type (might be due to invalid IL or missing references) //IL_017a: Unknown result type (might be due to invalid IL or missing references) AssignUniqueNetworkHash(prefab); prefab.SetActive(true); TrySetTag(prefab, "Enemy"); TrySetLayer(prefab, "Enemies"); prefab.transform.localScale = Vector3.one * Mathf.Clamp(1f, 0.5f, 2.5f); PoltergeistAI poltergeistAI = prefab.GetComponent<PoltergeistAI>(); if ((Object)(object)poltergeistAI == (Object)null) { poltergeistAI = prefab.AddComponent<PoltergeistAI>(); } if ((Object)(object)prefab.GetComponent<NetworkObject>() == (Object)null) { prefab.AddComponent<NetworkObject>(); } NetworkTransform[] components = prefab.GetComponents<NetworkTransform>(); for (int i = 0; i < components.Length; i++) { Object.DestroyImmediate((Object)(object)components[i]); } Animator val = prefab.GetComponent<Animator>() ?? prefab.GetComponentInChildren<Animator>(true); if ((Object)(object)val != (Object)null) { val.applyRootMotion = false; val.cullingMode = (AnimatorCullingMode)0; ((EnemyAI)poltergeistAI).creatureAnimator = val; } else { Log.LogWarning((object)"[Poltergeist] Prefab has no Animator."); } NavMeshAgent val2 = prefab.GetComponent<NavMeshAgent>(); if ((Object)(object)val2 == (Object)null) { val2 = prefab.AddComponent<NavMeshAgent>(); } ConfigureAgent(val2); ((EnemyAI)poltergeistAI).agent = val2; ((EnemyAI)poltergeistAI).creatureSFX = FindOrCreateAudioSource(prefab.transform, "CreatureSFX", 38f); ((EnemyAI)poltergeistAI).creatureVoice = FindOrCreateAudioSource(prefab.transform, "CreatureVoice", 44f); ((EnemyAI)poltergeistAI).eye = FindOrCreateChild(prefab.transform, "EyeTransform", new Vector3(0f, 1.7f, 0.4f)); poltergeistAI.attackOrigin = FindOrCreateChild(prefab.transform, "AttackOrigin", new Vector3(0f, 1.15f, 0.85f)); AssignPoltergeistAudio(poltergeistAI); if ((Object)(object)((Component)poltergeistAI).GetComponent<PassengerCueAudio>() == (Object)null) { ((Component)poltergeistAI).gameObject.AddComponent<PassengerCueAudio>(); } EnsureRenderers(prefab, (EnemyAI)(object)poltergeistAI); RepairBrokenMaterials(prefab); EnsureBehaviourStates(poltergeistAI); EnsureScanNode(prefab); EnsureCollision(prefab, poltergeistAI); } private static void ConfigureAgent(NavMeshAgent agent) { agent.speed = ModConfig.RoamSpeed.Value; agent.angularSpeed = 380f; agent.acceleration = 16f; agent.stoppingDistance = 0.12f; agent.radius = 0.55f; agent.height = 2.1f; agent.baseOffset = 0f; agent.autoBraking = true; agent.autoRepath = true; agent.updateRotation = false; agent.areaMask = -1; agent.obstacleAvoidanceType = (ObstacleAvoidanceType)4; agent.avoidancePriority = 34; } private static void EnsureRenderers(GameObject prefab, EnemyAI ai) { //IL_0020: 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_003e: Unknown result type (might be due to invalid IL or missing references) //IL_009d: Unknown result type (might be due to invalid IL or missing references) SkinnedMeshRenderer[] componentsInChildren = prefab.GetComponentsInChildren<SkinnedMeshRenderer>(true); MeshRenderer[] componentsInChildren2 = prefab.GetComponentsInChildren<MeshRenderer>(true); ai.skinnedMeshRenderers = componentsInChildren; ai.meshRenderers = componentsInChildren2; Bounds localBounds = default(Bounds); ((Bounds)(ref localBounds))..ctor(Vector3.up * 1.1f, new Vector3(5.5f, 4.5f, 5.5f)); foreach (SkinnedMeshRenderer val in componentsInChildren) { if (!((Object)(object)val == (Object)null) && !IsRuntimeHelperRenderer((Renderer)(object)val)) { ActivateRendererHierarchy(prefab.transform, ((Component)val).transform); ((Component)val).gameObject.SetActive(true); ((Renderer)val).enabled = true; ((Renderer)val).forceRenderingOff = false; val.updateWhenOffscreen = true; ((Renderer)val).localBounds = localBounds; ((Renderer)val).shadowCastingMode = (ShadowCastingMode)1; ((Renderer)val).receiveShadows = true; } } foreach (MeshRenderer val2 in componentsInChildren2) { if (!((Object)(object)val2 == (Object)null) && !IsRuntimeHelperRenderer((Renderer)(object)val2)) { ActivateRendererHierarchy(prefab.transform, ((Component)val2).transform); ((Component)val2).gameObject.SetActive(true); ((Renderer)val2).enabled = true; ((Renderer)val2).forceRenderingOff = false; ((Renderer)val2).shadowCastingMode = (ShadowCastingMode)1; ((Renderer)val2).receiveShadows = true; } } ManualLogSource log = Log; if (log != null) { log.LogInfo((object)$"[PoltergeistRenderer] Prepared {componentsInChildren.Length} skinned renderer(s), {componentsInChildren2.Length} mesh renderer(s)."); } } private static void RepairBrokenMaterials(GameObject prefab) { Renderer[] componentsInChildren = prefab.GetComponentsInChildren<Renderer>(true); int num = 0; foreach (Renderer val in componentsInChildren) { if ((Object)(object)val == (Object)null || IsRuntimeHelperRenderer(val)) { continue; } Material[] sharedMaterials = val.sharedMaterials; if (sharedMaterials == null || sharedMaterials.Length == 0) { continue; } bool flag = false; for (int j = 0; j < sharedMaterials.Length; j++) { if (IsMaterialBroken(sharedMaterials[j])) { Material val2 = RebuildMaterial(sharedMaterials[j]); if (!((Object)(object)val2 == (Object)null)) { sharedMaterials[j] = val2; flag = true; num++; } } } if (flag) { val.sharedMaterials = sharedMaterials; } } if (num > 0) { ManualLogSource log = Log; if (log != null) { log.LogWarning((object)$"[PoltergeistMaterial] Rebuilt {num} material(s) that lost their shader during bundling."); } } else { ManualLogSource log2 = Log; if (log2 != null) { log2.LogInfo((object)"[PoltergeistMaterial] All bundled materials kept their shader; no repair needed."); } } } private static bool IsMaterialBroken(Material material) { if ((Object)(object)material == (Object)null) { return false; } if ((Object)(object)material.shader == (Object)null) { return true; } if (((Object)material.shader).name.IndexOf("InternalError", StringComparison.OrdinalIgnoreCase) < 0) { return ((Object)material.shader).name.IndexOf("Hidden/InternalError", StringComparison.OrdinalIgnoreCase) >= 0; } return true; } private static Material RebuildMaterial(Material source) { //IL_0056: Unknown result type (might be due to invalid IL or missing references) //IL_005b: Unknown result type (might be due to invalid IL or missing references) //IL_0082: Expected O, but got Unknown //IL_00cc: Unknown result type (might be due to invalid IL or missing references) //IL_00dc: Unknown result type (might be due to invalid IL or missing references) Shader val = Shader.Find("HDRP/Lit") ?? Shader.Find("High Definition Render Pipeline/Lit") ?? Shader.Find("Universal Render Pipeline/Lit") ?? Shader.Find("Standard"); if ((Object)(object)val == (Object)null) { ManualLogSource log = Log; if (log != null) { log.LogError((object)"[PoltergeistMaterial] No usable shader found in the game; cannot repair materials."); } return null; } Material val2 = new Material(val) { name = (((Object)(object)source != (Object)null) ? ((Object)source).name : "Poltergeist") + "_Runtime" }; CopyTexture(source, val2, "_BaseColorMap", "_MainTex"); CopyTexture(source, val2, "_NormalMap", "_BumpMap"); CopyTexture(source, val2, "_MaskMap", "_MetallicGlossMap"); CopyTexture(source, val2, "_EmissiveColorMap", "_EmissionMap"); SetMaterialColor(val2, "_BaseColor", Color.white); SetMaterialColor(val2, "_Color", Color.white); SetMaterialFloat(val2, "_SurfaceType", 0f); SetMaterialFloat(val2, "_AlphaCutoffEnable", 1f); SetMaterialFloat(val2, "_AlphaCutoff", 0.5f); SetMaterialFloat(val2, "_Cutoff", 0.5f); val2.EnableKeyword("_ALPHATEST_ON"); SetMaterialFloat(val2, "_DoubleSidedEnable", 1f); SetMaterialFloat(val2, "_CullMode", 0f); SetMaterialFloat(val2, "_CullModeForward", 0f); val2.EnableKeyword("_DOUBLESIDED_ON"); val2.doubleSidedGI = true; if ((Object)(object)val2.GetTexture("_NormalMap") != (Object)null || (Object)(object)val2.GetTexture("_BumpMap") != (Object)null) { val2.EnableKeyword("_NORMALMAP"); } return val2; } private static void CopyTexture(Material source, Material destination, string hdrpProperty, string standardProperty) { if ((Object)(object)source == (Object)null) { return; } Texture val = GetTextureIfPresent(source, hdrpProperty) ?? GetTextureIfPresent(source, standardProperty); if (!((Object)(object)val == (Object)null)) { if (destination.HasProperty(hdrpProperty)) { destination.SetTexture(hdrpProperty, val); } if (destination.HasProperty(standardProperty)) { destination.SetTexture(standardProperty, val); } } } private static Texture GetTextureIfPresent(Material material, string property) { if (!((Object)(object)material != (Object)null) || !material.HasProperty(property)) { return null; } return material.GetTexture(property); } private static void SetMaterialColor(Material material, string property, Color value) { //IL_0014: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)material != (Object)null && material.HasProperty(property)) { material.SetColor(property, value); } } private static void SetMaterialFloat(Material material, string property, float value) { if ((Object)(object)material != (Object)null && material.HasProperty(property)) { material.SetFloat(property, value); } } private static void ActivateRendererHierarchy(Transform prefabRoot, Transform rendererTransform) { Transform val = rendererTransform; while ((Object)(object)val != (Object)null) { if (!((Component)val).gameObject.activeSelf) { ((Component)val).gameObject.SetActive(true); } if (!((Object)(object)val == (Object)(object)prefabRoot)) { val = val.parent; continue; } break; } } private static bool IsRuntimeHelperRenderer(Renderer renderer) { Transform val = (((Object)(object)renderer != (Object)null) ? ((Component)renderer).transform : null); while ((Object)(object)val != (Object)null) { string text = ((Object)val).name ?? string.Empty; if (text.IndexOf("ScanNode", StringComparison.OrdinalIgnoreCase) >= 0 || text.IndexOf("Collision", StringComparison.OrdinalIgnoreCase) >= 0 || text.IndexOf("MapDot", StringComparison.OrdinalIgnoreCase) >= 0) { return true; } val = val.parent; } return false; } private static void EnsureBehaviourStates(PoltergeistAI ai) { //IL_0009: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_001a: Expected O, but got Unknown //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Expected O, but got Unknown //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_0034: Unknown result type (might be due to invalid IL or missing references) //IL_0040: Expected O, but got Unknown //IL_0042: Unknown result type (might be due to invalid IL or missing references) //IL_0047: Unknown result type (might be due to invalid IL or missing references) //IL_0053: Expected O, but got Unknown //IL_0055: Unknown result type (might be due to invalid IL or missing references) //IL_005a: Unknown result type (might be due to invalid IL or missing references) //IL_0066: Expected O, but got Unknown //IL_0068: Unknown result type (might be due to invalid IL or missing references) //IL_006d: Unknown result type (might be due to invalid IL or missing references) //IL_0079: Expected O, but got Unknown //IL_007b: Unknown result type (might be due to invalid IL or missing references) //IL_0080: Unknown result type (might be due to invalid IL or missing references) //IL_008c: Expected O, but got Unknown //IL_008e: Unknown result type (might be due to invalid IL or missing references) //IL_0093: Unknown result type (might be due to invalid IL or missing references) //IL_009f: Expected O, but got Unknown ((EnemyAI)ai).enemyBehaviourStates = (EnemyBehaviourState[])(object)new EnemyBehaviourState[8] { new EnemyBehaviourState { name = "Roaming" }, new EnemyBehaviourState { name = "Stalking" }, new EnemyBehaviourState { name = "Phasing" }, new EnemyBehaviourState { name = "Retired" }, new EnemyBehaviourState { name = "Retired" }, new EnemyBehaviourState { name = "Possessing" }, new EnemyBehaviourState { name = "Fleeing" }, new EnemyBehaviourState { name = "Dead" } }; ((EnemyAI)ai).currentBehaviourStateIndex = 0; ((EnemyAI)ai).previousBehaviourStateIndex = 0; ((EnemyAI)ai).currentBehaviourState = ((EnemyAI)ai).enemyBehaviourStates[0]; } internal static void EnsureScanNode(GameObject prefab) { //IL_0125: Unknown result type (might be due to invalid IL or missing references) //IL_021a: Unknown result type (might be due to invalid IL or missing references) //IL_0234: Unknown result type (might be due to invalid IL or missing references) ScanNodeProperties val = null; ScanNodeProperties[] componentsInChildren = prefab.GetComponentsInChildren<ScanNodeProperties>(true); foreach (ScanNodeProperties val2 in componentsInChildren) { bool flag = val2.creatureScanID >= 0; bool flag2 = (Object)(object)val != (Object)null && val.creatureScanID >= 0; bool flag3 = string.Equals(((Object)((Component)val2).gameObject).name, "ScanNode", StringComparison.Ordinal); bool flag4 = (Object)(object)val != (Object)null && string.Equals(((Object)((Component)val).gameObject).name, "ScanNode", StringComparison.Ordinal); if ((Object)(object)val == (Object)null || (flag && !flag2) || (flag == flag2 && flag3 && !flag4)) { val = val2; } } if (componentsInChildren.Length > 1) { ManualLogSource log = Log; if (log != null) { log.LogWarning((object)$"[Poltergeist] Found {componentsInChildren.Length} scan nodes; retiring every duplicate."); } } for (int j = 0; j < componentsInChildren.Length; j++) { if ((Object)(object)componentsInChildren[j] != (Object)(object)val) { RetireExtraScanNode(componentsInChildren[j], val, prefab); } } Transform val3 = (((Object)(object)val != (Object)null) ? ((Component)val).transform : FindOrCreateChild(prefab.transform, "ScanNode", new Vector3(0f, 1.3f, 0f))); ((Object)((Component)val3).gameObject).name = "ScanNode"; TrySetTag(((Component)val3).gameObject, "DoNotSet"); TrySetLayer(((Component)val3).gameObject, "ScanNode"); EnsureHierarchyActive(val3, prefab.transform); ((Component)val3).gameObject.SetActive(true); if (!_loggedScanNodeLayer) { _loggedScanNodeLayer = true; ManualLogSource log2 = Log; if (log2 != null) { log2.LogInfo((object)($"[Poltergeist] Scan node layer resolved to {((Component)val3).gameObject.layer} " + string.Format("(NameToLayer(\"ScanNode\")={0}, fallback 22); ", LayerMask.NameToLayer("ScanNode")) + $"active={((Component)val3).gameObject.activeInHierarchy}.")); } } BoxCollider val4 = ((Component)val3).GetComponent<BoxCollider>(); if ((Object)(object)val4 == (Object)null) { val4 = ((Component)val3).gameObject.AddComponent<BoxCollider>(); } ((Collider)val4).enabled = true; ((Collider)val4).isTrigger = true; val4.center = Vector3.zero; val4.size = new Vector3(1.5f, 2.1f, 1.2f); bool num = (Object)(object)val == (Object)null; if (num) { val = ((Component)val3).gameObject.AddComponent<ScanNodeProperties>(); } PassengerContract.RepairScanNode(num, ref val.headerText, ref val.subText, ref val.maxRange, ref val.minRange); val.requiresLineOfSight = true; val.nodeType = 1; } private static void RetireExtraScanNode(ScanNodeProperties extra, ScanNodeProperties preferred, GameObject root) { //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_003a: Unknown result type (might be due to invalid IL or missing references) //IL_0080: Unknown result type (might be due to invalid IL or missing references) //IL_0085: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)extra == (Object)null) { return; } Scene scene; if ((Object)(object)((Component)extra).gameObject == (Object)(object)root || ((Object)(object)preferred != (Object)null && (Object)(object)((Component)extra).gameObject == (Object)(object)((Component)preferred).gameObject)) { scene = root.scene; if (((Scene)(ref scene)).IsValid()) { Object.Destroy((Object)(object)extra); } else { Object.DestroyImmediate((Object)(object)extra, true); } return; } GameObject gameObject = ((Component)extra).gameObject; gameObject.SetActive(false); Collider[] components = gameObject.GetComponents<Collider>(); for (int i = 0; i < components.Length; i++) { components[i].enabled = false; } scene = root.scene; if (((Scene)(ref scene)).IsValid()) { Object.Destroy((Object)(object)gameObject); } else { Object.DestroyImmediate((Object)(object)gameObject, true); } } private static void EnsureCollision(GameObject prefab, PoltergeistAI ai) { //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_0067: Unknown result type (might be due to invalid IL or missing references) //IL_00af: Unknown result type (might be due to invalid IL or missing references) //IL_00c8: Unknown result type (might be due to invalid IL or missing references) CapsuleCollider obj = prefab.GetComponent<CapsuleCollider>() ?? prefab.AddComponent<CapsuleCollider>(); ((Collider)obj).isTrigger = false; obj.direction = 1; obj.center = new Vector3(0f, 1.05f, 0f); obj.radius = 0.55f; obj.height = 2.1f; Transform val = FindOrCreateChild(prefab.transform, "Collision", new Vector3(0f, 1f, 0f)); TrySetTag(((Component)val).gameObject, "Enemy"); TrySetLayer(((Component)val).gameObject, "Enemies"); BoxCollider obj2 = ((Component)val).GetComponent<BoxCollider>() ?? ((Component)val).gameObject.AddComponent<BoxCollider>(); ((Collider)obj2).isTrigger = true; obj2.center = Vector3.zero; obj2.size = new Vector3(1.5f, 2f, 1.4f); Rigidbody obj3 = ((Component)val).GetComponent<Rigidbody>() ?? ((Component)val).gameObject.AddComponent<Rigidbody>(); obj3.isKinematic = true; obj3.useGravity = false; obj3.detectCollisions = true; EnemyAICollisionDetect obj4 = ((Component)val).GetComponent<EnemyAICollisionDetect>() ?? ((Component)val).gameObject.AddComponent<EnemyAICollisionDetect>(); obj4.mainScript = (EnemyAI)(object)ai; obj4.alwaysAllowHitting = true; obj4.canCollideWithEnemies = true; obj4.onlyCollideWhenGrounded = false; } private static EnemyType CreateEnemyType(GameObject prefab) { //IL_00e7: Unknown result type (might be due to invalid IL or missing references) EnemyType obj = ScriptableObject.CreateInstance<EnemyType>(); obj.enemyName = "Passenger"; obj.enemyPrefab = prefab; obj.PowerLevel = ModConfig.PowerLevel.Value; obj.DiversityPowerLevel = 1; obj.MaxCount = ModConfig.MaxCount.Value; obj.canDie = true; obj.canBeStunned = true; obj.canBeDestroyed = true; obj.stunTimeMultiplier = 1f; obj.stunGameDifficultyMultiplier = 1f; obj.destroyOnDeath = false; obj.doorSpeedMultiplier = 1f; obj.isOutsideEnemy = false; obj.isDaytimeEnemy = false; obj.normalizedTimeInDayToLeave = 1f; obj.probabilityCurve = AnimationCurve.Constant(0f, 1f, 1f); obj.numberSpawnedFalloff = AnimationCurve.Linear(0f, 1f, 1f, 0.35f); obj.useNumberSpawnedFalloff = true; obj.disableAnimatorWhenFar = false; obj.SizeLimit = (NavSizeLimit)1; PoltergeistAI component = prefab.GetComponent<PoltergeistAI>(); CreatureSfx.Apply(obj, (EnemyAI)(object)component, null, null, VanishDeathFallback(component)); return obj; } private static AudioClip VanishDeathFallback(PoltergeistAI ai) { if (!((Object)(object)ai != (Object)null) || !((Object)(object)ai.deathClip == (Object)null) || PassengerLooseCues.Pool(PassengerCue.Death).Length != 0) { return null; } return ai.vanishClip; } private static void RefreshDeathFallback() { EnemyType poltergeistEnemyType = PoltergeistEnemyType; PoltergeistAI poltergeistAI = (((Object)(object)poltergeistEnemyType != (Object)null && (Object)(object)poltergeistEnemyType.enemyPrefab != (Object)null) ? poltergeistEnemyType.enemyPrefab.GetComponent<PoltergeistAI>() : null); if (!((Object)(object)poltergeistAI == (Object)null)) { AudioClip val = VanishDeathFallback(poltergeistAI); AudioClip val2 = (((Object)(object)val != (Object)null) ? val : CreatureSfx.Silent); if ((Object)(object)poltergeistEnemyType.deathSFX != (Object)(object)val2) { Log.LogInfo((object)"[PoltergeistAudio] Loose death takes play the death wail; the vanish fallback is off."); } poltergeistEnemyType.deathSFX = val2; ((EnemyAI)poltergeistAI).dieSFX = val2; } } private static AudioSource FindOrCreateAudioSource(Transform parent, string childName, float maxDistance) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) Transform val = FindOrCreateChild(parent, childName, Vector3.zero); AudioSource obj = ((Component)val).GetComponent<AudioSource>() ?? ((Component)val).gameObject.AddComponent<AudioSource>(); ConfigureWorldAudioSource(obj, 3f, maxDistance); return obj; } internal static void ConfigureWorldAudioSource(AudioSource source, float minDistance, float maxDistance) { if (!((Object)(object)source == (Object)null)) { ApplyWorldPlacement(source, 1f, minDistance, maxDistance); source.reverbZoneMix = 1f; source.bypassReverbZones = false; OccludeAudio val = ((Component)source).GetComponent<OccludeAudio>(); if ((Object)(object)val == (Object)null) { val = ((Component)source).gameObject.AddComponent<OccludeAudio>(); } val.useReverb = true; } } internal static void ConfigureWorldAudioSourceDry(AudioSource source, float minDistance, float maxDistance) { if (!((Object)(object)source == (Object)null)) { ApplyWorldPlacement(source, 1f, minDistance, maxDistance); source.dopplerLevel = 0f; source.reverbZoneMix = 0f; source.bypassReverbZones = true; OccludeAudio component = ((Component)source).GetComponent<OccludeAudio>(); if ((Object)(object)component != (Object)null) { component.useReverb = false; ((Behaviour)component).enabled = false; } AudioLowPassFilter component2 = ((Component)source).GetComponent<AudioLowPassFilter>(); if ((Object)(object)component2 != (Object)null) { ((Behaviour)component2).enabled = false; } AudioReverbFilter component3 = ((Component)source).GetComponent<AudioReverbFilter>(); if ((Object)(object)component3 != (Object)null) { ((Behaviour)component3).enabled = false; } } } private static void ApplyWorldPlacement(AudioSource source, float spatialBlend, float minDistance, float maxDistance) { source.playOnAwake = false; source.spatialBlend = spatialBlend; source.rolloffMode = (AudioRolloffMode)1; source.minDistance = Mathf.Max(0.1f, minDistance); source.maxDistance = Mathf.Max(source.minDistance, maxDistance); AudioMixerGroup val = ResolveDiegeticMaster(); if ((Object)(object)val != (Object)null) { source.outputAudioMixerGroup = val; } } internal static void ConfigureLocalAudioSource(AudioSource source) { if (!((Object)(object)source == (Object)null)) { source.playOnAwake = false; source.spatialBlend = 0f; source.rolloffMode = (AudioRolloffMode)1; source.reverbZoneMix = 0f; source.bypassReverbZones = true; AudioMixerGroup val = ResolveDiegeticMaster(); if ((Object)(object)val != (Object)null) { source.outputAudioMixerGroup = val; } } } private static AudioMixerGroup ResolveDiegeticMaster() { if ((Object)(object)_diegeticMaster != (Object)null) { return _diegeticMaster; } SoundManager instance = SoundManager.Instance; if ((Object)(object)instance == (Object)null || (Object)(object)instance.diageticMixer == (Object)null) { return null; } AudioMixerGroup[] array = instance.diageticMixer.FindMatchingGroups("Master"); if (array != null && array.Length != 0) { _diegeticMaster = array[0]; } return _diegeticMaster; } private static void AssignPoltergeistAudio(PoltergeistAI ai) { if ((Object)(object)ai == (Object)null || (Object)(object)ModAssets == (Object)null) { return; } string[] allAssetNames = ModAssets.GetAllAssetNames(); ai.attackWhooshClips = LoadAudioClipSet(allAssetNames, "plt_attack_swipe_01"); AudioClip[] array = LoadAudioClipSet(allAssetNames, "plt_emerge_01"); ai.emergenceClip = ((array.Length != 0) ? array[0] : null); AudioClip[] array2 = LoadAudioClipSet(allAssetNames, "plt_vanish_01"); ai.vanishClip = ((array2.Length != 0) ? array2[0] : null); ai.hurtClips = LoadAudioClipSet(allAssetNames, false, "plt_hurt_01", "plt_hurt_02"); AudioClip[] array3 = LoadAudioClipSet(allAssetNames, false, "plt_death_01"); ai.deathClip = ((array3.Length != 0) ? array3[0] : null); PassengerLooseCues.RecordBundleCoverage(PassengerCue.Hurt, ai.hurtClips.Length != 0); PassengerLooseCues.RecordBundleCoverage(PassengerCue.Death, (Object)(object)ai.deathClip != (Object)null); ai.throwWhooshClips = (AudioClip[])(object)new AudioClip[2] { LoadAudioClip(allAssetNames, "plt_throw_whoosh_01"), LoadAudioClip(allAssetNames, "plt_throw_whoosh_02") }; int num = 0; for (int i = 0; i < ai.throwWhooshClips.Length; i++) { if ((Object)(object)ai.throwWhooshClips[i] != (Object)null) { num++; } } if (num == 0) { Log.LogWarning((object)"[PoltergeistAudio] Throw whoosh plt_throw_whoosh_01/02 missing from y4ngzpoltergeist.bundle: the scrap throw is silent at release."); } int num2 = ai.attackWhooshClips.Length + array.Length + array2.Length + ai.hurtClips.Length + array3.Length + num; ManualLogSource log = Log; if (log != null) { log.LogInfo((object)string.Format("[PoltergeistAudio] Loaded {0} authored world clip(s) from {1}.", num2, "y4ngzpoltergeist.bundle")); } } private static AudioClip[] LoadAudioClipSet(string[] bundleAssets, params string[] clipNames) { return LoadAudioClipSet(bundleAssets, warnMissing: true, clipNames); } private static AudioClip[] LoadAudioClipSet(string[] bundleAssets, bool warnMissing, params string[] clipNames) { List<AudioClip> list = new List<AudioClip>(clipNames.Length); for (int i = 0; i < clipNames.Length; i++) { AudioClip val = LoadAudioClip(bundleAssets, clipNames[i]); if ((Object)(object)val != (Object)null) { list.Add(val); } else if (warnMissing) { ManualLogSource log = Log; if (log != null) { log.LogWarning((object)("[PoltergeistAudio] Clip " + clipNames[i] + " missing from y4ngzpoltergeist.bundle.")); } } } return list.ToArray(); } private static AudioClip LoadAudioClip(string[] bundleAssets, string clipName) { foreach (string text in bundleAssets) { if (string.Equals(Path.GetFileNameWithoutExtension(text), clipName, StringComparison.OrdinalIgnoreCase)) { AudioClip val = ModAssets.LoadAsset<AudioClip>(text); if ((Object)(object)val != (Object)null) { return val; } } } return null; } private static Transform FindOrCreateChild(Transform parent, string name, Vector3 localPosition) { //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Unknown result type (might be due to invalid IL or missing references) Transform val = parent.Find(name); if ((Object)(object)val != (Object)null) { val.localPosition = localPosition; return val; } val = new GameObject(name).transform; val.SetParent(parent, false); val.localPosition = localPosition; return val; } private static void AssignUniqueNetworkHash(GameObject prefab) { try { NetworkObject val = prefab.GetComponent<NetworkObject>(); if ((Object)(object)val == (Object)null) { val = prefab.AddComponent<NetworkObject>(); } uint num = BitConverter.ToUInt32(MD5.Create().ComputeHash(Encoding.UTF8.GetBytes("y4ngz.lethalcompany.poltergeist.Poltergeist")), 0); PropertyInfo property = typeof(NetworkObject).GetProperty("GlobalObjectIdHash", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); if (property != null && property.CanWrite) { property.SetValue(val, num); return; } FieldInfo fieldInfo = typeof(NetworkObject).GetField("GlobalObjectIdHash", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic) ?? typeof(NetworkObject).GetField("<GlobalObjectIdHash>k__BackingField", BindingFlags.Instance | BindingFlags.NonPublic); if (fieldInfo != null) { fieldInfo.SetValue(val, num); } } catch (Exception ex) { Log.LogWarning((object)("Could not assign NetworkObject hash for Poltergeist: " + ex.Message)); } } private static void DumpBundleAssets() { if (!((Object)(object)ModAssets == (Object)null)) { string[] allAssetNames = ModAssets.GetAllAssetNames(); foreach (string text in allAssetNames) { Log.LogError((object)(" - " + text)); } } } private static void TrySetTag(GameObject gameObject, string tag) { try { gameObject.tag = tag; } catch { } } private static void TrySetLayer(GameObject gameObject, string layerName) { if ((Object)(object)gameObject == (Object)null) { return; } int num = LayerMask.NameToLayer(layerName); if (num < 0) { num = ResolveLayerFallback(layerName); } if (num >= 0 && num <= 31) { gameObject.layer = num; return; } ManualLogSource log = Log; if (log != null) { log.LogWarning((object)$"[Poltergeist] Layer '{layerName}' unresolved; '{((Object)gameObject).name}' stays on layer {gameObject.layer}."); } } private static int ResolveLayerFallback(string layerName) { if (string.Equals(layerName, "ScanNode", StringComparison.OrdinalIgnoreCase)) { return 22; } if (string.Equals(layerName, "Enemies", StringComparison.OrdinalIgnoreCase)) { return 19; } return -1; } private static void EnsureHierarchyActive(Transform child, Transform stopAt) { Transform val = child; while ((Object)(object)val != (Object)null) { ((Component)val).gameObject.SetActive(true); if (!((Object)(object)val == (Object)(object)stopAt)) { val = val.parent; continue; } break; } } } internal static class PluginInfo { public const string PLUGIN_GUID = "y4ngz.lethalcompany.poltergeist"; public const string PLUGIN_NAME = "Y4NGZ Poltergeist"; public const string PLUGIN_VERSION = "2.0.0"; } internal sealed class PoltergeistConfig { private const string SectionGeneral = "General"; private const string SectionSpawning = "Spawning"; private const string SectionCoreStats = "Core Stats"; private const string SectionDetection = "Detection"; private const string SectionMovement = "Movement"; private const string SectionCombat = "Combat"; private const string SectionAbilities = "Abilities"; private const string SectionPresentation = "Audio and Presentation"; private const string SectionHaunt = "Haunt"; private const string SectionReveal = "Reveal"; private const string SectionDiagnostics = "Diagnostics"; internal const string SectionPossession = "Possession"; internal const string SectionVoice = "Voice"; public ConfigEntry<bool> Enabled { get; } public ConfigEntry<float> SpawnWeightMultiplier { get; } public ConfigEntry<string> MoonWeightOverrides { get; } public ConfigEntry<int> MaxCount { get; } public ConfigEntry<float> PowerLevel { get; } public ConfigEntry<int> Health { get; } public ConfigEntry<float> SightRange { get; } public ConfigEntry<float> RoamSpeed { get; } public ConfigEntry<float> StalkSpeed { get; } public ConfigEntry<float> ChaseSpeed { get; } public ConfigEntry<float> FleeSpeed { get; } public ConfigEntry<bool> FlightEnabled { get; } public ConfigEntry<float> FlightAltitudeMin { get; } public ConfigEntry<float> FlightAltitudeMax { get; } public ConfigEntry<float> FlightClearanceMargin { get; } public ConfigEntry<float> FlightClimbRate { get; } public ConfigEntry<float> FlightSwayMeters { get; } public ConfigEntry<float> FlightTiltDegrees { get; } public ConfigEntry<float> StandOff { get; } public ConfigEntry<bool> TacticsEnabled { get; } public ConfigEntry<bool> ScrapThrowEnabled { get; } public ConfigEntry<int> ScrapThrowDamage { get; } public ConfigEntry<float> ScrapThrowCooldownSeconds { get; } public ConfigEntry<int> ScrapThrowsPerRound { get; } public ConfigEntry<float> ScrapThrowRange { get; } public ConfigEntry<bool> LiftEnabled { get; } public ConfigEntry<float> LiftCooldownSeconds { get; } public ConfigEntry<int> LiftsPerRound { get; } public ConfigEntry<float> LiftMinClearance { get; } public ConfigEntry<float> LiftHeight { get; } public ConfigEntry<float> LiftHoldSeconds { get; } public ConfigEntry<float> LiftReach { get; } public ConfigEntry<float> LiftAttachBehind { get; } public ConfigEntry<float> LiftAttachSide { get; } public ConfigEntry<float> LiftAttachPelvisBelowChest { get; } public ConfigEntry<bool> LungeEnabled { get; } public ConfigEntry<float> LungeCooldownSeconds { get; } public ConfigEntry<float> LungeMinRange { get; } public ConfigEntry<float> LungeMaxRange { get; } public ConfigEntry<float> LungeSpeed { get; } public ConfigEntry<float> LungeReappearDelay { get; } public ConfigEntry<int> LungeSweepDamage { get; } public ConfigEntry<int> LungeSwipeCount { get; } public ConfigEntry<bool> WallPhasingEnabled { get; } public ConfigEntry<float> PhaseCooldown { get; } public ConfigEntry<float> ManifestPressureSeconds { get; } public ConfigEntry<int> RevealAfterUnseen { get; } public ConfigEntry<float> ConcealWallWeight { get; } public ConfigEntry<float> ConcealFloorWeight { get; } public ConfigEntry<float> ConcealCeilingWeight { get; } public ConfigEntry<float> GhostTraversalWeight { get; } public ConfigEntry<float> GhostFloorWeight { get; } public ConfigEntry<float> WallPassSpeed { get; } public ConfigEntry<float> WallPassWeight { get; } public ConfigEntry<float> PursuitBreachWeight { get; } public ConfigEntry<float> WallLurkWeight { get; } public ConfigEntry<bool> HallwayCrossEnabled { get; } public ConfigEntry<float> HallwayCrossMinDistance { get; } public ConfigEntry<float> HallwayCrossMaxDistance { get; } public ConfigEntry<float> HallwayCrossMaxSideDistance { get; } public ConfigEntry<float> HallwayCrossSpeed { get; } public ConfigEntry<float> HallwayCrossCooldownMin { get; } public ConfigEntry<float> HallwayCrossCooldownMax { get; } public ConfigEntry<bool> PossessionEnabled { get; } public ConfigEntry<float> PossessionDurationSeconds { get; } public ConfigEntry<float> PossessionCooldownPerPlayerSeconds { get; } public ConfigEntry<bool> PossessedFriendlyFire { get; } public ConfigEntry<bool> PossessedAttacksEnabled { get; } public ConfigEntry<float> PossessedAttackCooldownSeconds { get; } public ConfigEntry<int> PossessedAttackDamage { get; } public ConfigEntry<bool> PhaseVfxEnabled { get; } public ConfigEntry<float> PossessionLoopVolume { get; } public ConfigEntry<bool> PossessedVoiceFilterEnabled { get; } public ConfigEntry<float> FaceHeight { get; } public ConfigEntry<float> ScreamWindowSeconds { get; } public ConfigEntry<float> ScreamRange { get; } public ConfigEntry<float> ScreamConeDegrees { get; } public ConfigEntry<bool> LightFlickerEnabled { get; } public ConfigEntry<float> LightFlickerCooldownSeconds { get; } public ConfigEntry<bool> DoorSlamEnabled { get; } public ConfigEntry<float> DoorSlamCooldownSeconds { get; } public ConfigEntry<float> VisibleFloorFraction { get; } public ConfigEntry<float> VisibleCeilingFraction { get; } public ConfigEntry<float> RevealMaxSeconds { get; } public ConfigEntry<float> RevealMinSeconds { get; } public ConfigEntry<float> StareMinSeconds { get; } public ConfigEntry<float> StareMaxSeconds { get; } public ConfigEntry<float> StareVanishOnLookAwayChance { get; } public ConfigEntry<float> TranslucentRevealChance { get; } public ConfigEntry<float> HiddenWindowMinSeconds { get; } public ConfigEntry<float> HiddenWindowMaxSeconds { get; } public ConfigEntry<float> AmbientIntervalMinSeconds { get; } public ConfigEntry<float> AmbientIntervalMaxSeconds { get; } public ConfigEntry<float> PhaseAMinSeconds { get; } public ConfigEntry<float> PhaseAMaxSeconds { get; } public ConfigEntry<float> PhaseBMinSeconds { get; } public ConfigEntry<float> PhaseBMaxSeconds { get; } public ConfigEntry<float> PhaseCMinSeconds { get; } public ConfigEntry<float> PhaseCMaxSeconds { get; } public ConfigEntry<float> PhaseDropAfterSeconds { get; } public ConfigEntry<float> HiddenWindowFloorCutSeconds { get; } public ConfigEntry<float> RevealIntervalMinSeconds { get; } public ConfigEntry<float> RevealIntervalMaxSeconds { get; } public ConfigEntry<float> ContactIntervalMinSeconds { get; } public ConfigEntry<float> ContactIntervalMaxSeconds { get; } public ConfigEntry<float> PossessionIntervalMinSeconds { get; } public ConfigEntry<float> PossessionIntervalMaxSeconds { get; } public ConfigEntry<float> LightFlickerWeight { get; } public ConfigEntry<float> DoorCloseWeight { get; } public ConfigEntry<float> LightsOutWeight { get; } public ConfigEntry<float> ItemNudgeWeight { get; } public ConfigEntry<float> PulseWeight { get; } public ConfigEntry<float> GhostHauntWeight { get; } public ConfigEntry<bool> ClutterEnabled { get; } public ConfigEntry<float> WatcherStareDissolveMinSeconds { get; } public ConfigEntry<float> WatcherStareDissolveMaxSeconds { get; } public ConfigEntry<float> WatcherProximityDissolveMeters { get; } public ConfigEntry<bool> DebugLogs { get; } public ConfigEntry<bool> PhaseDiagnostics { get; } public ConfigEntry<float> PhaseDiagnosticsSeconds { get; } public ConfigEntry<bool> PossessionDiagnostics { get; } public ConfigEntry<bool> PossessionDebugAllowSolo { get; } public ConfigEntry<float> DiveMinRange { get; private set; } public ConfigEntry<float> DiveMaxRange { get; private set; } public ConfigEntry<float> DiveSpeed { get; private set; } public ConfigEntry<int> MaxPossessionsPerWorkerPerRound { get; private set; } public ConfigEntry<float> ImpactKnockMeters { get; private set; } public ConfigEntry<float> PossessionShake { get; private set; } public ConfigEntry<float> PossessionBlur { get; private set; } public ConfigEntry<float> PossessionMuffle { get; private set; } public ConfigEntry<float> BoneSnapVolume { get; private set; } public ConfigEntry<bool> VoiceSenderSide { get; private set; } public ConfigEntry<float> VoicePitchSemitones { get; private set; } public ConfigEntry<bool> VoicePitchEnabled { get; private set; } public ConfigEntry<bool> VoiceOctaveEnabled { get; private set; } public ConfigEntry<bool> VoiceWhisperEnabled { get; private set; } public ConfigEntry<bool> VoiceRingEnabled { get; private set; } public ConfigEntry<bool> VoiceReverbEnabled { get; private set; } public ConfigEntry<bool> VoiceFreezeEnabled { get; private set; } public ConfigEntry<bool> VoiceDriveEnabled { get; private set; } public ConfigEntry<float> VoiceMonoBudgetMsPer20ms { get; private set; } private void BindPossession(ConfigFile config) { //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_0034: Expected O, but got Unknown //IL_0063: Unknown result type (might be due to invalid IL or missing references) //IL_006d: Expected O, but got Unknown //IL_009c: Unknown result type (might be due to invalid IL or missing references) //IL_00a6: Expected O, but got Unknown //IL_00ca: Unknown result type (might be due to invalid IL or missing references) //IL_00d4: Expected O, but got Unknown //IL_0103: Unknown result type (might be due to invalid IL or missing references) //IL_010d: Expected O, but got Unknown //IL_013c: Unknown result type (might be due to invalid IL or missing references) //IL_0146: Expected O, but got Unknown //IL_0175: Unknown result type (might be due to invalid IL or missing references) //IL_017f: Expected O, but got Unknown //IL_01ae: Unknown result type (might be due to invalid IL or missing references) //IL_01b8: Expected O, but got Unknown //IL_01e7: Unknown result type (might be due to invalid IL or missing references) //IL_01f1: Expected O, but got Unknown DiveMinRange = config.Bind<float>("Possession", "DiveMinRange", 4f, new ConfigDescription("Host-only: closest distance (m) from which Passenger dives at a worker to possess them. A closer worker makes him vanish and reappear hidden farther out, in the worker's sight; with no such spot he dives from where he stands if the route is clear.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(2f, 12f), Array.Empty<object>())); DiveMaxRange = config.Bind<float>("Possession", "DiveMaxRange", 14f, new ConfigDescription("Host-only: farthest distance (m) at which Passenger starts a possession dive. He needs line of sight and a clear straight route.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(6f, 25f), Array.Empty<object>())); DiveSpeed = config.Bind<float>("Possession", "DiveSpeed", 14f, new ConfigDescription("Host-only: speed (m/s) of the visible possession dive.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(6f, 30f), Array.Empty<object>())); MaxPossessionsPerWorkerPerRound = config.Bind<int>("Possession", "MaxPerWorkerPerRound", 1, new ConfigDescription("Host-only: how many times one worker can be possessed in a round, across all Passengers.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 10), Array.Empty<object>())); ImpactKnockMeters = config.Bind<float>("Possession", "ImpactKnockMeters", 0.8f, new ConfigDescription("Local to each player: how far (m) the possession impact shoves you along the dive direction (0 = off). Host dummies use the host's setting.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 1.5f), Array.Empty<object>())); PossessionShake = config.Bind<float>("Possession", "PossessionShake", 1f, new ConfigDescription("Local to each player: strength of the camera kick and shake you feel when the Passenger dives into you, and at half strength when she lifts you (0 = off, 1 = full).", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 1f), Array.Empty<object>())); PossessionBlur = config.Bind<float>("Possession", "PossessionBlur", 0.9f, new ConfigDescription("Local to each player: fear-filter blur while you are possessed, and lighter while she lifts you; also scales the possession and lift vignettes. The vanilla blur shows only above 0.4 (0 = off).", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 1f), Array.Empty<object>())); PossessionMuffle = config.Bind<float>("Possession", "PossessionMuffle", 0.7f, new ConfigDescription("Local to each player: how muffled the world sounds while you are possessed (0 = off, 1 = strongest, about 800 Hz).", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 1f), Array.Empty<object>())); BoneSnapVolume = config.Bind<float>("Possession", "BoneSnapVolume", 0.8f, new ConfigDescription("Local to each player: volume of the bone snaps when a possessed body contorts (0 = silent, 1 = full).", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 1f), Array.Empty<object>())); } private void BindVoice(ConfigFile config) { //IL_0046: Unknown result type (might be due to invalid IL or missing references) //IL_0050: Expected O, but got Unknown //IL_0143: Unknown result type (might be due to invalid IL or missing references) //IL_014d: Expected O, but got Unknown VoiceSenderSide = config.Bind<bool>("Voice", "SenderSide", true, "Process a possessed worker's voice on their own machine before it is sent, so every listener hears the same effect. Off: listeners apply the older listener-side effect."); VoicePitchSemitones = config.Bind<float>("Voice", "PitchSemitones", -6f, new ConfigDescription("Pitch of the possessed voice in semitones; the formant shift follows at half this value.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(-8f, -3f), Array.Empty<object>())); VoicePitchEnabled = config.Bind<bool>("Voice", "PitchEnabled", true, "Possessed voice stage: pitch shift."); VoiceOctaveEnabled = config.Bind<bool>("Voice", "OctaveEnabled", true, "Possessed voice stage: octave-down double."); VoiceWhisperEnabled = config.Bind<bool>("Voice", "WhisperEnabled", true, "Possessed voice stage: whispering noise layer."); VoiceRingEnabled = config.Bind<bool>("Voice", "RingEnabled", true, "Possessed voice stage: slow ring modulation."); VoiceReverbEnabled = config.Bind<bool>("Voice", "ReverbEnabled", true, "Possessed voice stage: short dark reverb."); VoiceFreezeEnabled = config.Bind<bool>("Voice", "FreezeEnabled", true, "Possessed voice stage: spectral freeze bursts."); VoiceDriveEnabled = config.Bind<bool>("Voice", "DriveEnabled", true, "Possessed voice stage: drive and bit crush."); VoiceMonoBudgetMsPer20ms = config.Bind<float>("Voice", "MonoBudgetMsPer20ms", 4f, new ConfigDescription("If chain A costs more than this many milliseconds per 20 ms of voice in game, the voice falls back to the lighter chain B for the session.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 20f), Array.Empty<object>())); } public PoltergeistConfig(ConfigFile config) { //IL_0090: Unknown result type (might be due to invalid IL or missing references) //IL_009a: Expected O, but got Unknown //IL_00dd: Unknown result type (might be due to invalid IL or missing references) //IL_00e7: Expected O, but got Unknown //IL_0116: Unknown result type (might be due to invalid IL or missing references) //IL_0120: Expected O, but got Unknown //IL_0144: Unknown result type (might be due to invalid IL or missing references) //IL_014e: Expected O, but got Unknown //IL_017d: Unknown result type (might be due to invalid IL or missing references) //IL_0187: Expected O, but got Unknown //IL_023e: Unknown result type (might be due to invalid IL or missing references) //IL_0248: Expected O, but got Unknown //IL_0277: Unknown result type (might be due to invalid IL or missing references) //IL_0281: Expected O, but got Unknown //IL_02b0: Unknown result type (might be due to invalid IL or missing references) //IL_02ba: Expected O, but got Unknown //IL_02e9: Unknown result type (might be due to invalid IL or missing references) //IL_02f3: Expected O, but got Unknown //IL_0322: Unknown result type (might be due to invalid IL or missing references) //IL_032c: Expected O, but got Unknown //IL_035b: Unknown result type (might be due to invalid IL or missing references) //IL_0365: Expected O, but got Unknown //IL_0394: Unknown result type (might be due to invalid IL or missing references) //IL_039e: Expected O, but got Unknown //IL_03fb: Unknown result type (might be due to invalid IL or missing references) //IL_0405: Expected O, but got Unknown //IL_0434: Unknown result type (might be due to invalid IL or missing references) //IL_043e: Expected O, but got Unknown //IL_0462: Unknown result type (might be due to invalid IL or missing references) //IL_046c: Expected O, but got Unknown //IL_049b: Unknown result type (might be due to invalid IL or missing references) //IL_04a5: Expected O, but got Unknown //IL_04f0: Unknown result type (might be due to invalid IL or missing references) //IL_04fa: Expected O, but got Unknown //IL_051e: Unknown result type (might be due to invalid IL or missing references) //IL_0528: Expected O, but got Unknown //IL_0557: Unknown result type (might be due to invalid IL or missing references) //IL_0561: Expected O, but got Unknown //IL_0590: Unknown result type (might be due to invalid IL or missing references) //IL_059a: Expected O, but got Unknown //IL_05c9: Unknown result type (might be due to invalid IL or missing references) //IL_05d3: Expected O, but got Unknown //IL_0602: Unknown result type (might be due to invalid IL or missing references) //IL_060c: Expected O, but got Unknown //IL_063b: Unknown result type (might be due to invalid IL or missing references) //IL_0645: Expected O, but got Unknown //IL_0674: Unknown result type (might be due to invalid IL or missing references) //IL_067e: Expected O, but got Unknown //IL_06ad: Unknown result type (might be due to invalid IL or missing references) //IL_06b7: Expected O, but got Unknown //IL_0702: Unknown result type (might be due to invalid IL or missing references) //IL_070c: Expected O, but got Unknown //IL_073b: Unknown result type (might be due to invalid IL or missing references) //IL_0745: Expected O, but got Unknown //IL_0774: Unknown result type (might be due to invalid IL or missing references) //IL_077e: Expected O, but got Unknown //IL_07ad: Unknown result type (might be due to invalid IL or missing references) //IL_07b7: Expected O, but got Unknown //IL_07e6: Unknown result type (might be due to invalid IL or missing references) //IL_07f0: Expected O, but got Unknown //IL_0815: Unknown result type (might be due to invalid IL or missing references) //IL_081f: Expected O, but got Unknown //IL_0842: Unknown result type (might be due to invalid IL or missing references) //IL_084c: Expected O, but got Unknown //IL_0897: Unknown result type (might be due to invalid IL or missing references) //IL_08a1: Expected O, but got Unknown //IL_08d0: Unknown result type (might be due to invalid IL or missing references) //IL_08da: Expected O, but got Unknown //IL_08fe: Unknown result type (might be due to invalid IL or missing references) //IL_0908: Expected O, but got Unknown //IL_0988: Unknown result type (might be due to invalid IL or missing references) //IL_0992: Expected O, but got Unknown //IL_09c1: Unknown result type (might be due to invalid IL or missing references) //IL_09cb: Expected O, but got Unknown //IL_0a82: Unknown result type (might be due to invalid IL or missing references) //IL_0a8c: Expected O, but got Unknown //IL_0abb: Unknown result type (might be due to invalid IL or missing references) //IL_0ac5: Expected O, but got Unknown //IL_0af4: Unknown result type (might be due to invalid IL or missing references) //IL_0afe: Expected O, but got Unknown //IL_0b2d: Unknown result type (might be due to invalid IL or missing references) //IL_0b37: Expected O, but got Unknown //IL_0b66: Unknown result type (might be due to invalid IL or missing references) //IL_0b70: Expected O, but got Unknown //IL_0b9f: Unknown result type (might be due to invalid IL or missing references) //IL_0ba9: Expected O, but got Unknown //IL_0bf4: Unknown result type (might be due to invalid IL or missing references) //IL_0bfe: Expected O, but got Unknown //IL_0c2d: Unknown result type (might be due to invalid IL or missing references) //IL_0c37: Expected O, but got Unknown //IL_0c9e: Unknown result type (might be due to invalid IL or missing references) //IL_0ca8: Expected O, but got Unknown //IL_0ccd: Unknown result type (might be due to invalid IL or missing references) //IL_0cd7: Expected O, but got Unknown //IL_0d29: Unknown result type (might be due to invalid IL or missing references) //IL_0d33: Expected O, but got Unknown //IL_0d7e: Unknown result type (might be due to invalid IL or missing references) //IL_0d88: Expected O, but got Unknown //IL_0db7: Unknown result type (might be due to invalid IL or missing references) //IL_0dc1: Expected O, but got Unknown //IL_0df0: Unknown result type (might be due to invalid IL or missing references) //IL_0dfa: Expected O, but got Unknown //IL_0e29: Unknown result type (might be due to invalid IL or missing references) //IL_0e33: Expected O, but got Unknown //IL_0e7e: Unknown result type (might be due to invalid IL or missing references) //IL_0e88: Expected O, but got Unknown //IL_0ed3: Unknown result type (might be due to invalid IL or missing references) //IL_0edd: Expected O, but got Unknown //IL_0f13: Unknown result type (might be due to invalid IL or missing references) //IL_0f1d: Expected O, but got Unknown //IL_0f4c: Unknown result type (might be due to invalid IL or missing references) //IL_0f56: Expected O, but got Unknown //IL_0f85: Unknown result type (might be due to invalid IL or missing references) //IL_0f8f: Expected O, but got Unknown //IL_0fbe: Unknown result type (might be due to invalid IL or missing references) //IL_0fc8: Expected O, but got Unknown //IL_0ff7: Unknown result type (might be due to invalid IL or missing references) //IL_1001: Expected O, but got Unknown //IL_1030: Unknown result type (might be due to invalid IL or missing references) //IL_103a: Expected O, but got Unknown //IL_1069: Unknown result type (might be due to invalid IL or missing references) //IL_1073: Expected O, but got Unknown //IL_10a2: Unknown result type (might be due to invalid IL or missing references) //IL_10ac: Expected O, but got Unknown //IL_10db: Unknown result type (might be due to invalid IL or missing references) //IL_10e5: Expected O, but got Unknown //IL_1114: Unknown result type (might be due to invalid IL or missing references) //IL_111e: Expected O, but got Unknown //IL_114d: Unknown result type (might be due to invalid IL or missing references) //IL_1157: Expected O, but got Unknown //IL_1186: Unknown result type (might be due to invalid IL or missing references) //IL_1190: Expected O, but got Unknown //IL_11bf: Unknown result type (might be due to invalid IL or missing references) //IL_11c9: Expected O, but got Unknown //IL_11f8: Unknown result type (might be due to invalid IL or missing references) //IL_1202: Expected O, but got Unknown //IL_1231: Unknown result type (might be due to invalid IL or missing references) //IL_123b: Expected O, but got Unknown //IL_126a: Unknown result type (might be due to invalid IL or missing references) //IL_1274: Expected O, but got Unknown //IL_12a3: Unknown result type (might be due to invalid IL or missing references) //IL_12ad: Expected O, but got Unknown //IL_12dc: Unknown result type (might be due to invalid IL or missing references) //IL_12e6: Expected O, but got Unknown //IL_1315: Unknown result type (might be due to invalid IL or missing references) //IL_131f: Expected O, but got Unknown //IL_134e: Unknown result type (might be due to invalid IL or missing references) //IL_1358: Expected O, but got Unknown //IL_1387: Unknown result type (might be due to invalid IL or missing references) //IL_1391: Expected O, but got Unknown //IL_13c0: Unknown result type (might be due to invalid IL or missing references) //IL_13ca: Expected O, but got Unknown //IL_13f9: Unknown result type (might be due to invalid IL or missing references) //IL_1403: Expected O, but got Unknown //IL_1432: Unknown result type (might be due to invalid IL or missing references) //IL_143c: Expected O, but got Unknown //IL_146b: Unknown result type (might be due to invalid IL or missing references) //IL_1475: Expected O, but got Unknown //IL_14a4: Unknown result type (might be due to invalid IL or missing references) //IL_14ae: Expected O, but got Unknown //IL_159b: Unknown result type (might be due to invalid IL or missing references) //IL_15a5: Expected O, but got Unknown //IL_15d4: Unknown result type (might be due to invalid IL or missing references) //IL_15de: Expected O, but got Unknown //IL_160d: Unknown result type (might be due to invalid IL or missing references) //IL_1617: Expected O, but got Unknown //IL_167e: Unknown result type (might be due to invalid IL or missing references) //IL_1688: Expected O, but got Unknown using (ConfigPersistence.BeginBinding(config, Plugin.Log, "Passenger")) { PoltergeistConfigMigration.TryMigrate(config, Plugin.Log); ConfigSectionNameMigration.TryMigrate(config, Plugin.Log, "Passenger"); PoltergeistConfigMigration.RetireReplacedEntries(config, Plugin.Log); PoltergeistConfigMigration.RetuneUntouchedDefaults(config, Plugin.Log); Enabled = config.Bind<bool>("General", "Enabled", true, "Enable the Passenger encounter. Host-only: the host's value decides whether it spawns; every install still registers the creature so clients stay in sync."); SpawnWeightMultiplier = config.Bind<float>("Spawning", "SpawnWeightMultiplier", 1f, new ConfigDescription("Multiplier applied to Passenger's contextual moon/interior spawn policy. 0 disables natural spawns.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 5f), Array.Empty<object>())); MoonWeightOverrides = config.Bind<string>("Spawning", "MoonWeightOverrides", string.Empty, "Optional comma-separated base moon weights, e.g. Experimentation:8,Offense:15 or namespace:moon=12. Use 0 to disable a moon; unlisted moons keep authored defaults."); MaxCount = config.Bind<int>("Spawning", "MaxCount", 1, new ConfigDescription("Maximum number of living Passengers at once.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 4), Array.Empty<object>())); PowerLevel = config.Bind<float>("Spawning", "PowerLevel", 2.5f, new ConfigDescription("Indoor enemy power budget cost for each Passenger.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.5f, 20f), Array.Empty<object>())); Health = config.Bind<int>("Core Stats", "Health", 5, new ConfigDescription("Hits Passenger can take before dying.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 100), Array.Empty<object>())); SightRange = config.Bind<float>("Detection", "SightRange", 45f, new ConfigDescription("Maximum distance at which Passenger tracks line of sight to players.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(5f, 150f), Array.Empty<object>())); RoamSpeed = BindSpeed(config, "RoamSpeed", 2.2f, "Movement speed while searching the interior."); StalkSpeed = BindSpeed(config, "StalkSpeed", 3f, "Movement speed while stalking a known target."); ChaseSpeed = BindSpeed(config, "ChaseSpeed", 6.2f, "Movement speed during committed pursuit."); FleeSpeed = BindSpeed(config, "FleeSpeed", 5.4f, "Movement speed while retreating after damage."); FlightEnabled = config.Bind<bool>("Movement", "FlightEnabled", true, "Host-only: Passenger floats above the floor, higher while roaming and fleeing, low while stalking, and sinks to the floor before every throw, lift, possession and wall, floor or ceiling passage. Off keeps the old floor-level glide."); FlightAltitudeMin = config.Bind<float>("Movement", "FlightAltitudeMin", 0.3f, new ConfigDescription("Host-only: lowest flight altitude in metres (the bottom of the roaming swell and his stalking height).", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 1.5f), Array.Empty<object>())); FlightAltitudeMax = config.Bind<float>("Movement", "FlightAltitudeMax", 1.5f, new ConfigDescription("Host-only: highest flight altitude in metres. A value below FlightAltitudeMin is treated as FlightAltitudeMin.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 3f), Array.Empty<object>())); FlightClearanceMargin = config.Bind<float>("Movement", "FlightClearanceMargin", 0.3f, new ConfigDescription("Host-only: space kept between his head top and the ceiling, in metres. A lower ceiling brings him down, to the floor if needed.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 1f), Array.Empty<object>())); FlightClimbRate = config.Bind<float>("Movement", "FlightClimbRate", 0.8f, new ConfigDescription("Host-only: the fastest he rises or sinks while travelling, in metres per second. Obstacles no longer move him up or down; only a low ceiling does, at this rate.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.2f, 5f), Array.Empty<object>())); FlightSwayMeters = config.Bind<float>("Movement", "FlightSwayMeters", 0.15f, new ConfigDescription("Local to each player: how far he sways from side to side while flying, in metres.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 0.5f), Array.Empty<object>())); FlightTiltDegrees = config.Bind<float>("Movement", "FlightTiltDegrees", 12f, new ConfigDescription("Local to each player: the most he banks into turns, in degrees; he pitches forward up to 0.6 times this when speeding up.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 30f), Array.Empty<object>())); StandOff = config.Bind<float>("Combat", "StandOff", 1.9f, new ConfigDescription("Distance Passenger keeps from his target when he closes in or dips out of flight. He never attacks from here.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.5f, 8f), Array.Empty<object>())); TacticsEnabled = config.Bind<bool>("Combat", "TacticsEnabled", true, "Allow wall passes, lurks and floor or ceiling relocations alongside direct wall crossings."); ScrapThrowEnabled = config.Bind<bool>("Combat", "ScrapThrowEnabled", true, "When she is stalking a worker inside the facility and free scrap lies near her, she sometimes picks it up and throws it at them."); ScrapThrowDamage = config.Bind<int>("Combat", "ScrapThrowDamage", 20, new ConfigDescription("Damage a thrown scrap item deals to the worker she threw it at; bystanders in its path are not hit (no knockback).", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 100), Array.Empty<object>())); ScrapThrowCooldownSeconds = config.Bind<float>("Combat", "ScrapThrowCooldownSeconds", 45f, new ConfigDescription("Shortest time between two scrap throws by one Passenger.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(20f, 600f), Array.Empty<object>())); ScrapThrowsPerRound = config.Bind<int>("Combat", "ScrapThrowsPerRound", 2, new ConfigDescription("The most scrap throws across all Passengers in a round; 0 disables the scrap throw.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 10), Array.Empty<object>())); ScrapThrowRange = config.Bind<float>("Combat", "ScrapThrowRange", 14f, new ConfigDescription("Farthest distance to her target for a scrap throw; the nearest is 4 m.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(5f, 30f), Array.Empty<object>())); LiftEnabled = config.Bind<bool>("Combat", "LiftEnabled", true, "When a worker inside the facility turns their back on her within reach and the ceiling is high enough, she sometimes lifts them straight up, makes them drop the item in their hand, holds them there and lets them fall."); LiftCooldownSeconds = config.Bind<float>("Combat", "LiftCooldownSeconds", 60f, new ConfigDescription("Shortest time between two lifts by one Passenger, counted from the end of the last one.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(20f, 600f), Array.Empty<object>())); LiftsPerRound = config.Bind<int>("Combat", "LiftsPerRound", 2, new ConfigDescription("The most lifts across all Passengers in a round; 0 disables the lift.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 10), Array.Empty<object>())); LiftMinClearance = config.Bind<float>("Combat", "LiftMinClearance", 3f, new ConfigDescription("Least space in metres between the worker's head and the ceiling for a lift.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(2f, 10f), Array.Empty<object>())); LiftHeight = config.Bind<float>("Combat", "LiftHeight", 2.5f, new ConfigDescription("How far in metres she lifts a worker; a lower ceiling lowers it so their head stays 0.5 m clear.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.5f, 5f), Array.Empty<object>())); LiftHoldSeconds = config.Bind<float>("Combat", "LiftHoldSeconds", 3f, new ConfigDescription("Seconds she holds a lifted worker at the top before letting them fall.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.3f, 5f), Array.Empty<object>())); LiftReach = config.Bind<float>("Combat", "LiftReach", 2.5f, new ConfigDescription("Farthest distance in metres to a worker she can lift.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 5f), Array.Empty<object>())); LiftAttachBehind = config.Bind<float>("Combat", "LiftAttachBehind", 0.45f, new ConfigDescription("How far in metres behind the lifted worker's chest she holds them, from her pelvis.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.1f, 1.5f), Array.Empty<object>())); LiftAttachSide = config.Bind<float>("Combat", "LiftAttachSide", 0f, new ConfigDescription("Sideways shift in metres of her hold; positive is to the worker's right.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(-0.5f, 0.5f), Array.Empty<object>())); LiftAttachPelvisBelowChest = config.Bind<float>("Combat", "LiftAttachPelvisBelowChest", 0.2f, new ConfigDescription("How far in metres her pelvis sits below the lifted worker's chest while she holds them.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(-0.5f, 1f), Array.Empty<object>())); LungeEnabled = config.Bind<bool>("Combat", "LungeEnabled", true, "She can materialize 2.5 m in front of a worker at eye height, sweep through them and dissolve. A haunting beat the director picks, so it needs Abilities.WallPhasingEnabled."); LungeCooldownSeconds = config.Bind<float>("Combat", "LungeCooldownSeconds", 20f, new ConfigDescription("Seconds between lunges (half after an interrupted lunge).", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 600f), Array.Empty<object>())); LungeMinRange = config.Bind<float>("Combat", "LungeMinRange", 5f, new ConfigDescription("Closest distance to the worker a lunge starts from.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(2f, 15f), Array.Empty<object>())); LungeMaxRange = config.Bind<float>("Combat", "LungeMaxRange", 12f, new ConfigDescription("Farthest distance to the worker a lunge starts from.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(3f, 16f), Array.Empty<object>())); LungeSpeed = config.Bind<float>("Combat", "LungeSpeed", 14f, new ConfigDescription("Speed in m/s of her hidden approach to the start of the lunge line (the approach lasts 0.3-0.9 s).", (AcceptableValueBase)(object)new AcceptableValueRange<float>(4f, 40f), Array.Empty<object>())); LungeReappearDelay = config.Bind<float>("Combat", "LungeReappearDelay", 1.2f, new ConfigDescription("Seconds the possession dive stays hidden after a missed dive (on top of 0.3 s) before she reappears 4-7 m from the worker. Lunges do not use it.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.3f, 5f), Array.Empty<object>())); LungeSweepDamage = config.Bind<int>("Combat", "LungeSweepDamage", 10, new ConfigDescription("Damage of each lunge swipe that connects. Every lunge swipes the same number of times; a worker who stays in her path takes all of them (0 = the lunge never hurts).", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 50), Array.Empty<object>())); LungeSwipeCount = config.Bind<int>("Combat", "LungeSwipeCount", 3, new ConfigDescription("Swipes in every lunge pass, spread evenly over its pass; each can land once.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 5), Array.Empty<object>())); WallPhasingEnabled = config.Bind<bool>("Abilities", "WallPhasingEnabled", true, "Allow paced ghost combat and independent wall traversal while exploring."); PhaseCooldown = config.Bind<float>("Abilities", "PhaseCooldown", 5f, new ConfigDescription("Base spacing after a completed wall action before the next one (varied by 0.75-1.2x, at least 3 seconds), and the cooldown between escape crossings while fleeing. Ghost combat uses the Haunt section.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 60f), Array.Empty<object>())); ManifestPressureSeconds = config.Bind<float>("Combat", "ManifestPressureSeconds", 3f, new ConfigDescription("Useful visible movement time between ghost actions; a blocked route ends early.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(2f, 6f), Array.Empty<object>())); RevealAfterUnseen = config.Bind<int>("Abilities", "RevealAfterUnseen", 2, new ConfigDescription("Host-only: after this many emergences go unseen by the target for 3 seconds, prefer a visible side or front exit 5-8 m away with a clear line of sight. A seen emergence resets the streak; 0 disables this preference. If no reveal candidate is safe, use the normal exit choice.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 10), Array.Empty<object>())); ConcealWallWeight = BindGhostWeight(config, "ConcealWallWeight", 50f, "Surface Passenger uses to leave and to re-enter the room during a concealment: walls."); ConcealFloorWeight = BindGhostWeight(config, "ConcealFloorWeight", 25f, "Surface Passenger uses to leave and to re-enter the room during a concealment: the floor (sinks in, rises 2-8 m from the worker)."); ConcealCeilingWeight = BindGhostWeight(config, "ConcealCeilingWeight", 25f, "Surface Passenger uses to leave and to re-enter the room during a concealment: the ceiling (rises in, drops 2-8 m from the worker; ceilings 2.6-6 m high)."); GhostFloorWeight = config.Bind<float>("Combat", "GhostFloorWeight", 30f, new ConfigDescription("Weight for a concealment that needs no wall: Passenger sinks into the floor where she stands and reappears from the floor or ceiling 2-8 m from the worker.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 100f), Array.Empty<object>())); GhostTraversalWeight = config.Bind<float>("Combat", "GhostTraversalWeight", 40f, new ConfigDescription("Relative preference for a useful continuous wall crossing.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 100f), Array.Empty<object>())); WallPassSpeed = BindSpeed(config, "WallPassSpeed", 8f, "Movement speed during a committed pass between walls."); WallPassWeight = BindGhostWeight(config, "WallPassWeight", 35f, "Visible passes between two walls."); PursuitBreachWeight = BindGhostWeight(config, "PursuitBreachWeight", 12f, "Direct wall crossings toward a nearby target."); WallLurkWeight = BindGhostWeight(config, "WallLurkWeight", 8f, "Longer hidden returns, occasionally from behind."); HallwayCrossEnabled = config.Bind<bool>("Combat", "HallwayCrossEnabled", true, "Host-only: allow the hallway drive-by. When the target looks down a corridor, Passenger comes out of one side wall 8-10 m ahead and crosses straight into the opposite wall without stopping, turning or attacking, then stays hidden. It is one of the director's reveal beats, offered only when the corridor qualifies and the target's drive-by cooldown is ready."); HallwayCrossMinDistance = config.Bind<float>("Combat", "HallwayCrossMinDistance", 8f, new ConfigDescription("Nearest distance in front of the target at which a hallway drive-by crosses. A max below the min is treated as the min.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(4f, 20f), Array.Empty<object>())); HallwayCrossMaxDistance = config.Bind<float>("Combat", "HallwayCrossMaxDistance", 10f, new ConfigDescription("Farthest distance in front of the target at which a hallway drive-by crosses.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(4f, 20f), Array.Empty<object>())); HallwayCrossMaxSideDistance = config.Bind<float>("Combat", "HallwayCrossMaxSideDistance", 2f, new ConfigDescription("Widest a corridor may be for a hallway drive-by: each side wall must be within this distance of the crossing point, facing the other.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 3f), Array.Empty<object>())); HallwayCrossSpeed = config.Bind<float>("Combat", "HallwayCrossSpeed", 8f, new ConfigDescription("Speed of the hallway drive-by from one side wall to the other, in metres per second.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(4f, 14f), Array.Empty<object>())); HallwayCrossCooldownMin = config.Bind<float>("Combat", "HallwayCrossCooldownMin", 60f, new ConfigDescription("Shortest wait before the same worker sees another hallway drive-by, picked at random between Min and Max. A Max below Min is treated as Min.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 600f), Array.Empty<object>())); HallwayCrossCooldownMax = config.Bind<float>("Combat", "HallwayCrossCooldownMax", 90f, new ConfigDescription("Longest wait before the same worker sees another hallway drive-by.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 600f), Array.Empty<object>())); PossessionEnabled = config.Bind<bool>("Abilities", "PossessionEnabled", true, "Allow Passenger to possess eligible workers."); PossessionDurationSeconds = config.Bind<float>("Abilities", "PossessionDurationSeconds", 21.3f, new ConfigDescription("Base possession duration in seconds.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 120f), Array.Empty<object>())); PossessionCooldownPerPlayerSeconds = config.Bind<float>("Abilities", "PossessionCooldownPerPlayerSeconds", 90f, new ConfigDescription("Seconds before the same worker can be possessed again.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 600f), Array.Empty<object>())); PossessedFriendlyFire = config.Bind<bool>("Abilities", "PossessedFriendlyFire", true, "Allow a possessed worker to attack teammates."); PossessedAttacksEnabled = config.Bind<bool>("Abilities", "PossessedAttacksEnabled", true, "Allow Passenger to force possessed workers to perform claw attacks."); PossessedAttackCooldownSeconds = config.Bind<float>("Abilities", "PossessedAttackCooldownSeconds", 1.6f, new ConfigDescription("Seconds between forced attacks by a possessed worker.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.1f, 30f), Array.Empty<object>())); PossessedAttackDamage = config.Bind<int>("Abilities", "PossessedAttackDamage", 10, new ConfigDescription("Damage dealt when a possessed worker hits a teammate.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 100), Array.Empty<object>())); BindPossession(config); PhaseVfxEnabled = config.Bind<bool>("Audio and Presentation", "PhaseVfxEnabled", true, "Show brief monochrome disturbances on entry/exit walls and body breakup during transit; clear both on emergence."); PossessionLoopVolume = config.Bind<float>("Audio and Presentation", "PossessionLoopVolume", 0.7f, new ConfigDescription("Volume of the local possession loop.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 1f), Array.Empty<object>())); PossessedVoiceFilterEnabled = config.Bind<bool>("Audio and Presentation", "PossessedVoiceFilterEnabled", true, "Apply Passenger's authored voice effect to a possessed worker."); FaceHeight = config.Bind<float>("Audio and Presentation", "FaceHeight", 2.3f, new ConfigDescription("Height of Passenger's face above the floor while she floats, in metres. Below her authored 3.29 m her whole body floats lower so workers meet her face nearer eye level; her arm swings and floor and ceiling emergences keep their authored height, she drops to it when she dies, and low ceilings lower her further on each machine (never below a 1.6 m jaw). It also places her face for the emergence check that spaces the doorway face per worker (ScreamRange, ScreamConeDegrees). Host-only: every player sees her at the host's value, taken when she spawns.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1.6f, 3.3f), Array.Empty<object>())); ScreamWindowSeconds = config.Bind<float>("Audio and Presentation", "ScreamWindowSeconds", 3f, new ConfigDescription("Seconds after Passenger has fully emerged from a wall, floor or ceiling during which a worker who looks at her face counts as having met it. The emergence is silent (W10-S1); a worker who met her face is then spared another doorway face for 15 seconds. Host-only.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.5f, 10f), Array.Empty<object>())); ScreamRange = config.Bind<float>("Audio and Presentation", "ScreamRange", 12f, new ConfigDescription("Greatest distance from a worker's eyes to Passenger's face at which looking at her as she emerges counts as meeting her face, which spaces the doorway face per worker (she makes no sound). Host-only.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(2f, 20f), Array.Empty<object>())); ScreamConeDegrees = config.Bind<float>("Audio and Presentation", "ScreamConeDegrees", 60f, new ConfigDescription("Full width, in degrees, of the cone around a worker's view direction that Passenger's face must be inside as she emerges for the worker to count as meeting her face, which spaces the doorway face per worker (she makes no sound). Host-only.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(10f, 120f), Array.Empty<object>())); LightFlickerEnabled = config.Bind<bool>("Audio and Presentation", "LightFlickerEnabled", true, "Allows the light flicker and lights-out haunts in the director's ambient haunt table while she is hidden; off sets the weights of both to 0 (LightFlickerWeight, LightsOutWeight). Each player's own value also decides whether that player sees them."); LightFlickerCooldownSeconds = config.Bind<float>("Audio and Presentation", "LightFlickerCooldownSeconds", 8f, new ConfigDescription("Shortest time between two light haunts from the same hidden Passenger. The light flicker and lights-out haunts share this one cooldown. Each player's own value decides what that player sees.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(2f, 60f), Array.Empty<object>())); DoorSlamEnabled = config.Bind<bool>("Audio and Presentation", "DoorSlamEnabled", true, "Host-only: allows the door-closing haunt in the director's ambient haunt table while she is hidden; off sets its weight to 0 (DoorCloseWeight). When the haunt is rolled, she slams the open, unlocked door nearest the haunted worker (within 15 m of that worker) shut, opens and slams it again a couple of times with the game's own door sounds, and normally leaves it shut. Chance-gated doors are never used. Only starts with a worker within 20 m of the door and none within 1 m. Clearance, door use and concealment are rechecked before every close and reopen; a worker approaching within 1 m during an open interval stops the sequence and leaves the door open. Spaced by DoorSlamCooldownSeconds."); DoorSlamCooldownSeconds = config.Bind<float>("Audio and Presentation", "DoorSlamCooldownSeconds", 45f, new ConfigDescription("Host-only: shortest time between two door slams by the same Passenger.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(10f, 600f), Array.Empty<object>())); BindVoice(config); VisibleFloorFraction = config.Bind<float>("Haunt", "VisibleFloorFraction", 0.1f, new ConfigDescription("From the second escalation phase on, the director keeps her visible at least this share of the encounter (the sounds-only first phase does not count). Below it, once 30 s have been measured, the current hidden window may end after HiddenWindowFloorCutSeconds and a reveal comes next, preferring the Watcher. A floor above VisibleCeilingFraction is swapped with it. Default 0.10 (S1 #509; was 0.25).", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 1f), Array.Empty<object>())); VisibleCeilingFraction = config.Bind<float>("Haunt", "VisibleCeilingFraction", 0.2f, new ConfigDescription("From the second escalation phase on, no new reveal starts while the share of the encounter during which a worker sees her is above this; she stays hidden until it falls back. Contact and possession attempts, and the encounter's one first glimpse, are not held back. Default 0.20 (S1 #509; was 0.35).", (AcceptableValueBase)(object)new AcceptableVal
Y4NGZScissorsCreature.dll
Decompiled a day ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security.Cryptography; using System.Text; using System.Text.RegularExpressions; using System.Threading; using BepInEx; using BepInEx.Configuration; using BepInEx.Logging; using Dawn; using GameNetcodeStuff; using HarmonyLib; using Microsoft.CodeAnalysis; using Unity.Netcode; using UnityEngine; using UnityEngine.AI; using UnityEngine.Audio; using UnityEngine.Networking; using UnityEngine.SceneManagement; using Y4NGZMonsters.Shared; using Y4NGZScissorsCreature.NetcodePatcher; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: AssemblyCompany("Y4NGZScissorsCreature")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0+3460ec64f0cec4948e51ddb3f02a4b0e414f105e")] [assembly: AssemblyProduct("Y4NGZScissorsCreature")] [assembly: AssemblyTitle("Y4NGZScissorsCreature")] [assembly: AssemblyVersion("1.0.0.0")] [module: RefSafetyRules(11)] [module: NetcodePatchedAssembly] 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 Y4NGZScissorsCreature { public sealed class ScissorsCreatureAI : EnemyAI { public const int StateIdleWalk = 0; public const int StateWindupWalk = 1; public const int StateRushSnipping = 2; public const int StateFallingApart = 3; internal const string IdleWalkTrigger = "DoIdleWalk"; internal const string WindupWalkTrigger = "DoWindupWalk"; internal const string RushSnippingTrigger = "DoRushSnipping"; internal const string FootstepsChildName = "Footsteps"; [Header("Scissors Creature anchors")] public Transform attackOrigin; public Transform wheelBone; public Collider bodyBlockerCollider; [Header("Scissors Creature audio")] public AudioClip windupClip; public AudioClip attackedByPlayerClip; public AudioClip footstepClip; public AudioClip attackRunClip; public AudioClip tickingClip; public AudioClip alarmClip; public AudioClip idleGrowlClip; public AudioClip snipKillClip; public AudioClip fallApartClip; public AudioClip[] snipClips; public AudioClip[] rushStepClips = (AudioClip[])(object)new AudioClip[0]; public AudioSource tickingAudioSource; public AudioSource alarmAudioSource; public AudioSource footstepAudioSource; private const float ScissorsDamageBehindOrigin = 1.1f; private const float ScissorsDamageAheadOfOrigin = 2.75f; private const float ScissorsDamageHalfWidth = 1.35f; private const float ScissorsDamageBelowOrigin = 0.75f; private const float ScissorsDamageAboveOrigin = 1.35f; private const float ScissorsApproachDistance = 2.35f; private const float ScissorsRushStoppingDistance = 0.6f; private const int ScissorsHittableForce = 2; private const float SnipjackDoorwayAgentRadius = 0.46071577f; private const float ScissorsNavigationRadius = 0.46071577f; private const float ScissorsIdleStoppingDistance = 0f; private const float ScissorsProgressSpeedFraction = 0.25f; private const float ScissorsStuckRecoverySeconds = 1.2f; private const float ScissorsOffMeshRepairInterval = 0.8f; private const float NavigationDoorProbeRadius = 0.75f; private const float AttackOverlapInterval = 0.15f; private const int EnemiesLayerFallback = 19; private const int MapHazardsLayerFallback = 21; private const int InteractableObjectLayerFallback = 9; private const float AttackedByPlayerVolume = 9f; private const float SnipKillVolume = 2.8f; private const float FallApartVolume = 2.2f; private const float NoiseMinLoudness = 0.5f; private const float NoiseHearingRange = 20f; private const float NoiseMemorySeconds = 3f; private const float NoiseReseedCooldown = 4f; private const int NoiseMaxRepeatsInOneSpot = 10; private const float WheelConnectorRadius = 0.055f; private const float HeadTrackAbandonYawDegrees = 100f; private const float HeadTrackSearchInterval = 0.25f; private const float HeadTrackDeadZoneDegrees = 0.4f; private const int NoTargetSlot = -1; private const int DefaultAttackDamage = 35; private const int SnipDeathAnimation = 7; private const string FallApartAnimatorState = "FallApart"; private const float FootstepMinSpeed = 0.1f; private const float MeasuredSpeedSmoothingSeconds = 0.3f; private static readonly string[] StunnedAnimatorBoolNames = new string[3] { "stunned", "Stunned", "stun" }; private static readonly Vector3 WheelFallbackLocalPosition = new Vector3(0f, 2.9422f, -0.55f); private static readonly Vector3 WheelConnectorBodyAnchorLocalPosition = new Vector3(0f, 2.9422f, -0.12f); private static readonly FieldRef<EnemyAI, float> VanillaTargetYaw = AccessTools.FieldRefAccess<EnemyAI, float>("targetYRotation"); private static readonly int IdleWalkTriggerHash = Animator.StringToHash("DoIdleWalk"); private static readonly int WindupWalkTriggerHash = Animator.StringToHash("DoWindupWalk"); private static readonly int RushSnippingTriggerHash = Animator.StringToHash("DoRushSnipping"); private static readonly int IdleWalkStateHash = Animator.StringToHash("IdleWalk"); private static readonly int WindupWalkStateHash = Animator.StringToHash("WindupWalk"); private const string TurnLeftState = "TurnLeft"; private const string TurnRightState = "TurnRight"; private const string MoveSpeedParameter = "MoveSpeed"; private const string TurningParameter = "Turning"; private const string TurnDirectionParameter = "TurnDirection"; private const string MovingParameter = "Moving"; private readonly RaycastHit[] _lineOfSightHits = (RaycastHit[])(object)new RaycastHit[32]; private readonly Collider[] _attackOverlapResults = (Collider[])(object)new Collider[64]; private readonly Dictionary<ulong, float> _lastDamageTimes = new Dictionary<ulong, float>(); private readonly Dictionary<int, float> _lastHittableDamageTimes = new Dictionary<int, float>(); private readonly Collider[] _doorProbeResults = (Collider[])(object)new Collider[16]; private readonly NoiseMemory _noiseMemory = new NoiseMemory(); private float _windupTimer; private float _rushDeadline; private float _snipAudioTimer; private float _footstepAudioTimer; private float _stepEventGap; private bool _stepEventArrived; private float _lastFootstepSoundTime = float.NegativeInfinity; private bool _loggedTimerFootsteps; private float _idleGrowlTimer; private int _tickingRepeatCount; private Vector3 _lastKnownTargetPosition; private float _lastTargetContactTime; private float _currentTargetLastContactTime; private Transform _wheelConnector; private Quaternion _wheelBaseLocalRotation = Quaternion.identity; private float _wheelVisualAngle; private Vector3 _lastNavigationRecoveryPosition; private float _navigationStuckTimer; private float _nextAgentRepairTime; private bool _capturedWheelBase; private bool _windupTickingActive; private Transform _headTrackBone; private bool _headTrackCalibrated; private Quaternion _headTrackBaseLocalRotation = Quaternion.identity; private Vector3 _headTrackFaceLocalAxis = Vector3.forward; private float _headTrackYawDegrees; private float _headTrackPitchDegrees; private float _nextHeadTrackSearchTime; private PlayerControllerB _headTrackTarget; private readonly NoiseMemory _listenNoise = new NoiseMemory(); private float _listenHeldSeconds; private bool _listenGlanceActive; private float _listenGlanceSeconds; private float _listenReleaseSeconds; private float _listenReleaseYawRate; private float _listenReleasePitchRate; private bool _audioRouted; private readonly ServerOwnershipGuard _ownershipGuard = new ServerOwnershipGuard(); private readonly NetworkVariable<int> _networkState = new NetworkVariable<int>(0, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); private readonly NetworkVariable<int> _networkTargetSlot = new NetworkVariable<int>(-1, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); private readonly NetworkVariable<int> _networkAttackDamage = new NetworkVariable<int>(35, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); private readonly NetworkVariable<Vector3> _networkCorpsePosition = new NetworkVariable<Vector3>(Vector3.zero, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); private readonly NetworkVariable<float> _networkCorpseYaw = new NetworkVariable<float>(0f, (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0); private bool _wasStunned; private float _stunStartTime; private int _stunnedAnimatorHash; private Vector3 _lastFootstepPosition; private float _measuredSpeed; private float _rawSpeed; private float _lastYawDegrees; private float _yawRate; private bool _walkHold; private bool _turnInPlaceActive; private readonly Vector3[] _turnGateCorners = (Vector3[])(object)new Vector3[8]; private bool _locomotionParametersResolved; private int _moveSpeedParameterHash; private int _turningParameterHash; private int _turnDirectionParameterHash; private int _movingParameterHash; private bool _turnStatesResolved; private float _roamTurnRate = 11.7f; private static bool _loggedRoamTurnRate; private float _attackOverlapTimer; private int _attackOverlapMask; private int _doorProbeMask; private int _appliedAgentState = -1; private bool _navigationRepathed; private float _nextNoiseReseedTime; private Material _connectorMaterial; private bool _fallApartBegun; private bool _fellApart; private bool _loggedRefusedSwitch; private Transform _connectorAnchorParent; private Vector3 _connectorAnchorOnParent; private readonly SnipjackRoamVisitMemory _roamVisits = new SnipjackRoamVisitMemory(); private readonly List<(int node, float flatDistance)> _roamNodes = new List<(int, float)>(); private readonly List<SnipjackRoamCandidate> _roamShortlist = new List<SnipjackRoamCandidate>(8); private readonly List<(int node, float pathLength, bool complete)> _roamProbes = new List<(int, float, bool)>(8); private readonly Vector3[] _roamProbePoints = (Vector3[])(object)new Vector3[8]; private readonly Vector3[] _roamCorners = (Vector3[])(object)new Vector3[32]; private Random _roamRandom; private NavMeshPath _roamPath; private bool _roamLegActive; private int _roamNode = -1; private Vector3 _roamDestination; private float _roamPathLength; private float _roamLegStartedAt; private float _roamProgressDistance; private float _roamSecondsWithoutProgress; private float _roamListenUntil; private bool _roamFallback; private float _nextRoamRetryTime; private float WalkSpeed { get { if (Plugin.ModConfig == null) { return 0.286f; } return Plugin.ModConfig.WalkSpeed.Value; } } private float WalkPlaybackScale { get { if (Plugin.ModConfig == null) { return 1f; } return Plugin.ModConfig.WalkPlaybackScale.Value; } } private float WindupMoveSpeed => 0.05f; private float WalkTurnSpeed => 11.7f; private float RushSpeed { get { if (Plugin.ModConfig == null) { return 6.24f; } return Plugin.ModConfig.RushSpeed.Value; } } private float TurnBeforeMoveDegrees { get { if (Plugin.ModConfig == null) { return 12f; } return Plugin.ModConfig.TurnBeforeMoveDegrees.Value; } } private float RoamTurnInPlaceSpeed { get { if (Plugin.ModConfig == null) { return 90f; } return Plugin.ModConfig.RoamTurnInPlaceSpeed.Value; } } private float WindupTurnInPlaceSpeed { get { if (Plugin.ModConfig == null) { return 60f; } return Plugin.ModConfig.WindupTurnInPlaceSpeed.Value; } } private float DetectionRange { get { if (Plugin.ModConfig == null) { return 28f; } return Plugin.ModConfig.DetectionRange.Value; } } private float DetectionWidth => 75f; private float ProximityAwareness => 4f; private float WindupDuration { get { if (Plugin.ModConfig == null) { return 12f; } return Plugin.ModConfig.WindupDuration.Value; } } private float ChaseDuration { get { if (Plugin.ModConfig == null) { return 8f; } return Plugin.ModConfig.ChaseDuration.Value; } } private float AttackDamageCooldown => 0.45f; private int ConfiguredAttackDamage { get { if (Plugin.ModConfig == null) { return 35; } return Plugin.ModConfig.AttackDamage.Value; } } private float DisengageDistance => 20f; private float LostContactGracePeriod => 7f; private bool HeadTrackingEnabled => true; private float HeadTrackingRange => 18f; private float HeadTrackingMaxYaw => Mathf.Clamp(22f, 0f, 45f); private float HeadTrackingMaxPitch => Mathf.Clamp(12f, 0f, 30f); private float HeadTrackingTurnSpeed => 90f; private bool RoamListening => _roamListenUntil > Time.time; private bool CanNavigateRoam { get { if ((Object)(object)base.agent != (Object)null && ((Behaviour)base.agent).enabled) { return base.agent.isOnNavMesh; } return false; } } public override void Awake() { try { ((EnemyAI)this).Awake(); ResolveRuntimeReferences(); } catch (Exception arg) { Plugin.Log.LogError((object)$"[ScissorsCreatureAI] Awake failed: {arg}"); } } public override void Start() { //IL_009f: Unknown result type (might be due to invalid IL or missing references) //IL_00a4: Unknown result type (might be due to invalid IL or missing references) //IL_00b0: Unknown result type (might be due to invalid IL or missing references) //IL_00b5: Unknown result type (might be due to invalid IL or missing references) //IL_00c1: Unknown result type (might be due to invalid IL or missing references) try { ((EnemyAI)this).Start(); Plugin.EnsureScanNode(((Component)this).gameObject); ResolveRuntimeReferences(); _audioRouted = RouteAudioSources(); _idleGrowlTimer = Random.Range(2f, 6f); _attackOverlapMask = (1 << ResolveLayer("Enemies", 19)) | (1 << ResolveLayer("MapHazards", 21)); _doorProbeMask = 1 << ResolveLayer("InteractableObject", 9); ApplyFixedBodyAndAgentSettings(); ConfigureAgentForState(base.currentBehaviourStateIndex); if (((NetworkBehaviour)this).IsServer) { InitializeRoam(); } _lastNavigationRecoveryPosition = ((Component)this).transform.position; _lastFootstepPosition = ((Component)this).transform.position; _lastYawDegrees = ((Component)this).transform.eulerAngles.y; if ((Object)(object)base.creatureAnimator != (Object)null) { base.creatureAnimator.applyRootMotion = false; if (!_fellApart) { ((EnemyAI)this).PlayAnimationOfCurrentState(); } _stunnedAnimatorHash = FindStunnedAnimatorBool(base.creatureAnimator); } if (_fellApart) { DisableCreatureColliders(); } } catch (Exception arg) { Plugin.Log.LogError((object)$"[ScissorsCreatureAI] Start failed: {arg}"); } } public override void OnNetworkSpawn() { ((NetworkBehaviour)this).OnNetworkSpawn(); if (((NetworkBehaviour)this).IsServer) { _networkAttackDamage.Value = Mathf.Max(0, ConfiguredAttackDamage); _networkState.Value = base.currentBehaviourStateIndex; return; } NetworkVariable<int> networkState = _networkState; networkState.OnValueChanged = (OnValueChangedDelegate<int>)(object)Delegate.Combine((Delegate?)(object)networkState.OnValueChanged, (Delegate?)(object)new OnValueChangedDelegate<int>(OnNetworkStateChanged)); NetworkVariable<int> networkTargetSlot = _networkTargetSlot; networkTargetSlot.OnValueChanged = (OnValueChangedDelegate<int>)(object)Delegate.Combine((Delegate?)(object)networkTargetSlot.OnValueChanged, (Delegate?)(object)new OnValueChangedDelegate<int>(OnNetworkTargetSlotChanged)); if (_networkState.Value == 3) { EnterFallApartLocal(instant: true); } ApplyNetworkState(_networkState.Value); base.targetPlayer = VictimRpc.FromSlot(_networkTargetSlot.Value); } public override void OnNetworkDespawn() { if (((NetworkBehaviour)this).IsServer) { ClearRoamState(); } NetworkVariable<int> networkState = _networkState; networkState.OnValueChanged = (OnValueChangedDelegate<int>)(object)Delegate.Remove((Delegate?)(object)networkState.OnValueChanged, (Delegate?)(object)new OnValueChangedDelegate<int>(OnNetworkStateChanged)); NetworkVariable<int> networkTargetSlot = _networkTargetSlot; networkTargetSlot.OnValueChanged = (OnValueChangedDelegate<int>)(object)Delegate.Remove((Delegate?)(object)networkTargetSlot.OnValueChanged, (Delegate?)(object)new OnValueChangedDelegate<int>(OnNetworkTargetSlotChanged)); ((NetworkBehaviour)this).OnNetworkDespawn(); } private void OnNetworkStateChanged(int previous, int next) { ApplyNetworkState(next); if (next == 3) { EnterFallApartLocal(instant: false); } } private void ApplyNetworkState(int state) { if (base.enemyBehaviourStates != null && state >= 0 && state < base.enemyBehaviourStates.Length) { if (state != 1) { _windupTickingActive = false; } if (state != base.currentBehaviourStateIndex && SnipjackLifecycle.CanSwitchState(base.currentBehaviourStateIndex, state)) { ((EnemyAI)this).SwitchToBehaviourStateOnLocalClient(state); } } } private void OnNetworkTargetSlotChanged(int previous, int next) { base.targetPlayer = VictimRpc.FromSlot(next); } public override void Update() { try { if (_networkState.Value == 3) { PinCorpsePose(); } _ownershipGuard.Ensure((EnemyAI)(object)this, Plugin.Log); ((EnemyAI)this).Update(); if (!_audioRouted) { _audioRouted = RouteAudioSources(); } if (((NetworkBehaviour)this).IsServer && base.currentBehaviourStateIndex == 2 && SnipjackLifecycle.RushExpired(Time.time, _rushDeadline)) { BeginFallApart(); } else { if (base.isEnemyDead || (Object)(object)StartOfRound.Instance == (Object)null) { return; } if (StartOfRound.Instance.allPlayersDead) { StopAllLoops(); return; } if ((Object)(object)base.creatureAnimator != (Object)null) { base.creatureAnimator.applyRootMotion = false; } StunEdge stunEdge = ((EnemyAI)(object)this).TrackStun(ref _wasStunned); if (stunEdge != StunEdge.None) { OnStunEdge(stunEdge); } if (((NetworkBehaviour)this).IsServer) { if (_wasStunned) { ((EnemyAI)(object)this).HoldAgent(); } else { TickServerState(Time.deltaTime); TickTurnInPlaceGate(Time.deltaTime); RepairAgentIfNeeded(); TickRoamProgress(Time.deltaTime); TickNavigationRecovery(Time.deltaTime); } } TickMeasuredSpeed(Time.deltaTime); TickLocomotionAnimator(Time.deltaTime); TickAttackAlarmAudio(); TickIdleGrowlAudio(Time.deltaTime); if (!_wasStunned) { TickFootstepAudio(Time.deltaTime); TickWindupTickingAudio(); TickSnipAudio(Time.deltaTime); DamageObjectsInAttackVolume(Time.deltaTime); } } } catch (Exception arg) { Plugin.Log.LogError((object)$"[ScissorsCreatureAI] Update failed: {arg}"); } } private void OnStunEdge(StunEdge edge) { bool flag = edge == StunEdge.Started; if (_stunnedAnimatorHash != 0 && (Object)(object)base.creatureAnimator != (Object)null) { base.creatureAnimator.SetBool(_stunnedAnimatorHash, flag); } if (flag) { PlayAttackedByPlayerAudio(); } if (!((NetworkBehaviour)this).IsServer) { return; } if (flag) { _stunStartTime = Time.time; ClearRoamState(); _turnInPlaceActive = false; ((EnemyAI)(object)this).HoldAgent(); return; } if (base.currentBehaviourStateIndex == 1) { float num = Time.time - _stunStartTime; _currentTargetLastContactTime = Mathf.Min(_currentTargetLastContactTime + num, Time.time); _lastTargetContactTime = Mathf.Min(_lastTargetContactTime + num, Time.time); } ((EnemyAI)(object)this).ReleaseAgent(); ResetNavigationRecovery(); if (base.currentBehaviourStateIndex == 0) { DoIdleWalk(); } } private static int FindStunnedAnimatorBool(Animator animator) { //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Invalid comparison between Unknown and I4 if ((Object)(object)animator.runtimeAnimatorController == (Object)null) { return 0; } AnimatorControllerParameter[] parameters = animator.parameters; foreach (AnimatorControllerParameter val in parameters) { if ((int)val.type == 4 && Array.IndexOf(StunnedAnimatorBoolNames, val.name) >= 0) { return val.nameHash; } } return 0; } private void TickMeasuredSpeed(float deltaTime) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_001a: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Unknown result type (might be due to invalid IL or missing references) Vector3 position = ((Component)this).transform.position; Vector3 val = position - _lastFootstepPosition; _lastFootstepPosition = position; if (!(deltaTime <= 0f)) { val.y = 0f; float num = (_rawSpeed = ((Vector3)(ref val)).magnitude / deltaTime); _measuredSpeed = Mathf.Lerp(_measuredSpeed, num, 1f - Mathf.Exp((0f - deltaTime) / 0.3f)); } } private void TickLocomotionAnimator(float deltaTime) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) float y = ((Component)this).transform.eulerAngles.y; if (deltaTime > 0f) { float num = Mathf.DeltaAngle(_lastYawDegrees, y) / deltaTime; _yawRate = Mathf.Lerp(_yawRate, num, 1f - Mathf.Exp((0f - deltaTime) / 0.15f)); } _lastYawDegrees = y; bool flag = base.currentBehaviourStateIndex == 0 || base.currentBehaviourStateIndex == 1; float commandedSpeed = ((base.currentBehaviourStateIndex == 1) ? WindupMoveSpeed : WalkSpeed); _walkHold = flag && !_wasStunned && SnipjackLocomotion.NextWalkHold(_walkHold, _rawSpeed, _measuredSpeed, Mathf.Abs(_yawRate), commandedSpeed); if (!((Object)(object)base.creatureAnimator == (Object)null) && !((Object)(object)base.creatureAnimator.runtimeAnimatorController == (Object)null)) { if (!_locomotionParametersResolved) { ResolveLocomotionParameters(base.creatureAnimator); } if (!_turnStatesResolved && base.creatureAnimator.isInitialized) { ResolveTurnStates(base.creatureAnimator); } bool flag2 = !_wasStunned && flag && Mathf.Abs(_yawRate) >= 30f; if (_moveSpeedParameterHash != 0) { base.creatureAnimator.SetFloat(_moveSpeedParameterHash, _measuredSpeed); } if (_turningParameterHash != 0) { base.creatureAnimator.SetBool(_turningParameterHash, flag2); } if (flag2 && _turnDirectionParameterHash != 0) { base.creatureAnimator.SetFloat(_turnDirectionParameterHash, Mathf.Sign(_yawRate)); } if (_movingParameterHash != 0) { base.creatureAnimator.SetBool(_movingParameterHash, !_walkHold); } base.creatureAnimator.speed = ((_wasStunned || !flag) ? 1f : WalkClipPlaybackSpeed(base.creatureAnimator, deltaTime)); } } private float WalkClipPlaybackSpeed(Animator animator, float deltaTime) { //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Unknown result type (might be due to invalid IL or missing references) AnimatorStateInfo val = (animator.IsInTransition(0) ? animator.GetNextAnimatorStateInfo(0) : animator.GetCurrentAnimatorStateInfo(0)); float referenceSpeed; if (((AnimatorStateInfo)(ref val)).shortNameHash == IdleWalkStateHash) { referenceSpeed = 0.286f; } else { if (((AnimatorStateInfo)(ref val)).shortNameHash != WindupWalkStateHash) { return 1f; } referenceSpeed = 0.183f; } if (!_walkHold) { return SnipjackLocomotion.WalkPlaybackSpeed(_measuredSpeed, referenceSpeed, WalkPlaybackScale); } return SnipjackLocomotion.HoldPlaybackSpeed(animator.speed, deltaTime); } private void ResolveLocomotionParameters(Animator animator) { //IL_001a: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Invalid comparison between Unknown and I4 //IL_0043: Unknown result type (might be due to invalid IL or missing references) //IL_0049: Invalid comparison between Unknown and I4 //IL_006c: Unknown result type (might be due to invalid IL or missing references) //IL_0072: Invalid comparison between Unknown and I4 //IL_0095: Unknown result type (might be due to invalid IL or missing references) //IL_009b: Invalid comparison between Unknown and I4 _locomotionParametersResolved = true; AnimatorControllerParameter[] parameters = animator.parameters; foreach (AnimatorControllerParameter val in parameters) { if ((int)val.type == 1 && val.name == "MoveSpeed") { _moveSpeedParameterHash = val.nameHash; } else if ((int)val.type == 4 && val.name == "Turning") { _turningParameterHash = val.nameHash; } else if ((int)val.type == 1 && val.name == "TurnDirection") { _turnDirectionParameterHash = val.nameHash; } else if ((int)val.type == 4 && val.name == "Moving") { _movingParameterHash = val.nameHash; } } } private void ResolveTurnStates(Animator animator) { _turnStatesResolved = true; string layerPrefix = ((animator.layerCount > 0) ? (animator.GetLayerName(0) + ".") : null); bool flag = HasBaseLayerState(animator, layerPrefix, "TurnLeft"); bool flag2 = HasBaseLayerState(animator, layerPrefix, "TurnRight"); _roamTurnRate = SnipjackLocomotion.RoamAgentTurnRate(flag, flag2); if ((Object)(object)base.agent != (Object)null && _appliedAgentState == 0) { base.agent.angularSpeed = _roamTurnRate; } if (!_loggedRoamTurnRate) { _loggedRoamTurnRate = true; if (flag && flag2) { Plugin.Log.LogInfo((object)$"[ScissorsCreature] Roam turn rate {_roamTurnRate:0.#} deg/s: the controller has TurnLeft and TurnRight states."); } else { Plugin.Log.LogInfo((object)$"[ScissorsCreature] Roam turn rate {_roamTurnRate:0.#} deg/s: the controller has no TurnLeft/TurnRight states (in-place turns still use the stop-and-turn gate)."); } } } private static bool HasBaseLayerState(Animator animator, string layerPrefix, string stateName) { if (layerPrefix == null) { return false; } if (!animator.HasState(0, Animator.StringToHash(stateName))) { return animator.HasState(0, Animator.StringToHash(layerPrefix + stateName)); } return true; } private void LateUpdate() { try { if (!base.isEnemyDead) { TickWheelVisual(Time.deltaTime); } AlignWheelConnector(); if (!base.isEnemyDead) { TickHeadTracking(Time.deltaTime); } } catch (Exception arg) { Plugin.Log.LogError((object)$"[ScissorsCreatureAI] LateUpdate failed: {arg}"); } } private void TickHeadTracking(float deltaTime) { //IL_0087: Unknown result type (might be due to invalid IL or missing references) //IL_01d5: Unknown result type (might be due to invalid IL or missing references) //IL_0215: Unknown result type (might be due to invalid IL or missing references) //IL_021a: Unknown result type (might be due to invalid IL or missing references) //IL_0222: Unknown result type (might be due to invalid IL or missing references) //IL_0224: Unknown result type (might be due to invalid IL or missing references) //IL_0229: Unknown result type (might be due to invalid IL or missing references) //IL_022e: Unknown result type (might be due to invalid IL or missing references) //IL_0233: Unknown result type (might be due to invalid IL or missing references) //IL_023c: Unknown result type (might be due to invalid IL or missing references) //IL_0241: Unknown result type (might be due to invalid IL or missing references) //IL_0246: Unknown result type (might be due to invalid IL or missing references) //IL_026d: Unknown result type (might be due to invalid IL or missing references) //IL_0274: Unknown result type (might be due to invalid IL or missing references) //IL_0279: Unknown result type (might be due to invalid IL or missing references) //IL_0284: Unknown result type (might be due to invalid IL or missing references) //IL_0289: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)_headTrackBone == (Object)null || !HeadTrackingEnabled || !CalibrateHeadTracking()) { return; } _listenHeldSeconds = SnipjackListenLook.NextListenSeconds(_listenHeldSeconds, !base.isEnemyDead, _wasStunned, base.currentBehaviourStateIndex == 0, _walkHold, _yawRate, deltaTime); float yaw = 0f; float pitch = 0f; float num = HeadTrackingTurnSpeed; Vector3 focusPoint; bool num2 = TryGetHeadTrackFocusPoint(out focusPoint); bool flag = !num2 && SnipjackListenLook.IsListening(_listenHeldSeconds); if (num2) { if (TryGetHeadAim(focusPoint, out var yaw2, out var pitch2) && Mathf.Abs(yaw2) <= 100f) { yaw = Mathf.Clamp(yaw2, 0f - HeadTrackingMaxYaw, HeadTrackingMaxYaw); pitch = Mathf.Clamp(pitch2, 0f - HeadTrackingMaxPitch, HeadTrackingMaxPitch); } } else if (flag) { if (!_listenGlanceActive) { _listenGlanceSeconds = 0f; } GetListenGlanceTarget(out yaw, out pitch); _listenGlanceSeconds += deltaTime; num = 90f; } float num3 = num * 0.6f; if (flag) { _listenReleaseSeconds = 0f; } else if (_listenGlanceActive) { _listenReleaseSeconds = 0.3f; _listenReleaseYawRate = SnipjackListenLook.ReleaseRate(_headTrackYawDegrees, yaw, num); _listenReleasePitchRate = SnipjackListenLook.ReleaseRate(_headTrackPitchDegrees, pitch, num3); } _listenGlanceActive = flag; if (_listenReleaseSeconds > 0f) { num = _listenReleaseYawRate; num3 = _listenReleasePitchRate; _listenReleaseSeconds -= deltaTime; } _headTrackYawDegrees = SnipjackListenLook.Step(_headTrackYawDegrees, yaw, num, deltaTime); _headTrackPitchDegrees = SnipjackListenLook.Step(_headTrackPitchDegrees, pitch, num3, deltaTime); if (_headTrackYawDegrees == yaw && _headTrackPitchDegrees == pitch) { _listenReleaseSeconds = 0f; } _headTrackBone.localRotation = _headTrackBaseLocalRotation; if (!(Mathf.Abs(_headTrackYawDegrees) < 0.4f) || !(Mathf.Abs(_headTrackPitchDegrees) < 0.4f)) { Quaternion val = Quaternion.Euler(_headTrackPitchDegrees, _headTrackYawDegrees, 0f); Vector3 val2 = ((Component)this).transform.TransformDirection(val * Vector3.forward); Vector3 val3 = _headTrackBone.TransformDirection(_headTrackFaceLocalAxis); if (!(((Vector3)(ref val2)).sqrMagnitude < 0.0001f) && !(((Vector3)(ref val3)).sqrMagnitude < 0.0001f)) { _headTrackBone.rotation = Quaternion.FromToRotation(((Vector3)(ref val3)).normalized, ((Vector3)(ref val2)).normalized) * _headTrackBone.rotation; } } } private bool CalibrateHeadTracking() { //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Unknown result type (might be due to invalid IL or missing references) //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_005a: Unknown result type (might be due to invalid IL or missing references) //IL_0051: Unknown result type (might be due to invalid IL or missing references) //IL_005f: Unknown result type (might be due to invalid IL or missing references) if (_headTrackCalibrated) { return true; } if ((Object)(object)_headTrackBone == (Object)null) { return false; } _headTrackBaseLocalRotation = _headTrackBone.localRotation; Vector3 val = _headTrackBone.InverseTransformDirection(((Component)this).transform.forward); _headTrackFaceLocalAxis = ((((Vector3)(ref val)).sqrMagnitude > 0.0001f) ? ((Vector3)(ref val)).normalized : Vector3.forward); _headTrackCalibrated = true; return true; } private bool TryGetHeadTrackFocusPoint(out Vector3 focusPoint) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_00b4: Unknown result type (might be due to invalid IL or missing references) //IL_00ba: Unknown result type (might be due to invalid IL or missing references) //IL_00d0: Unknown result type (might be due to invalid IL or missing references) //IL_00d5: Unknown result type (might be due to invalid IL or missing references) focusPoint = Vector3.zero; PlayerControllerB val = base.targetPlayer; if ((Object)(object)val == (Object)null || val.isPlayerDead || !((EnemyAI)this).PlayerIsTargetable(val, false, false, true)) { if (Time.time >= _nextHeadTrackSearchTime) { _nextHeadTrackSearchTime = Time.time + 0.25f; _headTrackTarget = FindClosestVisibleTargetablePlayer(HeadTrackingRange); } val = _headTrackTarget; } if ((Object)(object)val == (Object)null || val.isPlayerDead || !((EnemyAI)this).PlayerIsTargetable(val, false, false, true)) { _headTrackTarget = null; return false; } Transform val2 = (((Object)(object)val.gameplayCamera != (Object)null) ? ((Component)val.gameplayCamera).transform : ((Component)val).transform); if (Vector3.Distance(_headTrackBone.position, val2.position) > HeadTrackingRange) { return false; } focusPoint = val2.position; return true; } private bool TryGetHeadAim(Vector3 point, out float yaw, out float pitch) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Unknown result type (might be due to invalid IL or missing references) //IL_0039: Unknown result type (might be due to invalid IL or missing references) //IL_004c: Unknown result type (might be due to invalid IL or missing references) Vector3 val = ((Component)this).transform.InverseTransformDirection(point - _headTrackBone.position); if (((Vector3)(ref val)).sqrMagnitude > 0.0001f) { ((Vector3)(ref val)).Normalize(); yaw = Mathf.Atan2(val.x, val.z) * 57.29578f; pitch = (0f - Mathf.Asin(Mathf.Clamp(val.y, -1f, 1f))) * 57.29578f; return true; } yaw = 0f; pitch = 0f; return false; } private void GetListenGlanceTarget(out float yaw, out float pitch) { //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Unknown result type (might be due to invalid IL or missing references) //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_0037: Unknown result type (might be due to invalid IL or missing references) //IL_003d: Unknown result type (might be due to invalid IL or missing references) //IL_0057: Unknown result type (might be due to invalid IL or missing references) if (_listenNoise.HasRecent(3f)) { Vector3 position = _listenNoise.Position; Vector3 position2 = _headTrackBone.position; float num = position.x - position2.x; float num2 = position.z - position2.z; float num3 = 1f; if (num * num + num2 * num2 >= num3 * num3 && TryGetHeadAim(position, out var yaw2, out var pitch2)) { yaw = SnipjackListenLook.ClampYaw(yaw2); pitch = SnipjackListenLook.ClampPitch(pitch2); return; } } yaw = SnipjackListenLook.SweepYawDegrees(_listenGlanceSeconds); pitch = 0f; } public override void DoAIInterval() { try { ((EnemyAI)this).DoAIInterval(); if (!((NetworkBehaviour)this).IsServer || base.isEnemyDead || (Object)(object)StartOfRound.Instance == (Object)null || StartOfRound.Instance.allPlayersDead) { return; } if (_wasStunned || ((EnemyAI)(object)this).IsStunned()) { ((EnemyAI)(object)this).HoldAgent(); return; } switch (base.currentBehaviourStateIndex) { case 0: DoIdleWalk(); break; case 1: DoWindupWalk(); break; case 2: DoRushSnipping(); break; } } catch (Exception arg) { Plugin.Log.LogError((object)$"[ScissorsCreatureAI] DoAIInterval failed: {arg}"); } } private void TickServerState(float deltaTime) { if (base.currentBehaviourStateIndex != 1) { return; } _windupTimer += deltaTime; if (_windupTimer >= WindupDuration) { if (CanBeginRushSnipping()) { BeginRushSnipping(); } else { ReturnToIdleWalk(); } } } private void DoIdleWalk() { PlayerControllerB val = FindClosestVisibleTargetablePlayer(DetectionRange); if ((Object)(object)val != (Object)null) { BeginWindup(val); } else if (!TryInvestigateNoise()) { TickIdleRoam(); } } private void DoWindupWalk() { //IL_003a: Unknown result type (might be due to invalid IL or missing references) bool hasMeaningfulContact; bool flag = TryKeepCurrentTarget(out hasMeaningfulContact); if (!flag) { flag = TryAcquireMeaningfulTarget(); hasMeaningfulContact = flag; } if (!flag) { if (HasLostEveryTargetLongEnough()) { ReturnToIdleWalk(); } else { MoveTowardLastKnownTarget(); } } else if (hasMeaningfulContact) { MoveTowardCurrentOrLastTarget(); } else { ((EnemyAI)this).SetDestinationToPosition(_lastKnownTargetPosition, false); } } private void DoRushSnipping() { //IL_005e: Unknown result type (might be due to invalid IL or missing references) if (base.currentSearch != null && base.currentSearch.inProgress) { ((EnemyAI)this).StopSearch(base.currentSearch, true); } if ((Object)(object)base.targetPlayer == (Object)null || base.targetPlayer.isPlayerDead || !((EnemyAI)this).PlayerIsTargetable(base.targetPlayer, false, false, true)) { DropCurrentTarget(); if (!TryAcquireMeaningfulTarget()) { ((EnemyAI)this).SetDestinationToPosition(_lastKnownTargetPosition, false); return; } } MoveTowardCurrentOrLastTarget(); } private bool CanBeginRushSnipping() { if (!TryKeepCurrentTarget(out var _)) { return TryAcquireMeaningfulTarget(); } return true; } private bool TryKeepCurrentTarget(out bool hasMeaningfulContact) { hasMeaningfulContact = false; PlayerControllerB targetPlayer = base.targetPlayer; if (!TargetIsWithinDisengageDistance(targetPlayer)) { DropCurrentTarget(); return false; } if (PlayerHasMeaningfulContact(targetPlayer, DisengageDistance)) { SetTargetWithContact(targetPlayer); hasMeaningfulContact = true; return true; } if (Time.time - _currentTargetLastContactTime >= LostContactGracePeriod) { DropCurrentTarget(); return false; } return true; } private bool TryAcquireMeaningfulTarget() { PlayerControllerB val = FindClosestMeaningfulContactTargetablePlayer(DisengageDistance); if ((Object)(object)val == (Object)null) { return false; } SetTargetWithContact(val); return true; } private void SetTargetWithContact(PlayerControllerB player) { //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_0013: Unknown result type (might be due to invalid IL or missing references) base.targetPlayer = player; _lastKnownTargetPosition = ((Component)player).transform.position; _currentTargetLastContactTime = Time.time; _lastTargetContactTime = Time.time; _networkTargetSlot.Value = (int)player.playerClientId; } private void DropCurrentTarget() { base.targetPlayer = null; base.movingTowardsTargetPlayer = false; _networkTargetSlot.Value = -1; } private bool TargetIsWithinDisengageDistance(PlayerControllerB player) { //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)player != (Object)null && !player.isPlayerDead && ((EnemyAI)this).PlayerIsTargetable(player, false, false, true)) { return Vector3.Distance(((Component)this).transform.position, ((Component)player).transform.position) <= DisengageDistance; } return false; } private bool HasLostEveryTargetLongEnough() { if ((Object)(object)FindClosestMeaningfulContactTargetablePlayer(DisengageDistance) != (Object)null) { _lastTargetContactTime = Time.time; return false; } return Time.time - _lastTargetContactTime >= LostContactGracePeriod; } private void BeginWindup(PlayerControllerB player) { ClearRoamState(); ((EnemyAI)this).StopSearch(base.currentSearch, true); SetTargetWithContact(player); _windupTimer = 0f; _tickingRepeatCount = 0; ConfigureAgentForState(1); SwitchState(1); PlayWindupClientRpc(); } private void BeginRushSnipping() { ClearRoamState(); ((EnemyAI)this).StopSearch(base.currentSearch, true); _attackOverlapTimer = 0f; _rushDeadline = SnipjackLifecycle.RushDeadline(Time.time, ChaseDuration); ConfigureAgentForState(2); SwitchState(2); PlaySnipClientRpc(); } private void ReturnToIdleWalk() { ClearRoamState(); _windupTimer = 0f; DropCurrentTarget(); _currentTargetLastContactTime = 0f; ConfigureAgentForState(0); SwitchState(0); TickIdleRoam(); } private void SwitchState(int state) { if (base.currentBehaviourStateIndex == state) { return; } if (!SnipjackLifecycle.CanSwitchState(base.currentBehaviourStateIndex, state)) { if (!_loggedRefusedSwitch) { _loggedRefusedSwitch = true; Plugin.Log.LogDebug((object)$"[ScissorsCreatureAI] Refused state {state}: the Snipjack has fallen apart."); } return; } ((EnemyAI)this).SwitchToBehaviourState(state); _networkState.Value = state; if (state != 1) { _windupTickingActive = false; } } private void ConfigureAgentForState(int state) { if (state != 0 && state != 1) { ReleaseTurnInPlaceGate(); } if (!((Object)(object)base.agent == (Object)null) && state != _appliedAgentState) { _appliedAgentState = state; base.agent.speed = state switch { 1 => WindupMoveSpeed, 2 => RushSpeed, _ => WalkSpeed, }; base.agent.angularSpeed = state switch { 0 => _roamTurnRate, 2 => 324f, _ => WalkTurnSpeed, }; base.agent.acceleration = state switch { 1 => 0.6f, 2 => 36f, _ => 2.6f, }; base.agent.stoppingDistance = state switch { 1 => 2.35f, 2 => 0.6f, _ => 0f, }; base.agent.autoBraking = state != 2; } } private void ApplyFixedBodyAndAgentSettings() { if ((Object)(object)bodyBlockerCollider != (Object)null) { bodyBlockerCollider.isTrigger = false; bodyBlockerCollider.enabled = true; } if (!((Object)(object)base.agent == (Object)null)) { base.agent.radius = 0.46071577f; base.agent.obstacleAvoidanceType = (ObstacleAvoidanceType)4; base.agent.avoidancePriority = 35; } } private static int ResolveLayer(string layerName, int fallback) { int num = LayerMask.NameToLayer(layerName); if (num < 0) { return fallback; } return num; } private void MoveTowardLastKnownTarget() { //IL_0044: Unknown result type (might be due to invalid IL or missing references) //IL_0038: Unknown result type (might be due to invalid IL or missing references) //IL_003d: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)base.targetPlayer != (Object)null && !base.targetPlayer.isPlayerDead && ((EnemyAI)this).PlayerIsTargetable(base.targetPlayer, false, false, true)) { _lastKnownTargetPosition = ((Component)base.targetPlayer).transform.position; } ((EnemyAI)this).SetDestinationToPosition(_lastKnownTargetPosition, false); } private void MoveTowardCurrentOrLastTarget() { //IL_0058: Unknown result type (might be due to invalid IL or missing references) //IL_0038: Unknown result type (might be due to invalid IL or missing references) //IL_003d: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)base.targetPlayer != (Object)null && !base.targetPlayer.isPlayerDead && ((EnemyAI)this).PlayerIsTargetable(base.targetPlayer, false, false, true)) { _lastKnownTargetPosition = ((Component)base.targetPlayer).transform.position; base.moveTowardsDestination = true; ((EnemyAI)this).SetMovingTowardsTargetPlayer(base.targetPlayer); } else { ((EnemyAI)this).SetDestinationToPosition(_lastKnownTargetPosition, false); } } private void TickTurnInPlaceGate(float deltaTime) { //IL_0083: Unknown result type (might be due to invalid IL or missing references) //IL_0088: Unknown result type (might be due to invalid IL or missing references) //IL_008a: Unknown result type (might be due to invalid IL or missing references) //IL_009b: Unknown result type (might be due to invalid IL or missing references) //IL_00a1: Unknown result type (might be due to invalid IL or missing references) //IL_00a9: Unknown result type (might be due to invalid IL or missing references) //IL_00af: Unknown result type (might be due to invalid IL or missing references) //IL_00be: Unknown result type (might be due to invalid IL or missing references) //IL_00c3: Unknown result type (might be due to invalid IL or missing references) //IL_00c5: Unknown result type (might be due to invalid IL or missing references) //IL_011f: Unknown result type (might be due to invalid IL or missing references) //IL_014c: Unknown result type (might be due to invalid IL or missing references) //IL_0153: Unknown result type (might be due to invalid IL or missing references) int currentBehaviourStateIndex = base.currentBehaviourStateIndex; if (!((NetworkBehaviour)this).IsServer || base.isEnemyDead || (Object)(object)base.agent == (Object)null || !((Behaviour)base.agent).enabled || !base.agent.isOnNavMesh || (currentBehaviourStateIndex != 0 && currentBehaviourStateIndex != 1)) { ReleaseTurnInPlaceGate(); return; } if (base.agent.pathPending) { if (_turnInPlaceActive) { HoldForTurnInPlace(); } return; } if (!base.agent.hasPath) { ReleaseTurnInPlaceGate(); return; } Vector3 position = ((Component)this).transform.position; if (!TryGetTurnGateTarget(position, out var target)) { ReleaseTurnInPlaceGate(); return; } float dx = target.x - position.x; float dz = target.z - position.z; Vector3 eulerAngles = ((Component)this).transform.eulerAngles; float absYawErrorDegrees = Mathf.Abs(SnipjackLocomotion.YawErrorDegrees(eulerAngles.y, dx, dz)); if (!SnipjackLocomotion.NextTurnGate(_turnInPlaceActive, absYawErrorDegrees, TurnBeforeMoveDegrees, 1f)) { ReleaseTurnInPlaceGate(); return; } _turnInPlaceActive = true; HoldForTurnInPlace(); float num = ((currentBehaviourStateIndex == 1) ? WindupTurnInPlaceSpeed : RoamTurnInPlaceSpeed); eulerAngles.y = Mathf.MoveTowardsAngle(eulerAngles.y, SnipjackLocomotion.TargetYawDegrees(dx, dz), num * Mathf.Max(0f, deltaTime)); ((Component)this).transform.eulerAngles = eulerAngles; if (Mathf.Abs(SnipjackLocomotion.YawErrorDegrees(eulerAngles.y, dx, dz)) <= 1f) { ReleaseTurnInPlaceGate(); } } private bool TryGetTurnGateTarget(Vector3 position, out Vector3 target) { //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_0073: Unknown result type (might be due to invalid IL or missing references) //IL_0078: Unknown result type (might be due to invalid IL or missing references) //IL_007a: Unknown result type (might be due to invalid IL or missing references) //IL_0081: Unknown result type (might be due to invalid IL or missing references) //IL_0088: Unknown result type (might be due to invalid IL or missing references) //IL_008f: Unknown result type (might be due to invalid IL or missing references) //IL_00a1: Unknown result type (might be due to invalid IL or missing references) //IL_00a3: Unknown result type (might be due to invalid IL or missing references) float num = 0.0001f; target = base.agent.steeringTarget; float num2 = target.x - position.x; float num3 = target.z - position.z; if (num2 * num2 + num3 * num3 >= num) { return true; } if (base.agent.remainingDistance <= 0.01f) { return false; } int cornersNonAlloc = base.agent.path.GetCornersNonAlloc(_turnGateCorners); for (int i = 0; i < cornersNonAlloc; i++) { Vector3 val = _turnGateCorners[i]; float num4 = val.x - position.x; num3 = val.z - position.z; if (num4 * num4 + num3 * num3 >= num) { target = val; return true; } } return false; } private void HoldForTurnInPlace() { //IL_0012: Unknown result type (might be due to invalid IL or missing references) base.agent.isStopped = true; base.agent.velocity = Vector3.zero; } private void ReleaseTurnInPlaceGate() { if (_turnInPlaceActive) { _turnInPlaceActive = false; if ((Object)(object)base.agent != (Object)null && ((Behaviour)base.agent).enabled && base.agent.isOnNavMesh) { base.agent.isStopped = false; } } } private void RepairAgentIfNeeded() { //IL_0071: Unknown result type (might be due to invalid IL or missing references) //IL_008d: Unknown result type (might be due to invalid IL or missing references) if (!base.isEnemyDead && !((Object)(object)base.agent == (Object)null) && ((Behaviour)base.agent).enabled && !base.agent.isOnNavMesh && !(Time.time < _nextAgentRepairTime)) { _nextAgentRepairTime = Time.time + 0.8f; int num = ((base.agent.areaMask != 0) ? base.agent.areaMask : (-1)); NavMeshHit val = default(NavMeshHit); if (NavMesh.SamplePosition(((Component)this).transform.position, ref val, 4f, num) && base.agent.Warp(((NavMeshHit)(ref val)).position)) { ResetNavigationRecovery(); } } } private void TickNavigationRecovery(float deltaTime) { //IL_0141: Unknown result type (might be due to invalid IL or missing references) //IL_0147: Unknown result type (might be due to invalid IL or missing references) //IL_014c: Unknown result type (might be due to invalid IL or missing references) //IL_0151: Unknown result type (might be due to invalid IL or missing references) //IL_0193: Unknown result type (might be due to invalid IL or missing references) //IL_0198: Unknown result type (might be due to invalid IL or missing references) //IL_0251: Unknown result type (might be due to invalid IL or missing references) //IL_020a: Unknown result type (might be due to invalid IL or missing references) //IL_026e: Unknown result type (might be due to invalid IL or missing references) //IL_03a6: Unknown result type (might be due to invalid IL or missing references) //IL_0394: Unknown result type (might be due to invalid IL or missing references) //IL_03ab: Unknown result type (might be due to invalid IL or missing references) //IL_0407: Unknown result type (might be due to invalid IL or missing references) //IL_036f: Unknown result type (might be due to invalid IL or missing references) //IL_0303: Unknown result type (might be due to invalid IL or missing references) if (base.isEnemyDead || (Object)(object)base.agent == (Object)null || !((Behaviour)base.agent).enabled || !base.agent.isOnNavMesh) { ResetNavigationRecovery(); return; } bool flag = base.currentSearch != null && base.currentSearch.inProgress; bool num = base.currentBehaviourStateIndex == 1 || base.currentBehaviourStateIndex == 2 || (base.currentBehaviourStateIndex == 0 && !RoamListening && (_roamLegActive || flag)); bool flag2 = base.agent.hasPath && !base.agent.pathPending && base.agent.remainingDistance <= Mathf.Max(base.agent.stoppingDistance + 0.45f, 0.9f); if (!num || flag2) { ResetNavigationRecovery(); } else if (base.agent.pathPending || (flag && (base.currentSearch.waitingForTargetNode || (Object)(object)base.currentSearch.currentTargetNode == (Object)null))) { ResetNavigationWindow(); } else { if (_turnInPlaceActive) { return; } _navigationStuckTimer += Mathf.Max(0f, deltaTime); if (_navigationStuckTimer < 1.2f) { return; } Vector3 val = ((Component)this).transform.position - _lastNavigationRecoveryPosition; val.y = 0f; float num2 = Mathf.Max(0.01f, base.agent.speed) * 0.25f * _navigationStuckTimer; _navigationStuckTimer = 0f; _lastNavigationRecoveryPosition = ((Component)this).transform.position; if (((Vector3)(ref val)).sqrMagnitude >= num2 * num2) { _navigationRepathed = false; } else { if (IsTouchingClosedDoor()) { return; } if (!_navigationRepathed) { _navigationRepathed = true; ManualLogSource log = Plugin.Log; if (log != null) { log.LogInfo((object)$"[ScissorsCreatureAI] #{base.thisEnemyIndex} no progress for {1.2f:0.0} s in {StateName(base.currentBehaviourStateIndex)}; repathing."); } base.agent.SetDestination(base.destination); return; } _navigationRepathed = false; _nextAgentRepairTime = Time.time + 0.8f; int num3 = ((base.agent.areaMask != 0) ? base.agent.areaMask : (-1)); NavMeshHit val2 = default(NavMeshHit); bool flag3 = NavMesh.SamplePosition(((Component)this).transform.position, ref val2, 1.5f, num3) && base.agent.Warp(((NavMeshHit)(ref val2)).position); if (base.currentBehaviourStateIndex == 0) { if (!_roamFallback) { ManualLogSource log2 = Plugin.Log; if (log2 != null) { log2.LogInfo((object)$"[ScissorsCreatureAI] #{base.thisEnemyIndex} still no progress in {StateName(base.currentBehaviourStateIndex)}; warped={flag3}, retaining node {_roamNode} after {Time.time - _roamLegStartedAt:0.0} s."); } if (flag3) { base.agent.SetDestination(_roamDestination); } } else { ManualLogSource log3 = Plugin.Log; if (log3 != null) { log3.LogInfo((object)$"[ScissorsCreatureAI] #{base.thisEnemyIndex} still no progress in {StateName(base.currentBehaviourStateIndex)}; warped={flag3}, restarting the search."); } if (base.currentSearch != null && base.currentSearch.inProgress) { ((EnemyAI)this).StopSearch(base.currentSearch, false); } ((EnemyAI)this).StartSearch(((Component)this).transform.position, (AISearchRoutine)null); } } else { bool flag4 = PlayerHasMeaningfulContact(base.targetPlayer, DisengageDistance); Vector3 val3 = (flag4 ? ((Component)base.targetPlayer).transform.position : _lastKnownTargetPosition); ManualLogSource log4 = Plugin.Log; if (log4 != null) { log4.LogInfo((object)string.Format("[ScissorsCreatureAI] #{0} still no progress in {1}; warped={2}, re-pathing to the {3}.", base.thisEnemyIndex, StateName(base.currentBehaviourStateIndex), flag3, flag4 ? "target" : "last known target position")); } ((EnemyAI)this).SetDestinationToPosition(val3, false); } } } } private bool IsTouchingClosedDoor() { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_001a: Unknown result type (might be due to invalid IL or missing references) int num = Physics.OverlapSphereNonAlloc(((Component)this).transform.position + Vector3.up * 0.7f, 0.75f, _doorProbeResults, _doorProbeMask, (QueryTriggerInteraction)2); bool flag = false; DoorLock val2 = default(DoorLock); AnimatedObjectTrigger val3 = default(AnimatedObjectTrigger); for (int i = 0; i < num; i++) { Collider val = _doorProbeResults[i]; _doorProbeResults[i] = null; if (!flag && !((Object)(object)val == (Object)null) && ((Component)val).TryGetComponent<DoorLock>(ref val2) && !val2.isLocked) { flag = !((Component)val).TryGetComponent<AnimatedObjectTrigger>(ref val3) || !val3.boolValue; } } return flag; } private void ResetNavigationRecovery() { _navigationRepathed = false; ResetNavigationWindow(); } private void ResetNavigationWindow() { //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Unknown result type (might be due to invalid IL or missing references) _navigationStuckTimer = 0f; _lastNavigationRecoveryPosition = ((Component)this).transform.position; } private static string StateName(int state) { return state switch { 0 => "IdleWalk", 1 => "WindupWalk", 2 => "RushSnipping", 3 => "FallingApart", _ => state.ToString(), }; } private PlayerControllerB FindClosestMeaningfulContactTargetablePlayer(float range) { //IL_004d: 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) if ((Object)(object)StartOfRound.Instance == (Object)null) { return null; } PlayerControllerB result = null; float num = range; PlayerControllerB[] allPlayerScripts = StartOfRound.Instance.allPlayerScripts; foreach (PlayerControllerB val in allPlayerScripts) { if (!((Object)(object)val == (Object)null) && !val.isPlayerDead && ((EnemyAI)this).PlayerIsTargetable(val, false, false, true)) { float num2 = Vector3.Distance(((Component)this).transform.position, ((Component)val).transform.position); if (!(num2 > num) && PlayerHasMeaningfulContact(val, range)) { num = num2; result = val; } } } return result; } private bool PlayerHasMeaningfulContact(PlayerControllerB player, float range) { //IL_0025: 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_008d: 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) if ((Object)(object)player == (Object)null || player.isPlayerDead || !((EnemyAI)this).PlayerIsTargetable(player, false, false, true)) { return false; } float num = Vector3.Distance(((Component)this).transform.position, ((Component)player).transform.position); if (num > range) { return false; } if (num <= ProximityAwareness) { return true; } Transform val = (((Object)(object)base.eye != (Object)null) ? base.eye : ((Component)this).transform); Transform val2 = (((Object)(object)player.gameplayCamera != (Object)null) ? ((Component)player.gameplayCamera).transform : ((Component)player).transform); return !IsLineOfSightBlocked(val.position, val2.position); } private PlayerControllerB FindClosestVisibleTargetablePlayer(float range) { //IL_0099: Unknown result type (might be due to invalid IL or missing references) //IL_00a0: Unknown result type (might be due to invalid IL or missing references) //IL_00bc: Unknown result type (might be due to invalid IL or missing references) //IL_00c3: Unknown result type (might be due to invalid IL or missing references) //IL_00c9: Unknown result type (might be due to invalid IL or missing references) //IL_00ce: Unknown result type (might be due to invalid IL or missing references) //IL_00e2: Unknown result type (might be due to invalid IL or missing references) //IL_00e9: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)StartOfRound.Instance == (Object)null) { return null; } Transform val = (((Object)(object)base.eye != (Object)null) ? base.eye : ((Component)this).transform); PlayerControllerB result = null; float num = range; PlayerControllerB[] allPlayerScripts = StartOfRound.Instance.allPlayerScripts; foreach (PlayerControllerB val2 in allPlayerScripts) { if (!((Object)(object)val2 == (Object)null) && !val2.isPlayerDead && ((EnemyAI)this).PlayerIsTargetable(val2, false, false, true)) { Transform val3 = (((Object)(object)val2.gameplayCamera != (Object)null) ? ((Component)val2.gameplayCamera).transform : ((Component)val2).transform); float num2 = Vector3.Distance(val.position, val3.position); if (!(num2 > num) && (!(num2 > ProximityAwareness) || (!(Vector3.Angle(val.forward, val3.position - val.position) > DetectionWidth) && !IsLineOfSightBlocked(val.position, val3.position)))) { num = num2; result = val2; } } } return result; } private bool IsLineOfSightBlocked(Vector3 from, Vector3 to) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) if (!RaycastHasNonSelfBlocker(from, to)) { return RaycastHasNonSelfBlocker(to, from); } return true; } private bool RaycastHasNonSelfBlocker(Vector3 from, Vector3 to) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_0028: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Unknown result type (might be due to invalid IL or missing references) Vector3 val = to - from; float magnitude = ((Vector3)(ref val)).magnitude; if (magnitude <= 0.05f) { return false; } int collidersAndRoomMaskAndDefault = StartOfRound.Instance.collidersAndRoomMaskAndDefault; int num = Physics.RaycastNonAlloc(new Ray(from, val / magnitude), _lineOfSightHits, magnitude, collidersAndRoomMaskAndDefault, (QueryTriggerInteraction)1); for (int i = 0; i < num; i++) { Collider collider = ((RaycastHit)(ref _lineOfSightHits[i])).collider; if (!((Object)(object)collider == (Object)null) && !((Component)collider).transform.IsChildOf(((Component)this).transform)) { return true; } } return false; } private void DamageObjectsInAttackVolume(float deltaTime) { //IL_008b: Unknown result type (might be due to invalid IL or missing references) //IL_0090: Unknown result type (might be due to invalid IL or missing references) //IL_0091: 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_0097: Unknown result type (might be due to invalid IL or missing references) //IL_009c: Unknown result type (might be due to invalid IL or missing references) //IL_00a3: Unknown result type (might be due to invalid IL or missing references) //IL_00a8: Unknown result type (might be due to invalid IL or missing references) //IL_00ae: Unknown result type (might be due to invalid IL or missing references) //IL_00b3: Unknown result type (might be due to invalid IL or missing references) //IL_00b8: Unknown result type (might be due to invalid IL or missing references) //IL_00c2: Unknown result type (might be due to invalid IL or missing references) //IL_00c7: Unknown result type (might be due to invalid IL or missing references) //IL_00e2: Unknown result type (might be due to invalid IL or missing references) //IL_00e9: Unknown result type (might be due to invalid IL or missing references) //IL_013e: Unknown result type (might be due to invalid IL or missing references) //IL_0154: Unknown result type (might be due to invalid IL or missing references) if (base.currentBehaviourStateIndex != 2 || (Object)(object)attackOrigin == (Object)null || (Object)(object)StartOfRound.Instance == (Object)null) { return; } PlayerControllerB val = (((Object)(object)GameNetworkManager.Instance != (Object)null) ? GameNetworkManager.Instance.localPlayerController : null); if ((Object)(object)val != (Object)null && PlayerIsInsideScissorsDamageVolume(val)) { TryDamagePlayer(val, requireScissorsVolume: false); } if (!((NetworkBehaviour)this).IsServer) { return; } _attackOverlapTimer -= deltaTime; if (_attackOverlapTimer > 0f) { return; } _attackOverlapTimer = 0.15f; Vector3 scissorsForward = GetScissorsForward(); Quaternion val2 = Quaternion.LookRotation(scissorsForward, Vector3.up); Vector3 val3 = attackOrigin.position + scissorsForward * 0.825f + Vector3.up * 0.3f; Vector3 val4 = default(Vector3); ((Vector3)(ref val4))..ctor(1.35f, 1.05f, 1.925f); int num = Physics.OverlapBoxNonAlloc(val3, val4, _attackOverlapResults, val2, _attackOverlapMask, (QueryTriggerInteraction)2); EnemyAICollisionDetect enemyCollision = default(EnemyAICollisionDetect); IHittable hittable = default(IHittable); for (int i = 0; i < num; i++) { Collider val5 = _attackOverlapResults[i]; _attackOverlapResults[i] = null; if (!((Object)(object)val5 == (Object)null) && !((Component)val5).transform.IsChildOf(((Component)this).transform)) { if (((Component)val5).TryGetComponent<EnemyAICollisionDetect>(ref enemyCollision)) { TryDamageEnemy(enemyCollision, scissorsForward); } else if (((Component)val5).TryGetComponent<IHittable>(ref hittable)) { TryHitGenericHittable(hittable, scissorsForward); } } } } public override void OnCollideWithPlayer(Collider other) { ((EnemyAI)this).OnCollideWithPlayer(other); if (base.currentBehaviourStateIndex == 2) { PlayerControllerB val = ((EnemyAI)this).MeetsStandardPlayerCollisionConditions(other, false, false); if ((Object)(object)val != (Object)null) { TryDamagePlayer(val); } } } public override void OnCollideWithEnemy(Collider other, EnemyAI collidedEnemy = null) { //IL_0061: Unknown result type (might be due to invalid IL or missing references) ((EnemyAI)this).OnCollideWithEnemy(other, collidedEnemy); if (((NetworkBehaviour)this).IsServer && !base.isEnemyDead && !((EnemyAI)(object)this).IsStunned() && base.currentBehaviourStateIndex == 2 && !((Object)(object)collidedEnemy == (Object)null) && !collidedEnemy.isEnemyDead && ColliderIsInsideScissorsDamageVolume(other)) { EnemyAICollisionDetect val = ((Component)other).GetComponent<EnemyAICollisionDetect>() ?? ((Component)other).GetComponentInParent<EnemyAICollisionDetect>(); if ((Object)(object)val != (Object)null) { TryDamageEnemy(val, GetScissorsForward()); } } } private void TryDamageEnemy(EnemyAICollisionDetect enemyCollision, Vector3 hitDirection) { //IL_004b: Unknown result type (might be due to invalid IL or missing references) if (!((Object)(object)enemyCollision == (Object)null) && !((Object)(object)enemyCollision.mainScript == (Object)null) && !((Object)(object)enemyCollision.mainScript == (Object)(object)this) && !enemyCollision.mainScript.isEnemyDead) { int instanceID = ((Object)enemyCollision.mainScript).GetInstanceID(); if (CanDamageHittable(instanceID) && ((IHittable)enemyCollision).Hit(2, hitDirection, (PlayerControllerB)null, true, 7)) { _lastHittableDamageTimes[instanceID] = Time.realtimeSinceStartup; } } } private void TryHitGenericHittable(IHittable hittable, Vector3 hitDirection) { //IL_0025: Unknown result type (might be due to invalid IL or missing references) Object val = (Object)(object)((hittable is Object) ? hittable : null); if (val == (Object)null) { return; } int instanceID = val.GetInstanceID(); if (!CanDamageHittable(instanceID)) { return; } try { if (hittable.Hit(2, hitDirection, (PlayerControllerB)null, true, 7)) { _lastHittableDamageTimes[instanceID] = Time.realtimeSinceStartup; } } catch (Exception ex) { _lastHittableDamageTimes[instanceID] = Time.realtimeSinceStartup; Plugin.Log.LogWarning((object)("[ScissorsCreatureAI] Failed to hit " + val.name + " with scissors: " + ex.Message)); } } private bool CanDamageHittable(int key) { float realtimeSinceStartup = Time.realtimeSinceStartup; if (_lastHittableDamageTimes.TryGetValue(key, out var value)) { return realtimeSinceStartup - value >= AttackDamageCooldown; } return true; } private void TryDamagePlayer(PlayerControllerB player, bool requireScissorsVolume = true) { //IL_00bd: Unknown result type (might be due to invalid IL or missing references) //IL_00b0: Unknown result type (might be due to invalid IL or missing references) //IL_00c2: Unknown result type (might be due to invalid IL or missing references) //IL_00c9: Unknown result type (might be due to invalid IL or missing references) //IL_00ce: Unknown result type (might be due to invalid IL or missing references) //IL_00cf: Unknown result type (might be due to invalid IL or missing references) //IL_00d4: Unknown result type (might be due to invalid IL or missing references) //IL_00d8: Unknown result type (might be due to invalid IL or missing references) //IL_00e2: Unknown result type (might be due to invalid IL or missing references) //IL_00e7: Unknown result type (might be due to invalid IL or missing references) //IL_00fb: Unknown result type (might be due to invalid IL or missing references) //IL_0114: Unknown result type (might be due to invalid IL or missing references) //IL_011a: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)player == (Object)null || player.isPlayerDead || !((EnemyAI)this).PlayerIsTargetable(player, false, false, true)) { return; } PlayerControllerB val = (((Object)(object)GameNetworkManager.Instance != (Object)null) ? GameNetworkManager.Instance.localPlayerController : null); if (((Object)(object)val != (Object)null && (Object)(object)player != (Object)(object)val) || !MeetsSnipCollisionConditions(player) || (requireScissorsVolume && !PlayerIsInsideScissorsDamageVolume(player))) { return; } float realtimeSinceStartup = Time.realtimeSinceStartup; if (!_lastDamageTimes.TryGetValue(player.playerClientId, out var value) || !(realtimeSinceStartup - value < AttackDamageCooldown)) { _lastDamageTimes[player.playerClientId] = realtimeSinceStartup; Vector3 val2 = (((Object)(object)attackOrigin != (Object)null) ? attackOrigin.position : ((Component)this).transform.position); Vector3 val3 = ((Component)player).transform.position - val2; Vector3 val4 = ((Vector3)(ref val3)).normalized * 8f; player.DamagePlayer(_networkAttackDamage.Value, true, true, (CauseOfDeath)17, 7, false, val4); if (player.isPlayerDead) { ReportSnipKillServerRpc((int)player.playerClientId); } } } private bool MeetsSnipCollisionConditions(PlayerControllerB player) { //IL_002d: Unknown result type (might be due to invalid IL or missing references) if (!base.isEnemyDead && !((EnemyAI)(object)this).IsStunned() && base.ventAnimationFinished && (Object)(object)player.inAnimationWithEnemy == (Object)null) { return !IsSeparatedByClosedElevator(((Component)player).transform.position); } return false; } private bool IsSeparatedByClosedElevator(Vector3 target) { //IL_0050: Unknown result type (might be due to invalid IL or missing references) //IL_0055: Unknown result type (might be due to invalid IL or missing references) //IL_0058: 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) RoundManager instance = RoundManager.Instance; if ((Object)(object)instance == (Object)null || instance.currentDungeonType != 4 || base.isOutside) { return false; } MineshaftElevatorController currentMineshaftElevator = instance.currentMineshaftElevator; if ((Object)(object)currentMineshaftElevator == (Object)null || currentMineshaftElevator.elevatorDoorOpen || (Object)(object)currentMineshaftElevator.elevatorBounds == (Object)null) { return false; } Bounds bounds = currentMineshaftElevator.elevatorBounds.bounds; return ((Bounds)(ref bounds)).Contains(target) != ((Bounds)(ref bounds)).Contains(((Component)this).transform.position); } private bool PlayerIsInsideScissorsDamageVolume(PlayerControllerB player) { //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Unknown result type (might be due to invalid IL or missing references) //IL_003e: Unknown result type (might be due to invalid IL or missing references) //IL_0043: Unknown result type (might be due to invalid IL or missing references) //IL_0049: Unknown result type (might be due to invalid IL or missing references) //IL_004e: Unknown result type (might be due to invalid IL or missing references) //IL_004f: Unknown result type (might be due to invalid IL or missing references) //IL_0054: Unknown result type (might be due to invalid IL or missing references) //IL_0055: Unknown result type (might be due to invalid IL or missing references) //IL_005a: Unknown result type (might be due to invalid IL or missing references) //IL_007c: Unknown result type (might be due to invalid IL or missing references) //IL_007d: Unknown result type (might be due to invalid IL or missing references) //IL_0084: Unknown result type (might be due to invalid IL or missing references) //IL_0085: Unknown result type (might be due to invalid IL or missing references) //IL_008c: Unknown result type (might be due to invalid IL or missing references) //IL_006f: Unknown result type (might be due to invalid IL or missing references) //IL_0074: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)player == (Object)null || (Object)(object)attackOrigin == (Object)null) { return false; } Vector3 val = ((Component)player).transform.position + Vector3.up * 0.9f - attackOrigin.position; Vector3 scissorsForward = GetScissorsForward(); Vector3 val2 = Vector3.Cross(Vector3.up, scissorsForward); if (((Vector3)(ref val2)).sqrMagnitude <= 0.001f) { val2 = ((Component)this).transform.right; } ((Vector3)(ref val2)).Normalize(); float num = Vector3.Dot(val, scissorsForward); float num2 = Vector3.Dot(val, val2); float num3 = Vector3.Dot(val, Vector3.up); if (num >= -1.1f && num <= 2.75f && Mathf.Abs(num2) <= 1.35f && num3 >= -0.75f) { return num3 <= 1.35f; } return false; } private bool ColliderIsInsideScissorsDamageVolume(Collider hitCollider) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0013: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)hitCollider != (Object)null) { Bounds bounds = hitCollider.bounds; return PointIsInsideScissorsDamageVolume(((Bounds)(ref bounds)).center); } return false; } private bool PointIsInsideScissorsDamageVolume(Vector3 point) { //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_0028: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Unknown result type (might be due to invalid IL or missing references) //IL_0055: Unknown result type (might be due to invalid IL or missing references) //IL_0056: Unknown result type (might be due to invalid IL or missing references) //IL_005d: 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_0065: Unknown result type (might be due to invalid IL or missing references) //IL_0048: Unknown result type (might be due to invalid IL or missing references) //IL_004d: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)attackOrigin == (Object)null) { return false; } Vector3 val = point - attackOrigin.position; Vector3 scissorsForward = GetScissorsForward(); Vector3 val2 = Vector3.Cross(Vector3.up, scissorsForward); if (((Vector3)(ref val2)).sqrMagnitude <= 0.001f) { val2 = ((Component)this).transform.right; } ((Vector3)(ref val2)).Normalize(); float num = Vector3.Dot(val, scissorsForward); float num2 = Vector3.Dot(val, val2); float num3 = Vector3.Dot(val, Vector3.up); if (num >= -1.1f && num <= 2.75f && Mathf.Abs(num2) <= 1.35f && num3 >= -0.75f) { return num3 <= 1.35f; } return false; } private Vector3 GetScissorsForward() { //IL_0052: Unknown result type (might be due to invalid IL or missing references) //IL_0057: Unknown result type (might be due to invalid IL or missing references) //IL_005c: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_008a: Unknown result type (might be due to invalid IL or missing references) //IL_007d: Unknown result type (might be due to invalid IL or missing references) //IL_0082: Unknown result type (might be due to invalid IL or missing references) //IL_0046: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)attackOrigin != (Object)null) { Vector3 val = attackOrigin.position - ((Component)this).transform.position; val.y = 0f; if (((Vector3)(ref val)).sqrMagnitude > 0.001f) { return ((Vector3)(ref val)).normalized; } } Vector3 val2 = -((Component)this).transform.forward; val2.y = 0f; if (!(((Vector3)(ref val2)).sqrMagnitude > 0.001f)) { return -((Component)this).transform.forward; } return ((Vector3)(ref val2)).normalized; } private void ResolveRuntimeReferences() { if ((Object)(object)base.creatureAnimator == (Object)null) { base.creatureAnimator = ((Component)this).GetComponent<Animator>() ?? ((Component)this).GetComponentInChildren<Animator>(true); } if ((Object)(object)base.agent == (Object)null) { base.agent = ((Component)this).GetComponent<NavMeshAgent>() ?? ((Component)this).GetComponentInChildren<NavMeshAgent>(true); } if ((Object)(object)base.creatureSFX == (Object)null) { base.creatureSFX = FindAudioSource("CreatureSFX"); } if ((Object)(object)base.creatureVoice == (Object)null) { base.creatureVoice = FindAudioSource("CreatureVoice"); } if ((Object)(object)tickingAudioSource == (Object)null) { tickingAudioSource = FindAudioSource("TickingAudio"); } if ((Object)(object)alarmAudioSource == (Object)null) { alarmAudioSource = FindAudioSource("AlarmAudio"); } if ((Object)(object)footstepAudioSource == (Object)null) { footstepAudioSource = FindFootstepAudioSource(); } if ((Object)(object)attackOrigin == (Object)null) { attackOrigin = FindChildRecursive(((Component)this).transform, "AttackOrigin") ?? ((Component)this).transform; } if ((Object)(object)wheelBone == (Object)null) { wheelBone = FindChildRecursive(((Component)this).transform, "back_windup_wheel_mount"); } if ((Object)(object)_headTrackBone == (Object)null) { _headTrackBone = FindChildRecursive(((Component)this).transform, "head_track"); } if ((Object)(object)_wheelConnector == (Object)null) { _wheelConnector = FindChildRecursive(((Component)this).transform, "BackWindupWheelConnector"); } if ((Object)(object)bodyBlockerCollider == (Object)null) { object obj = ((Component)this).GetComponent<CapsuleCollider>(); if (obj == null) { obj = ((Component)this).GetComponent<Collider>(); if (obj == null) { Transform obj2 = FindChildRecursive(((Component)this).transform, "BodyBlocker"); obj = ((obj2 != null) ? ((Component)obj2).GetComponent<Collider>() : null); } } bodyBlockerCollider = (Collider)obj; } if ((Object)(object)base.eye == (Object)null) { base.eye = FindChildRecursive(((Component)this).transform, "EyeTransform") ?? ((Component)this).transform; } EnsureWheelConnector(); AlignWheelConnector(); } private AudioSource FindAudioSource(string childName) { Transform val = FindChildRecursive(((Component)this).transform, childName); AudioSource val2 = (((Object)(object)val != (Object)null) ? ((Component)val).GetComponent<AudioSource>() : null); if ((Object)(object)val2 != (Object)null) { return val2; } AudioSource componentInChildren = ((Component)this).GetComponentInChildren<AudioSource>(true); if ((Object)(object)componentInChildren != (Object)null && string.Equals(childName, "TickingAudio", StringComparison.Ordinal)) { Plugin.Log.LogWarning((object)("[ScissorsCreatureAI] Dedicated TickingAudio source is missing; ticking is falling back to shared AudioSource '" + ((Object)componentInChildren).name + "'.")); } return componentInChildren; } private AudioSource FindFootstepAudioSource() { Transform val = FindChildRecursive(((Component)this).transform, "Footsteps"); AudioSource val2 = (((Object)(object)val != (Object)null) ? ((Component)val).GetComponent<AudioSource>() : null); if ((Object)(object)val2 != (Object)null) { return val2; } Plugin.Log.LogWarning((object)"[ScissorsCreatureAI] No Footsteps AudioSource; footsteps fall back to CreatureSFX."); return base.creatureSFX; } private static Transform FindChildRecursive(Transform parent, string name) { if ((Object)(object)parent == (Object)null) { return null; } if (((Object)parent).name == name) { return parent; } for (int i = 0; i < parent.childCount; i++) { Transform val = FindChildRecursive(parent.GetChild(i), name); if ((Object)(object)val != (Object)null) { return val; } } return null; } private void TickWheelVisual(float deltaTime) { //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_0064: Unknown result type (might be due to invalid IL or missing references) //IL_006f: Unknown result type (might be due to invalid IL or missing references) //IL_0074: Unknown result type (might be due to invalid IL or missing references) //IL_0079: Unknown result type (might be due to invalid IL or missing references) if (!((Object)(object)wheelBone == (Object)null)) { if (!_capturedWheelBase) { _wheelBaseLocalRotation = wheelBone.localRotation; _capturedWheelBase = true; } float num = ((base.currentBehaviourStateIndex == 2) ? (420f * deltaTime) : 0f); if (num > 0f) { _wheelVisualAngle += num; } wheelBone.localRotation = _wheelBaseLocalRotation * Quaternion.AngleAxis(_wheelVisualAngle, Vector3.up); } } private void AlignWheelConnector() { //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_0029: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_0046: Unknown result type (might be due to invalid IL or missing references) //IL_004e: Unknown result type (might be due to invalid IL or missing references) //IL_0050: Unknown result type (might be due to invalid IL or missing references) EnsureWheelConnector(); if (!((Object)(object)_wheelConnector == (Object)null)) { Vector3 start = (((Object)(object)_connectorAnchorParent != (Object)null) ? _connectorAnchorParent.TransformPoint(_connectorAnchorOnParent) : ((Component)this).transform.TransformPoint(WheelConnectorBodyAnchorLocalPosition)); AlignConnectorCylinder(_wheelConnector, start, ResolveWheelCenterPosition(), 0.055f); } } private Vector3 ResolveWheelCenterPosition() { //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Unknown result type (might be due to invalid IL or missing references) if (!((Object)(object)wheelBone != (Object)null)) { return ((Component)this).transform.TransformPoint(WheelFallbackLocalPosition); } return wheelBone.position; } private void EnsureWheelConnector() { //IL_00d0: Unknown result type (might be due to invalid IL or missing references) //IL_00e6: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)_wheelConnector == (Object)null) { _wheelConnector = FindChildRecursive(((Component)this).transform, "BackWindupWheelConnector"); } if ((Object)(object)_wheelConnector != (Object)null) { return; } GameObject val = GameObject.CreatePrimitive((PrimitiveType)2); ((Object)val).name = "BackWindupWheelConnector"; val.transform.SetParent(((Component)this).transform, false); _wheelConnector = val.transform; Collider component = val.GetComponent<Collider>(); if ((Object)(object)component != (Object)null) { Object.Destroy((Object)(object)component); } Renderer component2 = val.GetComponent<Renderer>(); if ((Object)(object)component2 == (Object)null) { return; } Material val2 = (_connectorMaterial = component2.material); if (!((Object)(object)val2 == (Object)null)) { Color val3 = default(Color); ((Color)(ref val3))..ctor(0.035f, 0.03f, 0.028f, 1f); if (val2.HasProperty("_BaseColor")) { val2.SetColor("_BaseColor", val3); } else if (val2.HasProperty("_Color")) { val2.color = val3; } } } private void AlignConnectorCylinder(Transform connector, Vector3 start, Vector3 end, float radius) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_004c: Unknown result type (might be due to invalid IL or missing references) //IL_004d: Unknown result type (might be due to invalid IL or missing references) //IL_004e: Unknown result type (might be due to invalid IL or missing references) //IL_0058: Unknown result type (might be due to invalid IL or missing references) //IL_0063: 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_006f: Unknown result type (might be due to invalid IL or missing references) //IL_007f: Unknown result type (might be due to invalid IL or missing references) //IL_0084: Unknown result type (might be due to invalid IL or missing references) //IL_008d: Unknown result type (might be due to invalid IL or missing references) //IL_00aa: Unknown result type (might be due to invalid IL or missing references) //IL_00c2: Unknown result type (might be due to invalid IL or missing references) //IL_00d3: Unknown result type (might be due to invalid IL or missing references) Vector3 val = end - start; float magnitude = ((Vector3)(ref val)).magnitude; if (magnitude < 0.04f) { if (((Component)connector).gameObject.activeSelf) { ((Component)connector).gameObject.SetActive(false); } return; } if (!((Component)connector).gameObject.activeSelf) { ((Component)connector).gameObject.SetActive(true); } connector.position = (start + end) * 0.5f; connector.rotation = Quaternion.FromToRotation(Vector3.up, ((Vector3)(ref val)).normalized); Vector3 lossyScale = ((Component)this).transform.lossyScale; connector.localScale = new Vector3(radius / Mathf.Max(0.001f, Mathf.Abs(lossyScale.x)), magnitude * 0.5f / Mathf.Max(0.001f, Mathf.Abs(lossyScale.y)), radius / Mathf.Max(0.001f, Mathf.Abs(lossyScale.z))); } public void OnStep(AnimationEvent animationEvent) { //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_0031: Unknown result type (might be due to invalid IL or missing references) if (base.isEnemyDead || !((Behaviour)this).isActiveAndEnabled) { return; } _stepEventArrived = true; if (_wasStunned) { return; } if (animationEvent != null && animationEvent.isFiredByAnimator) { AnimatorClipInfo animatorClipInfo = animationEvent.animatorClipInfo; if (((AnimatorClipInfo)(ref animatorClipInfo)).weight < 0.5f) { return; } } bool flag = base.currentBehaviourStateIndex == 2; int num = ((rushStepClips != null) ? rushStepClips.Length : 0); float volume; AudioClip val = CurrentFootstepClip(out volume); if (flag && num > 0) { val = rushStepClips[Random.Range(0, num)]; } if (!((Object)(object)val == (Object)null)) { bool rushRunCue = SnipjackFootstepEvents.IsRushRunCue(flag, num, (Object)(object)val == (Object)(object)footstepClip); int foot = ((animationEvent != null) ? animationEvent.intParameter : 0); if (SnipjackFootstepEvents.ShouldPlayContact(rushRunCue, foot)) { PlayFootstep(val, volume); } } } private void TickFootstepAudio(float deltaTime) { _stepEventGap = SnipjackLocomotion.AdvanceStepEventGap(_stepEventGap, deltaTime, ((Object)(object)base.creatureAnimator != (Object)null) ? base.creatureAnimator.speed : 1f, _stepEventArrived); _stepEventArrived = false; if (base.currentBehaviourStateIndex != 0 && base.currentBehaviourStateIndex != 1 && base.currentBehaviourStateIndex != 2) { _footstepAudioTimer = 0f; } else { if (!SnipjackLocomotion.TimerFootstepsActive(_stepEventGap) || _walkHold || (base.currentBehaviourStateIndex == 0 && _measuredSpeed < 0.1f)) { return; } bool flag = base.currentBehaviourStateIndex == 2; float volume; AudioClip val = CurrentFootstepClip(out volume); if ((Object)(object)val == (Object)null) { return; } _footstepAudioTimer -= deltaTime; if (!(_footstepAudioTimer > 0f)) { float num = (flag ? 0.42f : 1.35f); _footstepAudioTimer = Mathf.Max(0.12f, (val.length > 0f) ? (val.length * 0.9f) : num); if (PlayFootstep(val, volume) && !_loggedTimerFootsteps) { _loggedTimerFootsteps = true; Plugin.Log.LogInfo((object)$"[ScissorsCreature] No OnStep animation events for {2f:0.##} s of walk animation; using timer footsteps (fallback)."); } } } } private AudioClip CurrentFootstepClip(out float volume) { if (base.currentBehaviourStateIndex == 2) { volume = 1.35f; if (!((Object)(object)attackRunClip != (Object)null)) { return footstepClip; } return attackRunClip; } volume = 1.15f; if (base.currentBehaviourStateIndex != 0 && base.currentBehaviourStateIndex != 1) { return null; } return footstepClip; } private bool PlayFootstep(AudioClip clip, float volume) { if ((Object)(object)footstepAudioSource == (Object)null || Time.time - _lastFootstepSoundTime < 0.08f) { return false; } _lastFootstepSoundTime = Time.time; footstepAudioSource.PlayOneShot(clip, volume); return true; } private void TickWindupTickingAudio() { if (!_windupTickingActive && base.currentBehaviourStateIndex != 1) { StopWindupTicking(resetRepeatCount: true); return; } _windupTickingActive = true; if (!((Object)(object)tickingClip == (Object)null) && !((Object)(object)tickingAudioSource == (Object)null) && !tickingAudioSource.isPlaying) { tickingAudioSource.clip = tickingClip; tickingAudioSource.loop = false; tickingAudioSource.volume = 1.25f; tickingAudioSource.pitch = Mathf.Min(2.5f, 1.15f + (float)_tickingRepeatCount * 0.2f); tickingAudioSource.time = 0f; tickingAudioSource.Play(); _tickingRepeatCount++; } } private void StopWindupTicking(bool resetRepeatCount) { if ((Object)(object)tickingAudioSource != (Object)null) { tickingAudioSource.Stop(); tickingAudioSource.loop = false; tickingAudioSource.pitch = 1f; tickingAudioSource.time = 0f; } if (resetRepeatCount) { _tickingRepeatCount = 0; } } private void TickAttackAlarmAudio() { if (base.currentBehaviourStateIndex != 2) { StopAttackAlarm(); } else if (!((Object)(object)alarmClip == (Object)null) && !((Object)(object)alarmAudioSource == (Object)null) && !alarmAudioSource.isPlaying) { alarmAudioSource.clip = alarmClip; alarmAudioSource.loop = true; alarmAudioSource.volume = 1.25f; alarmAudioSource.pitch = 1f; alarmAudioSource.Play(); } } private void StopAttackAlarm() { if (!((Object)(object)alarmAudioSource == (Object)null)) { alarmAudioSource.Stop(); alarmAudioSource.loop = false; alarmAudioSource.pitch = 1f; alarmAudioSource.time = 0f; } } private void TickSnipAudio(float deltaTime) { if (base.currentBehaviourStateIndex != 2 || snipClips == null || snipClips.Length == 0 || (Object)(object)base.creatureSFX == (Object)null) { return; } _snipAudioTimer -= deltaTime; if (!(_snipAudioTimer > 0f)) { _snipAudioTimer = 0.27f; AudioClip val = snipClips[Random.Range(0, snipClips.Length)]; if ((Object)(object)val != (Object)null) { base.creatureSFX.PlayOneShot(val, 2.6f); } } } private void PlayAttackedByPlayerAudio() { if (!((Object)(object)attackedByPlayerClip == (Object)null)) { AudioSource val = (((Object)(object)base.creatureVoice != (Object)null) ? base.creatureVoice : base.creatureSFX); if ((Object)(object)val != (Object)null) { val.PlayOneShot(attackedByPlayerClip, 9f); } } } [ServerRpc(RequireOwnership = false)] public void ReportSnipKillServerRpc(int victimSlot, ServerRpcParams rpcParams = default(ServerRpcParams)) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Invalid comparison between Unknown and I4 //IL_0099: Unknown result type (might be due to invalid IL or missing references) //IL_00a3: Invalid comparison between Unknown and I4 //IL_005f: Unknown result type (might be due to invalid IL or missing references) //IL_0068: Unknown result type (might be due to invalid IL or missing references) //IL_006d: Unknown result type (might be due to invalid IL or missing references) //IL_0071: Unknown result type (might be due to invalid IL or missing references) //IL_0089: Unknown result type (might be due to invalid IL or missing references) //IL_00ce: Unknown result type (might be due to invalid IL or missing references) //IL_00e9: Unknown result type (might be due to invalid IL or missing references) //IL_00ea: Unknown result type (might be due to invalid IL or missing references) NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager; if (networkManager == null || !networkManager.IsListening) { return; } if ((int)((NetworkBehaviour)this).__rpc_exec_stage != 1 && (networkManager.IsClient || networkManager.IsHost)) { FastBufferWriter val = ((NetworkBehaviour)this).__beginSendServerRpc(2154611850u, rpcParams, (RpcDelivery)0); BytePacker.WriteValueBitPacked(val, victimSlot); ((NetworkBehaviour)this).__endSendServerRpc(ref val, 2154611850u, rpcParams, (RpcDelivery)0); } if ((int)((NetworkBehaviour)this).__rpc_exec_stage == 1 && (networkManager.IsServer || networkManager.IsHost)) { ((NetworkBehaviour)this).__rpc_exec_stage = (__RpcExecStage)0; PlayerControllerB val2 = VictimRpc.FromSlot(victimSlot); if (!((Object)(object)val2 == (Object)null) && val2.actualClientId == rpcParams.Receive.SenderClientId) { PlaySnipKillClientRpc(); } } } [ClientRpc] private void PlaySnipKillClientRpc() { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Invalid comparison between Unknown and I4 //IL_008c: Unknown result type (might be due to invalid IL or missing references) //IL_0096: Invalid comparison between Unknown and I4 //IL_005f: Unknown result type (might be due to inval
Y4NGZToyZombies.dll
Decompiled a day ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security.Cryptography; using System.Text; using System.Text.RegularExpressions; using BepInEx; using BepInEx.Configuration; using BepInEx.Logging; using Dawn; using GameNetcodeStuff; using Microsoft.CodeAnalysis; using Unity.Netcode; using UnityEngine; using UnityEngine.AI; using UnityEngine.Audio; using UnityEngine.Events; using UnityEngine.Rendering; using UnityEngine.Rendering.HighDefinition; using UnityEngine.UI; using Y4NGZMonsters.Shared; using Y4NGZToyZombies; using Y4NGZToyZombies.NetcodePatcher; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: AssemblyCompany("Y4NGZToyZombies")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0+3460ec64f0cec4948e51ddb3f02a4b0e414f105e")] [assembly: AssemblyProduct("Y4NGZToyZombies")] [assembly: AssemblyTitle("Y4NGZToyZombies")] [assembly: AssemblyVersion("1.0.0.0")] [module: RefSafetyRules(11)] [module: NetcodePatchedAssembly] 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 Y4NGZToyZombies { internal static class FlashlightWatch { private const float SwitchStaleSeconds = 1f; private static readonly bool[] Seen = new bool[32]; private static readonly ulong[] Occupant = new ulong[32]; private static readonly float[] SampledAt = new float[32]; private static readonly bool[] Reported = new bool[32]; private static readonly bool[] On = new bool[32]; private static readonly float[] SwitchedOnAt = new float[32]; private static readonly int[] Source = new int[32]; private static int _sampledFrame = -1; private static int _localFrame = -1; private static bool _localOn; private static bool _localReported; private static float _localReadAt = float.NegativeInfinity; internal static void Sample() { int frameCount = Time.frameCount; if (frameCount == _sampledFrame) { return; } _sampledFrame = frameCount; StartOfRound instance = StartOfRound.Instance; PlayerControllerB[] array = (((Object)(object)instance != (Object)null) ? instance.allPlayerScripts : null); if (array == null) { return; } float time = Time.time; for (int i = 0; i < array.Length && i < 32; i++) { PlayerControllerB val = array[i]; if ((Object)(object)val == (Object)null) { continue; } int num = (int)val.playerClientId; if (num < 0 || num >= 32) { continue; } if (!ToyZombieAI.IsCounted(val)) { Clear(num); continue; } if (Occupant[num] != val.actualClientId) { Clear(num); Occupant[num] = val.actualClientId; } int source; bool flag = ReadOn(val, out source); int num2; if (Seen[num]) { num2 = ((time - SampledAt[num] > 1f) ? 1 : 0); if (num2 == 0) { goto IL_00e9; } } else { num2 = 1; } if (Seen[num]) { Reported[num] = false; } goto IL_00e9; IL_00e9: bool flag2 = flag || Reported[num]; if (num2 != 0) { Seen[num] = true; SwitchedOnAt[num] = float.NegativeInfinity; } else if (flag2 && !On[num] && source == Source[num]) { SwitchedOnAt[num] = time; } On[num] = flag2; Source[num] = source; SampledAt[num] = time; } } internal static bool IsOn(PlayerControllerB player) { int num = SeenSlot(player); if (num >= 0) { return On[num]; } return false; } internal static bool SwitchedOnThisTick(PlayerControllerB player, ref float handledAt) { int num = SeenSlot(player); if (num < 0) { return false; } float num2 = SwitchedOnAt[num]; if (num2 <= handledAt || Time.time - num2 > 1f) { return false; } handledAt = num2; return true; } internal static bool IsLighting(PlayerControllerB player, ToyZombieAI toy) { if (!Measure(player, toy, out var lineOfSight, out var distance, out var facingAngle)) { return false; } return IsLighting(player, lineOfSight, distance, facingAngle); } internal static bool IsLookingAt(PlayerControllerB player, ToyZombieAI toy) { if (!Measure(player, toy, out var lineOfSight, out var _, out var facingAngle)) { return false; } return IsLookingAt(lineOfSight, facingAngle); } internal static bool IsLighting(PlayerControllerB player, bool lineOfSight, float distance, float facingAngle) { ToyZombieConfig modConfig = Plugin.ModConfig; if (lineOfSight && distance <= modConfig.FlashlightBeamRange.Value && facingAngle <= modConfig.FlashlightBeamAngle.Value) { return IsOn(player); } return false; } internal static bool IsLookingAt(bool lineOfSight, float facingAngle) { if (lineOfSight) { return facingAngle <= Plugin.ModConfig.LookAngle.Value; } return false; } internal static void HostReport(PlayerControllerB player, bool on) { if ((Object)(object)player == (Object)null) { return; } int num = (int)player.playerClientId; if (num >= 0 && num < 32) { if (Occupant[num] != player.actualClientId) { Clear(num); Occupant[num] = player.actualClientId; } Reported[num] = on; } } internal static void LocalFrame(ToyZombieAI toy) { int frameCount = Time.frameCount; if (frameCount != _localFrame) { _localFrame = frameCount; float time = Time.time; if (time - _localReadAt > 1f) { _localReported = false; } _localReadAt = time; GameNetworkManager instance = GameNetworkManager.Instance; PlayerControllerB player = (((Object)(object)instance != (Object)null) ? instance.localPlayerController : null); _localOn = ToyZombieAI.IsCounted(player) && ReadOn(player, out var _); } if (_localOn != _localReported && !((Object)(object)toy == (Object)null) && ((NetworkBehaviour)toy).IsSpawned && toy.HasKind) { _localReported = _localOn; toy.ReportLocalFlashlightSwitch(_localOn); } } private static bool ReadOn(PlayerControllerB player, out int source) { GrabbableObject currentlyHeldObjectServer = player.currentlyHeldObjectServer; FlashlightItem val = (FlashlightItem)(object)((currentlyHeldObjectServer is FlashlightItem) ? currentlyHeldObjectServer : null); GrabbableObject pocketedFlashlight = player.pocketedFlashlight; FlashlightItem val2 = (FlashlightItem)(object)((pocketedFlashlight is FlashlightItem) ? pocketedFlashlight : null); if ((Object)(object)val2 != (Object)null && (!((GrabbableObject)val2).isHeld || !((Object)(object)((GrabbableObject)val2).playerHeldBy == (Object)(object)player))) { val2 = null; } source = (((Object)(object)val != (Object)null) ? ((Object)val).GetInstanceID() : (((Object)(object)val2 != (Object)null) ? ((Object)val2).GetInstanceID() : 0)); if ((!((Object)(object)val != (Object)null) || !((GrabbableObject)val).isBeingUsed) && (!((Object)(object)val2 != (Object)null) || !((GrabbableObject)val2).isBeingUsed)) { if ((Object)(object)player.helmetLight != (Object)null) { return ((Behaviour)player.helmetLight).enabled; } return false; } return true; } private static bool Measure(PlayerControllerB player, ToyZombieAI toy, out bool lineOfSight, out float distance, out float facingAngle) { //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_0034: Unknown result type (might be due to invalid IL or missing references) //IL_0040: Unknown result type (might be due to invalid IL or missing references) //IL_0041: Unknown result type (might be due to invalid IL or missing references) //IL_004a: 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_004c: Unknown result type (might be due to invalid IL or missing references) //IL_004d: Unknown result type (might be due to invalid IL or missing references) //IL_0059: Unknown result type (might be due to invalid IL or missing references) //IL_005a: Unknown result type (might be due to invalid IL or missing references) lineOfSight = false; distance = float.PositiveInfinity; facingAngle = 180f; if ((Object)(object)player == (Object)null || (Object)(object)toy == (Object)null || !ToyZombieAI.IsCounted(player)) { return false; } Vector3 eyePosition = toy.EyePosition; ToyZombieAI.PlayerEye(player, out var position, out var forward); distance = Vector3.Distance(eyePosition, position); facingAngle = Vector3.Angle(forward, eyePosition - position); lineOfSight = ToyZombieAI.HostLineOfSight(eyePosition, position, ((Component)toy).transform); return true; } private static int SeenSlot(PlayerControllerB player) { if ((Object)(object)player == (Object)null) { return -1; } int num = (int)player.playerClientId; if (num < 0 || num >= 32 || !Seen[num] || Occupant[num] != player.actualClientId) { return -1; } return num; } private static void Clear(int slot) { Seen[slot] = false; Reported[slot] = false; On[slot] = false; SwitchedOnAt[slot] = float.NegativeInfinity; } } internal static class HideSpots { private const int HideMaxHiddenTests = 12; private const float NavSampleDistance = 3f; private const float MinEyeHeight = 0.5f; private static readonly Func<int, Vector3, bool> HiddenTest = IsHidden; private static readonly ReachableSpot<Vector3> ToyReachableTest = IsReachableByToy; private static readonly Func<int, bool> PlayerReachableTest = IsReachableFromPlayer; private static Vector3[] _points = Array.Empty<Vector3>(); private static Vector3[] _snapped = Array.Empty<Vector3>(); private static float[] _distance = Array.Empty<float>(); private static float[] _toyDistance = Array.Empty<float>(); private static int[] _order = Array.Empty<int>(); private static NavMeshPath _path; private static ToyZombieAI _toy; private static float _eyeHeight; private static Vector3 _playerNavPoint; private static bool _hasPlayerNavPoint; private static NavMeshPath Path { get { //IL_0009: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Expected O, but got Unknown object obj = _path; if (obj == null) { NavMeshPath val = new NavMeshPath(); _path = val; obj = (object)val; } return (NavMeshPath)obj; } } internal static bool TryFindHidingSpot(ToyZombieAI toy, out Vector3 point) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_005b: Unknown result type (might be due to invalid IL or missing references) //IL_0060: Unknown result type (might be due to invalid IL or missing references) //IL_0062: Unknown result type (might be due to invalid IL or missing references) //IL_006f: Unknown result type (might be due to invalid IL or missing references) //IL_006c: Unknown result type (might be due to invalid IL or missing references) //IL_0070: Unknown result type (might be due to invalid IL or missing references) //IL_00e2: Unknown result type (might be due to invalid IL or missing references) //IL_00ec: Unknown result type (might be due to invalid IL or missing references) //IL_008e: Unknown result type (might be due to invalid IL or missing references) //IL_0093: Unknown result type (might be due to invalid IL or missing references) //IL_009c: Unknown result type (might be due to invalid IL or missing references) //IL_009e: Unknown result type (might be due to invalid IL or missing references) //IL_00aa: Unknown result type (might be due to invalid IL or missing references) //IL_00ab: Unknown result type (might be due to invalid IL or missing references) //IL_00ba: Unknown result type (might be due to invalid IL or missing references) //IL_00bb: Unknown result type (might be due to invalid IL or missing references) point = default(Vector3); if ((Object)(object)toy == (Object)null || !((NetworkBehaviour)toy).IsServer || !toy.HasKind || (Object)(object)((EnemyAI)toy).agent == (Object)null || !((EnemyAI)toy).agent.isOnNavMesh) { return false; } GameObject[] allAINodes = ((EnemyAI)toy).allAINodes; if (allAINodes == null || allAINodes.Length == 0) { return false; } EnsureCapacity(allAINodes.Length); Vector3 position = ((Component)toy).transform.position; Vector3 position2; Vector3 val = (NearestTargetablePlayer(toy, position, out position2) ? position2 : position); int num = 0; for (int i = 0; i < allAINodes.Length; i++) { if (!((Object)(object)allAINodes[i] == (Object)null)) { Vector3 position3 = allAINodes[i].transform.position; _points[num] = position3; _distance[num] = Vector3.Distance(val, position3); _toyDistance[num] = Vector3.Distance(position, position3); num++; } } _toy = toy; _eyeHeight = Mathf.Max(0.5f, toy.EyePosition.y - position.y); bool isHidden; int num2 = ToySensesLogic.ChooseHidingSpot(num, _distance, _toyDistance, Plugin.ModConfig.HideSearchRadius.Value, _order, HiddenTest, ToyReachableTest, 12, out isHidden, out point); _toy = null; return num2 >= 0; } internal static bool TryFindPointNear(PlayerControllerB player, float distance, out Vector3 point) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0065: Unknown result type (might be due to invalid IL or missing references) //IL_006a: Unknown result type (might be due to invalid IL or missing references) //IL_00c0: Unknown result type (might be due to invalid IL or missing references) //IL_00d5: Unknown result type (might be due to invalid IL or missing references) //IL_00da: Unknown result type (might be due to invalid IL or missing references) //IL_0088: Unknown result type (might be due to invalid IL or missing references) //IL_008d: Unknown result type (might be due to invalid IL or missing references) //IL_0096: Unknown result type (might be due to invalid IL or missing references) //IL_0098: Unknown result type (might be due to invalid IL or missing references) //IL_00a4: Unknown result type (might be due to invalid IL or missing references) //IL_00a5: Unknown result type (might be due to invalid IL or missing references) //IL_0107: Unknown result type (might be due to invalid IL or missing references) //IL_010c: Unknown result type (might be due to invalid IL or missing references) point = default(Vector3); NetworkManager singleton = NetworkManager.Singleton; RoundManager instance = RoundManager.Instance; if ((Object)(object)singleton == (Object)null || !singleton.IsServer || (Object)(object)instance == (Object)null || !ToyZombieAI.IsCounted(player)) { return false; } GameObject[] array = (player.isInsideFactory ? instance.insideAINodes : instance.outsideAINodes); if (array == null || array.Length == 0) { return false; } EnsureCapacity(array.Length); Vector3 position = ((Component)player).transform.position; int num = 0; for (int i = 0; i < array.Length; i++) { if (!((Object)(object)array[i] == (Object)null)) { Vector3 position2 = array[i].transform.position; _points[num] = position2; _distance[num] = Vector3.Distance(position, position2); num++; } } NavMeshHit val = default(NavMeshHit); _hasPlayerNavPoint = NavMesh.SamplePosition(position, ref val, 3f, -1); _playerNavPoint = ((NavMeshHit)(ref val)).position; int num2 = ToySensesLogic.ChoosePointNear(num, _distance, distance, _order, PlayerReachableTest); if (num2 < 0) { return false; } point = _snapped[num2]; return true; } private static bool IsHidden(int index, Vector3 spot) { //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Unknown result type (might be due to invalid IL or missing references) //IL_0063: Unknown result type (might be due to invalid IL or missing references) //IL_0065: Unknown result type (might be due to invalid IL or missing references) StartOfRound instance = StartOfRound.Instance; PlayerControllerB[] array = (((Object)(object)instance != (Object)null) ? instance.allPlayerScripts : null); if (array == null) { return true; } Vector3 to = spot + Vector3.up * _eyeHeight; Transform transform = ((Component)_toy).transform; for (int i = 0; i < array.Length && i < 32; i++) { PlayerControllerB player = array[i]; if (_toy.HostMayTarget(player)) { ToyZombieAI.PlayerEye(player, out var position, out var _); if (ToyZombieAI.HostLineOfSight(position, to, transform)) { return false; } } } return true; } private static bool IsReachableByToy(int index, out Vector3 snapped) { //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Unknown result type (might be due to invalid IL or missing references) //IL_003b: Unknown result type (might be due to invalid IL or missing references) //IL_0049: Unknown result type (might be due to invalid IL or missing references) //IL_0057: Unknown result type (might be due to invalid IL or missing references) //IL_005d: Invalid comparison between Unknown and I4 NavMeshAgent agent = ((EnemyAI)_toy).agent; snapped = default(Vector3); NavMeshHit val = default(NavMeshHit); if (!NavMesh.SamplePosition(_points[index], ref val, 3f, agent.areaMask)) { return false; } snapped = ((NavMeshHit)(ref val)).position; NavMeshPath path = Path; if (agent.CalculatePath(((NavMeshHit)(ref val)).position, path)) { return (int)path.status == 0; } return false; } private static bool IsReachableFromPlayer(int index) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_003d: Unknown result type (might be due to invalid IL or missing references) //IL_0044: Unknown result type (might be due to invalid IL or missing references) //IL_0053: Unknown result type (might be due to invalid IL or missing references) //IL_0059: Invalid comparison between Unknown and I4 NavMeshHit val = default(NavMeshHit); if (!NavMesh.SamplePosition(_points[index], ref val, 3f, -1)) { return false; } _snapped[index] = ((NavMeshHit)(ref val)).position; if (!_hasPlayerNavPoint) { return true; } NavMeshPath path = Path; if (NavMesh.CalculatePath(_playerNavPoint, ((NavMeshHit)(ref val)).position, -1, path)) { return (int)path.status == 0; } return false; } private static bool NearestTargetablePlayer(ToyZombieAI toy, Vector3 from, out Vector3 position) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0045: Unknown result type (might be due to invalid IL or missing references) //IL_004a: Unknown result type (might be due to invalid IL or missing references) //IL_004c: Unknown result type (might be due to invalid IL or missing references) //IL_004e: Unknown result type (might be due to invalid IL or missing references) //IL_004f: Unknown result type (might be due to invalid IL or missing references) //IL_0054: Unknown result type (might be due to invalid IL or missing references) //IL_0068: 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) position = default(Vector3); StartOfRound instance = StartOfRound.Instance; PlayerControllerB[] array = (((Object)(object)instance != (Object)null) ? instance.allPlayerScripts : null); if (array == null) { return false; } float num = float.PositiveInfinity; for (int i = 0; i < array.Length && i < 32; i++) { PlayerControllerB val = array[i]; if (toy.HostMayTarget(val)) { Vector3 position2 = ((Component)val).transform.position; Vector3 val2 = position2 - from; float sqrMagnitude = ((Vector3)(ref val2)).sqrMagnitude; if (sqrMagnitude < num) { num = sqrMagnitude; position = position2; } } } return num < float.PositiveInfinity; } private static void EnsureCapacity(int count) { if (_points.Length < count) { _points = (Vector3[])(object)new Vector3[count]; _snapped = (Vector3[])(object)new Vector3[count]; _distance = new float[count]; _toyDistance = new float[count]; _order = new int[count]; } } } internal interface IToyZombieSkill { void Attach(ToyZombieAI toy); void Reset(); void Detach(); bool HostTick(float dt); void HostFrame(float dt); bool IgnoresPlayer(PlayerControllerB player); bool ForcesNotice(PlayerControllerB player); ToyGait ChooseGait(ToyGait proposed, PlayerControllerB target); float GaitSpeed(ToyGait gait, float proposed); string GaitClip(ToyGait gait, string proposed); float GaitClipSpeed(ToyGait gait, float proposed); string IdleClip(string proposed); float IdleClipSpeed(float proposed); float DamageMultiplier(PlayerControllerB victim); bool OwnHitRange(PlayerControllerB victim, out int min, out int max); bool MayBeStunned(PlayerControllerB by); bool MayPeek(); bool MayWhisper(); bool IsShown(); bool MayCatch(PlayerControllerB victim); bool OwnsMovement(); void OnSpawned(); void OnTargetGained(PlayerControllerB player); void OnTargetLost(PlayerControllerB player); void OnNoiseHeard(Vector3 position, float loudness, int noiseID); void OnDamaged(int force, PlayerControllerB by); void OnFlashlightSwitchedOn(PlayerControllerB player); void OnStunned(PlayerControllerB by); void OnCatchLanded(PlayerControllerB victim, bool execution); void OnDied(); void OnRevived(); void OnReachedDestination(); void OnAlerted(PlayerControllerB player, float seconds); void OnClientReport(PlayerControllerB reporter, byte id, int value); void OnClipEvent(string name); void OnStateChanged(ToyState previous, ToyState current); void OnSkillStateChanged(byte previous, byte current); void OnSkillEvent(byte id, int value, Vector3 vector); void LocalFrame(float dt); } internal struct PeekVec3 { internal float X; internal float Y; internal float Z; internal static readonly PeekVec3 Up = new PeekVec3(0f, 1f, 0f); internal float Length => (float)Math.Sqrt(X * X + Y * Y + Z * Z); internal PeekVec3 Normalized { get { float length = Length; if (!(length > 0f)) { return default(PeekVec3); } return this * (1f / length); } } internal PeekVec3 Flat => new PeekVec3(X, 0f, Z); internal PeekVec3(float x, float y, float z) { X = x; Y = y; Z = z; } public static PeekVec3 operator +(PeekVec3 a, PeekVec3 b) { return new PeekVec3(a.X + b.X, a.Y + b.Y, a.Z + b.Z); } public static PeekVec3 operator -(PeekVec3 a, PeekVec3 b) { return new PeekVec3(a.X - b.X, a.Y - b.Y, a.Z - b.Z); } public static PeekVec3 operator -(PeekVec3 a) { return new PeekVec3(0f - a.X, 0f - a.Y, 0f - a.Z); } public static PeekVec3 operator *(PeekVec3 a, float scale) { return new PeekVec3(a.X * scale, a.Y * scale, a.Z * scale); } internal static float Dot(PeekVec3 a, PeekVec3 b) { return a.X * b.X + a.Y * b.Y + a.Z * b.Z; } internal static PeekVec3 Cross(PeekVec3 a, PeekVec3 b) { return new PeekVec3(a.Y * b.Z - a.Z * b.Y, a.Z * b.X - a.X * b.Z, a.X * b.Y - a.Y * b.X); } } internal struct PeekRayHit { internal PeekVec3 Point; internal PeekVec3 Normal; } internal interface IPeekWorld { bool Raycast(PeekVec3 from, PeekVec3 to, out PeekRayHit hit); bool SampleNavMesh(PeekVec3 point, float maxDistance, out PeekVec3 onMesh); bool Occupied(PeekVec3 point, float radius); } internal struct PeekCornerSettings { internal float ForwardRange; internal float SideOffset; internal float BodyWidth; internal float BodyHeight; internal float StepForward; internal float StepSide; internal float ViewYawOffsetDegrees; } internal enum PeekRefusal : byte { None, NoWallAhead, NoSideWall, SideInView, NoFloor, NoHeadroom, NoCornerWall, CornerNotVisible, TooNarrow, NoNavMesh, NotHidden, Occupied } internal struct PeekCorner { internal PeekVec3 Exit; internal PeekVec3 Hidden; internal PeekVec3 HiddenFacing; internal bool OnRight; internal int StepSign; } internal static class PeekCornerFinder { private const float SurfaceOffset = 0.04f; private const float EdgeMargin = 0.05f; private const float PastEdge = 0.17335501f; private const float Slack = 0.17335501f; private const float WallMaxNormalY = 0.5f; private const float MaxFloorDrop = 4f; private const float FloorStep = 0.3f; private const float FloorLevel = 0.05f; private const float NavSnap = 0.35f; private const float MinViewIntoWall = 0.2f; private const float MaxWallParallel = 0.5f; internal static PeekRefusal TryFind<TWorld>(ref TWorld world, PeekVec3 eye, PeekVec3 viewForward, in PeekCornerSettings settings, out PeekCorner corner) where TWorld : IPeekWorld { corner = default(PeekCorner); PeekVec3 up = PeekVec3.Up; PeekVec3 peekVec = RotateYaw(viewForward.Normalized, settings.ViewYawOffsetDegrees); if (peekVec.Flat.Length < 0.001f) { return PeekRefusal.NoWallAhead; } ref TWorld reference = ref world; TWorld val = default(TWorld); if (val == null) { val = reference; reference = ref val; } PeekVec3 to = eye + peekVec * settings.ForwardRange; if (!reference.Raycast(eye, to, out var hit)) { return PeekRefusal.NoWallAhead; } if (!IsWall(hit.Normal)) { peekVec = peekVec.Flat.Normalized; ref TWorld reference2 = ref world; val = default(TWorld); if (val == null) { val = reference2; reference2 = ref val; } PeekVec3 to2 = eye + peekVec * settings.ForwardRange; if (!reference2.Raycast(eye, to2, out hit) || !IsWall(hit.Normal)) { return PeekRefusal.NoWallAhead; } } PeekVec3 point = hit.Point; PeekVec3 normalized = hit.Normal.Flat.Normalized; PeekVec3 normalized2 = peekVec.Flat.Normalized; if (PeekVec3.Dot(-normalized2, normalized) < 0.2f) { return PeekRefusal.NoWallAhead; } PeekVec3 peekVec2 = PeekVec3.Cross(up, normalized2); PeekVec3 peekVec3 = point + normalized * 0.04f; ref TWorld reference3 = ref world; val = default(TWorld); if (val == null) { val = reference3; reference3 = ref val; } PeekVec3 to3 = eye - peekVec2 * settings.SideOffset; PeekRayHit hit2; bool flag = reference3.Raycast(peekVec3, to3, out hit2); ref TWorld reference4 = ref world; val = default(TWorld); if (val == null) { val = reference4; reference4 = ref val; } PeekVec3 to4 = eye + peekVec2 * settings.SideOffset; PeekRayHit hit3; bool flag2 = reference4.Raycast(peekVec3, to4, out hit3); if (!flag && !flag2) { return PeekRefusal.NoSideWall; } bool flag3 = !flag; PeekRayHit peekRayHit = (flag3 ? hit3 : hit2); ref TWorld reference5 = ref world; val = default(TWorld); if (val == null) { val = reference5; reference5 = ref val; } PeekVec3 peekVec4 = peekRayHit.Point + peekRayHit.Normal * 0.04f; if (!reference5.Raycast(peekVec4, eye, out var hit4)) { if (!(flag3 ? flag : flag2)) { return PeekRefusal.SideInView; } flag3 = !flag3; peekRayHit = (flag3 ? hit3 : hit2); ref TWorld reference6 = ref world; val = default(TWorld); if (val == null) { val = reference6; reference6 = ref val; } PeekVec3 peekVec5 = peekRayHit.Point + peekRayHit.Normal * 0.04f; if (!reference6.Raycast(peekVec5, eye, out hit4)) { return PeekRefusal.SideInView; } } PeekVec3 point2 = hit4.Point; PeekVec3 peekVec6 = point2 + hit4.Normal * 0.04f; ref TWorld reference7 = ref world; val = default(TWorld); if (val == null) { val = reference7; reference7 = ref val; } PeekVec3 to5 = peekVec6 - up * 4f; if (!reference7.Raycast(peekVec6, to5, out var hit5)) { return PeekRefusal.NoFloor; } if (!HasHeadroom(ref world, hit5.Point, settings.BodyHeight)) { return PeekRefusal.NoHeadroom; } float y = hit5.Point.Y + settings.BodyHeight * 0.5f; float num = PeekVec3.Dot(point2 - point, normalized); if (num <= 0f) { return PeekRefusal.NoCornerWall; } PeekVec3 peekVec7 = point - normalized2 * ((num + 0.05f) / PeekVec3.Dot(-normalized2, normalized)); peekVec7.Y = y; PeekVec3 peekVec8 = point2 + normalized * 0.05f; peekVec8.Y = y; PeekVec3 peekVec9 = peekVec7; PeekVec3 to6 = peekVec8; if (!world.Raycast(peekVec9, to6, out var hit6) || !IsWall(hit6.Normal)) { return PeekRefusal.NoCornerWall; } PeekVec3 normalized3 = hit6.Normal.Flat.Normalized; if (Math.Abs(PeekVec3.Dot(normalized3, normalized)) > 0.5f) { return PeekRefusal.NoCornerWall; } PeekVec3 point3 = hit6.Point; if (PeekVec3.Dot(normalized3, (peekVec7 - point3).Flat) <= 0f) { return PeekRefusal.NoCornerWall; } ref TWorld reference8 = ref world; val = default(TWorld); if (val == null) { val = reference8; reference8 = ref val; } PeekVec3 peekVec10 = point3 + normalized3 * 0.04f; if (reference8.Raycast(peekVec10, eye, out var hit7)) { return PeekRefusal.CornerNotVisible; } PeekVec3 peekVec11 = PeekVec3.Cross(up, normalized3); PeekVec3 peekVec12 = ((PeekVec3.Dot(peekVec11, normalized) > 0f) ? peekVec11 : (-peekVec11)); PeekVec3 peekVec13 = point3 - peekVec12 * 0.05f; float num2 = settings.BodyWidth + 0.17335501f; float num3 = settings.BodyWidth * 1.1f + 0.17335501f; PeekVec3 peekVec14 = peekVec13 - peekVec12 * 0.17335501f; PeekVec3 peekVec15 = peekVec14 + normalized3 * (num3 * 0.5f); PeekVec3 peekVec16 = peekVec15 - peekVec12 * num2; PeekVec3 peekVec17 = peekVec16 - normalized3 * num2; PeekVec3 peekVec18 = peekVec17 + normalized3 * settings.StepForward + peekVec12 * settings.StepSide; float num4 = settings.BodyHeight * 0.5f + 0.3f; ref TWorld reference9 = ref world; val = default(TWorld); if (val == null) { val = reference9; reference9 = ref val; } PeekVec3 peekVec19 = peekVec18; PeekVec3 to7 = peekVec18 - up * num4; if (!reference9.Raycast(peekVec19, to7, out var hit8)) { return PeekRefusal.NoFloor; } PeekVec3 point4 = hit8.Point; if (!world.SampleNavMesh(point4, 0.35f, out var onMesh)) { return PeekRefusal.NoNavMesh; } PeekVec3 flat = (onMesh - hit8.Point).Flat; if (flat.Length > 0.35f || Math.Abs(onMesh.Y - hit8.Point.Y) > 0.3f) { return PeekRefusal.NoNavMesh; } peekVec14 += flat; peekVec15 += flat; peekVec16 += flat; peekVec17 += flat; peekVec18 += flat; if (!Clear(ref world, peekVec14, peekVec14 + normalized3 * num3) || !Clear(ref world, peekVec15, peekVec16) || !Clear(ref world, peekVec16, peekVec17) || !Clear(ref world, peekVec17, peekVec17 + peekVec12 * settings.BodyWidth) || !Clear(ref world, peekVec17, peekVec17 - peekVec12 * settings.BodyWidth) || !Clear(ref world, peekVec17, peekVec17 - normalized3 * settings.BodyWidth) || !Clear(ref world, peekVec17, peekVec18)) { return PeekRefusal.TooNarrow; } ref TWorld reference10 = ref world; val = default(TWorld); if (val == null) { val = reference10; reference10 = ref val; } PeekVec3 peekVec20 = peekVec17; PeekVec3 to8 = peekVec17 - up * num4; if (reference10.Raycast(peekVec20, to8, out var hit9)) { ref TWorld reference11 = ref world; val = default(TWorld); if (val == null) { val = reference11; reference11 = ref val; } PeekVec3 peekVec21 = peekVec18; PeekVec3 to9 = peekVec18 - up * num4; if (reference11.Raycast(peekVec21, to9, out hit8) && !(Math.Abs(hit8.Point.Y - hit9.Point.Y) > 0.05f)) { if (!HasHeadroom(ref world, hit9.Point, settings.BodyHeight) || !HasHeadroom(ref world, hit8.Point, settings.BodyHeight)) { return PeekRefusal.NoHeadroom; } PeekVec3 peekVec22 = onMesh; PeekVec3 point5 = hit9.Point; PeekVec3 peekVec23 = up * (settings.BodyHeight * 0.5f); ref TWorld reference12 = ref world; val = default(TWorld); if (val == null) { val = reference12; reference12 = ref val; } PeekVec3 to10 = point5 + peekVec23; if (!reference12.Raycast(eye, to10, out hit7)) { return PeekRefusal.NotHidden; } ref TWorld reference13 = ref world; val = default(TWorld); if (val == null) { val = reference13; reference13 = ref val; } PeekVec3 to11 = peekVec22 + peekVec23; if (reference13.Raycast(eye, to11, out hit7)) { return PeekRefusal.CornerNotVisible; } ref TWorld reference14 = ref world; val = default(TWorld); if (val == null) { val = reference14; reference14 = ref val; } PeekVec3 peekVec24 = point5 + peekVec23; PeekVec3 to12 = peekVec22 + peekVec23; if (reference14.Raycast(peekVec24, to12, out hit7)) { return PeekRefusal.TooNarrow; } float radius = settings.BodyWidth * 2f; if (!world.Occupied(point5, radius)) { float radius2 = settings.BodyWidth * 2f; if (!world.Occupied(peekVec22, radius2)) { corner.Exit = peekVec22; corner.Hidden = point5; corner.HiddenFacing = normalized3; corner.OnRight = flag3; corner.StepSign = ((PeekVec3.Dot(peekVec12, PeekVec3.Cross(up, normalized3)) > 0f) ? 1 : (-1)); return PeekRefusal.None; } } return PeekRefusal.Occupied; } } return PeekRefusal.NoFloor; } private static bool IsWall(PeekVec3 normal) { return Math.Abs(normal.Y) <= 0.5f; } private static PeekVec3 RotateYaw(PeekVec3 v, float degrees) { double num = (double)degrees * Math.PI / 180.0; float num2 = (float)Math.Sin(num); float num3 = (float)Math.Cos(num); return new PeekVec3(v.X * num3 + v.Z * num2, v.Y, (0f - v.X) * num2 + v.Z * num3); } private static bool Clear<TWorld>(ref TWorld world, PeekVec3 from, PeekVec3 to) where TWorld : IPeekWorld { PeekRayHit hit; return !world.Raycast(from, to, out hit); } private static bool HasHeadroom<TWorld>(ref TWorld world, PeekVec3 floorPoint, float bodyHeight) where TWorld : IPeekWorld { PeekRayHit hit; return !world.Raycast(floorPoint + PeekVec3.Up * 0.04f, floorPoint + PeekVec3.Up * bodyHeight, out hit); } } internal enum PeekGate : byte { Open, Disabled, KindCannotPeek, NoTarget, SeenByPlayer, TargetFacing, FlashlightOn, LockedOut, SkillVeto } internal struct PeekGateFacts { internal bool Enabled; internal bool KindCanPeek; internal bool HasTarget; internal bool SeenByAnyPlayer; internal bool TargetFacingToy; internal bool TargetFlashlightOn; internal bool SkillAllows; internal float LockoutRemaining; } internal readonly struct PeekStep { internal readonly float Side; internal readonly float Forward; internal readonly float YawDegrees; internal readonly float Seconds; internal PeekStep(float side, float forward, float yawDegrees, float seconds) { Side = side; Forward = forward; YawDegrees = yawDegrees; Seconds = seconds; } } internal static class PeekRules { internal const string StalkLeft = "stalk_l"; internal const string StalkRight = "stalk_r"; internal const string ReverseSuffix = "_reverse"; private const float RadiansToDegrees = 180f / MathF.PI; private const float DegreesToRadians = MathF.PI / 180f; private const double JustBelowOne = 0.999999999999; private static readonly PeekStep[] LeftSteps = BuildSteps(left: true); private static readonly PeekStep[] RightSteps = BuildSteps(left: false); internal static PeekGate MayStart(in PeekGateFacts facts) { if (!facts.Enabled) { return PeekGate.Disabled; } if (!facts.KindCanPeek) { return PeekGate.KindCannotPeek; } if (!facts.HasTarget) { return PeekGate.NoTarget; } if (facts.LockoutRemaining > 0f) { return PeekGate.LockedOut; } if (!facts.SkillAllows) { return PeekGate.SkillVeto; } if (facts.SeenByAnyPlayer) { return PeekGate.SeenByPlayer; } if (facts.TargetFacingToy) { return PeekGate.TargetFacing; } if (facts.TargetFlashlightOn) { return PeekGate.FlashlightOn; } return PeekGate.Open; } internal static bool LookRuleOn(float lookAngleDegrees) { return lookAngleDegrees > 0f; } internal static bool FacesToward(PeekVec3 eye, PeekVec3 viewForward, PeekVec3 point, float halfAngleDegrees) { PeekVec3 flat = viewForward.Flat; PeekVec3 flat2 = (point - eye).Flat; if (flat2.Length < 0.0001f) { return true; } if (flat.Length < 0.0001f) { return false; } return (float)Math.Atan2(Math.Abs(flat.X * flat2.Z - flat.Z * flat2.X), PeekVec3.Dot(flat, flat2)) * (180f / MathF.PI) <= halfAngleDegrees; } internal static float Roll(float min, float max, float unit) { if (max < min) { float num = min; min = max; max = num; } return min + (max - min) * Math.Min(1f, Math.Max(0f, unit)); } internal static float StepRoll(float min, float max, float unit) { if (max < min) { float num = min; min = max; max = num; } return (float)(Math.Floor(Math.Min(0.999999999999, Math.Max(0.0, unit)) * ((double)max - (double)min + 1.0)) + (double)min); } internal static float ViewYawOffset(ToyKind kind) { if (kind != ToyKind.BoBiGo) { return 0f; } return 180f; } internal static bool HasShortLockout(ToyKind kind) { return kind == ToyKind.BoBiGo; } internal static bool TryGetStep(ToyKind kind, bool left, float scale, out PeekStep step) { PeekStep[] array = (left ? LeftSteps : RightSteps); if (array[(uint)kind].Seconds <= 0f) { step = default(PeekStep); return false; } PeekStep peekStep = array[(uint)kind]; step = new PeekStep(peekStep.Side * scale, peekStep.Forward * scale, peekStep.YawDegrees, peekStep.Seconds); return true; } internal static string ForwardClip(ToyKind kind, int stepSign) { if (!TryGetStep(kind, left: true, 1f, out var step)) { return null; } if (step.Side < 0f != stepSign < 0) { return "stalk_r"; } return "stalk_l"; } internal static void OffsetAt(in PeekStep step, float lean, out float x, out float z, out float yawDegrees) { float num = Math.Min(1f, Math.Max(0f, lean)) - 1f; float num2 = (0f - step.YawDegrees) * (MathF.PI / 180f); float num3 = (float)Math.Sin(num2); float num4 = (float)Math.Cos(num2); x = (step.Side * num4 + step.Forward * num3) * num; z = ((0f - step.Side) * num3 + step.Forward * num4) * num; yawDegrees = step.YawDegrees * num; } private static PeekStep[] BuildSteps(bool left) { return new PeekStep[12] { default(PeekStep), left ? new PeekStep(-0.5715f, 0.5715f, -90f, 1f) : new PeekStep(0.5715f, 0.5715f, 90f, 1f), left ? new PeekStep(0.6096f, 0.60937f, 90f, 1.01667f) : new PeekStep(-0.6096f, 0.60937f, -90f, 1.01667f), left ? new PeekStep(-0.47808f, 0.54165f, -90.8637f, 1f) : new PeekStep(0.47808f, 0.54165f, 90.8637f, 1f), default(PeekStep), default(PeekStep), default(PeekStep), default(PeekStep), default(PeekStep), default(PeekStep), default(PeekStep), default(PeekStep) }; } } internal enum BearState : byte { None, Frozen } internal static class BearRules { internal const float FreezeRangeMetres = 9.525001f; internal const float TeleportDistanceMetres = 66.675f; internal const float FootstepShakeRadiusMetres = 13.335f; internal const float TeleportBlockSeconds = 1f; internal const float FadeInSeconds = 0f; internal const float FadeHoldSeconds = 0.1f; internal const float FadeOutSeconds = 0.3f; internal static float TeleportDelaySeconds(int difficulty) { return 2f * (float)SkillsBDifficulty.Clamp(difficulty); } internal static bool IsFrozen(bool skillEnabled, bool teleportBlocked, bool flashlightOn, bool inView, float eyeDistanceMetres) { if (skillEnabled && !teleportBlocked && flashlightOn && inView) { return eyeDistanceMetres < 9.525001f; } return false; } internal static bool TeleportDue(bool frozen, float now, float deadline) { if (frozen) { return now > deadline; } return false; } internal static bool OwnsMovement(BearState state) { return state == BearState.Frozen; } internal static bool FootstepShakes(float distanceMetres) { return distanceMetres < 13.335f; } } internal static class LionmionRules { internal const byte AwakeState = 0; internal const byte AsleepState = 1; internal const byte WakingState = 2; internal const float CheckInterval = 0.3f; internal const float FarUnits = 3000f; internal const float SleepSpotRadiusUnits = 2500f; internal const float HiddenPointHeightUnits = 45f; internal const float CentreHeightUnits = 36f; internal const float SleepEndClipSeconds = 0.66667f; internal const float MinSpotSqrMetres = 1f; internal const float OnMeshMetres = 0.5f; private const float SearchUnitsPerDifficulty = 250f; private const float SilentSpeedUnits = 100f; private const float WalkSpeedUnits = 200f; private const float RunSpeedUnits = 400f; private const float SilentWakeUnits = 20f; private const float WalkWakeUnits = 50f; private const float RunWakeUnits = 150f; private const float FastWakeUnits = 350f; private const float UnlitFactor = 0.75f; private const float LitFactor = 2f; internal static float SearchRadiusUnits(int difficulty) { return 250f * (float)SkillsCRules.ClampDifficulty(difficulty); } internal static bool IsShown(byte skillState) { return skillState == 0; } internal static bool OwnsMovement(byte skillState) { return skillState != 0; } internal static bool SpotFarEnough(float sqrDistanceMetres) { return sqrDistanceMetres >= 1f; } internal static float Factor(int difficulty, bool flashlightOn) { int num = SkillsCRules.ClampDifficulty(difficulty); float num2 = ((num >= 4) ? 1f : (flashlightOn ? 0.8f : ((num >= 2) ? 0.5f : 0f))); return (flashlightOn ? 2f : 0.75f) * num2; } internal static float WakeDistanceUnits(float speedUnits, int difficulty, bool flashlightOn) { int num = SkillsCRules.ClampDifficulty(difficulty); float num2 = ((speedUnits <= 100f) ? ((num >= 5) ? 20f : 0f) : ((speedUnits <= 200f) ? ((num >= 4) ? 50f : 0f) : ((!(speedUnits <= 400f)) ? 350f : 150f))); return num2 * Factor(num, flashlightOn); } internal static bool Wakes(float distanceUnits, float speedUnits, int difficulty, bool flashlightOn) { if (distanceUnits <= SearchRadiusUnits(difficulty)) { return distanceUnits < WakeDistanceUnits(speedUnits, difficulty, flashlightOn); } return false; } internal static float WakeClipSeconds(int difficulty) { return 0.66667f / SkillsCRules.SlowRate(difficulty); } internal static bool MaySleepIdle(bool moving, bool hasTarget, bool executing, float nearestPlayerUnits) { if (!moving && !hasTarget && !executing) { return nearestPlayerUnits >= 3000f; } return false; } } internal static class MannequinRules { internal const byte HiddenState = 0; internal const byte ShownState = 1; internal const byte VanishingState = 2; internal const float AppearClipSpeed = 2f; internal const float VanishClipSpeed = 3f; internal const float ForceFlashlightRepeatSeconds = 1f; internal const float LockoutBaseSeconds = 10f; internal const int PatrolWaitMinSeconds = 3; internal const int PatrolWaitMaxSeconds = 7; internal static readonly float AppearRangeMetres = ToyUnits.Metres(800f); internal static readonly float DismissRangeMetres = ToyUnits.Metres(1500f); internal static readonly float CeilingOffsetMetres = ToyUnits.Metres(15f) * 1.82f; internal static readonly float CeilingTraceMetres = ToyUnits.Metres(2500f); internal static readonly float OpenHeightMetres = ToyUnits.Metres(120f) * 1.82f; internal static readonly float StringWidthMetres = ToyUnits.Metres(2f) * 1.82f; internal static float LockoutSeconds(int difficulty) { return 10f / (float)Math.Max(1, Math.Min(5, difficulty)); } internal static bool IsShown(byte skillState) { return skillState == 1; } internal static float PatrolWaitSeconds(double unit) { int num = 5; int val = (int)Math.Floor(unit * (double)num); return 3 + Math.Max(0, Math.Min(num - 1, val)); } internal static bool ShouldForceFlashlight(bool shown, bool targetLit, float distance, bool lockout) { if (!shown && !targetLit && !lockout) { return distance <= AppearRangeMetres; } return false; } internal static bool ShouldAppear(bool shown, bool targetLit, float distance, bool lockout) { if (!shown && targetLit && !lockout) { return distance <= AppearRangeMetres; } return false; } internal static bool DismissesOnLightOff(float distance, bool lineOfSightClear) { if (lineOfSightClear) { return distance <= DismissRangeMetres; } return false; } internal static bool LightSwitchedOff(bool targetable, bool lit, ref bool wasLit) { bool result = (targetable & wasLit) && !lit; wasLit = targetable && lit; return result; } internal static bool PatrolHides(bool shown, bool executing, bool lockout) { if (shown && !executing) { return !lockout; } return false; } internal static float VanishSeconds(float despawnClipSeconds) { if (!(despawnClipSeconds > 0f)) { return 0f; } return despawnClipSeconds / 3f; } internal static float ControllerHeight(bool hitCeiling, float ceilingHeightAboveOrigin) { if (!hitCeiling) { return OpenHeightMetres; } return ceilingHeightAboveOrigin - CeilingOffsetMetres; } } internal sealed class MannequinLockout { private const int InitialCapacity = 16; private readonly List<float> _pending = new List<float>(16); internal bool Active { get; private set; } internal int PendingCount => _pending.Count; internal void Start(float now, float seconds) { Active = true; _pending.Add(now + seconds); } internal void ClearFlag() { Active = false; } internal void Reset() { Active = false; _pending.Clear(); } internal void Update(float now) { int num = 0; for (int i = 0; i < _pending.Count; i++) { float num2 = _pending[i]; if (num2 <= now) { Active = false; continue; } _pending[num] = num2; num++; } _pending.RemoveRange(num, _pending.Count - num); } } internal enum MikeState : byte { None, WindUp, Lunge, Land, Stun, Crawl } internal static class MikeRules { private static readonly float[] ClipSpeeds = new float[5] { 0.2f, 0.5f, 0.7f, 1f, 1.2f }; internal const float DashStartSeconds = 2f / 3f; internal const float DashLandSeconds = 1f / 3f; internal const float DashStunSeconds = 1f; internal static readonly float LungeSpeed = ToyUnits.DashSpeed(2500f); internal static readonly float CrawlRunSpeed = ToyUnits.MoveSpeed(600f); internal const float RunClipSpeed = 2f; internal const float CrawlRunClipSpeed = 1f; internal const float CloseRangeMetres = 9.525001f; internal const float HeadroomMetres = 1.905f; internal const float StunIgnoreFromMetres = 2.8575f; internal const float WindUpTurnDegreesPerSecond = 250f; internal const float NoTargetLungeMetres = 47.625f; internal const int CrawlClearWaitMinSeconds = 3; internal const int CrawlClearWaitMaxSeconds = 7; internal static float SkillClipSpeed(int difficulty) { return ClipSpeeds[SkillsBDifficulty.Clamp(difficulty) - 1]; } internal static float WindUpSeconds(int difficulty) { return 2f / 3f / SkillClipSpeed(difficulty); } internal static float StunSeconds(int difficulty) { return 1f / SkillClipSpeed(difficulty); } internal static bool IsCrawling(MikeState state) { return state != MikeState.None; } internal static bool IsLunging(MikeState state) { if (state != MikeState.WindUp && state != MikeState.Lunge) { return state == MikeState.Land; } return true; } internal static bool OwnsMovement(MikeState state) { if (state != MikeState.WindUp && state != MikeState.Lunge && state != MikeState.Land) { return state == MikeState.Stun; } return true; } internal static float RunClipSpeedFor(MikeState state) { if (!IsCrawling(state)) { return 2f; } return 1f; } internal static bool MayLunge(bool skillEnabled, MikeState state, bool lineOfSight, bool headroomClear, float targetDistanceMetres) { if (skillEnabled && !IsLunging(state) && state != MikeState.Stun && lineOfSight && headroomClear) { if (IsCrawling(state)) { return !(targetDistanceMetres <= 9.525001f); } return true; } return false; } internal static float LungeSeconds(float distanceMetres, float speed) { if (!(speed <= 0f) && !(distanceMetres < 9.525001f)) { return distanceMetres / speed; } return 0f; } internal static bool StunnedByFlashlight(MikeState state, bool switchedOnThisTick, bool inView) { return state == MikeState.Lunge && switchedOnThisTick && inView; } internal static bool IgnoresWhileStunFleeing(bool stunFleeing, float distanceMetres) { if (stunFleeing) { return distanceMetres >= 2.8575f; } return false; } } internal static class MonoRules { internal const float ScreamSeconds = 9.506f; internal const float AlertExtraSeconds = 1f; internal const float CooldownExtraSeconds = 15f; internal const float RangeUnitsPerDifficulty = 500f; internal static float ScreamRange(int difficulty) { return ToyUnits.Metres(500f * (float)Math.Max(1, Math.Min(5, difficulty))); } internal static bool InScreamRange(float distance, float range) { return distance <= range; } internal static float AlertSeconds(float screamSeconds) { return screamSeconds + 1f; } internal static float CooldownSeconds(float screamSeconds) { return screamSeconds + 15f; } internal static bool AlertEndsEarly<T>(bool hasTarget, float now, float alertEndsAt, T judged, Func<T, bool> targetable) { if (hasTarget && now < alertEndsAt) { return !targetable(judged); } return false; } internal static float EmitterMultiplier(int otherToysAlerted, float screamMultiplier) { if (otherToysAlerted <= 0) { return 1f; } return screamMultiplier; } } internal enum MosciState : byte { None, Dash, Stun } internal static class MosciRules { private static readonly float[] DashRangeUnits = new float[5] { 250f, 320f, 450f, 550f, 700f }; internal static readonly float DashSpeed = ToyUnits.DashSpeed(1200f); internal const float StunSeconds = 1.3333334f; internal static float DashRangeMetres(int difficulty) { return ToyUnits.Metres(DashRangeUnits[SkillsBDifficulty.Clamp(difficulty) - 1]); } internal static float DashTurnDegreesPerSecond(int difficulty) { return 50f * (float)SkillsBDifficulty.Clamp(difficulty); } internal static float DashSeconds(int difficulty) { return 15f / (float)SkillsBDifficulty.Clamp(difficulty); } internal static bool MayDash(bool skillEnabled, MosciState state, float targetDistanceMetres, int difficulty) { if (skillEnabled && state == MosciState.None) { return targetDistanceMetres <= DashRangeMetres(difficulty); } return false; } internal static float DamageMultiplier(MosciState state) { if (state != MosciState.Dash) { return 1f; } return 2f; } internal static bool OwnsMovement(MosciState state) { return state != MosciState.None; } } internal static class MouseMaskRules { internal const string MaskBodygroup = "03"; internal const float SearchClipSeconds = 4.1666665f; internal const float MaskLockSeconds = 1f; internal const float DrawEventSeconds = 0.25f; internal static bool IgnoresBySpeed(bool hasMask, float speed, float limit) { if (!hasMask) { return speed < limit; } return false; } internal static float SearchSeconds(int difficulty) { return 4.1666665f / SkillsCRules.SlowRate(difficulty); } internal static float DamageMultiplier(bool maskBody, float maskMultiplier) { if (!maskBody) { return 1f; } return maskMultiplier; } internal static bool OwnsMovement(bool searchClipPlaying) { return searchClipPlaying; } } internal sealed class MouseMaskMask { private float _lockEnd = float.NegativeInfinity; private float _drawDue; private bool _drawPending; internal bool HasMask { get; private set; } internal bool MaskBody { get; private set; } internal bool Searching { get; private set; } internal void Reset() { HasMask = false; MaskBody = false; Searching = false; _lockEnd = float.NegativeInfinity; _drawPending = false; } internal bool Request(bool requested, bool running, float now) { bool flag = requested || running; if (flag == HasMask || now < _lockEnd) { return false; } HasMask = flag; _lockEnd = now + 1f; _drawDue = now + 0.25f; _drawPending = true; return true; } internal bool Tick(float now) { if (!_drawPending || now < _drawDue) { return false; } _drawPending = false; if (MaskBody == HasMask) { return false; } MaskBody = HasMask; return true; } internal void BeginSearch(bool running, float now) { Searching = true; Request(requested: true, running, now); MaskBody = true; } internal void EndSearchClip(bool running, float now) { Request(requested: true, running, now); } internal void PatrolReset(bool running, float now) { Searching = false; Request(requested: false, running, now); } } internal static class PlushneeRules { internal const float BlindBelowUnitsPerSecond = 2f; internal const float RunBeyondUnits = 1500f; private static readonly float[] RunAboveUnitsPerSecond = new float[5] { 550f, 400f, 400f, 100f, 60f }; internal static readonly float BlindBelowSpeed = ToyUnits.MoveSpeed(2f); internal static readonly float RunBeyondDistance = ToyUnits.Metres(1500f); internal static bool IsBlindTo(float speed) { return speed < BlindBelowSpeed; } internal static float RunAboveSpeed(int difficulty) { return ToyUnits.MoveSpeed(RunAboveUnitsPerSecond[Math.Max(1, Math.Min(5, difficulty)) - 1]); } internal static bool Runs(bool skillEnabled, int hitsLeft, int maxHits, float distance, float targetSpeed, int difficulty) { if (skillEnabled && hitsLeft * 2 >= maxHits && !(distance > RunBeyondDistance)) { return targetSpeed > RunAboveSpeed(difficulty); } return true; } } internal enum MiniPulpPhase : byte { Carried, Running, Attached } internal static class PulpRules { internal const int Slots = 6; internal const int MinDifficulty = 1; internal const int MaxDifficulty = 5; internal const int BiteDamage = 5; internal const int MaxHitForce = 255; internal const float RunnerSyncSeconds = 0.2f; internal const float AttachedSyncSeconds = 2f; internal const float AttachSurfaceMetres = 0.35f; internal const float SpawnNavMeshSampleMetres = 1f; internal const float HitReportReachMetres = 6f; internal const float RunClipAboveMetresPerSecond = 0.5f; internal static readonly int RunnerHits = ToyUnits.Hits(20); internal static readonly float RunnerRunSpeed = ToyUnits.MoveSpeed(600f); internal static readonly float AttachReachMetres = ToyUnits.Metres(30f) * 1.82f; internal static readonly float SpawnUpMetres = ToyUnits.Metres(5f) * 1.82f; internal static readonly float SpawnForwardMetres = ToyUnits.Metres(30f) * 1.82f; private const int ByteMask = 255; private const int MaxPackedPlayerSlot = 254; internal static int FirstFreeSlot(int awayMask) { for (int i = 0; i < 6; i++) { if ((awayMask & (1 << i)) == 0) { return i; } } return -1; } internal static bool IsSlot(int slot) { if (slot >= 0) { return slot < 6; } return false; } internal static bool IsAway(int awayMask, int slot) { if (IsSlot(slot)) { return (awayMask & (1 << slot)) != 0; } return false; } internal static int WithAway(int awayMask, int slot, bool away) { if (!IsSlot(slot)) { return awayMask; } int num = 1 << slot; if (!away) { return awayMask & ~num; } return awayMask | num; } internal static float SpawnCooldownSeconds(int difficulty, double unit) { int num = ClampDifficulty(difficulty); double num2 = 2.0 / (double)num; double num3 = 6.0 / (double)num - num2 + 1.0; int val = (int)Math.Ceiling(num3) - 1; int num4 = Math.Max(0, Math.Min(val, (int)Math.Floor(unit * num3))); return (float)(num2 + (double)num4); } internal static int AttachedHits(int difficulty) { return ToyUnits.Hits(25 * ClampDifficulty(difficulty)); } internal static float BiteIntervalSeconds(int difficulty) { return 1.5f / (float)ClampDifficulty(difficulty); } internal static bool ClingerLetsGo(bool victimTargetable, float secondsAttached, float lifetimeSeconds) { if (victimTargetable) { if (lifetimeSeconds > 0f) { return secondsAttached >= lifetimeSeconds; } return false; } return true; } internal static bool MayThrowAt(int attached, int running, int cap) { return attached + running < cap; } internal static int HitDamage(int force) { return Math.Max(1, Math.Min(255, force)); } internal static bool InAttachReach(float distance) { return distance <= AttachReachMetres; } internal static bool InReportReach(float distance) { return distance <= 6f; } internal static bool UsesRunClip(float metresPerSecond) { return metresPerSecond > 0.5f; } internal static void UnityHeadAngles(float pitch, float yaw, float roll, out float x, out float y, out float z) { x = pitch; y = 0f - yaw; z = 0f - roll; } internal static int PackMiniState(int slot, MiniPulpPhase phase, int playerSlot) { int num = ((playerSlot >= 0 && playerSlot <= 254) ? (playerSlot + 1) : 0); return (int)((uint)(slot & 0xFF) | ((uint)phase << 8)) | (num << 16); } internal static bool TryUnpackMiniState(int value, out int slot, out MiniPulpPhase phase, out int playerSlot) { slot = value & 0xFF; int num = (value >> 8) & 0xFF; phase = (MiniPulpPhase)num; playerSlot = ((value >> 16) & 0xFF) - 1; if (IsSlot(slot)) { if (num != 1) { return num == 2; } return true; } return false; } internal static int PackHitReport(int slot, int force) { return (slot & 0xFF) | (HitDamage(force) << 8); } internal static bool TryUnpackHitReport(int value, out int slot, out int force) { slot = value & 0xFF; force = HitDamage((value >> 8) & 0xFF); return IsSlot(slot); } private static int ClampDifficulty(int difficulty) { return Math.Max(1, Math.Min(5, difficulty)); } } internal static class SkillsBDifficulty { internal const int Min = 1; internal const int Max = 5; internal const int Default = 3; internal static int Clamp(int difficulty) { return Math.Max(1, Math.Min(5, difficulty)); } } internal static class SkillsCRules { internal const int MinDifficulty = 1; internal const int MaxDifficulty = 5; internal const float StillSpeed = 0.1f; internal const float StillSqrSpeed = 0.010000001f; private const int PatrolWaitMinSeconds = 3; private const int PatrolWaitChoices = 5; private static readonly float[] SlowRates = new float[5] { 0.2f, 0.5f, 0.7f, 1f, 1.2f }; internal static int ClampDifficulty(int difficulty) { return Math.Max(1, Math.Min(5, difficulty)); } internal static bool IsMoving(float sqrSpeed) { return sqrSpeed > 0.010000001f; } internal static float SlowRate(int difficulty) { return SlowRates[ClampDifficulty(difficulty) - 1]; } internal static int PatrolWaitSeconds(double unit) { double num = Math.Floor(unit * 5.0); if (!(num > 0.0)) { return 3; } return 3 + (int)Math.Min(num, 4.0); } internal static float BodyMetres(float units) { return units * 0.01905f * 1.82f; } internal static float BodyUnits(float metres) { return metres / 0.034671f; } internal static float Units(float metres) { return metres / 0.01905f; } internal static float UnitsPerSecond(float metresPerSecond) { return metresPerSecond / 0.025908f; } } internal static class SpiderplushRules { internal const float CeilingRayStartUnits = 15f; internal const float CeilingRayLengthUnits = 200f; internal const float CeilingPoseUnits = 143f; internal const float CeilingLightDropUnits = 35f; internal const float CeilingWalkClipSpeed = 0.5f; internal const float CeilingRunClipSpeed = 1f; internal const float CeilingIdleClipSpeed = 0.001f; internal const float DashRunMultiplier = 2f; internal const float DashPulseSeconds = 0.05f; internal const float DashReachUnits = 50f; internal const float DashHitHalfAngle = 37.5f; private static readonly float[] DashRanges = new float[5] { 450f, 400f, 300f, 250f, 200f }; internal static float DashRangeUnits(int difficulty) { return DashRanges[SkillsCRules.ClampDifficulty(difficulty) - 1]; } internal static float DashSeconds(int difficulty) { return 3f / (float)SkillsCRules.ClampDifficulty(difficulty); } internal static float DashCooldownSeconds(int difficulty) { return 4f / (float)SkillsCRules.ClampDifficulty(difficulty); } internal static float DashTurnRate(int difficulty) { return 10f * (float)SkillsCRules.ClampDifficulty(difficulty); } internal static float CeilingLift(bool ceiling, bool showsCeilingClip, float ceilingHeightAboveFeet, float poseHeight) { if (!(ceiling && showsCeilingClip)) { return 0f; } return ceilingHeightAboveFeet - poseHeight; } internal static float CeilingLightHeight(float ceilingHeightAboveFeet, float dropHeight) { return ceilingHeightAboveFeet - dropHeight; } internal static bool MayDash(bool onCeiling, bool dashing, float now, float lockedUntil, float distanceUnits, int difficulty) { if (onCeiling && !dashing && now >= lockedUntil) { return distanceUnits <= DashRangeUnits(difficulty); } return false; } internal static bool DashHits(float distanceUnits, float angleDegrees) { if (distanceUnits <= 50f) { return angleDegrees <= 37.5f; } return false; } } internal enum ToyCatchRule { HitsThenExecute, AlwaysExecute } internal enum ToyCatchOutcome { Refuse, Hit, Execute } internal enum ToyCatchReason { Hit, HitBusy, ExecuteRule, ExecuteThreshold, ExecuteLethal, NotTargetable, HitGap, NoDamage } internal enum ToyCatchPath { Touch, Masked, Mannequin, Dash, Lunge } internal enum ToyExecutionEnd { None, VictimGone, VictimDied, VictimLeft, ToyDied, StateChanged, RoundEnding, Escaped, NotTargetable, TimedOut, Teleported, Despawned } internal sealed class ToyHitGaps { private readonly float[] _endsAt; private readonly ulong[] _clientId; internal ToyHitGaps(int slots) { _endsAt = new float[slots]; _clientId = new ulong[slots]; Clear(); } internal void Start(int slot, ulong clientId, float now, float seconds) { if (slot >= 0 && slot < _endsAt.Length) { _endsAt[slot] = now + Math.Max(0f, seconds); _clientId[slot] = clientId; } } internal bool IsOpen(int slot, ulong clientId, float now) { if (slot >= 0 && slot < _endsAt.Length && now < _endsAt[slot]) { return _clientId[slot] == clientId; } return false; } internal void Sweep(int slot, ulong clientId, bool controlled, bool dead) { if (slot >= 0 && slot < _endsAt.Length && (dead || !controlled || _clientId[slot] != clientId)) { _endsAt[slot] = float.NegativeInfinity; } } internal void Clear() { for (int i = 0; i < _endsAt.Length; i++) { _endsAt[i] = float.NegativeInfinity; } } } internal static class ToyCatchLogic { internal const int FullHealth = 100; internal const int DefaultExecuteAtHealthPercent = 25; internal const float ExecutionClipSpeed = 2f; internal const float FallbackExecutionClipSeconds = 2f; internal const float ViewBlendSeconds = 0.2f; internal const float KillGraceSeconds = 1f; internal const float MaxContactDistance = 3.5f; internal const float StandDistance = 1.213485f; internal const float MaxHoldDistance = 4.713485f; internal const float NearVerticalDegrees = 5f; private const float DegreesPerRadian = 57.29578f; internal static int Damage(int min, int max, double roll, float multiplier) { min = Math.Max(0, min); max = Math.Max(0, max); if (max < min) { int num = min; min = max; max = num; } double num2 = Math.Floor(roll * (double)(max - min + 1)); if (!(num2 > 0.0)) { num2 = 0.0; } int num3 = (int)Math.Min(num2, max - min) + min; if (!(multiplier > 0f)) { return 0; } double num4 = Math.Round((double)num3 * (double)multiplier); if (!(num4 >= 2147483647.0)) { return (int)num4; } return int.MaxValue; } internal static int HealthAfterHit(int health, int damage, bool criticallyInjured) { int num = health - damage; if (num <= 0 && !criticallyInjured && damage < 50) { return 5; } return Math.Max(0, Math.Min(100, num)); } internal static ToyCatchOutcome Decide(ToyCatchRule rule, int health, int damage, int executeAtHealthPercent, bool targetable, bool gapOpen, bool busy, out ToyCatchReason reason) { if (!targetable) { reason = ToyCatchReason.NotTargetable; return ToyCatchOutcome.Refuse; } if (gapOpen) { reason = ToyCatchReason.HitGap; return ToyCatchOutcome.Refuse; } long num = Math.Max(0, Math.Min(100, executeAtHealthPercent)); ToyCatchReason toyCatchReason = ((rule == ToyCatchRule.AlwaysExecute) ? ToyCatchReason.ExecuteRule : (((long)health * 100L <= 100 * num) ? ToyCatchReason.ExecuteThreshold : ((damage >= health) ? ToyCatchReason.ExecuteLethal : ToyCatchReason.Hit))); if (toyCatchReason != ToyCatchReason.Hit && !busy) { reason = toyCatchReason; return ToyCatchOutcome.Execute; } if (damage <= 0) { reason = ToyCatchReason.NoDamage; return ToyCatchOutcome.Refuse; } reason = ((toyCatchReason != ToyCatchReason.Hit) ? ToyCatchReason.HitBusy : ToyCatchReason.Hit); return ToyCatchOutcome.Hit; } internal static ToyExecutionEnd ExecutionEnd<T>(bool victimPresent, bool victimDead, bool victimControlled, bool toyDead, bool executing, bool roundEnding, float distance, T judged, Func<T, bool> targetable, float elapsedSeconds, float executionSeconds) { if (!victimPresent) { return ToyExecutionEnd.VictimGone; } if (victimDead) { return ToyExecutionEnd.VictimDied; } if (!victimControlled) { return ToyExecutionEnd.VictimLeft; } if (toyDead) { return ToyExecutionEnd.ToyDied; } if (!executing) { return ToyExecutionEnd.StateChanged; } if (roundEnding) { return ToyExecutionEnd.RoundEnding; } if (HoldBroken(distance)) { return ToyExecutionEnd.Escaped; } if (!targetable(judged)) { return ToyExecutionEnd.NotTargetable; } if (!(elapsedSeconds >= executionSeconds + 1f)) { return ToyExecutionEnd.None; } return ToyExecutionEnd.TimedOut; } internal static bool ContactPlausible(float distance) { return distance <= 3.5f; } internal static bool HoldBroken(float distance) { return !(distance <= 4.713485f); } internal static float ExecutionSeconds(float clipSeconds) { return ((clipSeconds > 0f) ? clipSeconds : 2f) / 2f; } internal static int AttackClipIndex(int clipCount, double roll) { int num = Math.Max(1, clipCount); double num2 = Math.Floor(roll * (double)clipCount); if (!(num2 > 0.0)) { num2 = 0.0; } return 1 + (int)Math.Min(num2, num - 1); } internal static string Describe(ToyCatchPath path) { return path switch { ToyCatchPath.Touch => "touch", ToyCatchPath.Masked => "masked touch", ToyCatchPath.Mannequin => "Mannequin touch", ToyCatchPath.Dash => "dash", ToyCatchPath.Lunge => "lunge", _ => "unknown path", }; } internal static string Describe(ToyCatchReason reason) { return reason switch { ToyCatchReason.Hit => "no execution wanted", ToyCatchReason.HitBusy => "execution wanted but the victim is busy", ToyCatchReason.ExecuteRule => "the catch rule always executes", ToyCatchReason.ExecuteThreshold => "health at or under the execute share", ToyCatchReason.ExecuteLethal => "the hit would kill", ToyCatchReason.NotTargetable => "not targetable", ToyCatchReason.HitGap => "hit gap", ToyCatchReason.NoDamage => "no damage", _ => "unknown reason", }; } internal static string Describe(ToyExecutionEnd end) { return end switch { ToyExecutionEnd.VictimGone => "aborted: the victim is gone", ToyExecutionEnd.VictimDied => "finished: the victim died", ToyExecutionEnd.VictimLeft => "aborted: the victim is no longer controlled", ToyExecutionEnd.ToyDied => "aborted: the toy died", ToyExecutionEnd.StateChanged => "aborted: the state left Executing", ToyExecutionEnd.RoundEnding => "aborted: the round is ending", ToyExecutionEnd.Escaped => "aborted: the victim got past the hold distance", ToyExecutionEnd.NotTargetable => "aborted: the victim is not targetable", ToyExecutionEnd.TimedOut => "aborted: the clip and the kill grace ran out", ToyExecutionEnd.Teleported => "aborted: the victim was teleported", ToyExecutionEnd.Despawned => "aborted: the toy despawned", _ => "still running", }; } internal static float ViewBlend(float elapsedSeconds) { float num = elapsedSeconds / 0.2f; if (!(num > 0f)) { return 0f; } return Math.Min(num, 1f); } internal static void KillViewAxis(float x, float y, float z, out float viewX, out float viewY, out float viewZ) { viewX = 0f - z; viewY = y; viewZ = x; } internal static void ViewAngles(float forwardX, float forwardY, float forwardZ, float upX, float upY, float upZ, out float heading, out float pitch) { pitch = (float)Math.Atan2(0f - forwardY, Math.Sqrt(forwardX * forwardX + forwardZ * forwardZ)) * 57.29578f; if (90f - Math.Abs(pitch) >= 5f) { heading = Heading(forwardX, forwardZ); } else { heading = ((pitch > 0f) ? Heading(upX, upZ) : Heading(0f - upX, 0f - upZ)); } } internal static void BlendedView(float startHeading, float startPitch, float killHeading, float killPitch, float blend, out float heading, out float pitch) { float num = (killHeading - startHeading) % 360f; if (num > 180f) { num -= 360f; } else if (num < -180f) { num += 360f; } heading = startHeading + num * blend; pitch = startPitch * (1f - blend) + killPitch * blend; } private static float Heading(float x, float z) { return (float)Math.Atan2(x, z) * 57.29578f; } } internal enum ToyFlinchVerdict : byte { Flinch, Special, Killed, NoPlayer, Off, State, Dashing, SkillPhase, Flinching, TooSoon } internal enum ToyFlinchEnd : byte { None, Despawned, StateLeft, SkillPhase, Dashing, RoundEnding, TimeUp } internal static class ToyFlinchLogic { internal const float DefaultSeconds = 0.33f; internal const float DefaultIntervalSeconds = 1.5f; internal static ToyFlinchVerdict Decide(ToyTier tier, bool killed, bool byPlayer, float seconds, ToyState state, bool dashing, bool skillOwnsMovement, bool flinching, float now, float lastStart, float interval) { if (tier != ToyTier.Common) { return ToyFlinchVerdict.Special; } if (killed) { return ToyFlinchVerdict.Killed; } if (!byPlayer) { return ToyFlinchVerdict.NoPlayer; } if (!(seconds > 0f)) { return ToyFlinchVerdict.Off; } if (!ToySwingLogic.ActsIn(state)) { return ToyFlinchVerdict.State; } if (dashing) { return ToyFlinchVerdict.Dashing; } if (skillOwnsMovement) { return ToyFlinchVerdict.SkillPhase; } if (flinching) { return ToyFlinchVerdict.Flinching; } if (!(now - lastStart >= interval)) { return ToyFlinchVerdict.TooSoon; } return ToyFlinchVerdict.Flinch; } internal static ToyFlinchEnd End(bool despawned, ToyState state, bool skillOwnsMovement, bool dashing, bool roundEnding, float now, float endsAt) { if (despawned) { return ToyFlinchEnd.Despawned; } if (!ToySwingLogic.ActsIn(state)) { return ToyFlinchEnd.StateLeft; } if (skillOwnsMovement) { return ToyFlinchEnd.SkillPhase; } if (dashing) { return ToyFlinchEnd.Dashing; } if (roundEnding) { return ToyFlinchEnd.RoundEnding; } if (!(now >= endsAt)) { return ToyFlinchEnd.None; } return ToyFlinchEnd.TimeUp; } internal static bool RestoresClip(int heldHash, byte heldSerial, int hash, byte serial) { if (hash == heldHash) { return serial == heldSerial; } return false; } } internal struct ToyFlinchHold { private float _speed; internal bool Holding { get; private set; } internal void Start(float speed) { _speed = speed; Holding = true; } internal bool Keep(float requested) { if (Holding) { _speed = requested; } return Holding; } internal float Release() { Holding = false; return _speed; } } internal enum ToyTier : byte { Common, Special } internal static class ToyHitRules { internal const int PlainDamageMin = 10; internal const int PlainDamageMax = 20; internal const float BonusMultiplier = 2f; internal const int MikeCrawlDamageMin = 45; internal const int MikeCrawlDamageMax = 75; internal const int CommonHitCap = 49; internal const float CommonWeight = 1f; internal const float SpecialWeight = 0.5f; internal static float DefaultWeight(ToyTier tier) { if (tier != ToyTier.Special) { return 1f; } return 0.5f; } internal static float Multiplier(float own, float scream, bool ownRange) { if (!ownRange) { return Math.Max(own, scream); } return own; } internal static int Cap(ToyTier tier, int damage) { if (tier != ToyTier.Common) { return damage; } return Math.Min(damage, 49); } internal static int Damage(int min, int max, double roll, float own, float scream, bool ownRange, ToyTier tier) { return Cap(tier, ToyCatchLogic.Damage(min, max, roll, Multiplier(own, scream, ownRange))); } } internal static class ToyHudLogic { internal readonly struct FrameUv { internal readonly int Frame; internal readonly float X; internal readonly float Width; internal FrameUv(int frame, float x, float width) { Frame = frame; X = x; Width = width; } } internal readonly struct OverlayAlphas { internal readonly float Left; internal readonly float Right; internal readonly float Down; internal OverlayAlphas(float left, float right, float down) { Left = left; Right = right; Down = down; } } internal const float RangeUnits = 1500f; internal const float DefaultRangeMetres = 28.575f; internal const float SideWeight = 0.75f; internal const float ForwardWeight = 0.25f; internal const float BehindGain = 1.1f; internal const float AlphaScale = 0.25f; internal const float BehindMinMetres = 0.01905f; internal const float DefaultIntensity = 1f; internal const float MinIntensity = 0.05f; internal const float MaxIntensity = 10f; internal const string AmbienceClip = "tz_ambiencefull_short"; internal const string TargetAmbienceClip = "wav_targetactor_ambience"; internal const float DefaultAmbienceVolume = 0.5f; internal const float AmbienceFloorVolume = 0.01f; internal const float AmbienceGraceSeconds = 2f; internal const float OverlayFrameRate = 30f; internal const int NoiseLeftFrames = 11; internal const int NoiseRightFrames = 10; internal const int NoiseDownFrames = 11; internal static bool InRange(float distance, float range) { return distance <= range; } internal static OverlayAlphas Overlays(float rightOffset, float forwardOffset, float distance, float intensity) { if (!(distance > 0f)) { return new OverlayAlphas(0f, 0f, 0f); } float num = rightOffset / distance; float num2 = forwardOffset / distance; float num3 = Clamp01(num2) * 0.25f; float num4 = 0.25f * intensity; float value = (Clamp01(num) * 0.75f + num3) * num4; float value2 = (Clamp01(0f - num) * 0.75f + num3) * num4; return new OverlayAlphas(down: Clamp01((forwardOffset < -0.01905f) ? (Clamp01(0f - num2) * 1.1f * num4) : 0f), left: Clamp01(value2), right: Clamp01(value)); } internal static float AmbienceVolume(bool active, float secondsSinceActive, float configuredVolume) { if (configuredVolume <= 0f) { return 0f; } if (active) { return Math.Max(0.01f, Math.Min(configuredVolume, 1f)); } if (!(secondsSinceActive < 2f)) { return 0f; } return 0.01f; } internal static FrameUv StripFrame(double elapsedSeconds, int frameCount) { if (frameCount <= 1) { return new FrameUv(0, 0f, 1f); } int num = 0; double num2 = Math.Floor(elapsedSeconds * 30.0); if (!double.IsNaN(num2) && !double.IsInfinity(num2)) { double num3 = num2 % (double)frameCount; if (num3 < 0.0) { num3 += (double)frameCount; } num = (int)num3; } return new FrameUv(num, (float)num / (float)frameCount, 1f / (float)frameCount); } internal static int UsableFrameCount(int textureWidth, int frameCount) { if (frameCount <= 1 || textureWidth <= 0 || textureWidth % frameCount != 0) { return 1; } return frameCount; } private static float Clamp01(float value) { if (!(value < 0f)) { if (!(value > 1f)) { return value; } return 1f; } return 0f; } } internal enum ToyKind : byte { Mono, BoBiGo, Plushnee, Toplush, Bear, Mike, Mosci, MouseMask, Lionmion, Spiderplush, Mannequin, Pulp } internal static class ToyKindRoll { internal static ToyKind Roll(IReadOnlyList<float> weights, IReadOnlyList<bool> alive, ToyKind? forced, double unit) { if (forced.HasValue) { return forced.Value; } if (weights == null || weights.Count < 12) { throw new ArgumentException("One weight per kind is required.", "weights"); } if (alive == null || alive.Count < 12) { throw new ArgumentException("One alive flag per kind is required.", "alive"); } bool anyPositive = false; for (int i = 0; i < 12; i++) { if (weights[i] > 0f) { anyPositive = true; break; } } double num = ((unit > 0.0) ? Math.Min(unit, 1.0) : 0.0); for (int j = 0; j < 2; j++) { bool notAliveOnly = j == 0; double num2 = 0.0; for (int k = 0; k < 12; k++) { num2 += CandidateWeight(weights[k], alive[k], anyPositive, notAliveOnly); } if (num2 <= 0.0) { continue; } double num3 = num * num2; double num4 = 0.0; int num5 = -1; for (int l = 0; l < 12; l++) { double num6 = CandidateWeight(weights[l], alive[l], anyPositive, notAliveOnly); if (!(num6 <= 0.0)) { num4 += num6; num5 = l; if (num3 < num4) { return (ToyKind)l; } } } return (ToyKind)num5; } return ToyKind.Mono; } private static double CandidateWeight(float configured, bool alive, bool anyPositive, bool notAliveOnly) { if (notAliveOnly && alive) { return 0.0; } if (!anyPositive) { return 1.0; } if (!(configured > 0f)) { return 0.0; } return configured; } } internal sealed class ToyKindRow { internal ToyKind Kind; internal string Name; internal string DisplayName; internal string Model; internal ToyTier Tier; internal int Hits; internal float ModWalkSpeed; internal float ModRunSpeed; internal bool CanPeek; internal bool FlashlightStun; internal bool CanCrouch; internal float DamageMultiplier; internal string BreathSound; internal string WhisperSound; internal string JumpscareSound; internal string StalkSound; internal string[] ExtraSounds; internal int AttackClips; internal bool PatrolsTowardPlayers; internal string EyesBodygroup; internal bool SpawnsHidden; internal string FootstepSound; internal float WalkSpeed => ToyUnits.MoveSpeed(ModWalkSpeed); internal float RunSpeed => ToyUnits.MoveSpeed(ModRunSpeed); } internal static class ToyKindTable { internal const int Count = 12; private const string Breath = "tz.breath"; private const string Whisper = "tz_whisper"; private const string Jumpscare = "tz_jumpscare"; private const string Stalk = "wav_stalk_scare"; private static readonly string[] None = new string[0]; private static readonly ToyKindRow[] RowArray = new ToyKindRow[12] { new ToyKindRow { Kind = ToyKind.Mono, Name = "Mono", DisplayName = "Mono", Model = "mono_npc", Tier = ToyTier.Common, Hits = 2, ModWalkSpeed = 100f, ModRunSpeed = 300f, CanPeek = false, FlashlightStun = false, CanCrouch = false, DamageMultiplier = 1f, BreathSound = "tz.breath", WhisperSound = "tz_whisper", JumpscareSound = "tz_jumpscare", StalkSound = "wav_stalk_scare", ExtraSounds = new string[1] { "tz.monoscream" }, AttackClips = 2, PatrolsTowardPlayers = true, EyesBodygroup = "02", FootstepSound = "tz.step" }, new ToyKindRow { Kind = ToyKind.BoBiGo, Name = "BoBiGo", DisplayName = "BoBiGo", Model = "bobigo", Tier = ToyTier.Common, Hits = 4, ModWalkSpeed = 50f, ModRunSpeed = 250f, CanPeek = true, FlashlightStun = false, CanCrouch = false, DamageMultiplier = 1f, BreathSound = "tz.frogbreath", WhisperSound = "tz.frogwhisper", JumpscareSound = "tz.frogjumpscare", StalkSound = "tz.bobigostalk", ExtraSounds = None, AttackClips = 3, PatrolsTowardPlayers = true, EyesBodygroup = "03", FootstepSound = "tz.step" }, new ToyKindRow { Kind = ToyKind.Plushnee, Name = "Plushnee", DisplayName = "Plushnee", Model = "plushnee", Tier = ToyTier.Common, Hits = 1, ModWalkSpeed = 50f, ModRunSpeed = 2400f, CanPeek = true, FlashlightStun = false, CanCrouch = false, DamageMultiplier = 1f, BreathSound = "tz.plushneebreath", WhisperSound = "tz.plushneewhisper", JumpscareSound = "tz.plushneejumpscare", StalkSound = "tz.plushneestalk", ExtraSounds = None, AttackClips = 2, PatrolsTowardPlayers = false, EyesBodygroup = "02", FootstepSound = "tz.step" }, new ToyKindRow { Kind = ToyKind.Toplush, Name = "Toplush", DisplayName = "Toplush", Model = "toplush", Tier = ToyTier.Common, Hits = 2, ModWalkSpeed = 20f, ModRunSpeed = 350f, CanPeek = true, FlashlightStun = true, CanCrouch = true, DamageMultiplier = 1f, BreathSound = "tz.toplushbreath", WhisperSound = "tz.toplushwhisper", JumpscareSound = "tz.toplushjumpscare", StalkSound = "tz.toplushstalk", ExtraSounds = new string[1] { "tz.toplushscream" }, AttackClips = 2, PatrolsTowardPlayers = false, EyesBodygroup = "03", FootstepSound = "tz.step" }, new ToyKindRow { Kind = ToyKind.Bear, Name = "Bear", DisplayName = "Bear", Model = "bear", Tier = ToyTier.Common, Hits = 5, ModWalkSpeed = 50f, ModRunSpeed = 400f, CanPeek = false, FlashlightStun = false, CanCrouch = false, DamageMultiplier = 1f, BreathSound = "tz.bearbreath", WhisperSound = "tz.bearwhisper", JumpscareSound = "tz.bearjumpscare", StalkSound = "tz.bearstalk", ExtraSounds = None, AttackClips = 2, PatrolsTowardPlayers = false, EyesBodygroup = "02", FootstepSound = "tz.bearstep" }, new ToyKindRow { Kind = ToyKind.Mike, Name = "Mike", DisplayName = "Mike the Cat", Model = "mike", Tier = ToyTier.Special, Hits = 8, ModWalkSpeed = 50f, ModRunSpeed = 300f, CanPeek = false, FlashlightStun = false, CanCrouch = true, DamageMultiplier = 1f, BreathSound = "tz.breath", WhisperSound = "tz_whisper", JumpscareSound = "tz.frogjumpscare", StalkSound = "wav_stalk_scare", ExtraSounds = new string[2] { "tz.mikescream", "tz.mikestun" }, AttackClips = 2, PatrolsTowardPlayers = false, EyesBodygroup = "02", FootstepSound = "tz.step" }, new ToyKindRow { Kind = ToyKind.Mosci, Name = "Mosci", DisplayName = "Mosci", Model = "mosci", Tier = ToyTier.Common, Hits = 1, ModWalkSpeed = 100f, ModRunSpeed = 600f, CanPeek = false, FlashlightStun = false, CanCrouch = false, DamageMultiplier = 1f, BreathSound = "tz.plushneebreath", WhisperSound = "tz.plushneewhisper", JumpscareSound = "tz.plushneejumpscare", StalkSound = "tz.plushneestalk", ExtraSounds = new string[2] { "tz.moscidash", "tz.moscistun" }, AttackClips = 2, PatrolsTowardPlayers = false, EyesBodygroup = "02", FootstepSound = string.Empty }, new ToyKindRow { Kind = ToyKind.MouseMask, Name = "MouseMask", DisplayName = "MouseMask", Model = "mousemask", Tier = ToyTier.Common, Hits = 5, ModWalkSpeed = 100f, ModRunSpeed = 450f, CanPeek = false, FlashlightStun = false, CanCrouch = true, DamageMultiplier = 1f, BreathSound = "tz.breath", WhisperSound = "tz_whisper", JumpscareSound = "tz.frogjumpscare", StalkSound = "wav_stalk_scare", ExtraSounds = new string[1] { "tz.mousemasksearch" }, AttackClips = 2, PatrolsTowardPlayers = false, EyesBodygroup = "02", FootstepSound = "tz.step" }, new ToyKindRow { Kind = ToyKind.Lionmion, Name = "Lionmion", DisplayName = "Lionmion", Model = "lionmion", Tier = ToyTier.Common, Hits = 2, ModWalkSpeed = 50f, ModRunSpeed = 270f, CanPeek = false, FlashlightStun = false, CanCrouch = false, DamageMultiplier = 1f, BreathSound = "tz.breath", WhisperSound = "tz_whisper", JumpscareSound = "tz_jumpscare", StalkSound = "wav_stalk_scare", ExtraSounds = new string[2] { "tz.lionmionwakeup", "tz.lionmionsleep" }, AttackClips = 2, PatrolsTowardPlayers = false, EyesBodygroup = "02", FootstepSound = "tz.step" }, new ToyKindRow { Kind = ToyKind.Spiderplush, Name = "Spiderplush", DisplayName = "Spiderplush", Model = "spiderplush", Tier = ToyTier.Common, Hits = 3, ModWalkSpeed = 100f, ModRunSpeed = 350f, CanPeek = false, FlashlightStun = false, CanCrouch = true, DamageMultiplier = 1f, BreathSound = "tz.spiderbreath", WhisperSound = "tz.spiderwhisper", JumpscareSound = "tz.spiderjumpscare", StalkSound = "tz.plushneestalk", ExtraSounds = new string[1] { "tz.spiderdash" }, AttackClips = 2, PatrolsTowardPlayers = false, EyesBodygroup = "02", FootstepSound = "tz.step" }, new ToyKindRow { Kind = ToyKind.Mannequin, Name = "Mannequin", DisplayName = "The Mannequin", Model = "puppet", Tier = ToyTier.Special, Hits = 16, ModWalkSpeed = 100f, ModRunSpeed = 600f, CanPeek = false, FlashlightStun = false, CanCrouch = false, DamageMultiplier = 13f, BreathSound = "tz.mannequinbreath", WhisperSound = "tz.mannequinwhisper", JumpscareSound = "tz.mannequinjumpscare", StalkSound = "tz.frogstalk", ExtraSounds = new string[1] { "tz.mannequinpuppet" }, AttackClips = 2, PatrolsTowardPlayers = true, EyesBodygroup = string.Empty, SpawnsHidden = true, FootstepSound = string.Empty }, new ToyKindRow { Kind = ToyKind.Pulp, Name = "Pulp", DisplayName = "Pulp", Model = "pulp", Tier = ToyTier.Special, Hits = 12, ModWalkSpeed = 50f, ModRunSpeed = 100f, CanPeek = false, FlashlightStun = false, CanCrouch = false, DamageMultiplier = 1f, BreathSound = "tz.pulpbreath", WhisperSound = "tz.pulpwhisper", JumpscareSound = "tz.pulpjumpscare", StalkSound = "tz.frogstalk", ExtraSounds = new string[2] { "tz.minipulpbreath", "tz.minipulphurt" }, AttackClips = 2, PatrolsTowardPlayers = false, EyesBodygroup = "02", FootstepSound = "tz.pulpstep" } }; internal static IReadOnlyList<ToyKindRow> Rows => RowArray; internal static ToyKindRow Get(ToyKind kind) { return RowArray[(uint)kind]; } internal static bool TryParse(string text, out ToyKind kind) { kind = ToyKind.Mono; if (text == null) { return false; } string b = text.Trim(); for (int i = 0; i < RowArray.Length; i++) { if (string.Equals(RowArray[i].Name, b, StringComparison.OrdinalIgnoreCase)) { kind = RowArray[i].Kind; return true; } } return false; } } internal static class ToyReviveLogic { internal const float TwitchSeconds = 4f; internal const double TwitchMinInterval = 0.1; internal const double TwitchMaxInterval = 2.0; internal const int TwitchMaxSteps = 5; internal const float TwitchSpeedPerStep = 0.16f; internal const float FlashSeconds = 0.5f; internal const float FlashRangeMetres = 19.050001f; internal const float FlashLumens = 20000f; internal const float BodyNavSearchMetres = 2f; internal static bool Revives(int chancePercent, double unit) { if (chancePercent <= 0) { return false; } if (chancePercent >= 100) { return true; } return unit * 100.0 < (double)chancePercent; } internal static double ModRandom(double min, double max, double unit) { double num = max - min + 1.0; return Math.Min(Math.Floor(unit * num), Math.Ceiling(num) - 1.0) + min; } internal static float TwitchInterval(double unit) { return (float)ModRandom(0.1, 2.0, unit); } internal static int TwitchStep(double unit) { return (int)ModRandom(-5.0, 5.0, unit); } internal static float FlashLumensAt(float elapsed) { if (!(elapsed >= 0.5f)) { return 20000f * (1f - Math.Max(0f, elapsed) / 0.5f); } return 0f; } } internal sealed class ToyReviveClock { internal bool Dead { get; private set; } internal bool WillRevive { get; private set; } internal double ReviveAt { get; private set; } internal void Die(double now, int chancePercent, float delaySeconds, Func<double> draw) { if (!Dead) { Dead = true; WillRevive = ToyReviveLogic.Revives(chancePercent, draw()); ReviveAt = now + (double)Math.Max(0f, delaySeconds); } } internal bool IsDue(double now) { if (Dead && WillRevive) { return now >= ReviveAt; } return false; } internal void Cancel() { WillRevive = false; } internal void Clear() { Dead = false; WillRevive = false; ReviveAt = 0.0; } } internal enum ToyNotice : byte { None, Vetoed, Forced, Close, Stunned, Alerted, Lit, Marked, SpeedBand } internal readonly struct ToyNoticeLimits { internal readonly float SightRange; internal readonly float CloseRange; internal readonly float CrouchSpeed; internal readonly float CrouchRange; internal readonly float WalkSpeed; internal readonly float WalkRange; internal readonly float SprintSpeed; internal readonly float SprintRange; internal ToyNoticeLimits(float sightRange, float closeRange, float crouchSpeed, float crouchRange, float walkSpeed, float walkRange, float sprintSpeed, float sprintRange) { SightRange = sightRange; CloseRange = closeRange; CrouchSpeed = crouchSpeed; CrouchRange = crouchRange; WalkSpeed = walkSpeed; WalkRange = walkRange; SprintSpeed = sprintSpeed; SprintRange = sprintRange; } } internal enum ToyPatrolPlan : byte { Random, TowardPlayer, DetourThenTowardPlayer } internal readonly struct ToyNoiseReaction { internal readonly bool Mark; internal readonly bool Investigate; internal ToyNoiseReaction(bool mark, bool investigate) { Mark = mark; Investigate = investigate; } } internal delegate bool ReachableSpot<TPoint>(int index, out TPoint snapped); internal static class ToySensesLogic { internal const float StillStepMetres = 0.025908f; internal const float TowardNearMetres = 28.575f; internal const float TowardDetourMetres = 47.625f; internal static bool IsNoticed(ToyNotice notice) { if (notice != ToyNotice.Forced && notice != ToyNotice.Close && notice != ToyNotice.Alerted && notice != ToyNotice.Lit && notice != ToyNotice.Marked) { return notice == ToyNotice.SpeedBand; } return true; } internal static ToyNotice Notice(bool vetoed, bool forced, bool alerted, float distance, bool lineOfSight, bool toyStunned, bool fleeStunner, bool lit, bool marked, float speed, in ToyNoticeLimits limits) { if (vetoed) { return ToyNotice.Vetoed; } if (forced && lineOfSight && distance <= limits.SightRange) { return ToyNotice.Forced; } if (toyStunned && fleeStunner) { return ToyNotice.Stunned; } if (lineOfSight && distance < limits.CloseRange) { return ToyNotice.Close; } if (toyStunned) { return ToyNotice.Stunned; } if (alerted) { return ToyNotice.Alerted; } if (!lineOfSight || distance > limits.SightRange) { return ToyNotice.None; } if (lit) { return ToyNotice.Lit; } if (marked) { return ToyNotice.Marked; } if (!InSpeedBand(speed, distance, in limits)) { return ToyNotice.None; } return ToyNotice.SpeedBand; } internal static bool StillFleeStunner(ulong recordedClientId, ulong clientId, bool controlled, bool dead) { if (controlled && !dead) { return clientId == recordedClientId; } return false; } internal static bool JudgeWithOwnHoldAside<THolder, TPlayer>(ref THolder hold, THolder self, TPlayer player, Func<THolder, TPlayer, bool> judge) where THolder : class { if (hold != self) { return judge(self, player); } hold = null; try { return judge(self, player); } finally { hold = self; } } internal static bool InSpeedBand(float speed, float distance, in ToyNoticeLimits limits) { if (speed <= limits.CrouchSpeed) { return distance < limits.CrouchRange; } if (speed <= limits.WalkSpeed) { return distance < limits.WalkRange; } if (speed <= limits.SprintSpeed) { return distance < limits.SprintRange; } return true; } internal static bool ChaseExpired(float now, float lastNoticedAt, float memorySeconds) { return now - lastNoticedAt >= memorySeconds; } internal static int ChooseTarget(int count, bool[] noticed, float[] distance, int current, float switchMargin) { int num = -1; for (int i = 0; i < count; i++) { if (noticed[i] && (num < 0 || distance[i] < distance[num])) { num = i; } } if (num >= 0 && current >= 0 && current < count && noticed[current] && distance[num] + switchMargin >= distance[current]) { return current; } return num; } internal static bool FlashlightStuns(bool stateAllows, float distance, float facingAngle, bool lineOfSight, bool mayBeStunned, float stunRange, float stunAngle) { return stateAllows && distance <= stunRange && facingAngle < stunAngle && lineOfSight && mayBeStunned; } internal static int RandomWhole(int min, int max, double unit) { if (min > max) { int num = min; min = max; max = num; } int val = (int)Math.Floor(unit * ((double)max - (double)min + 1.0)) + min; return Math.Max(min, Math.Min(max, val)); } internal static ToyPatrolPlan ChoosePatrolPlan(bool kindPatrolsToward, bool hasPlayerPoint, float playerPointDistance) { if (!kindPatrolsToward || !hasPlayerPoint) { return ToyPatrolPlan.Random; } if (!(playerPointDistance < 28.575f)) { return ToyPatrolPlan.TowardPlayer; } return ToyPatrolPlan.DetourThenTowardPlayer; } internal static float SampleSpeed(float distance, float elapsed, float stillStep) { if (elapsed <= 0f || distance < stillStep) { return 0f; } return distance / elapsed; } internal static bool PatrolRuns(float pathLength, float runPathLength) { return pathLength > runPathLength; } internal static float GaitSpeed(float kindSpeed, float multiplier) { return Math.Min(kindSpeed * Math.Max(0f, multiplier), 16f); } internal static float TurnToward(float currentYaw, float targetYaw, float maxDegrees) { float num = (targetYaw - currentYaw) % 360f; if (num > 180f) { num -= 360f; } else if (num <= -180f) { num += 360f; } float num2 = Math.Max(0f, maxDegrees); num = Math.Max(0f - num2, Math.Min(num2, num)); float num3 = (currentYaw + num) % 360f; if (num3 < 0f) { num3 += 360f; } if (!(num3 >= 360f)) { return num3; } return 0f; } internal static ToyNoiseReaction ReactToNoise(bool playerBeside, bool targetable, bool ignored, bool alreadyMarked, bool walksToSounds) { if (playerBeside && !targetable) { return default(ToyNoiseReaction); } return new ToyNoiseReaction(playerBeside && !ignored && !alreadyMarked, walksToSounds); } internal static int ChooseHidingSpot<TPoint>(int count, float[] threatDistance, float[] toyDistance, float maxToyDistance, int[] order, Func<int, TPoint, bool> hidden, ReachableSpot<TPoint> reachable, int maxHiddenTests, out bool isHidden, out TPoint point) { isHidden = false; point = default(TPoint); if (order.Length < count) { return -1; } int num = 0; for (int i = 0; i < count; i++) { if (!(toyDistance[i] > maxToyDistance)) { int num2 = num++; while (num2 > 0 && HidesBefore(i, order[num2 - 1], threatDistance, toyDistance)) { order[num2] = order[num2 - 1]; num2--; } order[num2] = i; } } int num3 = -1; TPoint val = default(TPoint); int num4 = 0; for (int j = 0; j < num; j++) { if (num3 >= 0 && num4 >= maxHiddenTests) { break; } int num5 = order[j]; if (!reachable(num5, out var snapped)) { continue; } if (num3 < 0) { num3 = num5
Y4NGZType05.dll
Decompiled a day ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security.Cryptography; using System.Text; using System.Text.RegularExpressions; using BepInEx; using BepInEx.Bootstrap; using BepInEx.Configuration; using BepInEx.Logging; using Dawn; using Dissonance; using DunGen; using DunGen.Graph; using GameNetcodeStuff; using HarmonyLib; using Microsoft.CodeAnalysis; using Unity.Netcode; using UnityEngine; using UnityEngine.AI; using UnityEngine.Animations; using UnityEngine.Audio; using UnityEngine.Events; using UnityEngine.Experimental.Animations; using UnityEngine.Playables; using UnityEngine.Rendering; using UnityEngine.Rendering.HighDefinition; using UnityEngine.Video; using Y4NGZCompany.Facility.Interior.Placement; using Y4NGZMonsters.Shared; using Y4NGZType05; using Y4NGZType05.NetcodePatcher; using Y4NGZType05.Patches; using Y4NGZType05.World; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: AssemblyCompany("Y4NGZType05")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0+3460ec64f0cec4948e51ddb3f02a4b0e414f105e")] [assembly: AssemblyProduct("Y4NGZType05")] [assembly: AssemblyTitle("Y4NGZType05")] [assembly: AssemblyVersion("1.0.0.0")] [module: RefSafetyRules(11)] [module: NetcodePatchedAssembly] 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 Y4NGZType05 { internal static class Type05AudioAssets { private const string CuesTablePath = "Assets/Y4NGZ/Type05/Tables/cues.json"; private const string EventsTablePath = "Assets/Y4NGZ/Type05/Tables/events.json"; private const int ListedMissingFiles = 10; internal static Type05CueCatalogue Catalogue { get; private set; } internal static AudioClip[] Clips { get; private set; } internal static bool Load(AssetBundle bundle) { TextAsset val = bundle.LoadAsset<TextAsset>("Assets/Y4NGZ/Type05/Tables/cues.json"); TextAsset val2 = bundle.LoadAsset<TextAsset>("Assets/Y4NGZ/Type05/Tables/events.json"); if ((Object)(object)val == (Object)null || (Object)(object)val2 == (Object)null) { return Fail("the bundle has no " + (((Object)(object)val != (Object)null) ? "Assets/Y4NGZ/Type05/Tables/events.json" : (((Object)(object)val2 != (Object)null) ? "Assets/Y4NGZ/Type05/Tables/cues.json" : "Assets/Y4NGZ/Type05/Tables/cues.json or Assets/Y4NGZ/Type05/Tables/events.json"))); } Type05CueCatalogue type05CueCatalogue; try { type05CueCatalogue = Type05CueCatalogue.Compile(val.text, val2.text); } catch (Type05CueDataException ex) { return Fail(ex.Message); } string error; Type05CatchTimeline[] array = Type05CatchTimeline.Compile(Type05CueTables.Read(val.text, val2.text), out error); if (array == null) { Plugin.Log.LogError((object)("[Type05] catch timelines not compiled, the robot cannot catch: " + error)); } Plugin.CatchTimelines = array; for (int i = 0; i < type05CueCatalogue.CueCount; i++) { if (type05CueCatalogue.MaxLeaves(i) > 255) { return Fail($"cue '{type05CueCatalogue.CueName(i)}' can play {type05CueCatalogue.MaxLeaves(i)} sounds at once, more than the {byte.MaxValue} one cue message carries"); } } AudioClip[] array2 = (AudioClip[])(object)new AudioClip[type05CueCatalogue.FileCount]; StringBuilder stringBuilder = new StringBuilder(); int num = 0; for (int j = 0; j < array2.Length; j++) { array2[j] = bundle.LoadAsset<AudioClip>(type05CueCatalogue.FileAssetPath(j)); if ((Object)(object)array2[j] == (Object)null && num++ < 10) { stringBuilder.Append((num == 1) ? string.Empty : ", ").Append(type05CueCatalogue.FileAssetPath(j)); } } if (num > 0) { Plugin.Log.LogWarning((object)string.Format("[Type05] audio catalogue: {0} of {1} sound files are missing from the bundle, those sounds stay silent: {2}{3}", num, array2.Length, stringBuilder, (num > 10) ? ", ..." : string.Empty)); } Catalogue = type05CueCatalogue; Clips = array2; Plugin.Log.LogInfo((object)FormattableString.Invariant($"[Type05] audio catalogue: {type05CueCatalogue.CueCount} cues, {array2.Length - num} of {type05CueCatalogue.FileCount} files resolved, {type05CueCatalogue.SoundEventCount} sound events in {type05CueCatalogue.ClipsWithSoundEvents} clips, checksum 0x{type05CueCatalogue.Checksum:X8}")); return true; } private static bool Fail(string reason) { Plugin.Log.LogError((object)("[Type05] audio catalogue not loaded, the robot stays silent: " + reason)); return false; } } internal sealed class Type05AudioPlayer { private struct ProofSample { public ulong EventId; public int Cue; public double Start; public double SampleAt; public float MaxRms; } private const float MinPitch = 0.05f; private const float MaxPitch = 4f; private const int PooledSourcePriority = 192; private const double ProofSampleDelay = 0.25; private const int ProofSampleLength = 1024; private static readonly AnimationCurve FlatRolloff = new AnimationCurve((Keyframe[])(object)new Keyframe[2] { new Keyframe(0f, 1f), new Keyframe(1f, 1f) }); private static readonly bool ProofEnabled = Environment.GetEnvironmentVariable("Y4NGZ_PILOT") == "1"; private readonly Transform _anchor; private readonly Type05CueCatalogue _catalogue; private readonly AudioClip[] _clips; private readonly float _maxDistance; private readonly Type05CueSchedule _schedule; private readonly List<AudioSource> _sources; private readonly List<int> _sourceLeaf; private readonly List<int> _stops = new List<int>(); private readonly List<int> _starts = new List<int>(); private readonly List<ProofSample> _proof; private readonly float[] _proofBuffer; private readonly StringBuilder _proofLine; public bool Routed { get; private set; } public bool Idle { get { for (int i = 0; i < _schedule.Capacity; i++) { if (_schedule.Record(i).State != Type05LeafState.Free) { return false; } } return true; } } public Type05AudioPlayer(Transform anchor, Type05CueCatalogue catalogue, AudioClip[] clips, int poolSize, float maxDistance) { _anchor = anchor; _catalogue = catalogue; _clips = clips; _maxDistance = maxDistance; _schedule = new Type05CueSchedule(catalogue, poolSize); _sources = new List<AudioSource>(poolSize); _sourceLeaf = new List<int>(poolSize); for (int i = 0; i < poolSize; i++) { AddSource(); } if (ProofEnabled) { _proof = new List<ProofSample>(); _proofBuffer = new float[1024]; _proofLine = new StringBuilder(); } } public static Vector3 ListenerPosition() { //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_0053: 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) StartOfRound instance = StartOfRound.Instance; if ((Object)(object)instance == (Object)null) { return Vector3.positiveInfinity; } if ((Object)(object)instance.audioListener != (Object)null) { return ((Component)instance.audioListener).transform.position; } if (!((Object)(object)instance.activeCamera != (Object)null)) { return Vector3.positiveInfinity; } return ((Component)instance.activeCamera).transform.position; } public float ListenerDistance() { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) return Vector3.Distance(_anchor.position, ListenerPosition()); } public bool Route(AudioSource extraA, AudioSource extraB) { bool flag = CreatureAudioSetup.ConfigureSpatial(extraA) & CreatureAudioSetup.ConfigureSpatial(extraB); for (int i = 0; i < _sources.Count; i++) { flag &= CreatureAudioSetup.ConfigureSpatial(_sources[i]); } Routed = flag; return flag; } public bool Accept(ulong eventId, int cue, double cueStart, float volume, float pitch, Type05CueGroup group, Type05CueLeafChoice[] leaves, int count, out string reject) { _stops.Clear(); bool num = _schedule.Accept(eventId, cue, cueStart, volume, pitch, group, leaves, count, _stops, out reject); StopReported(); if (num && _proof != null) { _proof.Add(new ProofSample { EventId = eventId, Cue = cue, Start = cueStart, SampleAt = cueStart + 0.25 }); } return num; } public void StopGroup(ulong eventId, Type05CueGroup group) { _stops.Clear(); _schedule.StopGroup(eventId, group, _stops, out var _); StopReported(); } public void Tick(double now, Vector3 listener) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) float distance = Vector3.Distance(_anchor.position, listener); for (int i = 0; i < _sources.Count; i++) { int num = _sourceLeaf[i]; if (num >= 0) { if (_sources[i].isPlaying) { Apply(_sources[i], num, now, distance); continue; } _schedule.Release(num); _sourceLeaf[i] = -1; } } _starts.Clear(); _schedule.Due(now, _starts, out var _); for (int j = 0; j < _starts.Count; j++) { int num2 = _starts[j]; AudioClip val = _clips[_schedule.Record(num2).File]; if ((Object)(object)val == (Object)null) { _schedule.Release(num2); continue; } int num3 = FreeSource(); AudioSource val2 = _sources[num3]; val2.clip = val; float num4 = _schedule.Seek(num2, now); if (num4 > 0f) { val2.time = num4; } Apply(val2, num2, now, distance); val2.Play(); _schedule.MarkPlaying(num2, num3); _sourceLeaf[num3] = num2; } if (_proof != null && _proof.Count > 0) { SampleProof(now, distance); } } public void StopAll(out int stopped, out int cancelled) { _stops.Clear(); _schedule.Reset(_stops, out cancelled); stopped = _stops.Count; StopReported(); if (_proof != null) { _proof.Clear(); } } private void Apply(AudioSource source, int leaf, double now, float distance) { ref readonly Type05LeafRecord reference = ref _schedule.Record(leaf); _catalogue.Envelope(reference.Cue, reference.Path, (float)(now - reference.CueStart), out var volume, out var pitch); source.volume = Mathf.Clamp01(reference.Volume * reference.CallerVolume * _catalogue.LayerGain(reference.Cue, reference.Path, distance) * volume); source.pitch = Mathf.Clamp(reference.Pitch * reference.CallerPitch * pitch, 0.05f, 4f); } private void StopReported() { for (int i = 0; i < _stops.Count; i++) { AudioSource val = _sources[_stops[i]]; if ((Object)(object)val != (Object)null) { val.Stop(); } _sourceLeaf[_stops[i]] = -1; } } private int FreeSource() { for (int i = 0; i < _sourceLeaf.Count; i++) { if (_sourceLeaf[i] < 0) { return i; } } int result = AddSource(); Plugin.Log.LogInfo((object)$"[Type05] audio sources grown to {_sources.Count}"); return result; } private int AddSource() { //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Unknown result type (might be due to invalid IL or missing references) GameObject val = new GameObject("Type05Voice" + _sources.Count); val.transform.SetParent(_anchor, false); AudioSource val2 = val.AddComponent<AudioSource>(); val2.playOnAwake = false; val2.loop = false; val2.priority = 192; val2.spatialBlend = 1f; val2.rolloffMode = (AudioRolloffMode)2; val2.SetCustomCurve((AudioSourceCurveType)0, FlatRolloff); val2.maxDistance = _maxDistance; if (Routed) { CreatureAudioSetup.ConfigureSpatial(val2); } _sources.Add(val2); _sourceLeaf.Add(-1); return _sources.Count - 1; } private void SampleProof(double now, float distance) { AudioListener.GetOutputData(_proofBuffer, 0); float num = 0f; for (int i = 0; i < _proofBuffer.Length; i++) { num += _proofBuffer[i] * _proofBuffer[i]; } float num2 = Mathf.Sqrt(num / (float)_proofBuffer.Length); for (int num3 = _proof.Count - 1; num3 >= 0; num3--) { ProofSample sample = _proof[num3]; if (now >= sample.Start && num2 > sample.MaxRms) { sample.MaxRms = num2; _proof[num3] = sample; } if (!(now < sample.SampleAt)) { LogProof(in sample, distance); _proof[num3] = _proof[_proof.Count - 1]; _proof.RemoveAt(_proof.Count - 1); } } } private void LogProof(in ProofSample sample, float distance) { StringBuilder stringBuilder = _proofLine.Clear().Append(FormattableString.Invariant($"[Type05] cue-listener event={sample.EventId} cue={_catalogue.CueName(sample.Cue)} dist={distance:F1} rms={sample.MaxRms:F4} leaves:")); string value = " "; for (int i = 0; i < _sources.Count; i++) { int num = _sourceLeaf[i]; if (num >= 0 && _schedule.Record(num).EventId == sample.EventId) { ref readonly Type05LeafRecord reference = ref _schedule.Record(num); AudioSource val = _sources[i]; AudioLowPassFilter component = ((Component)val).GetComponent<AudioLowPassFilter>(); string text = (((Object)(object)component != (Object)null) ? FormattableString.Invariant($"{component.cutoffFrequency:F0}") : "none"); string text2 = (((Object)(object)val.outputAudioMixerGroup != (Object)null) ? ((Object)val.outputAudioMixerGroup).name : "none"); stringBuilder.Append(value).Append(FormattableString.Invariant($"{_catalogue.FileName(reference.File)} vol={val.volume:F3} layer={_catalogue.LayerGain(reference.Cue, reference.Path, distance):F3} lowpass={text} occlude={(Object)(object)((Component)val).GetComponent<OccludeAudio>() != (Object)null} mixer={text2}")); value = "; "; } } Plugin.Log.LogInfo((object)stringBuilder.ToString()); } } internal enum Type05CueGroup : byte { None, Personality, Scanner, Weld, PowerState, Choke } internal enum Type05FootSide : byte { None, Left, Right } internal enum Type05CurveMode : byte { Linear, Cubic, Constant } internal readonly struct Type05CurveKey { public readonly float Time; public readonly float Value; public readonly float Arrive; public readonly float Leave; public readonly Type05CurveMode Mode; public Type05CurveKey(float time, float value, float arrive, float leave, Type05CurveMode mode) { Time = time; Value = value; Arrive = arrive; Leave = leave; Mode = mode; } } internal sealed class Type05Curve { private readonly Type05CurveKey[] _keys; public Type05Curve(Type05CurveKey[] keys) { _keys = keys; } public float Evaluate(float t, float fallback) { if (_keys.Length == 0) { return fallback; } if (t <= _keys[0].Time) { return _keys[0].Value; } for (int i = 1; i < _keys.Length; i++) { Type05CurveKey type05CurveKey = _keys[i]; if (!(t > type05CurveKey.Time)) { Type05CurveKey type05CurveKey2 = _keys[i - 1]; if (type05CurveKey2.Mode == Type05CurveMode.Constant) { return type05CurveKey2.Value; } float num = type05CurveKey.Time - type05CurveKey2.Time; float num2 = Type05AudioRules.Saturate((t - type05CurveKey2.Time) / Math.Max(1E-05f, num)); if (type05CurveKey2.Mode == Type05CurveMode.Cubic) { float num3 = num2 * num2; float num4 = num3 * num2; return (2f * num4 - 3f * num3 + 1f) * type05CurveKey2.Value + (num4 - 2f * num3 + num2) * num * type05CurveKey2.Leave + (-2f * num4 + 3f * num3) * type05CurveKey.Value + (num4 - num3) * num * type05CurveKey.Arrive; } return type05CurveKey2.Value + (type05CurveKey.Value - type05CurveKey2.Value) * num2; } } return _keys[_keys.Length - 1].Value; } } internal readonly struct Type05CrossFade { public readonly float FadeInStart; public readonly float FadeInEnd; public readonly float FadeOutStart; public readonly float FadeOutEnd; public readonly float Volume; public Type05CrossFade(float fadeInStart, float fadeInEnd, float fadeOutStart, float fadeOutEnd, float volume) { FadeInStart = fadeInStart; FadeInEnd = fadeInEnd; FadeOutStart = fadeOutStart; FadeOutEnd = fadeOutEnd; Volume = volume; } public float Gain(float metres) { float num = Volume; if (FadeInEnd > FadeInStart) { num *= Type05AudioRules.Saturate((metres - FadeInStart) / (FadeInEnd - FadeInStart)); } if (FadeOutEnd > FadeOutStart) { num *= 1f - Type05AudioRules.Saturate((metres - FadeOutStart) / (FadeOutEnd - FadeOutStart)); } return num; } } internal struct Type05Lehmer { private const long Multiplier = 48271L; private const long Modulus = 2147483647L; private long _state; public Type05Lehmer(ushort seed) { _state = seed; } public double Next(double a, double b) { _state = _state * 48271 % int.MaxValue; return a + (b - a) * (double)_state / 2147483647.0; } } internal static class Type05AudioRules { private static readonly string[] VictimVoicePrefixes = new string[3] { "type5_throw_vo_", "sfx_helmethit_voice_", "type5_choke_vo_" }; public const double SourceUnitMetres = 0.0254; public const string GappedCueName = "RT_sfx_t5_ChatterRandom"; public const double GapSeconds = 3.0; public static float UnitsToMetres(double units) { return (float)(units * 0.0254); } public static float CentimetresToMetres(double centimetres) { return (float)(centimetres / 100.0); } public static float Saturate(float value) { if (!(value < 0f)) { if (!(value > 1f)) { return value; } return 1f; } return 0f; } public static bool VictimVoice(string fileName) { for (int i = 0; i < VictimVoicePrefixes.Length; i++) { if (fileName.StartsWith(VictimVoicePrefixes[i], StringComparison.OrdinalIgnoreCase)) { return true; } } return false; } public static float DistanceGain(float[] stopsMetres, float[] row, float metres, float maxMetres, bool layered) { if (row == null) { if (layered) { return 1f; } float num = UnitsToMetres(70.0); return 1f - Saturate((metres - num) / Math.Max(UnitsToMetres(1.0), maxMetres - num)); } int num2 = row.Length - 1; float num3; if (metres <= stopsMetres[0]) { num3 = row[0]; } else if (metres >= stopsMetres[num2]) { num3 = row[num2]; } else { int i; for (i = 1; metres > stopsMetres[i]; i++) { } float num4 = stopsMetres[i] - stopsMetres[i - 1]; float num5 = ((num4 > 0f) ? ((metres - stopsMetres[i - 1]) / num4) : 1f); num3 = row[i - 1] + (row[i] - row[i - 1]) * num5; } return num3 * (1f - Saturate((metres - 0.85f * maxMetres) / (0.15f * maxMetres))); } } internal readonly struct Type05ClipSoundEvent { public readonly float Time; public readonly int Cue; public readonly float Volume; public readonly float Pitch; public readonly Type05FootSide Side; public Type05ClipSoundEvent(float time, int cue, float volume, float pitch, Type05FootSide side) { Time = time; Cue = cue; Volume = volume; Pitch = pitch; Side = side; } } internal readonly struct Type05ClipCrossing { public readonly int Event; public readonly int Cycle; public readonly double Progress; public Type05ClipCrossing(int eventIndex, int cycle, double progress) { Event = eventIndex; Cycle = cycle; Progress = progress; } } internal readonly struct Type05ClipKey : IEquatable<Type05ClipKey> { public readonly Type05Phase Phase; public readonly Type05Clip Clip; public readonly double Start; public bool IsNone => Phase == Type05Phase.Dormant; public Type05ClipKey(Type05Phase phase, Type05Clip clip, double start) { Phase = phase; Clip = clip; Start = start; } public static Type05ClipKey Of(in Type05State state) { switch (state.Phase) { case Type05Phase.Waking: return new Type05ClipKey(state.Phase, Type05Clip.Wake, state.ClipStartTime); case Type05Phase.Idle: return new Type05ClipKey(state.Phase, Type05Clip.Idle, state.ClipStartTime); case Type05Phase.Walking: case Type05Phase.Turning: case Type05Phase.Working: case Type05Phase.Hurt: case Type05Phase.Shutdown: case Type05Phase.Dying: case Type05Phase.Attacking: case Type05Phase.Inspecting: return new Type05ClipKey(state.Phase, (Type05Clip)state.Clip, state.ClipStartTime); default: return default(Type05ClipKey); } } public bool Equals(Type05ClipKey other) { if (Phase == other.Phase && Clip == other.Clip) { return Start.Equals(other.Start); } return false; } public override bool Equals(object obj) { if (obj is Type05ClipKey other) { return Equals(other); } return false; } public override int GetHashCode() { return (int)(((uint)((int)Phase * 397) ^ (uint)Clip) * 397) ^ Start.GetHashCode(); } public static bool operator ==(Type05ClipKey a, Type05ClipKey b) { return a.Equals(b); } public static bool operator !=(Type05ClipKey a, Type05ClipKey b) { return !a.Equals(b); } } internal static class Type05ClipAudio { public static bool Loops(Type05Phase phase) { if (phase != Type05Phase.Idle) { return phase == Type05Phase.Walking; } return true; } } internal sealed class Type05ClipAudioCursor { private Type05ClipSoundEvent[] _events; private float _length; private bool _loops; private bool _fresh; private double _progress; public bool Active { get; private set; } public Type05ClipKey Key { get; private set; } public double Progress => _progress; public void Begin(Type05ClipKey key, Type05ClipSoundEvent[] events, float length, bool loops, double startProgress) { if (key.IsNone) { Clear(); return; } Key = key; _events = events; _length = length; _loops = loops; _progress = startProgress; _fresh = true; Active = true; } public void Clear() { Active = false; Key = default(Type05ClipKey); _events = null; } public Type05ClipSoundEvent Event(int index) { return _events[index]; } public void Advance(double to, List<Type05ClipCrossing> crossings) { if (!Active || _length <= 0f) { return; } if (!_loops && to > (double)_length) { to = _length; } if (!(to >= _progress)) { return; } long num = (_loops ? ((long)Math.Floor(_progress / (double)_length)) : 0); long num2 = (_loops ? ((long)Math.Floor(to / (double)_length)) : 0); for (long num3 = num; num3 <= num2; num3++) { for (int i = 0; i < _events.Length; i++) { double num4 = (double)num3 * (double)_length + (double)_events[i].Time; if ((_fresh ? (num4 >= _progress) : (num4 > _progress)) && num4 <= to) { crossings.Add(new Type05ClipCrossing(i, (int)num3, num4)); } } } _progress = to; _fresh = false; } } internal sealed class Type05CueDataException : Exception { public Type05CueDataException(string message) : base(message) { } } internal sealed class Type05JsonReader { private const int MaxNesting = 64; private readonly string _text; private int _pos; private Type05JsonReader(string text) { _text = text; } public static object Parse(string text) { if (text == null) { throw new Type05CueDataException("JSON error: no text."); } Type05JsonReader type05JsonReader = new Type05JsonReader(text); if (text.Length > 0 && text[0] == '\ufeff') { type05JsonReader._pos = 1; } object result = type05JsonReader.ReadValue(0); type05JsonReader.SkipSpace(); if (type05JsonReader._pos != text.Length) { throw type05JsonReader.Error("unexpected text after the value"); } return result; } private Type05CueDataException Error(string what) { return new Type05CueDataException($"JSON error at character {_pos}: {what}."); } private void SkipSpace() { while (_pos < _text.Length) { char c = _text[_pos]; if (c != ' ' && c != '\t' && c != '\r' && c != '\n') { break; } _pos++; } } private object ReadValue(int depth) { SkipSpace(); if (_pos >= _text.Length) { throw Error("the text ends where a value is expected"); } if (depth > 64) { throw Error("nesting is too deep"); } char c = _text[_pos]; switch (c) { case '{': return ReadObject(depth); case '[': return ReadArray(depth); case '"': return ReadString(); case 't': ReadWord("true"); return true; case 'f': ReadWord("false"); return false; case 'n': ReadWord("null"); return null; default: switch (c) { case '-': case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': return ReadNumber(); default: throw Error($"unexpected character '{c}'"); } } } private void ReadWord(string word) { if (string.CompareOrdinal(_text, _pos, word, 0, word.Length) != 0) { throw Error("expected '" + word + "'"); } _pos += word.Length; } private Dictionary<string, object> ReadObject(int depth) { Dictionary<string, object> dictionary = new Dictionary<string, object>(StringComparer.Ordinal); _pos++; SkipSpace(); if (_pos < _text.Length && _text[_pos] == '}') { _pos++; return dictionary; } while (true) { SkipSpace(); if (_pos >= _text.Length || _text[_pos] != '"') { throw Error("expected a quoted key"); } int pos = _pos; string text = ReadString(); SkipSpace(); if (_pos >= _text.Length || _text[_pos] != ':') { throw Error("expected ':' after the key"); } _pos++; object value = ReadValue(depth + 1); if (dictionary.ContainsKey(text)) { _pos = pos; throw Error("duplicate key '" + text + "'"); } dictionary.Add(text, value); SkipSpace(); if (_pos >= _text.Length) { throw Error("the text ends inside an object"); } if (_text[_pos] != ',') { break; } _pos++; } if (_text[_pos] == '}') { _pos++; return dictionary; } throw Error("expected ',' or '}'"); } private List<object> ReadArray(int depth) { List<object> list = new List<object>(); _pos++; SkipSpace(); if (_pos < _text.Length && _text[_pos] == ']') { _pos++; return list; } while (true) { list.Add(ReadValue(depth + 1)); SkipSpace(); if (_pos >= _text.Length) { throw Error("the text ends inside an array"); } if (_text[_pos] != ',') { break; } _pos++; } if (_text[_pos] == ']') { _pos++; return list; } throw Error("expected ',' or ']'"); } private string ReadString() { _pos++; int pos = _pos; StringBuilder stringBuilder = null; while (true) { if (_pos >= _text.Length) { throw Error("the text ends inside a string"); } char c = _text[_pos]; if (c == '"') { string text = _text.Substring(pos, _pos - pos); _pos++; if (stringBuilder != null) { return stringBuilder.Append(text).ToString(); } return text; } if (c < ' ') { throw Error("a control character in a string"); } if (c != '\\') { _pos++; continue; } stringBuilder = (stringBuilder ?? new StringBuilder()).Append(_text, pos, _pos - pos); _pos++; if (_pos >= _text.Length) { break; } char c2 = _text[_pos++]; switch (c2) { case '"': case '/': case '\\': stringBuilder.Append(c2); break; case 'b': stringBuilder.Append('\b'); break; case 'f': stringBuilder.Append('\f'); break; case 'n': stringBuilder.Append('\n'); break; case 'r': stringBuilder.Append('\r'); break; case 't': stringBuilder.Append('\t'); break; case 'u': stringBuilder.Append(ReadHex4()); break; default: _pos--; throw Error($"unknown escape '\\{c2}'"); } pos = _pos; } throw Error("the text ends inside an escape"); } private char ReadHex4() { if (_pos + 4 > _text.Length) { throw Error("the text ends inside a \\u escape"); } int num = 0; for (int i = 0; i < 4; i++) { char c = _text[_pos + i]; int num2 = ((c >= '0' && c <= '9') ? (c - 48) : ((c >= 'a' && c <= 'f') ? (c - 97 + 10) : ((c >= 'A' && c <= 'F') ? (c - 65 + 10) : (-1)))); if (num2 < 0) { _pos += i; throw Error("a \\u escape needs four hex digits"); } num = num * 16 + num2; } _pos += 4; return (char)num; } private double ReadNumber() { int pos = _pos; if (_text[_pos] == '-') { _pos++; } if (_pos >= _text.Length || _text[_pos] < '0' || _text[_pos] > '9') { throw Error("a number needs a digit"); } if (_text[_pos] == '0') { _pos++; } else { SkipDigits(); } if (_pos < _text.Length && _text[_pos] == '.') { _pos++; if (_pos >= _text.Length || _text[_pos] < '0' || _text[_pos] > '9') { throw Error("a fraction needs a digit"); } SkipDigits(); } if (_pos < _text.Length && (_text[_pos] == 'e' || _text[_pos] == 'E')) { _pos++; if (_pos < _text.Length && (_text[_pos] == '+' || _text[_pos] == '-')) { _pos++; } if (_pos >= _text.Length || _text[_pos] < '0' || _text[_pos] > '9') { throw Error("an exponent needs a digit"); } SkipDigits(); } if (!double.TryParse(_text.Substring(pos, _pos - pos), NumberStyles.Float, CultureInfo.InvariantCulture, out var result) || double.IsInfinity(result)) { _pos = pos; throw Error("the number is out of range"); } return result; } private void SkipDigits() { while (_pos < _text.Length && _text[_pos] >= '0' && _text[_pos] <= '9') { _pos++; } } } internal enum Type05NodeKind : byte { Mixer, Random, WavePlayer, Delay, Modulator, Enveloper, DistanceCrossFade } internal sealed class Type05RawNode { public int Id; public Type05NodeKind Kind; public int[] Children; public double[] Values; public double Min; public double Max; public double PitchMin; public double PitchMax; public Type05CrossFade[] Fades; public Type05Curve VolumeCurve; public Type05Curve PitchCurve; public string File; public float Duration; } internal sealed class Type05RawCue { public string Name; public double Volume; public double MaxDistance; public int Root; public float[] DistanceGains; public SortedList<int, Type05RawNode> Nodes; } internal readonly struct Type05RawSoundEvent { public readonly float Time; public readonly string Cue; public readonly float Volume; public readonly float Pitch; public readonly Type05FootSide Side; public Type05RawSoundEvent(float time, string cue, float volume, float pitch, Type05FootSide side) { Time = time; Cue = cue; Volume = volume; Pitch = pitch; Side = side; } } internal readonly struct Type05RawGameplayEvent { public readonly float Time; public readonly Type05CatchEffect Effect; public Type05RawGameplayEvent(float time, Type05CatchEffect effect) { Time = time; Effect = effect; } } internal sealed class Type05RawTables { public double[] DistanceStops; public List<Type05RawCue> Cues; public Dictionary<string, List<Type05RawSoundEvent>> Clips; public Dictionary<string, List<Type05RawGameplayEvent>> Gameplay; } internal static class Type05CueTables { public static Type05RawTables Read(string cuesJson, string eventsJson) { Dictionary<string, object> o = Obj(Type05JsonReader.Parse(cuesJson), "cues table"); Type05RawTables type05RawTables = new Type05RawTables { DistanceStops = Numbers(Get(o, "distance_stops", "cues table"), "cues table distance_stops"), Cues = new List<Type05RawCue>(), Clips = new Dictionary<string, List<Type05RawSoundEvent>>(StringComparer.Ordinal), Gameplay = new Dictionary<string, List<Type05RawGameplayEvent>>(StringComparer.Ordinal) }; for (int i = 1; i < type05RawTables.DistanceStops.Length; i++) { if (type05RawTables.DistanceStops[i] < type05RawTables.DistanceStops[i - 1]) { throw new Type05CueDataException("cues table distance_stops must not decrease."); } } foreach (KeyValuePair<string, object> item in Obj(Get(o, "cues", "cues table"), "cues table cues")) { if (item.Key.Length == 0) { throw new Type05CueDataException("cues table has a cue with an empty name."); } type05RawTables.Cues.Add(ReadCue(item.Key, item.Value, type05RawTables.DistanceStops)); } bool flag = default(bool); foreach (KeyValuePair<string, object> item2 in Obj(Get(Obj(Type05JsonReader.Parse(eventsJson), "events table"), "clips", "events table"), "events table clips")) { List<Type05RawSoundEvent> list = new List<Type05RawSoundEvent>(); List<Type05RawGameplayEvent> list2 = null; string text = "events table clip '" + item2.Key + "'"; foreach (object item3 in Arr(item2.Value, text)) { Dictionary<string, object> dictionary = Obj(item3, text + " event"); if (!dictionary.TryGetValue("kind", out var value) || !(value is string text2)) { continue; } Type05CatchEffect type05CatchEffect = GameplayEffect(text2); if (text2 != "sound" && type05CatchEffect == Type05CatchEffect.None) { continue; } int num; if (dictionary.TryGetValue("used_by_addon", out var value2)) { if (value2 is bool) { flag = (bool)value2; num = 1; } else { num = 0; } } else { num = 0; } if (((uint)num & (flag ? 1u : 0u)) == 0) { continue; } if (type05CatchEffect != Type05CatchEffect.None) { float num2 = (float)Num(Get(dictionary, "time", text), text + " time"); if (!(num2 >= 0f) || float.IsInfinity(num2)) { throw new Type05CueDataException(text + ", " + text2 + " event: the event time must be a number of seconds from 0."); } (list2 ?? (list2 = new List<Type05RawGameplayEvent>())).Add(new Type05RawGameplayEvent(num2, type05CatchEffect)); continue; } string text3 = Str(Get(dictionary, "cue", text), text + " cue"); float num3 = (float)Num(Get(dictionary, "time", text), text + " time"); if (!(num3 >= 0f) || float.IsInfinity(num3)) { throw new Type05CueDataException(text + ", cue '" + text3 + "': the event time must be a number of seconds from 0."); } Type05FootSide side = Type05FootSide.None; if (dictionary.TryGetValue("side", out var value3) && value3 != null) { string text4 = Str(value3, text + " side"); int num4; if (!(text4 == "l")) { if (!(text4 == "r")) { throw new Type05CueDataException(text + ", cue '" + text3 + "': the side must be \"l\" or \"r\"."); } num4 = 2; } else { num4 = 1; } side = (Type05FootSide)num4; } list.Add(new Type05RawSoundEvent(num3, text3, (float)Num(Get(dictionary, "volume", text), text + " volume"), (float)Num(Get(dictionary, "pitch", text), text + " pitch"), side)); } type05RawTables.Clips.Add(item2.Key, list); if (list2 != null) { type05RawTables.Gameplay.Add(item2.Key, list2); } } return type05RawTables; } private static Type05CatchEffect GameplayEffect(string kind) { return kind switch { "grab_pickup" => Type05CatchEffect.Pickup, "grab_throw" => Type05CatchEffect.Launch, "damage" => Type05CatchEffect.Damage, "release_victim" => Type05CatchEffect.Release, _ => Type05CatchEffect.None, }; } private static Type05RawCue ReadCue(string name, object value, double[] stops) { string text = "cue '" + name + "'"; Dictionary<string, object> dictionary = Obj(value, text); Type05RawCue type05RawCue = new Type05RawCue { Name = name, Volume = Num(Get(dictionary, "volume", text), text + " volume"), MaxDistance = Num(Get(dictionary, "max_distance", text), text + " max_distance"), Root = Int(Num(Get(dictionary, "root", text), text + " root"), text + " root"), Nodes = new SortedList<int, Type05RawNode>() }; if (!(type05RawCue.MaxDistance > 0.0)) { throw new Type05CueDataException(text + ": max_distance must be above 0."); } if (dictionary.TryGetValue("distance_gains", out var value2) && value2 != null) { double[] array = Numbers(value2, text + " distance_gains"); if (array.Length != stops.Length) { throw new Type05CueDataException($"{text}: distance_gains has {array.Length} entries for {stops.Length} distance stops."); } type05RawCue.DistanceGains = new float[array.Length]; for (int i = 0; i < array.Length; i++) { type05RawCue.DistanceGains[i] = (float)array[i]; } } foreach (KeyValuePair<string, object> item in Obj(Get(dictionary, "nodes", text), text + " nodes")) { if (!int.TryParse(item.Key, NumberStyles.None, CultureInfo.InvariantCulture, out var result)) { throw new Type05CueDataException(text + ": node id '" + item.Key + "' is not a non-negative number."); } type05RawCue.Nodes.Add(result, ReadNode(name, result, item.Value)); } return type05RawCue; } private static Type05RawNode ReadNode(string cue, int id, object value) { string text = $"cue '{cue}' node {id}"; Dictionary<string, object> dictionary = Obj(value, text); string text2 = Str(Get(dictionary, "type", text), text + " type"); Type05RawNode type05RawNode = new Type05RawNode { Id = id }; switch (text2) { case "Mixer": type05RawNode.Kind = Type05NodeKind.Mixer; break; case "Random": type05RawNode.Kind = Type05NodeKind.Random; break; case "WavePlayer": type05RawNode.Kind = Type05NodeKind.WavePlayer; break; case "Delay": type05RawNode.Kind = Type05NodeKind.Delay; break; case "Modulator": type05RawNode.Kind = Type05NodeKind.Modulator; break; case "Enveloper": type05RawNode.Kind = Type05NodeKind.Enveloper; break; case "DistanceCrossFade": type05RawNode.Kind = Type05NodeKind.DistanceCrossFade; break; default: throw new Type05CueDataException(text + ": unknown node type '" + text2 + "'."); } double[] array = Numbers(Get(dictionary, "children", text), text + " children"); type05RawNode.Children = new int[array.Length]; for (int i = 0; i < array.Length; i++) { type05RawNode.Children[i] = Int(array[i], text + " children"); } object value2; Dictionary<string, object> dictionary2 = ((dictionary.TryGetValue("props", out value2) && value2 != null) ? Obj(value2, text + " props") : new Dictionary<string, object>()); switch (type05RawNode.Kind) { case Type05NodeKind.Mixer: type05RawNode.Values = Fill(dictionary2, "InputVolume", type05RawNode.Children.Length, text); break; case Type05NodeKind.Random: type05RawNode.Values = Fill(dictionary2, "Weights", type05RawNode.Children.Length, text); break; case Type05NodeKind.WavePlayer: { Dictionary<string, object> o2 = Obj(Get(dictionary, "wave", text), text + " wave"); type05RawNode.File = Str(Get(o2, "file", text + " wave"), text + " wave.file"); if (type05RawNode.File.Length == 0) { throw new Type05CueDataException(text + ": wave.file is empty."); } type05RawNode.Duration = (float)Num(Get(o2, "duration", text + " wave"), text + " wave.duration"); if (!(type05RawNode.Duration >= 0f)) { throw new Type05CueDataException(text + ": wave.duration must be seconds from 0."); } break; } case Type05NodeKind.Delay: type05RawNode.Min = Num(Get(dictionary2, "DelayMin", text + " props"), text + " DelayMin"); type05RawNode.Max = Num(Get(dictionary2, "DelayMax", text + " props"), text + " DelayMax"); break; case Type05NodeKind.Modulator: { type05RawNode.Min = Num(Get(dictionary2, "VolumeMin", text + " props"), text + " VolumeMin"); type05RawNode.Max = Num(Get(dictionary2, "VolumeMax", text + " props"), text + " VolumeMax"); type05RawNode.PitchMin = (dictionary2.TryGetValue("PitchMin", out var value3) ? Num(value3, text + " PitchMin") : 0.95); type05RawNode.PitchMax = (dictionary2.TryGetValue("PitchMax", out var value4) ? Num(value4, text + " PitchMax") : 1.05); break; } case Type05NodeKind.Enveloper: type05RawNode.VolumeCurve = ReadCurve(dictionary2, "VolumeCurve", text); type05RawNode.PitchCurve = ReadCurve(dictionary2, "PitchCurve", text); break; case Type05NodeKind.DistanceCrossFade: { List<object> list = Arr(Get(dictionary2, "CrossFadeInput", text + " props"), text + " CrossFadeInput"); if (list.Count != type05RawNode.Children.Length) { throw new Type05CueDataException($"{text}: CrossFadeInput has {list.Count} entries for {type05RawNode.Children.Length} children."); } type05RawNode.Fades = new Type05CrossFade[list.Count]; for (int j = 0; j < list.Count; j++) { string text3 = $"{text} CrossFadeInput[{j}]"; Dictionary<string, object> o = Obj(list[j], text3); type05RawNode.Fades[j] = new Type05CrossFade(Type05AudioRules.CentimetresToMetres(Num(Get(o, "FadeInDistanceStart", text3), text3 + " FadeInDistanceStart")), Type05AudioRules.CentimetresToMetres(Num(Get(o, "FadeInDistanceEnd", text3), text3 + " FadeInDistanceEnd")), Type05AudioRules.CentimetresToMetres(Num(Get(o, "FadeOutDistanceStart", text3), text3 + " FadeOutDistanceStart")), Type05AudioRules.CentimetresToMetres(Num(Get(o, "FadeOutDistanceEnd", text3), text3 + " FadeOutDistanceEnd")), (float)Num(Get(o, "Volume", text3), text3 + " Volume")); } break; } } return type05RawNode; } private static double[] Fill(Dictionary<string, object> props, string key, int count, string where) { double[] array = new double[count]; for (int i = 0; i < count; i++) { array[i] = 1.0; } if (props.TryGetValue(key, out var value) && value != null) { double[] array2 = Numbers(value, where + " " + key); Array.Copy(array2, array, Math.Min(array2.Length, count)); } return array; } private static Type05Curve ReadCurve(Dictionary<string, object> props, string key, string where) { if (!props.TryGetValue(key, out var value) || value == null) { return new Type05Curve(Array.Empty<Type05CurveKey>()); } string text = where + " " + key; List<object> list = Arr(Get(Obj(Get(Obj(value, text), "EditorCurveData", text), text), "Keys", text + " EditorCurveData"), text + " Keys"); Type05CurveKey[] array = new Type05CurveKey[list.Count]; for (int i = 0; i < list.Count; i++) { string text2 = $"{text} key {i}"; Dictionary<string, object> o = Obj(list[i], text2); string text3 = Str(Get(o, "InterpMode", text2), text2 + " InterpMode"); Type05CurveMode mode = text3 switch { "RCIM_Constant" => Type05CurveMode.Constant, "RCIM_Cubic" => Type05CurveMode.Cubic, "RCIM_Linear" => Type05CurveMode.Linear, _ => throw new Type05CueDataException(text2 + ": unknown InterpMode '" + text3 + "'."), }; array[i] = new Type05CurveKey((float)Num(Get(o, "Time", text2), text2 + " Time"), (float)Num(Get(o, "Value", text2), text2 + " Value"), (float)Num(Get(o, "ArriveTangent", text2), text2 + " ArriveTangent"), (float)Num(Get(o, "LeaveTangent", text2), text2 + " LeaveTangent"), mode); if (i > 0 && array[i].Time < array[i - 1].Time) { throw new Type05CueDataException(text2 + ": key times must not decrease."); } } return new Type05Curve(array); } private static object Get(Dictionary<string, object> o, string key, string where) { if (!o.TryGetValue(key, out var value)) { throw new Type05CueDataException(where + ": '" + key + "' is missing."); } return value; } private static Dictionary<string, object> Obj(object value, string what) { return (value as Dictionary<string, object>) ?? throw new Type05CueDataException(what + " must be an object."); } private static List<object> Arr(object value, string what) { return (value as List<object>) ?? throw new Type05CueDataException(what + " must be an array."); } private static string Str(object value, string what) { return (value as string) ?? throw new Type05CueDataException(what + " must be a string."); } private static double Num(object value, string what) { if (value is double) { return (double)value; } throw new Type05CueDataException(what + " must be a number."); } private static int Int(double d, string what) { if (d != Math.Floor(d) || d < -1.0 || d > 2147483647.0) { throw new Type05CueDataException(what + " must be a whole number, got " + d.ToString(CultureInfo.InvariantCulture) + "."); } return (int)d; } private static double[] Numbers(object value, string what) { List<object> list = Arr(value, what); double[] array = new double[list.Count]; for (int i = 0; i < array.Length; i++) { array[i] = Num(list[i], $"{what}[{i}]"); } return array; } } internal struct Type05CueLeafChoice { public ushort Path; public ushort File; public float Delay; public float Volume; public float Pitch; } internal sealed class Type05CueCatalogue { private struct EnvelopeStage { public float Start; public Type05Curve Volume; public Type05Curve Pitch; } private sealed class Occurrence { public Type05RawNode Node; public Occurrence[] Children; public int Path = -1; public int RandomIndex = -1; public int MaxLeaves; } private sealed class PathModel { public ushort File; public Type05CrossFade[] Filters; public EnvelopeStage[] Stages; } private sealed class CueModel { public string Name; public double Volume; public float MaxMetres; public float[] Row; public double Gap; public Occurrence Root; public Type05RawNode[] RandomNodes; public PathModel[] Paths; } private sealed class CueBuild { public Type05RawCue Raw; public Dictionary<int, int> RandomIndexById; public HashSet<int> OnStack = new HashSet<int>(); public List<Type05CrossFade> Filters = new List<Type05CrossFade>(); public List<EnvelopeStage> Stages = new List<EnvelopeStage>(); public List<PathModel> Paths = new List<PathModel>(); } public const string FootstepCueName = "Type5_TestFootstep"; private const string AudioFolder = "Assets/Y4NGZ/Type05/Source/Audio/"; private const int MaxDepth = 32; private static readonly Type05ClipSoundEvent[] NoEvents = new Type05ClipSoundEvent[0]; private readonly CueModel[] _cues; private readonly Dictionary<string, int> _cueIndex = new Dictionary<string, int>(StringComparer.Ordinal); private readonly float[] _stopsMetres; private readonly List<string> _fileNames = new List<string>(); private readonly List<string> _fileAssets = new List<string>(); private readonly List<float> _fileDurations = new List<float>(); private readonly List<bool> _fileVictimVoice = new List<bool>(); private readonly Dictionary<string, int> _fileIndex = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase); private readonly Dictionary<string, Type05ClipSoundEvent[]> _eventsByName = new Dictionary<string, Type05ClipSoundEvent[]>(StringComparer.Ordinal); private readonly Type05ClipSoundEvent[][] _eventsByClip = new Type05ClipSoundEvent[39][]; public int CueCount => _cues.Length; public int FootstepCue { get; } public int FileCount => _fileNames.Count; public int SoundEventCount { get; } public int ClipsWithSoundEvents { get; } public uint Checksum { get; } private Type05CueCatalogue(Type05RawTables raw, uint checksum) { Checksum = checksum; _stopsMetres = new float[raw.DistanceStops.Length]; for (int i = 0; i < _stopsMetres.Length; i++) { _stopsMetres[i] = Type05AudioRules.UnitsToMetres(raw.DistanceStops[i]); } _cues = new CueModel[raw.Cues.Count]; for (int j = 0; j < _cues.Length; j++) { if (_cueIndex.ContainsKey(raw.Cues[j].Name)) { throw new Type05CueDataException("cue '" + raw.Cues[j].Name + "' appears twice."); } _cueIndex.Add(raw.Cues[j].Name, j); _cues[j] = BuildCue(raw.Cues[j]); } FootstepCue = (_cueIndex.TryGetValue("Type5_TestFootstep", out var value) ? value : (-1)); foreach (KeyValuePair<string, List<Type05RawSoundEvent>> clip in raw.Clips) { Type05ClipSoundEvent[] array = BuildEvents(clip.Key, clip.Value); _eventsByName.Add(clip.Key, array); SoundEventCount += array.Length; if (array.Length != 0) { int clipsWithSoundEvents = ClipsWithSoundEvents; ClipsWithSoundEvents = clipsWithSoundEvents + 1; } } for (int k = 0; k < _eventsByClip.Length; k++) { _eventsByClip[k] = EventsFor(Type05ClipPlan.StateName((Type05Clip)k)); } } public static Type05CueCatalogue Compile(string cuesJson, string eventsJson) { return new Type05CueCatalogue(Type05CueTables.Read(cuesJson, eventsJson), Fnv1a(eventsJson, Fnv1a(cuesJson, 2166136261u))); } public string CueName(int cue) { return _cues[cue].Name; } public bool TryFindCue(string name, out int cue) { return _cueIndex.TryGetValue(name, out cue); } public string FileName(int file) { return _fileNames[file]; } public string FileAssetPath(int file) { return _fileAssets[file]; } public float FileDuration(int file) { return _fileDurations[file]; } public bool VictimVoice(int file) { return _fileVictimVoice[file]; } public Type05ClipSoundEvent[] EventsFor(Type05Clip clip) { return _eventsByClip[(int)clip]; } public Type05ClipSoundEvent[] EventsFor(string clipName) { if (!_eventsByName.TryGetValue(clipName, out var value)) { return NoEvents; } return value; } public int MaxLeaves(int cue) { return _cues[cue].Root.MaxLeaves; } public float MaxDistance(int cue) { return _cues[cue].MaxMetres; } public bool IsLeafOf(int cue, in Type05CueLeafChoice leaf) { if (cue < 0 || cue >= _cues.Length) { return false; } PathModel[] paths = _cues[cue].Paths; if (leaf.Path < paths.Length) { return paths[leaf.Path].File == leaf.File; } return false; } public float LayerGain(int cue, int path, float metres) { CueModel cueModel = _cues[cue]; if (metres > cueModel.MaxMetres) { return 0f; } Type05CrossFade[] filters = cueModel.Paths[path].Filters; float num = 1f; for (int i = 0; i < filters.Length; i++) { num *= filters[i].Gain(metres); } return num * Type05AudioRules.DistanceGain(_stopsMetres, cueModel.Row, metres, cueModel.MaxMetres, filters.Length != 0); } public void Envelope(int cue, int path, float cueElapsed, out float volume, out float pitch) { EnvelopeStage[] stages = _cues[cue].Paths[path].Stages; volume = 1f; pitch = 1f; for (int i = 0; i < stages.Length; i++) { float t = cueElapsed - stages[i].Start; volume *= stages[i].Volume.Evaluate(t, 1f); pitch *= stages[i].Pitch.Evaluate(t, 1f); } } internal double GapSeconds(int cue) { return _cues[cue].Gap; } internal int RandomCount(int cue) { return _cues[cue].RandomNodes.Length; } internal int RandomChildCount(int cue, int random) { return _cues[cue].RandomNodes[random].Children.Length; } internal double RandomWeight(int cue, int random, int child) { Type05RawNode type05RawNode = _cues[cue].RandomNodes[random]; if (type05RawNode.Children[child] < 0 || !(type05RawNode.Values[child] > 0.0)) { return 0.0; } return type05RawNode.Values[child]; } internal void Decode(int cue, int[] picks, ushort seed, List<Type05CueLeafChoice> leaves) { CueModel cueModel = _cues[cue]; Type05Lehmer stream = new Type05Lehmer(seed); DecodeNode(cueModel, cueModel.Root, 0.0, cueModel.Volume, 1.0, picks, ref stream, leaves); } private static void DecodeNode(CueModel model, Occurrence occurrence, double delay, double volume, double pitch, int[] picks, ref Type05Lehmer stream, List<Type05CueLeafChoice> leaves) { Type05RawNode node = occurrence.Node; switch (node.Kind) { case Type05NodeKind.WavePlayer: leaves.Add(new Type05CueLeafChoice { Path = (ushort)occurrence.Path, File = model.Paths[occurrence.Path].File, Delay = (float)delay, Volume = (float)volume, Pitch = (float)pitch }); return; case Type05NodeKind.Delay: delay += stream.Next(node.Min, node.Max); break; case Type05NodeKind.Modulator: volume *= stream.Next(node.Min, node.Max); pitch *= stream.Next(node.PitchMin, node.PitchMax); break; case Type05NodeKind.Enveloper: volume *= stream.Next(1.0, 1.0); pitch *= stream.Next(1.0, 1.0); break; case Type05NodeKind.Random: { int num = picks[occurrence.RandomIndex]; if (num >= 0 && occurrence.Children[num] != null) { DecodeNode(model, occurrence.Children[num], delay, volume, pitch, picks, ref stream, leaves); } return; } } for (int i = 0; i < occurrence.Children.Length; i++) { if (occurrence.Children[i] != null) { double volume2 = ((node.Kind == Type05NodeKind.Mixer) ? (volume * node.Values[i]) : volume); DecodeNode(model, occurrence.Children[i], delay, volume2, pitch, picks, ref stream, leaves); } } } private CueModel BuildCue(Type05RawCue raw) { string arg = "cue '" + raw.Name + "'"; List<Type05RawNode> list = new List<Type05RawNode>(); Dictionary<int, int> dictionary = new Dictionary<int, int>(); foreach (Type05RawNode value in raw.Nodes.Values) { int[] children = value.Children; foreach (int num in children) { if (num >= 0 && !raw.Nodes.ContainsKey(num)) { throw new Type05CueDataException($"{arg} node {value.Id}: child {num} is not a node of the cue."); } } if (value.Kind == Type05NodeKind.Random) { dictionary.Add(value.Id, list.Count); list.Add(value); } } if (!raw.Nodes.ContainsKey(raw.Root)) { throw new Type05CueDataException($"{arg}: the root {raw.Root} is not a node of the cue."); } CueBuild cueBuild = new CueBuild { Raw = raw, RandomIndexById = dictionary }; return new CueModel { Name = raw.Name, Volume = raw.Volume, MaxMetres = Type05AudioRules.UnitsToMetres(raw.MaxDistance), Row = raw.DistanceGains, Gap = ((raw.Name == "RT_sfx_t5_ChatterRandom") ? 3.0 : 0.0), RandomNodes = list.ToArray(), Root = Expand(cueBuild, raw.Root, 0, 0.0, ranged: false), Paths = cueBuild.Paths.ToArray() }; } private Occurrence Expand(CueBuild build, int id, int depth, double delay, bool ranged) { if (depth > 32) { throw new Type05CueDataException($"cue '{build.Raw.Name}' node {id}: the graph is deeper than {32} nodes."); } if (!build.OnStack.Add(id)) { throw new Type05CueDataException($"cue '{build.Raw.Name}' node {id}: the graph loops back to this node."); } Type05RawNode type05RawNode = build.Raw.Nodes[id]; Occurrence occurrence = new Occurrence { Node = type05RawNode, Children = new Occurrence[type05RawNode.Children.Length] }; switch (type05RawNode.Kind) { case Type05NodeKind.WavePlayer: if (build.Paths.Count > 65535) { throw new Type05CueDataException($"cue '{build.Raw.Name}' has more than {ushort.MaxValue} leaf paths."); } occurrence.Path = build.Paths.Count; occurrence.MaxLeaves = 1; build.Paths.Add(new PathModel { File = RegisterFile(type05RawNode), Filters = build.Filters.ToArray(), Stages = build.Stages.ToArray() }); build.OnStack.Remove(id); return occurrence; case Type05NodeKind.Delay: delay += type05RawNode.Min; ranged |= type05RawNode.Min != type05RawNode.Max; break; case Type05NodeKind.Enveloper: if (ranged) { throw new Type05CueDataException($"cue '{build.Raw.Name}' node {id}: an Enveloper below a Delay with DelayMin != DelayMax has no fixed start."); } build.Stages.Add(new EnvelopeStage { Start = (float)delay, Volume = type05RawNode.VolumeCurve, Pitch = type05RawNode.PitchCurve }); break; case Type05NodeKind.Random: occurrence.RandomIndex = build.RandomIndexById[id]; break; } for (int i = 0; i < type05RawNode.Children.Length; i++) { if (type05RawNode.Children[i] >= 0) { bool num = type05RawNode.Kind == Type05NodeKind.DistanceCrossFade; if (num) { build.Filters.Add(type05RawNode.Fades[i]); } occurrence.Children[i] = Expand(build, type05RawNode.Children[i], depth + 1, delay, ranged); if (num) { build.Filters.RemoveAt(build.Filters.Count - 1); } int maxLeaves = occurrence.Children[i].MaxLeaves; occurrence.MaxLeaves = ((type05RawNode.Kind == Type05NodeKind.Random) ? Math.Max(occurrence.MaxLeaves, maxLeaves) : (occurrence.MaxLeaves + maxLeaves)); } } if (type05RawNode.Kind == Type05NodeKind.Enveloper) { build.Stages.RemoveAt(build.Stages.Count - 1); } build.OnStack.Remove(id); return occurrence; } private ushort RegisterFile(Type05RawNode node) { int num = Math.Max(node.File.LastIndexOf('/'), node.File.LastIndexOf('\\')); string text = node.File.Substring(num + 1); if (_fileIndex.TryGetValue(text, out var value)) { return (ushort)value; } if (_fileNames.Count > 65535) { throw new Type05CueDataException($"the cues name more than {ushort.MaxValue} sound files."); } int num2 = text.LastIndexOf('.'); string text2 = ((num2 > 0) ? text.Substring(0, num2) : text); _fileIndex.Add(text, _fileNames.Count); _fileNames.Add(text2); _fileAssets.Add("Assets/Y4NGZ/Type05/Source/Audio/" + text); _fileDurations.Add(node.Duration); _fileVictimVoice.Add(Type05AudioRules.VictimVoice(text2)); return (ushort)(_fileNames.Count - 1); } private Type05ClipSoundEvent[] BuildEvents(string clip, List<Type05RawSoundEvent> sounds) { if (sounds.Count == 0) { return NoEvents; } Type05ClipSoundEvent[] array = new Type05ClipSoundEvent[sounds.Count]; for (int i = 0; i < array.Length; i++) { Type05RawSoundEvent type05RawSoundEvent = sounds[i]; if (!_cueIndex.TryGetValue(type05RawSoundEvent.Cue, out var value)) { throw new Type05CueDataException("events table clip '" + clip + "': unknown cue '" + type05RawSoundEvent.Cue + "'."); } Type05ClipSoundEvent type05ClipSoundEvent = new Type05ClipSoundEvent(type05RawSoundEvent.Time, value, type05RawSoundEvent.Volume, type05RawSoundEvent.Pitch, type05RawSoundEvent.Side); int num = i; while (num > 0 && array[num - 1].Time > type05ClipSoundEvent.Time) { array[num] = array[num - 1]; num--; } array[num] = type05ClipSoundEvent; } return array; } private static uint Fnv1a(string text, uint hash) { for (int i = 0; i < text.Length; i++) { hash = (hash ^ (byte)text[i]) * 16777619; hash = (hash ^ (byte)((int)text[i] >> 8)) * 16777619; } return hash; } } internal sealed class Type05CueHost { private readonly Type05CueCatalogue _catalogue; private readonly Random _random; private readonly bool[][][] _used; private readonly double[] _nextAllowed; private readonly int[] _picks; private ulong _eventId; public Type05CueHost(Type05CueCatalogue catalogue, Random random) { _catalogue = catalogue; _random = random; _used = new bool[catalogue.CueCount][][]; _nextAllowed = new double[catalogue.CueCount]; int num = 0; for (int i = 0; i < _used.Length; i++) { int num2 = catalogue.RandomCount(i); num = Math.Max(num, num2); _used[i] = new bool[num2][]; for (int j = 0; j < num2; j++) { _used[i][j] = new bool[catalogue.RandomChildCount(i, j)]; } } _picks = new int[num]; Reset(); } public bool TryResolve(int cue, double now, List<Type05CueLeafChoice> leaves, out ushort seed) { leaves.Clear(); seed = 0; double num = _catalogue.GapSeconds(cue); if (num > 0.0) { if (now < _nextAllowed[cue]) { return false; } _nextAllowed[cue] = now + num; } int num2 = _catalogue.RandomCount(cue); for (int i = 0; i < num2; i++) { _picks[i] = Pick(cue, i); } seed = (ushort)_random.Next(1, 65536); _catalogue.Decode(cue, _picks, seed, leaves); int num3 = 0; for (int j = 0; j < leaves.Count; j++) { if (!_catalogue.VictimVoice(leaves[j].File)) { leaves[num3++] = leaves[j]; } } leaves.RemoveRange(num3, leaves.Count - num3); return true; } public ulong NextEventId() { return ++_eventId; } public void Reset() { for (int i = 0; i < _used.Length; i++) { bool[][] array = _used[i]; foreach (bool[] array2 in array) { Array.Clear(array2, 0, array2.Length); } } for (int k = 0; k < _nextAllowed.Length; k++) { _nextAllowed[k] = double.NegativeInfinity; } _eventId = 0uL; } private int Pick(int cue, int node) { bool[] array = _used[cue][node]; double num = Remaining(cue, node, array); if (num <= 0.0) { Array.Clear(array, 0, array.Length); num = Remaining(cue, node, array); if (num <= 0.0) { return -1; } } double num2 = _random.NextDouble() * num; int num3 = -1; double num4 = 0.0; for (int i = 0; i < array.Length; i++) { double num5 = (array[i] ? 0.0 : _catalogue.RandomWeight(cue, node, i)); if (!(num5 <= 0.0)) { num3 = i; num4 += num5; if (num4 >= num2) { break; } } } array[num3] = true; return num3; } private double Remaining(int cue, int node, bool[] used) { double num = 0.0; for (int i = 0; i < used.Length; i++) { if (!used[i]) { num += _catalogue.RandomWeight(cue, node, i); } } return num; } } internal enum Type05LeafState : byte { Free, Pending, Playing } internal struct Type05LeafRecord { public ulong EventId; public int Cue; public Type05CueGroup Group; public ushort Path; public ushort File; public double CueStart; public double Due; public float Volume; public float Pitch; public float CallerVolume; public float CallerPitch; public Type05LeafState State; public int Source; } internal sealed class Type05CueSchedule { private readonly Type05CueCatalogue _catalogue; private Type05LeafRecord[] _records; public ulong LastEventId { get; private set; } public int Capacity => _records.Length; public Type05CueSchedule(Type05CueCatalogue catalogue, int initialCapacity) { _catalogue = catalogue; _records = new Type05LeafRecord[Math.Max(1, initialCapacity)]; } public ref readonly Type05LeafRecord Record(int index) { return ref _records[index]; } public bool Accept(ulong eventId, int cue, double cueStart, float callerVolume, float callerPitch, Type05CueGroup group, Type05CueLeafChoice[] leaves, int count, List<int> stopSources, out string reject) { reject = null; if (eventId <= LastEventId) { reject = $"event id {eventId} is not above the last accepted {LastEventId}"; return false; } if (cue < 0 || cue >= _catalogue.CueCount) { reject = $"cue {cue} does not exist"; return false; } if (leaves == null || count < 0 || count > leaves.Length || count > _catalogue.MaxLeaves(cue)) { reject = $"{count} leaves do not fit cue '{_catalogue.CueName(cue)}'"; return false; } if (!IsFinite(cueStart) || !IsFinite(callerVolume) || !IsFinite(callerPitch)) { reject = "the cue start, volume or pitch is not a finite number"; return false; } for (int i = 0; i < count; i++) { Type05CueLeafChoice leaf = leaves[i]; if (!_catalogue.IsLeafOf(cue, in leaf)) { reject = $"leaf {i} (path {leaf.Path}, file {leaf.File}) is not a leaf of cue '{_catalogue.CueName(cue)}'"; return false; } if (!IsFinite(leaf.Delay) || leaf.Delay < 0f || !IsFinite(leaf.Volume) || !IsFinite(leaf.Pitch)) { reject = $"leaf {i} of cue '{_catalogue.CueName(cue)}' has a delay, volume or pitch that is not valid"; return false; } } LastEventId = eventId; FreeGroup(eventId, group, stopSources, out var _); int j = 0; for (int k = 0; k < count; k++) { for (; j < _records.Length && _records[j].State != Type05LeafState.Free; j++) { } if (j == _records.Length) { Array.Resize(ref _records, _records.Length * 2); } _records[j] = new Type05LeafRecord { EventId = eventId, Cue = cue, Group = group, Path = leaves[k].Path, File = leaves[k].File, CueStart = cueStart, Due = cueStart + (double)leaves[k].Delay, Volume = leaves[k].Volume, Pitch = leaves[k].Pitch, CallerVolume = callerVolume, CallerPitch = callerPitch, State = Type05LeafState.Pending, Source = -1 }; } return true; } public bool StopGroup(ulong eventId, Type05CueGroup group, List<int> stopSources, out int stopped) { stopped = 0; if (eventId <= LastEventId) { return false; } LastEventId = eventId; FreeGroup(eventId, group, stopSources, out stopped); return true; } public void Due(double now, List<int> starts, out int dropped) { dropped = 0; for (int i = 0; i < _records.Length; i++) { if (_records[i].State == Type05LeafState.Pending && !(now < _records[i].Due)) { if (FilePosition(i, now) >= (double)_catalogue.FileDuration(_records[i].File)) { _records[i].State = Type05LeafState.Free; dropped++; } else { starts.Add(i); } } } } public float Seek(int index, double now) { double num = FilePosition(index, now); if (!(num > 0.0) || !(num < (double)_catalogue.FileDuration(_records[index].File))) { return 0f; } return (float)num; } public void MarkPlaying(int index, int source) { _records[index].State = Type05LeafState.Playing; _records[index].Source = source; } public void Release(int index) { _records[index].State = Type05LeafState.Free; _records[index].Source = -1; } public void Reset(List<int> stopSources, out int cancelled) { cancelled = 0; for (int i = 0; i < _records.Length; i++) { if (_records[i].State == Type05LeafState.Playing) { stopSources.Add(_records[i].Source); } else if (_records[i].State == Type05LeafState.Pending) { cancelled++; } _records[i].State = Type05LeafState.Free; _records[i].Source = -1; } LastEventId = 0uL; } private void FreeGroup(ulong eventId, Type05CueGroup group, List<int> stopSources, out int freed) { freed = 0; if (group == Type05CueGroup.None) { return; } for (int i = 0; i < _records.Length; i++) { if (_records[i].State != Type05LeafState.Free && _records[i].Group == group && _records[i].EventId < eventId) { if (_records[i].State == Type05LeafState.Playing) { stopSources.Add(_records[i].Source); } _records[i].State = Type05LeafState.Free; _records[i].Source = -1; freed++; } } } private double FilePosition(int index, double now) { return (now - _records[index].Due) * (double)Math.Max(0.1f, _records[index].Pitch * _records[index].CallerPitch); } private static bool IsFinite(double value) { if (!double.IsNaN(value)) { return !double.IsInfinity(value); } return false; } } internal static class Type05BloodAssets { private sealed class Composite { public Texture BaseMap; public Type05BloodPart Part; public int Level; public RenderTexture Target; public int References; } private const string PrintFramePrefix = "Assets/Y4NGZ/Type05/Source/Blood/mechanical_blood_footprint_"; private const string PrintMaterialPath = "Assets/Y4NGZ/Type05/Blood/Type05_BloodFootprint.mat"; private const string DropMaterialPath = "Assets/Y4NGZ/Type05/Blood/Type05_BloodDrop.mat"; private const string BlitShaderName = "UI/Default"; private const float ColorMaskRgb = 14f; private const float LiveCheckSeconds = 1f; private const int PartCount = 6; private static readonly int ColorId = Shader.PropertyToID("_Color"); private static readonly int ColorMaskId = Shader.PropertyToID("_ColorMask"); private static readonly int TextureSampleAddId = Shader.PropertyToID("_TextureSampleAdd"); private static readonly int UnlitColorMapId = Shader.PropertyToID("_UnlitColorMap"); private static readonly int UnlitColorId = Shader.PropertyToID("_UnlitColor"); private static readonly int BaseColorMapId = Shader.PropertyToID("_BaseColorMap"); private static readonly int BaseColorId = Shader.PropertyToID("_BaseColor"); private static readonly Texture2D[] Sheets = (Texture2D[])(object)new Texture2D[18]; private static readonly Texture2D[] PrintFrames = (Texture2D[])(object)new Texture2D[4]; private static readonly List<Composite> Composites = new List<Composite>(18); private static readonly Action<ScriptableRenderContext, List<Camera>> LiveCheck = CheckLive; private static Shader _blitShader; private static bool _blitSearched; private static Material _blit; private static int _targets; private static float _liveAt; internal static bool PrintsReady { get; private set; } internal static bool DripReady { get; private set; } internal static Material PrintMaterial { get; private set; } internal static Material DropMaterial { get; private set; } internal static int PrintMapId { get; private set; } = BaseColorMapId; internal static int PrintColorId { get; private set; } = BaseColorId; internal static Color PrintTint { get; private set; } = Color.white; internal static int CompositeCount => Composites.Count; internal static void Load(AssetBundle bundle) { //IL_01b9: Unknown result type (might be due to invalid IL or missing references) StringBuilder stringBuilder = new StringBuilder(); int num = 0; for (int i = 1; i <= 6; i++) { for (int j = 1; j <= 3; j++) { string text = Type05BloodRules.SheetPath((Type05BloodPart)i, j); Texture2D val = bundle.LoadAsset<Texture2D>(text); Sheets[SheetIndex((Type05BloodPart)i, j)] = val; if ((Object)(object)val == (Object)null) { stringBuilder.Append((num++ == 0) ? string.Empty : ", ").Append(text); } } } if (num > 0) { Plugin.Log.LogWarning((object)$"[Type05] blood coat: {num} of {Sheets.Length} sheets missing from the bundle, those coats stay off: {stringBuilder}"); } stringBuilder.Clear(); for (int k = 0; k < PrintFrames.Length; k++) { string text2 = "Assets/Y4NGZ/Type05/Source/Blood/mechanical_blood_footprint_" + k + ".png"; PrintFrames[k] = bundle.LoadAsset<Texture2D>(text2); if ((Object)(object)PrintFrames[k] == (Object)null) { stringBuilder.Append((stringBuilder.Length == 0) ? string.Empty : ", ").Append(text2); } } PrintMaterial = bundle.LoadAsset<Material>("Assets/Y4NGZ/Type05/Blood/Type05_BloodFootprint.mat"); if ((Object)(object)PrintMaterial == (Object)null) { stringBuilder.Append((stringBuilder.Length == 0) ? string.Empty : ", ").Append("Assets/Y4NGZ/Type05/Blood/Type05_BloodFootprint.mat"); } PrintsReady = stringBuilder.Length == 0; if (PrintsReady) { bool num2 = PrintMaterial.HasProperty(UnlitColorMapId); PrintMapId = (num2 ? UnlitColorMapId : BaseColorMapId); PrintColorId = (num2 ? UnlitColorId : BaseColorId); if (PrintMaterial.HasProperty(PrintColorId)) { PrintTint = PrintMaterial.GetColor(PrintColorId); } } else { Plugin.Log.LogInfo((object)$"[Type05] blood prints off: {stringBuilder}"); } DropMaterial = bundle.LoadAsset<Material>("Assets/Y4NGZ/Type05/Blood/Type05_BloodDrop.mat"); DripReady = (Object)(object)DropMaterial != (Object)null; if (!DripReady) { Plugin.Log.LogInfo((object)"[Type05] blood drip off: Assets/Y4NGZ/Type05/Blood/Type05_BloodDrop.mat"); } Plugin.Log.LogInfo((object)string.Format("[Type05] blood assets: {0} of {1} sheets, prints {2}, drip {3}", Sheets.Length - num, Sheets.Length, PrintsReady ? "on" : "off", DripReady ? "on" : "off")); } internal static Texture2D Sheet(Type05BloodPart part, int level) { if ((int)part <= 0 || (int)part > 6 || level < 1 || level > 3) { return null; } return Sheets[SheetIndex(part, level)]; } internal static Texture2D PrintFrame(int frame) { return PrintFrames[frame]; } internal static RenderTexture Acquire(Texture baseMap, Type05BloodPart part, int level) { Texture2D val = Sheet(part, level); if ((Object)(object)baseMap == (Object)null || (Object)(object)val == (Object)null) { return null; } for (int i = 0; i < Composites.Count; i++) { Composite composite = Composites[i]; if (composite.BaseMap == baseMap && composite.Part == part && composite.Level == level) { composite.References++; return composite.Target; } } RenderTexture val2 = CreateTarget(baseMap, $"Type05BloodCoat_{((Object)baseMap).name}_{part}_{level}"); if ((Object)(object)val2 == (Object)null) { return null; } Compose(val2, baseMap, null, 0f, (Texture)(object)val, 1f); Composites.Add(new Composite { BaseMap = baseMap, Part = part, Level = level, Target = val2, References = 1 }); return val2; } internal static void Release(RenderTexture target) { for (int i = 0; i < Composites.Count; i++) { Composite composite = Composites[i]; if (composite.Target == target) { if (--composite.References <= 0) { int index = Composites.Count - 1; Composites[i] = Composites[index]; Composites.RemoveAt(index); DestroyTarget(target); } break; } } } internal static RenderTexture CreateTarget(Texture baseMap, string name) { //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_0034: Unknown result type (might be due to invalid IL or missing references) //IL_003e: 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_004a: Unknown result type (might be due to invalid IL or missing references) //IL_004c: Unknown result type (might be due to invalid IL or missing references) //IL_0056: Unknown result type (might be due to invalid IL or missing references) //IL_0062: Unknown result type (might be due to invalid IL or missing references) //IL_0084: Expected O, but got Unknown if (!EnsureBlit()) { return null; } RenderTexture val = new RenderTexture(baseMap.width, baseMap.height, 0, (RenderTextureFormat)0, (RenderTextureReadWrite)2) { name = name, useMipMap = true, autoGenerateMips = true, wrapModeU = baseMap.wrapModeU, wrapModeV = baseMap.wrapModeV, filterMode = baseMap.filterMode, anisoLevel = baseMap.anisoLevel }; val.Create(); if (++_targets == 1) { RenderPipelineManager.beginContextRendering += LiveCheck; } return val; } internal static void DestroyTarget(RenderTexture target) { if ((Object)(object)target != (Object)null) { target.Release(); Object.Destroy((Object)(object)target); } if (--_targets <= 0) { _targets = 0; RenderPipelineManager.beginContextRendering -= LiveCheck; if ((Object)(object)_blit != (Object)null) { Object.Destroy((Object)(object)_blit); } _blit = null; } } internal static void Compose(RenderTexture target, Texture baseMap, Texture under, float underAlpha, Texture over, float overAlpha) { RenderTexture active = RenderTexture.active; bool sRGBWrite = GL.sRGBWrite; GL.sRGBWrite = true; try { Graphics.Blit(baseMap, target); Overlay(target, under, underAlpha); Overlay(target, over, overAlpha); } finally { GL.sRGBWrite = sRGBWrite; RenderTexture.active = active; } } private static void CheckLive(ScriptableRenderContext context, List<Camera> cameras) { float unscaledTime = Time.unscaledTime; if (unscaledTime < _liveAt) { return; } _liveAt = unscaledTime + 1f; for (int i = 0; i < Composites.Count; i++) { Composite composite = Composites[i]; if (!composite.Target.IsCreated() && !((Object)(object)composite.BaseMap == (Object)null)) { composite.Target.Create(); Compose(composite.Target, composite.BaseMap, null, 0f, (Texture)(object)Sheet(composite.Part, composite.Level), 1f); } } } private static int SheetIndex(Type05BloodPart part, int level) { return (int)(part - 1) * 3 + level - 1; } private static void Overlay(RenderTexture target, Texture sheet, float alpha) { //IL_0039: Unknown result type (might be due to invalid IL or missing references) if (!((Object)(object)sheet == (Object)null) && !(alpha <= 0f) && !((Object)(object)_blit == (Object)null)) { _blit.SetColor(ColorId, new Color(1f, 1f, 1f, alpha)); Graphics.Blit(sheet, target, _blit); } } private static bool EnsureBlit() { //IL_005b: Unknown result type (might be due to invalid IL or missing references) //IL_0060: Unknown result type (might be due to invalid IL or missing references) //IL_0070: Expected O, but got Unknown //IL_008e: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)_blit != (Object)null) { return true; } if (!_blitSearched) { _blitSearched = true; _blitShader = Shader.Find("UI/Default"); if ((Object)(object)_blitShader == (Object)null) { Plugin.Log.LogWarning((object)"[Type05] blood coat off: no UI/Default shader to draw the composites with"); } } if ((Object)(object)_blitShader == (Object)null) { return false; } _blit = new Material(_blitShader) { name = "Type05BloodBlit" }; _blit.SetFloat(ColorMaskId, 14f); _blit.SetVector(TextureSampleAddId, Vector4.zero); return true; } } internal sealed class Type05BloodCoat { private struct Slot { public Renderer Renderer; public int Index; public Type05BloodPart Part; public Texture BaseMap; public int Group; public RenderTexture Composite; public bool Coated; } private static readonly int BaseColorMapId = Shader.PropertyToID("_BaseColorMap"); private static MaterialPropertyBlock _scratch; private readonly Slot[] _slots; private readonly Texture[] _groupMaps; private readonly Type05BloodPart[] _groupParts; private readonly RenderTexture[] _fadeTargets; private readonly int _plateSlot = -1; private double _fadeStart; private bool _applied; public byte Shown { get; private set; } public bool Fading { get; private set; } public Type05BloodCoat(Renderer[] renderers) { List<Slot> list = new List<Slot>(); List<Texture> list2 = new List<Texture>(); List<Type05BloodPart> list3 = new List<Type05BloodPart>(); foreach (Renderer val in renderers) { if ((Object)(object)val == (Object)null) { continue; } bool flag = ((Object)val).name == "Type05Plate"; Material[] sharedMaterials = val.sharedMaterials; for (int j = 0; j < sharedMaterials.Length; j++) { Material val2 = sharedMaterials[j]; Type05BloodPart type05BloodPart = (((Object)(object)val2 != (Object)null) ? Type05BloodRules.PartFor(((Object)val2).name) : Type05BloodPart.None); Texture val3 = ((type05BloodPart != Type05BloodPart.None && val2.HasProperty(BaseColorMapId)) ? val2.GetTexture(BaseColorMapId) : null); if (!((Object)(object)val3 == (Object)null)) { int k; for (k = 0; k < list2.Count && (list2[k] != val3 || list3[k] != type05BloodPart); k++) { } if (k == list2.Count) { list2.Add(val3); list3.Add(type05BloodPart); } if (flag && j == 0) { _plateSlot = list.Count; } list.Add(new Slot { Renderer = val, Index = j, Part = type05BloodPart, BaseMap = val3, Group = k }); } } } _slots = list.ToArray(); _groupMaps = list2.ToArray(); _groupParts = list3.ToArray(); _fadeTargets = (RenderTexture[])(object)new RenderTexture[_groupMaps.Length]; if (_slots.Length == 0) { Plugin.Log.LogWarning((object)$"[Type05] blood coat: none of {renderers.Length} renderers shows a blood material; no coat"); } } internal static void SetBaseMap(Renderer renderer, int index, Texture map) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Expected O, but got Unknown if (_scratch == null) { _scratch = new MaterialPropertyBlock(); } renderer.GetPropertyBlock(_scratch, index); _scratch.SetTexture(BaseColorMapId, map); renderer.SetPropertyBlock(_scratch, index); } public void Show(byte level) { if (!_applied && level == 0) { _applied = true; Shown = 0; return; } _applied = true; for (int i = 0; i < _slots.Length; i++) { ref Slot reference = ref _slots[i]; RenderTexture val = ((level > 0) ? Type05BloodAssets.Acquire(reference.BaseMap, reference.Part, level) : null); RenderTexture composite = reference.Composite; reference.Composite = val; if ((Object)(object)val != (Object)null) { Write(ref reference, (Texture)(object)val); } else if (reference.Coated) { Write(ref reference, reference.BaseMap); } if (composite != null) { Type05BloodAssets.Release(composite); } } DropFade(); Shown = level; } public void FadeTo(byte level, double start) { if (Fading) { Show(Shown); } if (level == 0 || _slots.Length == 0) { Show(level); return; } for (int i = 0; i < _fadeTargets.Length; i++) { _fadeTargets[i] = Type05BloodAssets.CreateTarget(_groupMaps[i], $"Type05BloodFade_{_groupParts[i]}"); if ((Object)(object)_fadeTargets[i] == (Object)null) { DropFade(); Show(level); return; } } _applied = true; Fading = true; Shown = level; _fadeStart = start; ComposeFade(0f); for (int j = 0; j < _slots.Length; j++) { ref Slot reference = ref _slots[j]; RenderTexture composite = reference.Composite; reference.Composite = null; Write(ref reference, (Texture)(object)_fadeTargets[reference.Group]); if (composite != null) { Type05BloodAssets.Release(composite); } } } public void Tick(double now) { if (Fading) { float num = Type05BloodRules.CoatFade(_fadeStart, now); if (num >= 1f) { Show(Shown); } else { ComposeFade(num); } } } public RenderTexture AcquirePlate(byte level, out Texture baseMap) { baseMap = ((_plateSlot >= 0) ? _slots[_plateSlot].BaseMap : null); if (level <= 0 || !((Object)(object)baseMap != (Object)null)) { return null; } return Type05BloodAssets.Acquire(baseMap, _slots[_plateSlot].Part, level); } public void Release() { for (int i = 0; i < _slots.Length; i++) { ref Slot reference = ref _slots[i]; if (reference.Coated) { Write(ref reference, reference.BaseMap); } if (reference.Composite != null) { Type05BloodAssets.Release(reference.Composite); } reference.Composite = null; } DropFade(); Shown = 0; _applied = false; } private void ComposeFade(float fade) { for (int i = 0; i < _fadeTargets.Length; i++) { Type05BloodPart part = _groupParts[i]; Type05BloodAssets.Compose(_fadeTargets[i], _groupMaps[i], (Texture)(object)Type05BloodAssets.Sheet(part, Shown - 1), 1f - fade, (Texture)(object)Type05BloodAssets.Sheet(part, Shown), fade); } } private void DropFade() { for (int i = 0; i < _fadeTargets.Length; i++) { if (_fadeTargets[i] != null) { Type05BloodAssets.DestroyTarget(_fadeTargets[i]); _fadeTargets[i] = null; } } Fading = false; } private static void Write(ref Slot slot, Texture map) { slot.Coated = map != slot.BaseMap; if ((Object)(object)slot.Renderer != (Object)null) { SetBaseMap(slot.Renderer, slot.Index, map); } } } internal sealed class Type05BloodDrip { private const int MaxDrops = 64; private static readonly Color32 DropColor = new Color32((byte)120, (byte)7, (byte)5, (byte)245); private readonly ulong _robot; private GameObject _object; private ParticleSystem _system; private EmitParams _emit; private double _next; private bool _live; private bool _second; public int ActiveDrops { get { if (!((Object)(object)_system != (Object)null)) { return 0; } return _system.particleCount; } } public Type05BloodDrip(ulong robot) { //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Expected O, but got Unknown //IL_0040: Unknown result type (might be due to invalid IL or missing references) //IL_0045: Unknown result type (might be due to invalid IL or missing references) //IL_006e: Unknown result type (might be due to invalid IL or missing references) //IL_0078: Unknown result type (might be due to invalid IL or missing references) //IL_009c: Unknown result type (might be due to invalid IL or missing references) //IL_00ac: Unknown result type (might be due to invalid IL or missing references) //IL_00b1: Unknown result type (might be due to invalid IL or missing references) //IL_00c0: Unknown result type (might be due to invalid IL or missing references) //IL_00c5: Unknown result type (might be due to invalid IL or missing references) //IL_00ee: Unknown result type (might be due to invalid IL or missing references) //IL_00fe: Unknown result type (might be due to invalid IL or missing references) //IL_0103: 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_013d: Unknown result type (might be due to invalid IL or missing references) //IL_0160: Unknown result type (might be due to invalid IL or missing references) _robot = robot; _object = new GameObject("Type05BloodDrops"); _object.SetActive(false); _system = _object.AddComponent<ParticleSystem>(); MainModule main = _system.main; ((MainModule)(ref main)).playOnAwake = false; ((MainModule)(ref main)).loop = false; ((MainModule)(ref main)).simulationSpace = (ParticleSystemSimulationSpace)1; ((MainModule)(ref main)).maxParticles = 64; ((MainModule)(ref main)).startLifetime = MinMaxCurve.op_Implicit(1.45f); float num = 0f - Physics.gravity.y; ((MainModule)(ref main)).gravityModifier = MinMaxCurve.op_Implicit((num > 0f) ? (15.24f / num) : 0f); EmissionModule emission = _system.emission; ((EmissionModule)(ref emission)).enabled = false; SizeOverLifetimeModule sizeOverLifetime = _system.sizeOverLifetime; ((SizeOverLifetimeModule)(ref sizeOverLifetime)).enabled = true; ((SizeOverLifetimeModule)(ref sizeOverLifetime)).size = new MinMaxCurve(1f, AnimationCurve.Linear(0f, 1f, 1f, 28f / 55f)); CollisionModule collision = _system.collision; ((CollisionModule)(ref collision)).enabled = true; ((CollisionModule)(ref collision)).type = (ParticleSystemCollisionType)1; ((CollisionModule)(ref collision)).mode = (ParticleSystemCollisionMode)0; ((CollisionModule)(ref collision)).quality = (ParticleSystemCollisionQuality)2; ((CollisionModule)(ref collision)).lifetimeLoss = MinMaxCurve.op_Implicit(1f); ((CollisionModule)(ref collision)).bounce = MinMaxCurve.op_Implicit(0f); if ((Object)(object)StartOfRound.Instance != (Object)null) { ((CollisionModule)(ref collision)).collidesWith = LayerMask.op_Implicit(StartOfRound.Instance.collidersAndRoomMaskAndDefault); } ParticleSystemRenderer component = _object.GetComponent<ParticleSystemRenderer>(); component.renderMode = (ParticleSystemRenderMode)0; ((Renderer)component).sharedMaterial = Type05BloodAssets.DropMaterial; ((Renderer)component).shadowCastingMode = (ShadowCastingMode)0; ((Renderer)component).receiveShadows = false; _object.SetActive(true); } public void Tick(double now, double killAt, bool awake, Vector3 velocity, Transform a, Transform b) { //IL_007e: Unknown result type (might be due to invalid IL or missing references) //IL_008e: Unknown result type (might be due to invalid IL or missing references) //IL_0095: Unknown result type (might be due to invalid IL or missing references) //IL_009a: Unknown result type (might be due to invalid IL or missing references) //IL_00a4: Unknown result type (might be due to invalid IL or missing references) //IL_00a9: Unknown result type (might be due to invalid IL or missing references) //IL_00c9: Unknown result type (might be due to invalid IL or missing references) //IL_0102: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)_system == (Object)null) { return; } bool flag = Type05BloodRules.DripLive(killAt, now, awake); if (flag != _live) { _live = flag; _next = now; Plugin.Log.LogInfo((object)string.Format("[Type05] blood-drip robot={0} {1}", _robot, flag ? "start" : "stop")); } if (flag && !(now < _next)) { ((EmitParams)(ref _emit)).position = (_second ? b : a).position; ((EmitParams)(ref _emit)).velocity = velocity * 0.65f + Vector3.down * 0.4064f; ((EmitParams)(ref _emit)).startSize = 0.01397f; ((EmitParams)(ref _emit)).startColor = DropColor; _second = !_second; if (!_system.isPlaying) { _system.Play(false); } _system.Emit(_emit, 1); _next = now + (double)Type05BloodRules.DripInterval(now - killAt); } } public void Release() { if ((Object)(object)_object != (Object)null) { Object.Destroy((Object)(object)_object); } _object = null; _system = null; } } internal enum Type05BloodPart : byte { None, Armour, Head, GripHand, RightLegArmour, Innards, RightLegInnards } internal static class Type05BloodRules { private const string SheetFolder = "Assets/Y4NGZ/Type05/Source/Blood/"; private static readonly string[] PartNames = new string[7] { null, "armour", "head", "griphand", "rightlegarmour", "innards", "rightleginnards" }; private static readonly string[] Sheets = BuildSheets(); public static bool TryCredit(byte level, int serial, int lastCreditedSerial, out byte next) { if (serial <= lastCreditedSerial) { next = level; return false; } next = (byte)Math.Min(level + 1, 3); return true; } public static Type05State WithCredit(Type05State state, byte level, double now) { state.BloodLevel = level; state.BloodKillAt = now; return state; } public static Type05State WithBody(Type05State state, byte level) { state.BloodLevel = level; state.BloodKillAt = 0.0; return state; } public static bool IsNewCredit(in Type05State previous, in Type05State current, bool spawn) { if (!spawn && previous.BodyIndex == current.BodyIndex && current.BloodKillAt > 0.0) { return !current.BloodKillAt.Equals(previous.BloodKillAt); } return false; } public static bool CoatRose(in Type05State previous, in Type05State current, bool spawn) { if (IsNewCredit(in previous, in current, spawn)) { return current.BloodLevel > previous.BloodLevel; } return false; } public static bool IsAwakePhase(Type05Phase phase) { if (phase != Type05Phase.Dormant && phase != Type05Phase.Shutdown && phase != Type05Phase.Dying) { return phase != Type05Phase.Dead; } return false; } public static bool DripLive(double killAt, double now, bool awake) { double num = now - killAt; if (awake && killAt > 0.0 && num >= 0.0) { return num < 12.0; } return false; } public static float DripInterval(double age) { float num = (float)Math.Clamp(age / 12.0, 0.0, 1.0); return 0.14f * (1f - num) + 0.58f * num; } public static float CoatFade(double start, double now) { return (float)Math.Clamp((now - start) / 2.0, 0.0, 1.0); } public static bool FloorAccepts(bool hit, float normalY, bool water) { if (hit && normalY >= 0.65f) { return !water; } return false; } public static bool TooClose(bool hasLast, Type05Point last, float lastAge, Type05Point next) { if (!hasLast || lastAge >= 45f) { return false; } float num = next.X - last.X; float num2 = next.Y - last.Y; float num3 = next.Z - last.Z; return num * num + num2 * num2 + num3 * num3 < 0.02322576f; } public static int NextFrame(int last, int roll) { if (roll < last || last < 0) { return roll; } return roll + 1; } public static float PrintAlpha(int budgetBefore, float pressure, float age) { if (age >= 45f) { return 0f; } float num = MathF.Pow(Math.Clamp((float)budgetBefore / 8f, 0f, 1f), 0.7f); float num2 = Math.Clamp((45f - age) / 10f, 0f, 1f); return num * pressure * num2; } public static int NextSlot(int slot) { return (slot + 1) % 32; } public static Type05BloodPart PartFor(string materialName) { if (materialName == null) { return Type05BloodPart.None; } if (Has(materialName, "Head_Default")) { return Type05BloodPart.Head; } if (Has(materialName, "RightForearm_Default")) { return Type05BloodPart.Armour; } if (Has(materialName, "GripHand_Default")) { return Type05BloodPart.GripHand; } if (Has(materialName, "RightLegArmour_Default")) { return Type05BloodPart.RightLegArmour; } if (Has(materialName, "RightLegInnards_Default")) { return Type05BloodPart.RightLegInnards; } if (Has(materialName, "Innards_Default")) { return Type05BloodPart.Innards; } if (!Has(materialName, "Armour_Default")) { return Type05BloodPart.None; } return Type05BloodPart.Armour; } public static string SheetPath(Type05BloodPart part, int level) { if (part == Type05BloodPart.None || (int)part >= PartNames.Length || level < 1 || level > 3) { return null; } return Sheets[(int)(part - 1) * 3 + level - 1]; } private static bool Has(string name, string part) { return name.IndexOf(part, StringComparison.Ordinal) >= 0; } private static string[] BuildSheets() { string[] array = new string[(PartNames.Length - 1) * 3]; for (int i = 1; i < PartNames.Length; i++) { for (int j = 1; j <= 3; j++) { array[(i - 1) * 3 + j - 1] = string.Format("{0}blood_{1}_{2}.png", "Assets/Y4NGZ/Type05/Source/Blood/", PartNames[i], j); } } return array; } } internal static class Type05BloodTuning { public const byte MaxLevel = 3; public const int PrintsPerKill = 8; public const double CoatFadeSeconds = 2.0; public const double DripSeconds = 12.0; public const float DripIntervalStart = 0.14f; public const float DripIntervalEnd = 0.58f; public const float PrintLifetime = 45f; public const float PrintFadeSeconds = 10f; public const float PrintSpacing = 0.1524f; public const float PrintWidth = 0.304292f; public const float PrintLift = 0.003048f; public const float FloorMinNormalY = 0.65f; public const int PrintPoolSize = 32; public const int PrintFrames = 4; public const float PrintStrengthExponent = 0.7f; public const float PressureMin = 0.75f; public const float PressureMax = 1f; public const float PrintFadeInterval = 0.125f; public const float FootForward = 0.0938276f; public const float FootLateral = 0.009652f; public const float ProbeAboveFoot = 0.254f; public const float ProbeAboveRoot = 0.508f; public const float ProbeBelowRoot = 0.6096f; public const float DropLifetime = 1.45f; public const float DropStartSize = 0.01397f; public const float DropEndSize = 0.007112f; public const float DropGravity = 15.24f; public const float DropFallSpeed = 0.4064f; public const float DropInheritVelocity = 0.65f; } internal sealed class Type05FootprintPool { private sealed class Mark { public Transform Transform; public MeshRenderer Renderer; public MaterialPropertyBlock Block; public float PlacedAt; public int BudgetBefore; public float Pressure; public float Alpha; public bool Live; } private readonly Mark[] _marks = new Mark[32]; private GameObject _container; private Mesh _mesh; private int _slot = 31; private float _nextFade; public int Active { get; private set; } public Type05FootprintPool() { //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Expected O, but got Unknown //IL_004d: Unknown result type (might be due to invalid IL or missing references) //IL_0053: Expected O, but got Unknown //IL_00c2: Unknown result type (might be due to invalid IL or missing references) //IL_00cc: Expected O, but got Unknown _container = new GameObject("Type05BloodFootprints"); _mesh = BuildQuad(); for (int i = 0; i < _marks.Length; i++) { GameObject val = new GameObject($"Footprint_{i:00}"); val.transform.SetParent(_container.transform, false); val.AddComponent<MeshFilter>().sharedMesh = _mesh; MeshRenderer val2 = val.AddComponent<MeshRenderer>(); ((Renderer)val2).sharedMaterial = Type05BloodAssets.PrintMaterial; ((Renderer)val2).shadowCastingMode = (ShadowCastingMode)0; ((Renderer)val2).receiveShadows = false; ((Renderer)val2).enabled = false; _marks[i] = new Mark { Transform = val.transform, Renderer = val2, Block = new MaterialPropertyBlock() }; } } public void Place(Vector3 point, Vector3 normal, Vector3 forward, int frame, int budgetBefore, float pressure, float now) { //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Unknown result type (might be due to invalid IL or missing references) //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_0056: Unknown result type (might be due to invalid IL or missing references) //IL_0057: Unknown result type (might be due to invalid IL or missing references) //IL_005d: Unknown result type (might be due to invalid IL or missing references) //IL_0062: Unknown result type (might be due to invalid IL or missing references) //IL_0067: Unknown result type (might be due to invalid IL or missing references) //IL_0068: Unknown result type (might be due to invalid IL or missing references) //IL_0069: Unknown result type (might be due to invalid IL or missing references) //IL_0044: Unknown result type (might be due to invalid IL or missing