using System;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Threading;
using Agents;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using BepInEx.Unity.IL2CPP;
using HarmonyLib;
using Il2CppInterop.Runtime.InteropTypes;
using Microsoft.CodeAnalysis;
using Player;
using SNetwork;
using UnityEngine;
[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")]
[assembly: AssemblyCompany("RFFPlus")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.10.0")]
[assembly: AssemblyInformationalVersion("1.0.10")]
[assembly: AssemblyProduct("RFFPlus")]
[assembly: AssemblyTitle("RFFPlus")]
[assembly: AssemblyVersion("1.0.10.0")]
namespace Microsoft.CodeAnalysis
{
[CompilerGenerated]
[Embedded]
internal sealed class EmbeddedAttribute : Attribute
{
}
}
namespace System.Runtime.CompilerServices
{
[CompilerGenerated]
[Embedded]
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
internal sealed class NullableAttribute : Attribute
{
public readonly byte[] NullableFlags;
public NullableAttribute(byte P_0)
{
NullableFlags = new byte[1] { P_0 };
}
public NullableAttribute(byte[] P_0)
{
NullableFlags = P_0;
}
}
[CompilerGenerated]
[Embedded]
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
internal sealed class NullableContextAttribute : Attribute
{
public readonly byte Flag;
public NullableContextAttribute(byte P_0)
{
Flag = P_0;
}
}
}
namespace RFFPlus
{
public enum DamagePoint
{
Limb,
Base,
Local,
Hp
}
public enum DamageAction
{
PassThrough,
Suppress,
Reflect,
ReflectSuppressed,
SuppressPacket
}
public enum PassReason
{
None,
ImmunityOff,
ImmunityAndReflectOff,
NotMaster,
AttackerNotPlayer,
ZeroOriginalDamage,
NoDamageComponent
}
public enum FeedbackMode
{
OriginalPath,
Suppressed
}
public readonly struct DamageConfigSnapshot
{
public readonly bool Immunity;
public readonly bool Reflect;
public readonly float FriendlyFireMultiplier;
public readonly float ReflectMultiplier;
public readonly bool ReflectToDeath;
public readonly bool ClientSelfSuppress;
public DamageConfigSnapshot(bool immunity, bool reflect, float friendlyFireMultiplier, float reflectMultiplier, bool reflectToDeath, bool clientSelfSuppress = true)
{
Immunity = immunity;
Reflect = reflect;
FriendlyFireMultiplier = friendlyFireMultiplier;
ReflectMultiplier = reflectMultiplier;
ReflectToDeath = reflectToDeath;
ClientSelfSuppress = clientSelfSuppress;
}
}
public readonly struct DamageInput
{
public readonly DamagePoint Point;
public readonly bool Immunity;
public readonly bool Reflect;
public readonly bool IsMaster;
public readonly float FriendlyFireMultiplier;
public readonly float ReflectMultiplier;
public readonly bool ReflectToDeath;
public readonly bool Sentry;
public readonly bool AttackerIsPlayer;
public readonly bool AttackerDamageKnown;
public readonly float OriginalDamage;
public readonly float AttackerHealth;
public readonly float AttackerHealthMax;
public readonly bool VictimKnown;
public readonly bool VictimDowned;
public readonly bool AttackerIsVictim;
public readonly bool ClientSelfSuppress;
public DamageInput(DamagePoint point, bool immunity, bool reflect, bool isMaster, float friendlyFireMultiplier, float reflectMultiplier, bool reflectToDeath, bool sentry, bool attackerIsPlayer, bool attackerDamageKnown, float originalDamage, float attackerHealth = 0f, float attackerHealthMax = 0f, bool victimKnown = false, bool victimDowned = false, bool attackerIsVictim = false, bool clientSelfSuppress = true)
{
Point = point;
Immunity = immunity;
Reflect = reflect;
IsMaster = isMaster;
FriendlyFireMultiplier = friendlyFireMultiplier;
ReflectMultiplier = reflectMultiplier;
ReflectToDeath = reflectToDeath;
Sentry = sentry;
AttackerIsPlayer = attackerIsPlayer;
AttackerDamageKnown = attackerDamageKnown;
OriginalDamage = originalDamage;
AttackerHealth = attackerHealth;
AttackerHealthMax = attackerHealthMax;
VictimKnown = victimKnown;
VictimDowned = victimDowned;
AttackerIsVictim = attackerIsVictim;
ClientSelfSuppress = clientSelfSuppress;
}
}
public readonly struct DamageDecision
{
public readonly DamageAction Action;
public readonly PassReason PassReason;
public readonly float HpMultiplier;
public readonly float VictimDamage;
public readonly bool ReflectAttacker;
public readonly float Reflected;
public readonly float NewAttackerHealth;
public readonly bool KillAttacker;
public readonly FeedbackMode Feedback;
public readonly bool SkipOriginal;
public readonly string Verdict;
public readonly string Mode;
public float? HpWrite
{
get
{
if (Action != DamageAction.PassThrough && Action != DamageAction.SuppressPacket)
{
return HpMultiplier;
}
return null;
}
}
public bool PacketSuppress => Action == DamageAction.SuppressPacket;
public float? PacketWrite => null;
internal DamageDecision(DamageAction action, PassReason passReason, float hpMultiplier, float victimDamage, bool reflectAttacker, float reflected, float newAttackerHealth, bool killAttacker, FeedbackMode feedback, bool skipOriginal, string verdict, string mode)
{
Action = action;
PassReason = passReason;
HpMultiplier = hpMultiplier;
VictimDamage = victimDamage;
ReflectAttacker = reflectAttacker;
Reflected = reflected;
NewAttackerHealth = newAttackerHealth;
KillAttacker = killAttacker;
Feedback = feedback;
SkipOriginal = skipOriginal;
Verdict = verdict;
Mode = mode;
}
}
public static class DamageCompose
{
public static DamageInput Limb(in DamageConfigSnapshot config, bool isMaster, bool sentryFire, bool sentryOwnerKnown, bool sourceIsPlayerAgent, float damage)
{
bool flag = sentryFire && sentryOwnerKnown;
bool attackerIsPlayer = flag || sourceIsPlayerAgent;
return new DamageInput(DamagePoint.Limb, config.Immunity, config.Reflect, isMaster, config.FriendlyFireMultiplier, config.ReflectMultiplier, config.ReflectToDeath, flag, attackerIsPlayer, attackerDamageKnown: true, damage, 0f, 0f, victimKnown: false, victimDowned: false, attackerIsVictim: false, config.ClientSelfSuppress);
}
public static DamageInput Receive(in DamageConfigSnapshot config, DamagePoint point, bool isMaster, bool sentryFire, bool sentryOwnerKnown, bool attackerIsPlayerAgent, bool attackerDamageKnown, float originalDamage, float attackerHealth, float attackerHealthMax, bool victimKnown, bool victimDowned, bool attackerIsVictim = false)
{
bool flag = sentryFire && sentryOwnerKnown;
bool attackerIsPlayer = flag || attackerIsPlayerAgent;
return new DamageInput(point, config.Immunity, config.Reflect, isMaster, config.FriendlyFireMultiplier, config.ReflectMultiplier, config.ReflectToDeath, flag, attackerIsPlayer, attackerDamageKnown, originalDamage, attackerHealth, attackerHealthMax, victimKnown, victimDowned, attackerIsVictim, config.ClientSelfSuppress);
}
}
public static class DamageResolver
{
public const string VerdictImmunityBlocked = "immunity-blocked";
public const string VerdictImmunityBlockedSentry = "immunity-blocked:sentry";
public const string VerdictReflectApplied = "reflect-applied";
public const string VerdictReflectSkipDowned = "reflect-skip:downed-victim";
public const string VerdictReflectSkipSelf = "reflect-skip:self-damage";
public const string VerdictPassImmunityOff = "passthrough:immunity-off";
public const string VerdictPassNotMaster = "skip:not-master";
public const string VerdictPassNotPlayer = "passthrough:not-player";
public const string VerdictPassZeroOriginal = "skip:zero-original";
public const string VerdictPassNoDamageComp = "skip:no-damage-comp";
public const string VerdictLocalSuppressPacket = "immunity-blocked:local-packet";
public const string VerdictClientApplyBlocked = "immunity-blocked:client-apply";
public const string VerdictPassClientSelfOff = "skip:client-self-off";
public const float FallbackFriendlyFireMultiplier = 1f;
public static float EffectiveFriendlyFireMultiplier(float configured)
{
if (float.IsNaN(configured) || float.IsInfinity(configured))
{
return 1f;
}
if (!(configured > 0f))
{
return 1f;
}
return configured;
}
public static bool NeedsMultiplierWarning(float configured)
{
if (float.IsNaN(configured))
{
return true;
}
return configured <= 0f;
}
public static float EffectiveReflectMultiplier(float configured)
{
if (float.IsNaN(configured) || float.IsInfinity(configured))
{
return 0f;
}
if (!(configured > 0f))
{
return 0f;
}
return configured;
}
public static bool NeedsReflectMultiplierWarning(float configured)
{
if (!float.IsNaN(configured))
{
return float.IsInfinity(configured);
}
return true;
}
public static DamageDecision Resolve(in DamageInput input)
{
if (!input.Immunity && !input.Reflect)
{
return Pass(PassReason.ImmunityAndReflectOff, "passthrough:immunity-off");
}
if (input.Point != DamagePoint.Limb && input.Point != DamagePoint.Hp && !input.IsMaster)
{
if (!input.ClientSelfSuppress)
{
return Pass(PassReason.NotMaster, "skip:client-self-off");
}
if (input.Immunity && input.AttackerIsPlayer)
{
return Suppress(input.Sentry ? "immunity-blocked:sentry" : "immunity-blocked:client-apply");
}
return Pass(PassReason.NotMaster, "skip:not-master");
}
if (!input.AttackerIsPlayer)
{
return Pass(PassReason.AttackerNotPlayer, "passthrough:not-player");
}
if (input.Point == DamagePoint.Hp)
{
return Pass(PassReason.None, "passthrough:immunity-off");
}
if (input.Point == DamagePoint.Limb)
{
if (!input.Immunity)
{
return Pass(PassReason.ImmunityOff, "passthrough:immunity-off");
}
if (!input.IsMaster)
{
if (!input.ClientSelfSuppress)
{
return Pass(PassReason.NotMaster, "skip:client-self-off");
}
return SuppressPacket(input.Sentry ? "immunity-blocked:sentry" : "immunity-blocked:local-packet");
}
return Suppress(input.Sentry ? "immunity-blocked:sentry" : "immunity-blocked");
}
if (input.OriginalDamage <= 0f)
{
return Pass(PassReason.ZeroOriginalDamage, "skip:zero-original");
}
if (input.Immunity)
{
bool flag = input.Reflect && input.AttackerDamageKnown && !input.AttackerIsVictim && (!input.VictimKnown || !input.VictimDowned);
float reflected;
float newHealth;
bool kill;
if (flag)
{
ComputeReflect(in input, out reflected, out newHealth, out kill);
}
else
{
reflected = 0f;
newHealth = 0f;
kill = false;
}
string text = (input.Sentry ? "immunity-blocked:sentry" : "immunity-blocked");
if (input.Reflect && input.AttackerIsVictim)
{
text += " reflect-skip:self-damage";
}
return Suppress(text, flag && reflected > 0f, reflected, newHealth, kill);
}
if (!input.AttackerDamageKnown)
{
return Pass(PassReason.NoDamageComponent, "skip:no-damage-comp");
}
float num = EffectiveFriendlyFireMultiplier(input.FriendlyFireMultiplier);
float victimDamage = input.OriginalDamage * num;
if (input.VictimKnown && input.VictimDowned)
{
return ReflectSkipDowned(num, victimDamage);
}
if (input.AttackerIsVictim)
{
return ReflectSkipSelf(num, victimDamage);
}
ComputeReflect(in input, out var reflected2, out var newHealth2, out var kill2);
return new DamageDecision(DamageAction.Reflect, PassReason.None, num, victimDamage, reflected2 > 0f, reflected2, newHealth2, kill2, FeedbackMode.OriginalPath, skipOriginal: false, "reflect-applied", "write");
}
private static DamageDecision Pass(PassReason reason, string verdict)
{
return new DamageDecision(DamageAction.PassThrough, reason, 1f, 0f, reflectAttacker: false, 0f, 0f, killAttacker: false, FeedbackMode.OriginalPath, skipOriginal: false, verdict, "pass");
}
private static DamageDecision Suppress(string verdict)
{
return new DamageDecision(DamageAction.Suppress, PassReason.None, 0f, 0f, reflectAttacker: false, 0f, 0f, killAttacker: false, FeedbackMode.OriginalPath, skipOriginal: false, verdict, "zero");
}
private static DamageDecision SuppressPacket(string verdict)
{
return new DamageDecision(DamageAction.SuppressPacket, PassReason.None, 0f, 0f, reflectAttacker: false, 0f, 0f, killAttacker: false, FeedbackMode.OriginalPath, skipOriginal: false, verdict, "zero");
}
private static DamageDecision Suppress(string verdict, bool reflect, float reflected, float newHealth, bool kill)
{
return new DamageDecision(DamageAction.Suppress, PassReason.None, 0f, 0f, reflect, reflected, newHealth, kill, FeedbackMode.OriginalPath, skipOriginal: false, verdict, "zero");
}
private static void ComputeReflect(in DamageInput input, out float reflected, out float newHealth, out bool kill)
{
float attackerHealthMax = input.AttackerHealthMax;
float num = (input.ReflectToDeath ? 0f : 0.001f);
if (num > attackerHealthMax)
{
num = attackerHealthMax;
}
float num2 = EffectiveReflectMultiplier(input.ReflectMultiplier);
reflected = Clamp(input.OriginalDamage * num2, 0f, attackerHealthMax);
newHealth = Clamp(input.AttackerHealth - reflected, num, attackerHealthMax);
kill = input.ReflectToDeath && attackerHealthMax > 0f && reflected > 0f && newHealth == 0f;
}
private static DamageDecision ReflectSkipDowned(float multiplier, float victimDamage)
{
return new DamageDecision(DamageAction.ReflectSuppressed, PassReason.None, multiplier, victimDamage, reflectAttacker: false, 0f, 0f, killAttacker: false, FeedbackMode.OriginalPath, skipOriginal: false, "reflect-skip:downed-victim", "write");
}
private static DamageDecision ReflectSkipSelf(float multiplier, float victimDamage)
{
return new DamageDecision(DamageAction.ReflectSuppressed, PassReason.None, multiplier, victimDamage, reflectAttacker: false, 0f, 0f, killAttacker: false, FeedbackMode.OriginalPath, skipOriginal: false, "reflect-skip:self-damage", "write");
}
private static float Clamp(float value, float min, float max)
{
if (value < min)
{
return min;
}
if (value > max)
{
return max;
}
return value;
}
}
internal static class Diag
{
internal static long HpSkipThrottleMs = 1000L;
private const string SkipLinePrefix = "[RFFPlus][diag] hp-skip site=on-incoming reason=";
private const string IdentityLinePrefix = "[RFFPlus][diag] hp-identity site=on-incoming reason=";
internal const string RoutineSkipReason = "nearest-unarmed";
private static long _hpEventLastMs = -2305843009213693952L;
private static string _hpEventLastReason = string.Empty;
private static int _hpEventSuppressed;
private static string _hpRoutineLatch;
internal static bool Enabled
{
get
{
try
{
return Plugin.Cfg_Verbose != null && Plugin.Cfg_Verbose.Value;
}
catch
{
return false;
}
}
}
internal static string Master
{
get
{
try
{
return SNet.IsMaster ? "True" : "False";
}
catch
{
return "?";
}
}
}
internal static string SourceKind(bool attackerIsPlayer)
{
if (!attackerIsPlayer)
{
return "non-player";
}
return "player";
}
internal static bool MustLog(in DamageDecision decision)
{
if (decision.Action != DamageAction.PassThrough)
{
return true;
}
return Enabled;
}
internal static void Limb(in DamageInput input, in DamageDecision decision, Agent sourceAgent, float original)
{
if (MustLog(in decision))
{
bool attackerIsPlayer;
try
{
attackerIsPlayer = (Object)(object)sourceAgent != (Object)null && (Object)(object)((Il2CppObjectBase)sourceAgent).TryCast<PlayerAgent>() != (Object)null;
}
catch
{
attackerIsPlayer = false;
}
if (input.Sentry)
{
attackerIsPlayer = true;
}
Write("[RFFPlus][diag] limb verdict=" + decision.Verdict + " mode=" + decision.Mode + " source=" + SourceKind(attackerIsPlayer) + " sentry=" + Bool(input.Sentry) + " immunity=" + Bool(input.Immunity) + " feedback=" + decision.Feedback.ToString() + " hp=" + decision.HpMultiplier.ToString("0.###") + " original=" + original.ToString("0.###") + " victim=" + decision.VictimDamage.ToString("0.###") + " packet=" + original.ToString("0.###") + " master=" + Master);
}
}
internal static void Receive(in DamageInput input, in DamageDecision decision, DamagePoint point, float original, bool victimKnown, bool victimDowned, float packetAfter)
{
if (MustLog(in decision))
{
Write("[RFFPlus][diag] receive point=" + Point(point) + " verdict=" + decision.Verdict + " mode=" + decision.Mode + " source=" + SourceKind(input.AttackerIsPlayer) + " sentry=" + Bool(input.Sentry) + " master=" + Master + " downed=" + (victimKnown ? Bool(victimDowned) : "unknown") + " immunity=" + Bool(input.Immunity) + " reflect=" + Bool(input.Reflect) + " feedback=" + decision.Feedback.ToString() + " hp=" + decision.HpMultiplier.ToString("0.###") + " original=" + original.ToString("0.###") + " victim=" + decision.VictimDamage.ToString("0.###") + " packet=" + packetAfter.ToString("0.###") + " reflected=" + (decision.ReflectAttacker ? decision.Reflected.ToString("0.###") : "na") + " newHealth=" + (decision.ReflectAttacker ? decision.NewAttackerHealth.ToString("0.###") : "na") + " applied=" + Bool(decision.ReflectAttacker));
}
}
internal static void LocalPacketSuppressed(DamagePoint point, bool sentry)
{
Write("[RFFPlus][diag] packet-suppress site=limb point=" + Point(point) + " sentry=" + Bool(sentry) + " reason=client-authoritative-host master=" + Master);
}
internal static void ReceivePass(DamagePoint point, string verdict, bool sentry, bool attackerIsPlayer, bool victimKnown)
{
if (Enabled)
{
Write("[RFFPlus][diag] receive point=" + Point(point) + " verdict=" + verdict + " mode=pass source=" + SourceKind(attackerIsPlayer) + " sentry=" + Bool(sentry) + " master=" + Master + " downed=" + (victimKnown ? "known" : "unknown") + " immunity=" + Bool(SafeBool(Plugin.Cfg_IgnoreFriendlyBullets)) + " reflect=" + Bool(SafeBool(Plugin.Cfg_ReflectEnabled)));
}
}
internal static void Hp(float before, float after, Agent sourceAgent)
{
float num = ((before != 0f) ? (after / before) : 0f);
string text = ((after == 0f) ? "zero" : "write");
bool attackerIsPlayer;
try
{
attackerIsPlayer = (Object)(object)sourceAgent != (Object)null && (Object)(object)((Il2CppObjectBase)sourceAgent).TryCast<PlayerAgent>() != (Object)null;
}
catch
{
attackerIsPlayer = false;
}
Write("[RFFPlus][diag] hp site=on-incoming verdict=hp-rewrite mode=" + text + " before=" + before.ToString("0.###") + " after=" + after.ToString("0.###") + " hp=" + num.ToString("0.###") + " source=" + SourceKind(attackerIsPlayer) + " feedback=OriginalPath master=" + Master);
}
internal static void HpFailsafe(float before, float after, Agent sourceAgent, string reason)
{
float num = ((before != 0f) ? (after / before) : 0f);
bool flag;
try
{
flag = (Object)(object)sourceAgent != (Object)null && (Object)(object)((Il2CppObjectBase)sourceAgent).TryCast<PlayerAgent>() != (Object)null;
}
catch
{
flag = false;
}
Write("[RFFPlus][diag] hp site=on-incoming verdict=hp-failsafe reason=" + reason + " mode=" + ((after == 0f) ? "zero" : "write") + " before=" + before.ToString("0.###") + " after=" + after.ToString("0.###") + " hp=" + num.ToString("0.###") + " source=" + SourceKind(flag || reason.EndsWith("sentry", StringComparison.Ordinal)) + " feedback=OriginalPath master=" + Master);
}
internal static void HpSkip(string reason, int depth, long victimPointer, long instancePointer, bool victimBound, bool armed)
{
EmitHpEvent("[RFFPlus][diag] hp-skip site=on-incoming reason=", reason, depth, victimPointer, instancePointer, victimBound, armed, "skip");
}
internal static void HpIdentity(string reason, int depth, long victimPointer, long instancePointer, bool victimBound, bool armed)
{
EmitHpEvent("[RFFPlus][diag] hp-identity site=on-incoming reason=", reason, depth, victimPointer, instancePointer, victimBound, armed, "applied");
}
private static void EmitHpEvent(string prefix, string reason, int depth, long victimPointer, long instancePointer, bool victimBound, bool armed, string action)
{
string text = reason ?? "unknown";
string master = Master;
if (string.Equals(text, "nearest-unarmed", StringComparison.Ordinal))
{
if (Enabled)
{
string text2 = text + "|" + master;
if (!string.Equals(text2, _hpRoutineLatch, StringComparison.Ordinal))
{
_hpRoutineLatch = text2;
Write(BuildHpEvent(prefix, text, depth, victimPointer, instancePointer, victimBound, armed, action, 0, master));
}
}
return;
}
long num;
try
{
num = Environment.TickCount64;
}
catch
{
num = 0L;
}
long hpSkipThrottleMs = HpSkipThrottleMs;
bool flag = string.Equals(text, _hpEventLastReason, StringComparison.Ordinal);
if (hpSkipThrottleMs > 0 && flag && num - _hpEventLastMs < hpSkipThrottleMs)
{
_hpEventSuppressed++;
return;
}
int hpEventSuppressed = _hpEventSuppressed;
_hpEventSuppressed = 0;
_hpEventLastReason = text;
_hpEventLastMs = num;
Write(BuildHpEvent(prefix, text, depth, victimPointer, instancePointer, victimBound, armed, action, hpEventSuppressed, master));
}
private static string BuildHpEvent(string prefix, string reason, int depth, long victimPointer, long instancePointer, bool victimBound, bool armed, string action, int suppressed, string master)
{
return prefix + reason + " depth=" + depth + " victim=" + PointerText(victimPointer) + " instance=" + PointerText(instancePointer) + " bound=" + Bool(victimBound) + " armed=" + Bool(armed) + " action=" + action + " suppressed=" + suppressed + " master=" + master;
}
private static string PointerText(long pointer)
{
if (pointer != 0L)
{
return "0x" + pointer.ToString("X");
}
return "na";
}
internal static void ResetHpEventState()
{
_hpEventLastMs = -2305843009213693952L;
_hpEventLastReason = string.Empty;
_hpEventSuppressed = 0;
_hpRoutineLatch = null;
}
internal static void Sentry(string phase, bool active, Agent owner)
{
if (Enabled)
{
Write("[RFFPlus][diag] sentry phase=" + phase + " active=" + Bool(active) + " owner=" + (((Object)(object)owner == (Object)null) ? "none" : "player") + " master=" + Master);
}
}
internal static void Reload(string phase, int attempt, bool ok, string detail, string effective)
{
string text = "[RFFPlus][diag] reload phase=" + phase + " attempt=" + attempt + " result=" + (ok ? "ok" : "failed") + " master=" + Master;
if (!string.IsNullOrEmpty(detail))
{
text = text + " detail=" + detail;
}
if (!string.IsNullOrEmpty(effective))
{
text = text + " effective=" + effective;
}
Write(text);
}
internal static void Fault(string site, Exception error)
{
try
{
Write("[RFFPlus][diag] fault site=" + site + " type=" + ((error == null) ? "null" : error.GetType().Name) + " message=" + ((error == null) ? string.Empty : error.Message) + " fallback=legacy-1.0.3");
}
catch
{
}
}
private static void Write(string line)
{
try
{
if (Plugin.Logger != null)
{
Plugin.Logger.LogInfo((object)line);
}
}
catch
{
}
}
private static bool SafeBool(ConfigEntry<bool> entry)
{
try
{
return entry?.Value ?? false;
}
catch
{
return false;
}
}
private static string Point(DamagePoint point)
{
return point switch
{
DamagePoint.Local => "local",
DamagePoint.Hp => "hp",
_ => "base",
};
}
private static string Bool(bool value)
{
if (!value)
{
return "False";
}
return "True";
}
}
public interface IClock
{
long NowMs { get; }
}
public sealed class StopwatchClock : IClock
{
private static readonly Stopwatch Watch = Stopwatch.StartNew();
public long NowMs => Watch.ElapsedMilliseconds;
}
public interface ILogSink
{
void Info(string line);
void Warn(string line);
}
public sealed class HotReloadCoordinator
{
public static readonly int[] BackoffMs = new int[5] { 200, 400, 800, 1600, 3200 };
public const long ProbeIntervalMs = 1000L;
private const long Never = long.MaxValue;
private readonly object _gate = new object();
private readonly IClock _clock;
private readonly Func<long?> _readMtimeMs;
private readonly Func<bool> _attemptReload;
private readonly ILogSink _log;
private readonly Func<string> _describeEffective;
private long? _appliedMtimeMs;
private long? _seenMtimeMs;
private long _nextAttemptAtMs = long.MaxValue;
private long _lastProbeMs;
private bool _probedOnce;
private int _attemptCount;
private bool _pending;
public bool IsPending
{
get
{
lock (_gate)
{
return _pending;
}
}
}
public int AttemptCount
{
get
{
lock (_gate)
{
return _attemptCount;
}
}
}
public long? AppliedMtimeMs
{
get
{
lock (_gate)
{
return _appliedMtimeMs;
}
}
}
public long NextAttemptAtMs
{
get
{
lock (_gate)
{
return _nextAttemptAtMs;
}
}
}
internal bool IsLockHeld => Monitor.IsEntered(_gate);
public HotReloadCoordinator(IClock clock, Func<long?> readMtimeMs, Func<bool> attemptReload, ILogSink log, Func<string> describeEffective)
{
if (clock == null)
{
throw new ArgumentNullException("clock");
}
if (attemptReload == null)
{
throw new ArgumentNullException("attemptReload");
}
_clock = clock;
_readMtimeMs = readMtimeMs;
_attemptReload = attemptReload;
_log = log;
_describeEffective = describeEffective;
_appliedMtimeMs = SafeMtime();
_seenMtimeMs = _appliedMtimeMs;
}
public void NotifyChanged()
{
lock (_gate)
{
long? seenMtimeMs = SafeMtime();
if (seenMtimeMs.HasValue)
{
_seenMtimeMs = seenMtimeMs;
}
BeginPendingLocked();
TickLocked();
}
}
public bool BeforeDecision()
{
lock (_gate)
{
long nowMs = _clock.NowMs;
if (_probedOnce && nowMs - _lastProbeMs < 1000)
{
return false;
}
_probedOnce = true;
_lastProbeMs = nowMs;
long? seenMtimeMs = SafeMtime();
bool num = seenMtimeMs.HasValue && (!_appliedMtimeMs.HasValue || seenMtimeMs.Value != _appliedMtimeMs.Value);
bool flag = seenMtimeMs.HasValue && (!_seenMtimeMs.HasValue || seenMtimeMs.Value != _seenMtimeMs.Value);
if (!num || !flag)
{
return false;
}
_seenMtimeMs = seenMtimeMs;
BeginPendingLocked();
return true;
}
}
public bool Tick()
{
lock (_gate)
{
return TickLocked();
}
}
public T ReadSnapshot<T>(Func<T> read)
{
if (read == null)
{
return default(T);
}
lock (_gate)
{
return read();
}
}
private bool TickLocked()
{
if (!_pending)
{
return false;
}
if (_clock.NowMs < _nextAttemptAtMs)
{
return false;
}
_attemptCount++;
int attemptCount = _attemptCount;
string text = Describe();
string text2 = null;
bool flag;
try
{
flag = _attemptReload();
}
catch (Exception ex)
{
flag = false;
text2 = ex.GetType().Name + ": " + ex.Message;
}
if (flag)
{
string text3 = Describe();
long? num = SafeMtime();
bool flag2 = !num.HasValue || !_appliedMtimeMs.HasValue || num.Value != _appliedMtimeMs.Value;
if (num.HasValue)
{
_appliedMtimeMs = num;
_seenMtimeMs = num;
}
_pending = false;
_nextAttemptAtMs = long.MaxValue;
string detail = null;
if (!string.IsNullOrEmpty(text) && text == text3)
{
detail = (flag2 ? "effective-unchanged:file-changed" : "effective-unchanged:file-unchanged");
}
LogSuccess(attemptCount, text3, detail);
_attemptCount = 0;
return true;
}
if (_attemptCount < BackoffMs.Length)
{
_nextAttemptAtMs = _clock.NowMs + BackoffMs[_attemptCount - 1];
LogFailure(attemptCount, text2 ?? "reload-returned-false", exhausted: false);
}
else
{
_nextAttemptAtMs = _clock.NowMs + BackoffMs[BackoffMs.Length - 1];
LogFailure(attemptCount, (text2 ?? "reload-returned-false") + ";backoff-exhausted", exhausted: true);
_attemptCount = BackoffMs.Length - 1;
}
return true;
}
private void BeginPendingLocked()
{
_pending = true;
_attemptCount = 0;
_nextAttemptAtMs = 0L;
}
private long? SafeMtime()
{
if (_readMtimeMs == null)
{
return null;
}
try
{
return _readMtimeMs();
}
catch
{
return null;
}
}
private string Describe()
{
if (_describeEffective == null)
{
return null;
}
try
{
return _describeEffective();
}
catch (Exception ex)
{
return "describe-failed:" + ex.GetType().Name;
}
}
private void LogSuccess(int attempt, string effective, string detail)
{
try
{
Diag.Reload("config", attempt, ok: true, detail, effective);
}
catch
{
}
if (_log != null)
{
try
{
_log.Info("[RFFPlus] 配置热重载 成功 (第 " + attempt + " 次):" + (effective ?? string.Empty));
}
catch
{
}
}
if (detail == null || _log == null)
{
return;
}
bool flag = detail.EndsWith("file-changed", StringComparison.Ordinal);
try
{
string line = "[RFFPlus] 配置热重载 成功但生效值未变化(" + detail + "):" + (effective ?? string.Empty) + (flag ? " —— 若刚改过配置,请检查是否有行写坏/被占用。" : " —— 文件本身没有变化(watcher 噪声),无需处理。");
if (flag)
{
_log.Warn(line);
}
else
{
_log.Info(line);
}
}
catch
{
}
}
private void LogFailure(int attempt, string detail, bool exhausted)
{
try
{
Diag.Reload("config", attempt, ok: false, detail, null);
}
catch
{
}
if (_log == null)
{
return;
}
try
{
string text = "[RFFPlus] 配置热重载 失败 (第 " + attempt + " 次):" + detail;
if (exhausted)
{
text += " —— 退避序列已用尽,将继续按最长间隔重试";
}
_log.Warn(text);
}
catch
{
}
}
}
public readonly struct HpRewritePlan
{
public readonly bool Armed;
public readonly float Multiplier;
public static HpRewritePlan None => default(HpRewritePlan);
public HpRewritePlan(bool armed, float multiplier)
{
Armed = armed;
Multiplier = multiplier;
}
}
internal readonly struct SentryFireState
{
internal readonly bool WasActive;
internal readonly PlayerAgent PreviousOwner;
internal SentryFireState(bool wasActive, PlayerAgent previousOwner)
{
WasActive = wasActive;
PreviousOwner = previousOwner;
}
}
[HarmonyPatch(typeof(Dam_PlayerDamageLimb), "BulletDamage")]
internal static class Patch_LimbBulletDamage
{
private static bool Prefix(ref float dam, Agent sourceAgent, out int __state)
{
__state = HpRewriteScope.Depth;
float num = dam;
bool flag = false;
float multiplier = 0f;
try
{
DamageConfigSnapshot config = ReflectPatches.Snapshot();
bool isSentryFire = ReflectPatches.IsSentryFire;
bool sourceIsPlayerAgent = (Object)(object)sourceAgent != (Object)null && (Object)(object)((Il2CppObjectBase)sourceAgent).TryCast<PlayerAgent>() != (Object)null;
bool flag2 = isSentryFire || ReflectPatches.IsSentrySource(sourceAgent);
DamageInput input = DamageCompose.Limb(in config, SNet.IsMaster, flag2, flag2, sourceIsPlayerAgent, num);
DamageDecision decision = DamageResolver.Resolve(in input);
Diag.Limb(in input, in decision, sourceAgent, num);
if (decision.PacketSuppress)
{
dam = 0f;
Diag.LocalPacketSuppressed(DamagePoint.Limb, isSentryFire);
}
else
{
flag = decision.HpWrite.HasValue;
if (flag)
{
multiplier = decision.HpWrite.Value;
}
}
}
catch (Exception error)
{
Diag.Fault("limb", error);
try
{
if (Plugin.Cfg_IgnoreFriendlyBullets != null && Plugin.Cfg_IgnoreFriendlyBullets.Value)
{
if (SNet.IsMaster)
{
flag = true;
multiplier = 0f;
}
else
{
dam = 0f;
}
}
}
catch (Exception error2)
{
Diag.Fault("limb-fallback", error2);
}
}
HpRewriteScope.EnterLimb(flag, multiplier);
return true;
}
private static void Finalizer(int __state)
{
HpRewriteScope.RestoreDepth(__state);
}
}
[HarmonyPatch(typeof(Dam_PlayerDamageBase), "ReceiveBulletDamage")]
internal static class Patch_BaseReceiveBulletDamage
{
private static void Prefix(Dam_PlayerDamageBase __instance, ref pBulletDamageData data, out int __state)
{
__state = HpRewriteScope.Depth;
HpRewritePlan hpRewritePlan = ReflectPatches.HandleIncomingBulletDamage(__instance, ref data, DamagePoint.Base);
HpRewriteScope.EnterReceive(__instance, hpRewritePlan.Armed, hpRewritePlan.Multiplier);
}
private static void Finalizer(int __state)
{
HpRewriteScope.RestoreDepth(__state);
}
}
[HarmonyPatch(typeof(Dam_PlayerDamageLocal), "ReceiveBulletDamage")]
internal static class Patch_LocalReceiveBulletDamage
{
private static void Prefix(Dam_PlayerDamageLocal __instance, ref pBulletDamageData data, out int __state)
{
__state = HpRewriteScope.Depth;
HpRewritePlan hpRewritePlan = ReflectPatches.HandleIncomingBulletDamage((Dam_PlayerDamageBase)(object)__instance, ref data, DamagePoint.Local);
HpRewriteScope.EnterReceive((Dam_PlayerDamageBase)(object)__instance, hpRewritePlan.Armed, hpRewritePlan.Multiplier);
}
private static void Finalizer(int __state)
{
HpRewriteScope.RestoreDepth(__state);
}
}
[HarmonyPatch(typeof(Dam_PlayerDamageBase), "OnIncomingDamage")]
internal static class Patch_PlayerOnIncomingDamage
{
private static void Prefix(Dam_PlayerDamageBase __instance, ref float damage, Agent sourceAgent)
{
try
{
float before = damage;
HpRewriteScope.ApplyResult applyResult = HpRewriteScope.TryApply(__instance, ref damage);
if (applyResult.Applied)
{
Diag.Hp(before, damage, sourceAgent);
}
if (applyResult.NeedsReport)
{
if (applyResult.Applied)
{
Diag.HpIdentity(applyResult.Reason, applyResult.Depth, applyResult.VictimPointer, applyResult.InstancePointer, applyResult.VictimBound, applyResult.Armed);
}
else
{
Diag.HpSkip(applyResult.Reason, applyResult.Depth, applyResult.VictimPointer, applyResult.InstancePointer, applyResult.VictimBound, applyResult.Armed);
}
}
if (!applyResult.Applied && HpRewriteScope.Depth == 0 && damage != 0f)
{
string text = ReflectPatches.TryFailsafeSuppress(sourceAgent, ref damage);
if (text != null)
{
Diag.HpFailsafe(before, damage, sourceAgent, text);
}
}
}
catch (Exception error)
{
Diag.Fault("hp", error);
}
}
}
[HarmonyPatch(typeof(SentryGunInstance_Firing_Bullets), "FireBullet")]
internal static class Patch_SentryFireBullet
{
private static void Prefix(SentryGunInstance_Firing_Bullets __instance, out SentryFireState __state)
{
__state = ReflectPatches.CaptureSentryState();
ReflectPatches.BeginSentryBurst(__instance, "burst-begin");
}
private static void Postfix(SentryFireState __state)
{
ReflectPatches.RestoreSentryState(__state);
}
private static void Finalizer(SentryFireState __state)
{
ReflectPatches.RestoreSentryState(__state);
}
}
[HarmonyPatch(typeof(SentryGunInstance_Firing_Bullets), "UpdateFireShotgunSemi")]
internal static class Patch_SentryUpdateFireShotgunSemi
{
private static void Prefix(SentryGunInstance_Firing_Bullets __instance, out SentryFireState __state)
{
__state = ReflectPatches.CaptureSentryState();
ReflectPatches.BeginSentryBurst(__instance, "burst-begin-shotgun");
}
private static void Postfix(SentryFireState __state)
{
ReflectPatches.RestoreSentryState(__state);
}
private static void Finalizer(SentryFireState __state)
{
ReflectPatches.RestoreSentryState(__state);
}
}
internal static class HpRewriteScope
{
internal enum IdentityMatch
{
Same,
Different,
Unknown
}
internal readonly struct ApplyResult
{
internal readonly bool Applied;
internal readonly string Reason;
internal readonly int Depth;
internal readonly long VictimPointer;
internal readonly long InstancePointer;
internal readonly bool VictimBound;
internal readonly bool Armed;
internal bool NeedsReport => !string.IsNullOrEmpty(Reason);
internal ApplyResult(bool applied, string reason, int depth, long victimPointer, long instancePointer, bool victimBound, bool armed)
{
Applied = applied;
Reason = reason;
Depth = depth;
VictimPointer = victimPointer;
InstancePointer = instancePointer;
VictimBound = victimBound;
Armed = armed;
}
}
private readonly struct Frame
{
public readonly Dam_PlayerDamageBase Victim;
public readonly float Multiplier;
public readonly bool Armed;
public Frame(Dam_PlayerDamageBase victim, bool armed, float multiplier)
{
Victim = victim;
Armed = armed;
Multiplier = (armed ? multiplier : 0f);
}
}
private const int MaxDepth = 8;
[ThreadStatic]
private static Frame[] _frames;
[ThreadStatic]
private static bool[] _consumed;
[ThreadStatic]
private static int _depth;
internal static int Depth => _depth;
private static int Limit
{
get
{
if (_depth >= 8)
{
return 8;
}
return _depth;
}
}
internal static void EnterLimb(bool armed, float multiplier)
{
Push(null, armed, multiplier);
}
internal static void EnterReceive(Dam_PlayerDamageBase victim, bool armed, float multiplier)
{
Push(victim, armed, multiplier);
}
internal static void RestoreDepth(int depth)
{
if (depth >= 0 && _depth > depth)
{
_depth = depth;
}
}
internal static IdentityMatch CompareNativeIdentity(Dam_PlayerDamageBase a, Dam_PlayerDamageBase b, out long pointerA, out long pointerB)
{
pointerA = SafePointer(a);
pointerB = SafePointer(b);
if (pointerA != 0L && pointerB != 0L)
{
if (pointerA != pointerB)
{
return IdentityMatch.Different;
}
return IdentityMatch.Same;
}
if ((Object)(object)a == (Object)null && (Object)(object)b == (Object)null)
{
return IdentityMatch.Same;
}
if ((Object)(object)a == (Object)null || (Object)(object)b == (Object)null)
{
return IdentityMatch.Different;
}
return IdentityMatch.Unknown;
}
private static long SafePointer(Dam_PlayerDamageBase damage)
{
if ((Object)(object)damage == (Object)null)
{
return 0L;
}
try
{
return ((Il2CppObjectBase)damage).Pointer.ToInt64();
}
catch
{
return 0L;
}
}
internal static ApplyResult TryApply(Dam_PlayerDamageBase instance, ref float damage)
{
int limit = Limit;
if (limit == 0)
{
return new ApplyResult(applied: false, null, 0, 0L, 0L, victimBound: false, armed: false);
}
int num = limit - 1;
Frame frame = _frames[num];
bool flag = (Object)(object)frame.Victim != (Object)null;
if (_consumed[num])
{
string reason = (frame.Armed ? "already-consumed" : "nearest-unarmed");
return new ApplyResult(applied: false, reason, limit, SafePointer(frame.Victim), SafePointer(instance), flag, frame.Armed);
}
long pointerA;
long pointerB;
if (flag)
{
switch (CompareNativeIdentity(frame.Victim, instance, out pointerA, out pointerB))
{
case IdentityMatch.Different:
return new ApplyResult(applied: false, "victim-mismatch", limit, pointerA, pointerB, victimBound: true, armed: true);
case IdentityMatch.Unknown:
Apply(num, frame.Multiplier, ref damage);
return new ApplyResult(applied: true, "pointer-unavailable", limit, pointerA, pointerB, victimBound: true, armed: true);
default:
Apply(num, frame.Multiplier, ref damage);
return new ApplyResult(applied: true, null, limit, pointerA, pointerB, victimBound: true, armed: true);
}
}
Apply(num, frame.Multiplier, ref damage);
return new ApplyResult(applied: true, null, limit, 0L, SafePointer(instance), victimBound: false, armed: true);
}
private static void Apply(int top, float multiplier, ref float damage)
{
for (int num = top; num >= 0; num--)
{
_consumed[num] = true;
}
damage *= multiplier;
}
private static void Push(Dam_PlayerDamageBase victim, bool armed, float multiplier)
{
if (_depth < 8)
{
if (_frames == null)
{
_frames = new Frame[8];
}
if (_consumed == null)
{
_consumed = new bool[8];
}
_frames[_depth] = new Frame(victim, armed, multiplier);
_consumed[_depth] = !armed;
}
_depth++;
}
}
internal static class ReflectPatches
{
internal static bool IsSentryFire;
internal static PlayerAgent SentryOwner;
internal static DamageConfigSnapshot Snapshot()
{
Plugin.EnsureConfigFresh();
return Plugin.Reload?.ReadSnapshot(BuildSnapshot) ?? BuildSnapshot();
}
private static DamageConfigSnapshot BuildSnapshot()
{
return new DamageConfigSnapshot(Plugin.Cfg_IgnoreFriendlyBullets.Value, Plugin.Cfg_ReflectEnabled.Value, Plugin.Cfg_FFMulti.Value, Plugin.Cfg_ReflectMulti.Value, Plugin.Cfg_ReflectToDeath.Value, Plugin.Cfg_ClientSelfSuppress == null || Plugin.Cfg_ClientSelfSuppress.Value);
}
internal static SentryFireState CaptureSentryState()
{
return new SentryFireState(IsSentryFire, SentryOwner);
}
internal static void RestoreSentryState(SentryFireState state)
{
IsSentryFire = state.WasActive;
SentryOwner = state.PreviousOwner;
}
internal static void BeginSentryBurst(SentryGunInstance_Firing_Bullets instance, string phase)
{
if (SNet.IsMaster)
{
bool isSentryFire = IsSentryFire;
IsSentryFire = true;
iSentrygunInstanceCore val = (((Object)(object)instance != (Object)null) ? instance.m_core : null);
SentryOwner = ((val != null) ? val.Owner : null);
if (!isSentryFire)
{
Diag.Sentry(phase, active: true, (Agent)(object)SentryOwner);
}
}
}
public static HpRewritePlan HandleIncomingBulletDamage(Dam_PlayerDamageBase victimDamage, ref pBulletDamageData data, DamagePoint point)
{
try
{
bool isSentryFire = IsSentryFire;
PlayerAgent val = null;
Agent val2 = null;
bool flag;
if (isSentryFire)
{
val = SentryOwner;
flag = true;
}
else
{
flag = ((pAgent)(ref data.source)).TryGet(ref val2) && (Object)(object)val2 != (Object)null;
if (!flag)
{
Diag.ReceivePass(point, "passthrough:not-player", isSentryFire, attackerIsPlayer: false, victimKnown: false);
return HpRewritePlan.None;
}
val = ((Il2CppObjectBase)val2).TryCast<PlayerAgent>();
}
bool flag2 = isSentryFire || ((Object)(object)val == (Object)null && flag && IsSentrySource(val2));
if ((Object)(object)val == (Object)null && !flag2)
{
Diag.ReceivePass(point, "passthrough:not-player", isSentryFire, attackerIsPlayer: false, victimKnown: false);
return HpRewritePlan.None;
}
Dam_SyncedDamageBase val3 = (Dam_SyncedDamageBase)(object)(((Object)(object)val != (Object)null) ? val.Damage : null);
bool flag3 = (Object)(object)val3 != (Object)null;
float num;
float attackerHealth;
if (flag3)
{
num = val3.HealthMax;
attackerHealth = val3.Health;
}
else
{
num = SafeHealthMax(victimDamage);
attackerHealth = 0f;
}
float num2 = ((UFloat16)(ref data.damage)).Get(num);
bool flag4 = false;
bool victimDowned = false;
PlayerAgent val4 = null;
try
{
val4 = (((Object)(object)victimDamage != (Object)null) ? victimDamage.Owner : null);
if ((Object)(object)val4 != (Object)null)
{
flag4 = true;
victimDowned = IsDowned(val4);
}
}
catch (Exception error)
{
Diag.Fault("victim-lookup", error);
flag4 = false;
victimDowned = false;
}
bool flag5 = false;
try
{
flag5 = HpRewriteScope.CompareNativeIdentity((Dam_PlayerDamageBase)(object)((val3 is Dam_PlayerDamageBase) ? val3 : null), victimDamage, out var _, out var _) == HpRewriteScope.IdentityMatch.Same;
}
catch
{
flag5 = false;
}
if (!flag5 && flag4)
{
try
{
flag5 = SamePlayer(val, val4);
}
catch
{
flag5 = false;
}
}
DamageInput input = DamageCompose.Receive(Snapshot(), point, SNet.IsMaster, flag2, flag2, attackerIsPlayerAgent: true, flag3, num2, attackerHealth, num, flag4, victimDowned, flag5);
DamageDecision decision = DamageResolver.Resolve(in input);
if (decision.Action == DamageAction.PassThrough)
{
Diag.ReceivePass(point, decision.Verdict, flag2, attackerIsPlayer: true, flag4);
return HpRewritePlan.None;
}
if (decision.ReflectAttacker && (Object)(object)val3 != (Object)null)
{
val3.SendSetHealth(decision.NewAttackerHealth);
if (decision.KillAttacker)
{
val3.SendSetDead(true);
}
}
Diag.Receive(in input, in decision, point, num2, flag4, victimDowned, ((UFloat16)(ref data.damage)).Get(num));
if (!decision.HpWrite.HasValue)
{
return HpRewritePlan.None;
}
return new HpRewritePlan(armed: true, decision.HpWrite.Value);
}
catch (Exception error2)
{
Diag.Fault("receive", error2);
try
{
if (Plugin.Cfg_IgnoreFriendlyBullets != null && Plugin.Cfg_IgnoreFriendlyBullets.Value)
{
if (SNet.IsMaster)
{
return new HpRewritePlan(armed: true, 0f);
}
((UFloat16)(ref data.damage)).Set(0f, SafeHealthMax(victimDamage));
Diag.LocalPacketSuppressed(point, sentry: false);
return HpRewritePlan.None;
}
}
catch (Exception error3)
{
Diag.Fault("receive-fallback", error3);
}
return HpRewritePlan.None;
}
}
internal static bool IsSentrySource(Agent agent)
{
//IL_000d: Unknown result type (might be due to invalid IL or missing references)
//IL_0013: Invalid comparison between Unknown and I4
if ((Object)(object)agent == (Object)null)
{
return false;
}
try
{
return (int)agent.m_type == 3;
}
catch
{
return false;
}
}
internal static bool IsFriendlyFireSource(Agent agent)
{
if ((Object)(object)agent == (Object)null)
{
return false;
}
try
{
if ((Object)(object)((Il2CppObjectBase)agent).TryCast<PlayerAgent>() != (Object)null)
{
return true;
}
}
catch
{
}
return IsSentrySource(agent);
}
internal static string TryFailsafeSuppress(Agent sourceAgent, ref float damage)
{
try
{
if (Plugin.Cfg_IgnoreFriendlyBullets == null || !Plugin.Cfg_IgnoreFriendlyBullets.Value)
{
return null;
}
if (!IsFriendlyFireSource(sourceAgent))
{
return null;
}
damage = 0f;
return IsSentrySource(sourceAgent) ? "on-incoming-failsafe:sentry" : "on-incoming-failsafe:player";
}
catch (Exception error)
{
Diag.Fault("hp-failsafe", error);
return null;
}
}
internal static float SafeHealthMax(Dam_PlayerDamageBase victim)
{
try
{
if ((Object)(object)victim != (Object)null)
{
float healthMax = ((Dam_SyncedDamageBase)victim).HealthMax;
if (healthMax > 0f && !float.IsInfinity(healthMax) && !float.IsNaN(healthMax))
{
return healthMax;
}
}
}
catch
{
}
return 1f;
}
internal static bool SamePlayer(PlayerAgent a, PlayerAgent b)
{
if ((Object)(object)a == (Object)null || (Object)(object)b == (Object)null)
{
return false;
}
if (a == b)
{
return true;
}
try
{
ulong num = PlayerLookup(a);
ulong num2 = PlayerLookup(b);
if (num != 0L && num2 != 0L)
{
return num == num2;
}
}
catch
{
}
try
{
long num3 = ((Il2CppObjectBase)a).Pointer.ToInt64();
long num4 = ((Il2CppObjectBase)b).Pointer.ToInt64();
if (num3 != 0L && num4 != 0L)
{
return num3 == num4;
}
}
catch
{
}
return false;
}
internal static ulong PlayerLookup(PlayerAgent player)
{
if ((Object)(object)player == (Object)null)
{
return 0uL;
}
try
{
SNet_Player owner = player.Owner;
if ((Object)(object)owner == (Object)null)
{
return 0uL;
}
return owner.Lookup;
}
catch
{
return 0uL;
}
}
internal static bool IsDowned(PlayerAgent agent)
{
//IL_0021: Unknown result type (might be due to invalid IL or missing references)
//IL_0027: Invalid comparison between Unknown and I4
if ((Object)(object)agent == (Object)null)
{
return false;
}
try
{
PlayerLocomotion locomotion = agent.Locomotion;
if ((Object)(object)locomotion == (Object)null)
{
return false;
}
return (int)locomotion.m_currentStateEnum == 7;
}
catch (Exception error)
{
Diag.Fault("downed-probe", error);
return false;
}
}
}
[BepInPlugin("RFFPlus", "ReverseFriendlyFire Plus (Standalone)", "1.0.10")]
public class Plugin : BasePlugin
{
private sealed class BepInExLogSink : ILogSink
{
private readonly ManualLogSource _log;
internal BepInExLogSink(ManualLogSource log)
{
_log = log;
}
public void Info(string line)
{
try
{
ManualLogSource log = _log;
if (log != null)
{
log.LogInfo((object)line);
}
}
catch
{
}
}
public void Warn(string line)
{
try
{
ManualLogSource log = _log;
if (log != null)
{
log.LogWarning((object)line);
}
}
catch
{
}
}
}
internal static ConfigEntry<bool> Cfg_IgnoreFriendlyBullets;
internal static ConfigEntry<bool> Cfg_ReflectEnabled;
internal static ConfigEntry<float> Cfg_FFMulti;
internal static ConfigEntry<float> Cfg_ReflectMulti;
internal static ConfigEntry<bool> Cfg_ReflectToDeath;
internal static ConfigEntry<bool> Cfg_Verbose;
internal static ConfigEntry<bool> Cfg_ClientSelfSuppress;
internal static ManualLogSource Logger;
internal static HotReloadCoordinator Reload;
internal static bool DisableBackgroundServices = false;
private Harmony _harmony;
private FileSystemWatcher _cfgWatcher;
private Timer _retryTimer;
private static float _warnedMultiplier = float.NaN;
private static float? _warnedReflectInvalid;
public override void Load()
{
//IL_0079: Unknown result type (might be due to invalid IL or missing references)
//IL_0083: Expected O, but got Unknown
//IL_00b6: Unknown result type (might be due to invalid IL or missing references)
//IL_00c0: Expected O, but got Unknown
//IL_0193: Unknown result type (might be due to invalid IL or missing references)
//IL_019d: Expected O, but got Unknown
Logger = ((BasePlugin)this).Log;
Cfg_IgnoreFriendlyBullets = ((BasePlugin)this).Config.Bind<bool>("免伤模式 (任何端生效)", "启用玩家子弹免伤", true, "玩家(含哨戒炮)的子弹不扣血(只在 HP 扣减点压制,数据包伤害、受击语音与画面保持原版真实值)。以主机结算为准:主机安装即对全队生效(客机只本地预演,权威结算仍在主机)。");
Cfg_ReflectEnabled = ((BasePlugin)this).Config.Bind<bool>("反伤模式 (主机生效)", "启用友伤反伤", true, "主机权威:友方子弹伤害先按友伤倍率缩放,再按反伤倍率反噬开枪者。");
Cfg_FFMulti = ((BasePlugin)this).Config.Bind<float>("反伤模式 (主机生效)", "友伤倍率", 1f, new ConfigDescription("被队友打到的实际承伤倍率(1 = 原版伤害)。0 或负数按 1 处理 —— 要“不掉血”请用「启用玩家子弹免伤」,不要用 0 当开关。", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 10f), Array.Empty<object>()));
Cfg_ReflectMulti = ((BasePlugin)this).Config.Bind<float>("反伤模式 (主机生效)", "反伤倍率", 1f, new ConfigDescription("按原始伤害值反噬开枪者的倍率", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 10f), Array.Empty<object>()));
Cfg_ReflectToDeath = ((BasePlugin)this).Config.Bind<bool>("反伤模式 (主机生效)", "反伤致死", true, "反伤足以耗尽开枪者血量时,直接将其击杀");
Cfg_Verbose = ((BasePlugin)this).Config.Bind<bool>("诊断 (排查用)", "输出诊断日志", false, "输出 PassThrough 明细与逐帧细节。命中判决(非放行)、任何一次 HP 改写与 HP 改写被拒(hp-skip)始终输出,不受此开关影响。");
Cfg_ClientSelfSuppress = ((BasePlugin)this).Config.Bind<bool>("免伤模式 (任何端生效)", "客户端自救压包", true, "客机是否在本机自己拦:开 = 客机在本机把数据包/HP 压下来(主机没装插件也有效,代价是该次命中在本机没有受击反馈);关 = 客机一个字节都不改、受击语音与画面保持原版,免疫完全由主机端压制(主机必须装本插件)。");
Reload = new HotReloadCoordinator(new StopwatchClock(), ReadConfigMtimeMs, ReloadConfigNow, new BepInExLogSink(((BasePlugin)this).Log), DescribeEffectiveValues);
if (!DisableBackgroundServices)
{
StartConfigWatcher();
StartRetryTimer();
}
else
{
((BasePlugin)this).Log.LogInfo((object)"[RFFPlus] 后台服务已禁用(测试接缝):不启 watcher / 重试定时器,仍保留 mtime 兜底补读。");
}
WarnMultiplierIfNeeded();
_harmony = new Harmony("RFFPlus");
_harmony.PatchAll(typeof(Plugin).Assembly);
((BasePlugin)this).Log.LogInfo((object)("[RFFPlus] 加载完成 v1.0.10:" + DescribeEffectiveValues()));
}
internal static void EnsureConfigFresh()
{
HotReloadCoordinator reload = Reload;
if (reload == null)
{
return;
}
try
{
reload.BeforeDecision();
}
catch (Exception error)
{
Diag.Fault("reload-probe", error);
}
}
internal static string DescribeEffectiveValues()
{
try
{
float value = Cfg_FFMulti.Value;
string text = DamageResolver.EffectiveFriendlyFireMultiplier(value).ToString("0.###");
if (DamageResolver.NeedsMultiplierWarning(value))
{
text = text + "(配置 " + value.ToString("0.###") + " → 按 1 处理)";
}
return "免伤=" + Cfg_IgnoreFriendlyBullets.Value + " 反伤=" + Cfg_ReflectEnabled.Value + " 友伤倍率=" + text + " 反伤倍率=" + Cfg_ReflectMulti.Value.ToString("0.###") + " 反伤致死=" + Cfg_ReflectToDeath.Value + " 客机自救=" + Cfg_ClientSelfSuppress.Value + " 诊断=" + Cfg_Verbose.Value;
}
catch (Exception ex)
{
return "describe-failed:" + ex.GetType().Name;
}
}
private static void WarnMultiplierIfNeeded()
{
try
{
float value = Cfg_FFMulti.Value;
if (DamageResolver.NeedsMultiplierWarning(value) && (float.IsNaN(_warnedMultiplier) || Math.Abs(_warnedMultiplier - value) >= 0.0001f))
{
_warnedMultiplier = value;
string text = "[RFFPlus] 友伤倍率配置为 " + value.ToString("0.###") + ",按 1.0 处理(否则“关免伤”会等于打不出伤害)。要关闭友伤请用「启用玩家子弹免伤」开关。";
try
{
ManualLogSource logger = Logger;
if (logger != null)
{
logger.LogWarning((object)text);
}
}
catch
{
}
Diag.Reload("multiplier", 0, ok: true, "ff-multiplier-normalized", DescribeEffectiveValues());
}
else if (!DamageResolver.NeedsMultiplierWarning(value))
{
_warnedMultiplier = value;
}
float value2 = Cfg_ReflectMulti.Value;
bool flag = _warnedReflectInvalid.HasValue && SameWarnedValue(_warnedReflectInvalid.Value, value2);
if (!DamageResolver.NeedsReflectMultiplierWarning(value2) || flag)
{
return;
}
_warnedReflectInvalid = value2;
try
{
ManualLogSource logger2 = Logger;
if (logger2 != null)
{
logger2.LogWarning((object)("[RFFPlus] 反伤倍率配置为非法值(" + value2.ToString("0.###") + ",NaN/∞),按 0 处理:不会再反噬开枪者。"));
}
}
catch
{
}
Diag.Reload("multiplier", 0, ok: true, "reflect-multiplier-normalized", DescribeEffectiveValues());
}
catch
{
}
}
private static bool SameWarnedValue(float a, float b)
{
bool flag = float.IsNaN(a);
bool flag2 = float.IsNaN(b);
if (flag || flag2)
{
return flag && flag2;
}
return a.Equals(b);
}
private long? ReadConfigMtimeMs()
{
try
{
string configFilePath = ((BasePlugin)this).Config.ConfigFilePath;
if (string.IsNullOrEmpty(configFilePath) || !File.Exists(configFilePath))
{
return null;
}
return new FileInfo(configFilePath).LastWriteTimeUtc.Ticks / 10000;
}
catch
{
return null;
}
}
private bool ReloadConfigNow()
{
try
{
((BasePlugin)this).Config.Reload();
WarnMultiplierIfNeeded();
return true;
}
catch (Exception ex)
{
try
{
((BasePlugin)this).Log.LogWarning((object)("[RFFPlus] 配置重载抛出异常: " + ex.GetType().Name + ": " + ex.Message));
}
catch
{
}
return false;
}
}
private void StartConfigWatcher()
{
try
{
string configFilePath = ((BasePlugin)this).Config.ConfigFilePath;
string directoryName = Path.GetDirectoryName(configFilePath);
string fileName = Path.GetFileName(configFilePath);
_cfgWatcher = new FileSystemWatcher(directoryName, fileName)
{
NotifyFilter = (NotifyFilters.Size | NotifyFilters.LastWrite | NotifyFilters.CreationTime)
};
_cfgWatcher.Changed += OnConfigFileChanged;
_cfgWatcher.Created += OnConfigFileChanged;
_cfgWatcher.Renamed += OnConfigFileChanged;
_cfgWatcher.EnableRaisingEvents = true;
((BasePlugin)this).Log.LogInfo((object)("[RFFPlus] 配置热重载监视已启动: " + configFilePath));
}
catch (Exception ex)
{
((BasePlugin)this).Log.LogWarning((object)("[RFFPlus] 配置监视启动失败(仍会由伤害决策前的 mtime 兜底补读): " + ex.Message));
}
}
private void StartRetryTimer()
{
try
{
_retryTimer = new Timer(delegate
{
try
{
Reload?.Tick();
}
catch (Exception error)
{
Diag.Fault("reload-tick", error);
}
}, null, 200, 200);
}
catch (Exception ex)
{
((BasePlugin)this).Log.LogWarning((object)("[RFFPlus] 热重载重试定时器启动失败(仍会在伤害决策前补读): " + ex.Message));
}
}
private void OnConfigFileChanged(object sender, FileSystemEventArgs e)
{
try
{
Reload?.NotifyChanged();
}
catch (Exception ex)
{
((BasePlugin)this).Log.LogWarning((object)("[RFFPlus] 配置热重载触发失败: " + ex.Message));
}
}
public override bool Unload()
{
try
{
_retryTimer?.Dispose();
}
catch
{
}
_cfgWatcher?.Dispose();
Harmony harmony = _harmony;
if (harmony != null)
{
harmony.UnpatchSelf();
}
return true;
}
}
}