using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Configuration;
using Microsoft.CodeAnalysis;
using UnityEngine;
using UnityEngine.Rendering.Universal;
[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: IgnoresAccessChecksTo("GameAssembly")]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("SBG-PiPBallCam")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.2.1.0")]
[assembly: AssemblyInformationalVersion("1.2.1+e4e4b9621761c4e6961cb9148a7fa345fb0f0923")]
[assembly: AssemblyProduct("Picture-in-Picture Ball Camera")]
[assembly: AssemblyTitle("SBG-PiPBallCam")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.2.1.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
[CompilerGenerated]
[Embedded]
internal sealed class EmbeddedAttribute : Attribute
{
}
}
namespace System.Runtime.CompilerServices
{
[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;
}
}
}
[BepInPlugin("com.kingcox.sbg.pipballcam", "SBG PiP Ball Cam", "1.2.1")]
public class BallCamMod : BaseUnityPlugin
{
private struct BenchmarkStep
{
public string Name;
public bool PipOn;
public float Scale;
public float Distance;
public bool Shadows;
public bool Textures;
public int MaxFps;
public BenchmarkStep(string name, bool pipOn, float scale = 1f, float distance = 1000f, bool shadows = true, bool textures = true, int maxFps = 0)
{
Name = name;
PipOn = pipOn;
Scale = scale;
Distance = distance;
Shadows = shadows;
Textures = textures;
MaxFps = maxFps;
}
}
private struct BenchmarkResult
{
public string Name;
public bool PipOn;
public float Fps;
public float FrameTimeMs;
public float PipVisibleFraction;
}
private static readonly string[] PlayerNameMembers = new string[3] { "Username", "Name", "playerName" };
private static readonly string[] PlayerIdNameMembers = new string[5] { "PlayerName", "Username", "_playerName", "networkedPlayerName", "playerName" };
private static readonly string[] GolferMembers = new string[1] { "AsGolfer" };
private static readonly string[] BallVelocityMembers = new string[2] { "linearVelocity", "velocity" };
private static readonly BindingFlags InstanceMembers = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
private static readonly BindingFlags PublicInstanceMembers = BindingFlags.Instance | BindingFlags.Public;
private static readonly Dictionary<Type, MemberInfo> PlayerNameMemberCache = new Dictionary<Type, MemberInfo>();
private static readonly Dictionary<Type, MemberInfo> PlayerIdNameMemberCache = new Dictionary<Type, MemberInfo>();
private static readonly Dictionary<Type, MemberInfo> GolferMemberCache = new Dictionary<Type, MemberInfo>();
private static readonly Dictionary<Type, MemberInfo> BallVelocityMemberCache = new Dictionary<Type, MemberInfo>();
private ConfigEntry<KeyboardShortcut> _toggleKey;
private ConfigEntry<float> _pipPositionX;
private ConfigEntry<float> _pipPositionY;
private ConfigEntry<float> _pipSize;
private ConfigEntry<bool> _performanceDiagnostics;
private ConfigEntry<float> _renderScale;
private ConfigEntry<float> _renderDistance;
private ConfigEntry<bool> _renderShadows;
private ConfigEntry<bool> _renderDepthOpaqueTextures;
private ConfigEntry<int> _maxFps;
private float _nextPipRenderTime;
private static readonly BenchmarkStep BenchmarkBaseline = new BenchmarkStep("PiP off", pipOn: false);
private static readonly BenchmarkStep[] BenchmarkConfigs = new BenchmarkStep[10]
{
new BenchmarkStep("Full quality", pipOn: true),
new BenchmarkStep("Shadows off", pipOn: true, 1f, 1000f, shadows: false),
new BenchmarkStep("Depth/opaque textures off", pipOn: true, 1f, 1000f, shadows: true, textures: false),
new BenchmarkStep("Render scale 50%", pipOn: true, 0.5f),
new BenchmarkStep("Render distance 250", pipOn: true, 1f, 250f),
new BenchmarkStep("Max FPS 60", pipOn: true, 1f, 1000f, shadows: true, textures: true, 60),
new BenchmarkStep("Max FPS 30", pipOn: true, 1f, 1000f, shadows: true, textures: true, 30),
new BenchmarkStep("Shadows off, Max FPS 60", pipOn: true, 1f, 1000f, shadows: false, textures: true, 60),
new BenchmarkStep("Shadows off, Max FPS 30", pipOn: true, 1f, 1000f, shadows: false, textures: true, 30),
new BenchmarkStep("Minimum (no shadows/textures, 25%, 50, 30 FPS)", pipOn: true, 0.25f, 50f, shadows: false, textures: false, 30)
};
private const float BenchmarkWarmupSeconds = 2f;
private const float BenchmarkSampleSeconds = 10f;
private ConfigEntry<KeyboardShortcut> _benchmarkKey;
private bool _benchmarkRunning;
private int _benchmarkStepIndex;
private float _benchmarkStepElapsed;
private float _benchmarkSampleTime;
private int _benchmarkFrames;
private int _benchmarkPipFrames;
private string _benchmarkStatus = "";
private readonly List<BenchmarkResult> _benchmarkResults = new List<BenchmarkResult>();
private bool _savedSaveOnConfigSet;
private bool _savedPipEnabled;
private float _savedRenderScale;
private float _savedRenderDistance;
private bool _savedRenderShadows;
private bool _savedRenderDepthOpaqueTextures;
private int _savedMaxFps;
private Camera _ballCam;
private GameObject _ballCamObj;
private RenderTexture _ballCamTexture;
private int _renderTextureWidth;
private int _renderTextureHeight;
private bool _isPipEnabled = true;
private bool _hasLastBallPos;
private float _smoothSpeed = 10f;
private float _movementThreshold = 0.02f;
private float _lingerTime = 1.5f;
private float _lastMoveTime;
private string _currentTargetName = "";
private Vector3 _lastBallPos;
private Vector3 _stableDirection = Vector3.back;
private GUIStyle _labelStyle;
private GUIStyle _outlineStyle;
private bool _wasDiagnosticsEnabled;
private float _diagnosticWindowSeconds;
private float _diagnosticFrameTimeTotal;
private float _diagnosticFrameTimeMax;
private float _diagnosticUpdateTimeTotal;
private int _diagnosticFrameCount;
private float _lastFrameTimeMs;
private float _lastUpdateTimeMs;
private bool _hasDiagnosticAverage;
private float _averageFps;
private float _averageFrameTimeMs;
private float _averageMaxFrameTimeMs;
private float _averageUpdateTimeMs;
private const int DiagnosticWindowId = 1346519857;
private ConfigEntry<float> _diagnosticWindowX;
private ConfigEntry<float> _diagnosticWindowY;
private Rect _diagnosticWindowRect;
private string _diagnosticText = "";
private bool _diagnosticTextChanged = true;
private float _nextDiagnosticTextTime;
private int _diagnosticResultsCount = -1;
private string _diagnosticResultsText = "";
private float _diagnosticWindowHeight;
private const float DiagnosticTextInterval = 0.25f;
private long _onGuiTicks;
private float _lastOnGuiTimeMs;
private float _diagnosticOnGuiTimeTotal;
private float _averageOnGuiTimeMs;
private bool _diagnosticWindowPlaced;
private static int BenchmarkStepCount => BenchmarkConfigs.Length * 2 + 1;
private static BenchmarkStep GetBenchmarkStep(int index)
{
if (index % 2 != 0)
{
return BenchmarkConfigs[index / 2];
}
return BenchmarkBaseline;
}
private void Awake()
{
//IL_001b: 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_0068: 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_00da: Unknown result type (might be due to invalid IL or missing references)
//IL_00e4: Expected O, but got Unknown
//IL_0125: Unknown result type (might be due to invalid IL or missing references)
//IL_01b2: Unknown result type (might be due to invalid IL or missing references)
//IL_01bc: 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_0269: Unknown result type (might be due to invalid IL or missing references)
//IL_0273: Expected O, but got Unknown
//IL_0279: Unknown result type (might be due to invalid IL or missing references)
//IL_0283: Expected O, but got Unknown
//IL_029a: Unknown result type (might be due to invalid IL or missing references)
//IL_02c4: Unknown result type (might be due to invalid IL or missing references)
//IL_02ce: Expected O, but got Unknown
//IL_02d9: Unknown result type (might be due to invalid IL or missing references)
_toggleKey = ((BaseUnityPlugin)this).Config.Bind<KeyboardShortcut>("General", "ToggleKey", new KeyboardShortcut((KeyCode)289, Array.Empty<KeyCode>()), "Keyboard shortcut for enabling or disabling the PiP ball camera.");
_pipPositionX = ((BaseUnityPlugin)this).Config.Bind<float>("PiP", "Position X", 98.75f, new ConfigDescription("Horizontal position of the PiP. 0 = touching the left edge of the screen, 100 = touching the right edge.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 100f), Array.Empty<object>()));
_pipPositionY = ((BaseUnityPlugin)this).Config.Bind<float>("PiP", "Position Y", 31.25f, new ConfigDescription("Vertical position of the PiP. 0 = touching the bottom edge of the screen, 100 = touching the top edge.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 100f), Array.Empty<object>()));
_pipSize = ((BaseUnityPlugin)this).Config.Bind<float>("PiP", "Size", 20f, new ConfigDescription("Width and height of the PiP, as a percentage of the screen's width and height.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(5f, 50f), Array.Empty<object>()));
_performanceDiagnostics = ((BaseUnityPlugin)this).Config.Bind<bool>("Personal Diagnostics", "Enabled", false, "Show a performance overlay and periodically log frame and mod update timings. While enabled, the PiP camera stays open even when the ball is not moving so its cost can be measured.");
_benchmarkKey = ((BaseUnityPlugin)this).Config.Bind<KeyboardShortcut>("Personal Diagnostics", "Benchmark Key", new KeyboardShortcut((KeyCode)290, Array.Empty<KeyCode>()), "Runs through a set of PiP settings (including PiP off) for ~12 seconds each and reports the average FPS of each. Requires diagnostics to be enabled. Press again to cancel. Your saved settings are restored afterwards.");
_diagnosticWindowX = ((BaseUnityPlugin)this).Config.Bind<float>("Personal Diagnostics", "Window X", 10f, "Horizontal position of the diagnostics window, in pixels from the left edge. Drag the window to change it.");
_diagnosticWindowY = ((BaseUnityPlugin)this).Config.Bind<float>("Personal Diagnostics", "Window Y", -1f, "Vertical position of the diagnostics window, in pixels from the top edge. -1 places it at the bottom of the screen.");
_renderScale = ((BaseUnityPlugin)this).Config.Bind<float>("Performance", "Render Scale", 1f, new ConfigDescription("Resolution scale for the PiP camera. Lower values reduce the number of rendered pixels. Below 1, the PiP is drawn as an overlay on top of the game's HUD.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.25f, 1f), Array.Empty<object>()));
_renderDistance = ((BaseUnityPlugin)this).Config.Bind<float>("Performance", "Render Distance", 1000f, new ConfigDescription("Maximum distance rendered by the PiP camera, in Unity units. Lower values skip distant objects.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(50f, 1000f), Array.Empty<object>()));
_renderShadows = ((BaseUnityPlugin)this).Config.Bind<bool>("Performance", "Shadows", false, "Render shadows in the PiP. Turning this on adds a second shadow map pass, which is a noticeable part of the PiP's cost.");
_renderDepthOpaqueTextures = ((BaseUnityPlugin)this).Config.Bind<bool>("Performance", "Depth And Opaque Textures", true, "Let the PiP camera generate the depth and opaque textures some effects (water, transparency) rely on. Turning this off saves GPU time, but those effects may look different in the PiP.");
_maxFps = ((BaseUnityPlugin)this).Config.Bind<int>("Performance", "Max FPS", 60, new ConfigDescription("Maximum frame rate for the PiP camera. 0 renders it every frame. Any limit makes the PiP draw as an overlay on top of the game's HUD.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 240), Array.Empty<object>()));
_labelStyle = new GUIStyle();
_labelStyle.alignment = (TextAnchor)1;
_labelStyle.normal.textColor = Color.white;
_labelStyle.fontStyle = (FontStyle)1;
_labelStyle.fontSize = 16;
_outlineStyle = new GUIStyle(_labelStyle);
_outlineStyle.normal.textColor = Color.black;
}
private string GetSafeName(PlayerInfo info)
{
if ((Object)(object)info == (Object)null)
{
return "Unknown";
}
Type type = ((object)info).GetType();
MemberInfo cachedMember = GetCachedMember(PlayerNameMemberCache, type, PlayerNameMembers, InstanceMembers);
if (cachedMember != null)
{
return GetMemberValue(cachedMember, info)?.ToString() ?? "Unknown";
}
Component component = ((Component)info).GetComponent("PlayerId");
if ((Object)(object)component != (Object)null)
{
Type type2 = ((object)component).GetType();
MemberInfo cachedMember2 = GetCachedMember(PlayerIdNameMemberCache, type2, PlayerIdNameMembers, InstanceMembers);
if (cachedMember2 != null)
{
return GetMemberValue(cachedMember2, component)?.ToString() ?? "Unknown";
}
}
return "Golfer";
}
private static MemberInfo GetCachedMember(Dictionary<Type, MemberInfo> cache, Type type, string[] memberNames, BindingFlags bindingFlags, bool includeFields = true)
{
if (!cache.TryGetValue(type, out var value))
{
value = FindMember(type, memberNames, bindingFlags, includeFields);
cache.Add(type, value);
}
return value;
}
private static MemberInfo FindMember(Type type, string[] memberNames, BindingFlags bindingFlags, bool includeFields)
{
foreach (string name in memberNames)
{
PropertyInfo property = type.GetProperty(name, bindingFlags);
if (property != null)
{
return property;
}
if (includeFields)
{
FieldInfo field = type.GetField(name, bindingFlags);
if (field != null)
{
return field;
}
}
}
return null;
}
private static object GetMemberValue(MemberInfo member, object target)
{
if (member is PropertyInfo propertyInfo)
{
return propertyInfo.GetValue(target);
}
if (member is FieldInfo fieldInfo)
{
return fieldInfo.GetValue(target);
}
return null;
}
private PlayerGolfer GetAsGolfer(PlayerInfo info)
{
if ((Object)(object)info == (Object)null)
{
return null;
}
object memberValue = GetMemberValue(GetCachedMember(GolferMemberCache, ((object)info).GetType(), GolferMembers, PublicInstanceMembers, includeFields: false), info);
return (PlayerGolfer)((memberValue is PlayerGolfer) ? memberValue : null);
}
private Vector3 GetBallVelocity(Rigidbody rb)
{
//IL_0009: 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_003b: Unknown result type (might be due to invalid IL or missing references)
if ((Object)(object)rb == (Object)null)
{
return Vector3.zero;
}
MemberInfo cachedMember = GetCachedMember(BallVelocityMemberCache, ((object)rb).GetType(), BallVelocityMembers, PublicInstanceMembers, includeFields: false);
if (cachedMember != null)
{
return (Vector3)GetMemberValue(cachedMember, rb);
}
return Vector3.zero;
}
private void Update()
{
((MonoBehaviour)this).useGUILayout = _performanceDiagnostics.Value;
if (!_performanceDiagnostics.Value)
{
_wasDiagnosticsEnabled = false;
UpdatePlugin();
return;
}
if (!_wasDiagnosticsEnabled)
{
ResetPerformanceWindow();
_hasDiagnosticAverage = false;
_wasDiagnosticsEnabled = true;
}
long timestamp = Stopwatch.GetTimestamp();
try
{
UpdatePlugin();
}
finally
{
RecordPerformanceSample(timestamp);
}
if (Time.unscaledTime >= _nextDiagnosticTextTime)
{
_nextDiagnosticTextTime = Time.unscaledTime + 0.25f;
_diagnosticText = BuildDiagnosticsText();
_diagnosticTextChanged = true;
}
}
private void UpdatePlugin()
{
//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_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_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)
KeyboardShortcut value = _benchmarkKey.Value;
if (((KeyboardShortcut)(ref value)).IsDown())
{
if (_benchmarkRunning)
{
StopBenchmark("cancelled");
}
else if (_performanceDiagnostics.Value)
{
StartBenchmark();
}
else
{
((BaseUnityPlugin)this).Logger.LogWarning((object)"Enable [Personal Diagnostics] in the config to run the PiP benchmark.");
}
}
if (_benchmarkRunning)
{
UpdateBenchmark();
}
else
{
value = _toggleKey.Value;
if (((KeyboardShortcut)(ref value)).IsDown())
{
_isPipEnabled = !_isPipEnabled;
if (!_isPipEnabled)
{
ClosePip();
}
if (_performanceDiagnostics.Value)
{
ResetPerformanceWindow();
}
}
}
if (!_isPipEnabled)
{
return;
}
if ((Object)(object)_ballCam != (Object)null)
{
UpdateBallCameraSettings();
}
if ((Object)(object)Camera.main == (Object)null || (Object)(object)GameManager.LocalPlayerInfo == (Object)null)
{
ClosePip();
return;
}
GolfBall val = DetermineTargetBall();
if ((Object)(object)val != (Object)null)
{
Vector3 ballVelocity = GetBallVelocity(val.Rigidbody);
float magnitude = ((Vector3)(ref ballVelocity)).magnitude;
if (_performanceDiagnostics.Value || magnitude > _movementThreshold || Time.time - _lastMoveTime < _lingerTime)
{
if (magnitude > _movementThreshold)
{
_lastMoveTime = Time.time;
}
ShowPip(val);
}
else
{
ClosePip();
}
}
else
{
ClosePip();
}
}
private void ResetPerformanceWindow()
{
_diagnosticWindowSeconds = 0f;
_diagnosticFrameTimeTotal = 0f;
_diagnosticFrameTimeMax = 0f;
_diagnosticUpdateTimeTotal = 0f;
_diagnosticOnGuiTimeTotal = 0f;
_diagnosticFrameCount = 0;
_lastFrameTimeMs = 0f;
_lastUpdateTimeMs = 0f;
_lastOnGuiTimeMs = 0f;
}
private void RecordPerformanceSample(long updateStart)
{
float unscaledDeltaTime = Time.unscaledDeltaTime;
_lastFrameTimeMs = unscaledDeltaTime * 1000f;
_lastUpdateTimeMs = (float)((double)(Stopwatch.GetTimestamp() - updateStart) * 1000.0 / (double)Stopwatch.Frequency);
_lastOnGuiTimeMs = (float)((double)_onGuiTicks * 1000.0 / (double)Stopwatch.Frequency);
_onGuiTicks = 0L;
_diagnosticWindowSeconds += unscaledDeltaTime;
_diagnosticFrameTimeTotal += _lastFrameTimeMs;
_diagnosticFrameTimeMax = Mathf.Max(_diagnosticFrameTimeMax, _lastFrameTimeMs);
_diagnosticUpdateTimeTotal += _lastUpdateTimeMs;
_diagnosticOnGuiTimeTotal += _lastOnGuiTimeMs;
_diagnosticFrameCount++;
if (!(_diagnosticWindowSeconds < 10f))
{
_averageFrameTimeMs = _diagnosticFrameTimeTotal / (float)_diagnosticFrameCount;
_averageFps = (float)_diagnosticFrameCount / _diagnosticWindowSeconds;
_averageMaxFrameTimeMs = _diagnosticFrameTimeMax;
_averageUpdateTimeMs = _diagnosticUpdateTimeTotal / (float)_diagnosticFrameCount;
_averageOnGuiTimeMs = _diagnosticOnGuiTimeTotal / (float)_diagnosticFrameCount;
_hasDiagnosticAverage = true;
bool flag = IsPipShowing();
((BaseUnityPlugin)this).Logger.LogInfo((object)($"Performance diagnostics (10s): avg FPS={_averageFps:F1}, " + $"avg frame={_averageFrameTimeMs:F2} ms, max frame={_averageMaxFrameTimeMs:F2} ms, " + $"avg mod Update={_averageUpdateTimeMs:F3} ms, avg mod GUI={_averageOnGuiTimeMs:F3} ms, " + $"PiP enabled={_isPipEnabled}, active={flag}, " + $"render scale={_renderScale.Value:P0}, distance={_renderDistance.Value:F0}."));
ResetPerformanceWindow();
}
}
private void StartBenchmark()
{
_savedPipEnabled = _isPipEnabled;
_savedRenderScale = _renderScale.Value;
_savedRenderDistance = _renderDistance.Value;
_savedRenderShadows = _renderShadows.Value;
_savedRenderDepthOpaqueTextures = _renderDepthOpaqueTextures.Value;
_savedMaxFps = _maxFps.Value;
_savedSaveOnConfigSet = ((BaseUnityPlugin)this).Config.SaveOnConfigSet;
((BaseUnityPlugin)this).Config.SaveOnConfigSet = false;
_benchmarkResults.Clear();
_benchmarkRunning = true;
((BaseUnityPlugin)this).Logger.LogInfo((object)($"PiP benchmark started: {BenchmarkStepCount} steps, " + $"{12f:F0}s each."));
ApplyBenchmarkStep(0);
}
private void ApplyBenchmarkStep(int index)
{
BenchmarkStep benchmarkStep = GetBenchmarkStep(index);
_benchmarkStepIndex = index;
_benchmarkStepElapsed = 0f;
_benchmarkSampleTime = 0f;
_benchmarkFrames = 0;
_benchmarkPipFrames = 0;
_renderScale.Value = benchmarkStep.Scale;
_renderDistance.Value = benchmarkStep.Distance;
_renderShadows.Value = benchmarkStep.Shadows;
_renderDepthOpaqueTextures.Value = benchmarkStep.Textures;
_maxFps.Value = benchmarkStep.MaxFps;
_isPipEnabled = benchmarkStep.PipOn;
if (!_isPipEnabled)
{
ClosePip();
}
}
private void UpdateBenchmark()
{
BenchmarkStep benchmarkStep = GetBenchmarkStep(_benchmarkStepIndex);
float unscaledDeltaTime = Time.unscaledDeltaTime;
_benchmarkStepElapsed += unscaledDeltaTime;
string text = $"Benchmark {_benchmarkStepIndex + 1}/{BenchmarkStepCount}: {benchmarkStep.Name}";
if (_benchmarkStepElapsed <= 2f)
{
_benchmarkStatus = text + " (settling...)";
return;
}
_benchmarkSampleTime += unscaledDeltaTime;
_benchmarkFrames++;
if (IsPipShowing())
{
_benchmarkPipFrames++;
}
_benchmarkStatus = $"{text} ({10f - _benchmarkSampleTime:F0}s left)";
if (!(_benchmarkSampleTime < 10f))
{
BenchmarkResult item = new BenchmarkResult
{
Name = benchmarkStep.Name,
PipOn = benchmarkStep.PipOn,
Fps = (float)_benchmarkFrames / _benchmarkSampleTime,
FrameTimeMs = _benchmarkSampleTime * 1000f / (float)_benchmarkFrames,
PipVisibleFraction = (float)_benchmarkPipFrames / (float)_benchmarkFrames
};
_benchmarkResults.Add(item);
((BaseUnityPlugin)this).Logger.LogInfo((object)($"PiP benchmark step {_benchmarkStepIndex + 1}/{BenchmarkStepCount}: " + $"{item.Name}: {item.Fps:F1} FPS ({item.FrameTimeMs:F2} ms)"));
if (_benchmarkStepIndex + 1 < BenchmarkStepCount)
{
ApplyBenchmarkStep(_benchmarkStepIndex + 1);
}
else
{
StopBenchmark("complete");
}
}
}
private void StopBenchmark(string reason)
{
//IL_0094: Unknown result type (might be due to invalid IL or missing references)
_benchmarkRunning = false;
_renderScale.Value = _savedRenderScale;
_renderDistance.Value = _savedRenderDistance;
_renderShadows.Value = _savedRenderShadows;
_renderDepthOpaqueTextures.Value = _savedRenderDepthOpaqueTextures;
_maxFps.Value = _savedMaxFps;
((BaseUnityPlugin)this).Config.SaveOnConfigSet = _savedSaveOnConfigSet;
_isPipEnabled = _savedPipEnabled;
if (!_isPipEnabled)
{
ClosePip();
}
_benchmarkStatus = $"Benchmark {reason}. Press {_benchmarkKey.Value} to run again.";
((BaseUnityPlugin)this).Logger.LogInfo((object)("PiP benchmark " + reason + ". Settings restored."));
if (_benchmarkResults.Count > 0)
{
((BaseUnityPlugin)this).Logger.LogInfo((object)("PiP benchmark summary:\n" + string.Join("\n", FormatBenchmarkResults())));
}
ResetPerformanceWindow();
}
private List<string> FormatBenchmarkResults()
{
List<string> list = new List<string>();
float num = float.MaxValue;
float num2 = 0f;
int num3 = 0;
for (int i = 0; i < _benchmarkResults.Count; i += 2)
{
num = Mathf.Min(num, _benchmarkResults[i].Fps);
num2 = Mathf.Max(num2, _benchmarkResults[i].Fps);
num3++;
}
if (num3 > 0)
{
list.Add($"PiP off baseline: {num:F1}-{num2:F1} FPS across {num3} runs");
}
for (int j = 1; j < _benchmarkResults.Count; j += 2)
{
BenchmarkResult benchmarkResult = _benchmarkResults[j];
string text = $"{benchmarkResult.Name}: {benchmarkResult.Fps:F1} FPS";
if (j + 1 < _benchmarkResults.Count)
{
float num4 = (_benchmarkResults[j - 1].FrameTimeMs + _benchmarkResults[j + 1].FrameTimeMs) / 2f;
float num5 = benchmarkResult.FrameTimeMs - num4;
float num6 = benchmarkResult.Fps - 1000f / num4;
text += $" | PiP cost {num5:+0.00;-0.00} ms ({num6:+0.0;-0.0} FPS)";
}
else
{
text += " | cost pending next baseline";
}
if (benchmarkResult.PipVisibleFraction < 0.9f)
{
text += $" | PiP only visible {benchmarkResult.PipVisibleFraction:P0} of the time";
}
list.Add(text);
}
return list;
}
private GolfBall DetermineTargetBall()
{
PlayerInfo localPlayerInfo = GameManager.LocalPlayerInfo;
if ((Object)(object)localPlayerInfo == (Object)null)
{
return null;
}
PlayerSpectator component = ((Component)localPlayerInfo).GetComponent<PlayerSpectator>();
if ((Object)(object)component != (Object)null && component.IsSpectating)
{
if ((Object)(object)component.TargetBall != (Object)null)
{
_currentTargetName = "Spectated Ball";
return component.TargetBall;
}
if ((Object)(object)component.TargetPlayer != (Object)null)
{
_currentTargetName = GetSafeName(component.TargetPlayer);
PlayerGolfer asGolfer = GetAsGolfer(component.TargetPlayer);
if (asGolfer == null)
{
return null;
}
return asGolfer.OwnBall;
}
}
_currentTargetName = GetSafeName(localPlayerInfo);
PlayerGolfer asGolfer2 = GetAsGolfer(localPlayerInfo);
if (asGolfer2 == null)
{
return null;
}
return asGolfer2.OwnBall;
}
private void ShowPip(GolfBall ball)
{
//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_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_00b1: 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_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_00db: Unknown result type (might be due to invalid IL or missing references)
//IL_00f2: Unknown result type (might be due to invalid IL or missing references)
//IL_00f7: 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_0119: Unknown result type (might be due to invalid IL or missing references)
//IL_011a: Unknown result type (might be due to invalid IL or missing references)
//IL_0124: Unknown result type (might be due to invalid IL or missing references)
//IL_0129: Unknown result type (might be due to invalid IL or missing references)
//IL_004d: 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_0059: 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_0067: 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_0089: 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)
if ((Object)(object)_ballCamObj == (Object)null)
{
CreateBallCamera();
}
UpdateBallCameraSettings();
if (!_ballCamObj.activeSelf)
{
_ballCamObj.SetActive(true);
}
UpdatePipFrameLimit();
Vector3 position = ((Component)ball).transform.position;
if (_hasLastBallPos)
{
Vector3 val = position - _lastBallPos;
Vector3 val2 = default(Vector3);
((Vector3)(ref val2))..ctor(val.x, 0f, val.z);
if (((Vector3)(ref val2)).magnitude > 0.01f)
{
_stableDirection = Vector3.Slerp(_stableDirection, ((Vector3)(ref val2)).normalized, Time.deltaTime * 5f);
}
}
_lastBallPos = position;
_hasLastBallPos = true;
Vector3 val3 = position - _stableDirection * 3f + Vector3.up * 1.2f;
((Component)_ballCam).transform.position = Vector3.Lerp(((Component)_ballCam).transform.position, val3, Time.deltaTime * _smoothSpeed);
((Component)_ballCam).transform.LookAt(position + Vector3.up * 0.15f);
}
private void ClosePip()
{
if ((Object)(object)_ballCamObj != (Object)null)
{
_ballCamObj.SetActive(false);
if ((Object)(object)_ballCam != (Object)null)
{
((Behaviour)_ballCam).enabled = false;
}
}
_currentTargetName = "";
_hasLastBallPos = false;
_nextPipRenderTime = 0f;
}
private void UpdatePipFrameLimit()
{
if (_maxFps.Value <= 0)
{
((Behaviour)_ballCam).enabled = true;
return;
}
float unscaledTime = Time.unscaledTime;
if (unscaledTime < _nextPipRenderTime)
{
((Behaviour)_ballCam).enabled = false;
return;
}
float num = 1f / (float)_maxFps.Value;
_nextPipRenderTime = Mathf.Max(_nextPipRenderTime + num, unscaledTime);
((Behaviour)_ballCam).enabled = true;
}
private bool IsPipShowing()
{
if ((Object)(object)_ballCamObj != (Object)null && _ballCamObj.activeInHierarchy)
{
return (Object)(object)_ballCam != (Object)null;
}
return false;
}
private void OnGUI()
{
if (!_performanceDiagnostics.Value || !((MonoBehaviour)this).useGUILayout)
{
DrawPipOverlay();
return;
}
long timestamp = Stopwatch.GetTimestamp();
DrawDiagnosticsWindow();
DrawPipOverlay();
_onGuiTicks += Stopwatch.GetTimestamp() - timestamp;
}
private void DrawPipOverlay()
{
//IL_000a: Unknown result type (might be due to invalid IL or missing references)
//IL_000f: Unknown result type (might be due to invalid IL or missing references)
//IL_0023: Unknown result type (might be due to invalid IL or missing references)
//IL_0029: Invalid comparison between Unknown and I4
//IL_002b: 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_00ef: Unknown result type (might be due to invalid IL or missing references)
//IL_0123: Unknown result type (might be due to invalid IL or missing references)
//IL_0157: 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)
if (IsPipShowing())
{
Rect pipScreenRect = GetPipScreenRect();
if ((Object)(object)_ballCamTexture != (Object)null && (int)Event.current.type == 7)
{
GUI.DrawTexture(pipScreenRect, (Texture)(object)_ballCamTexture, (ScaleMode)0, false);
}
if (!string.IsNullOrEmpty(_currentTargetName) && _labelStyle != null)
{
float x = ((Rect)(ref pipScreenRect)).x;
float num = ((Rect)(ref pipScreenRect)).y + 5f;
Rect val = default(Rect);
((Rect)(ref val))..ctor(x, num, ((Rect)(ref pipScreenRect)).width, 5f);
string text = "<b>" + _currentTargetName + "</b>";
float num2 = 2f;
GUI.Label(new Rect(((Rect)(ref val)).x - num2, ((Rect)(ref val)).y - num2, ((Rect)(ref val)).width, ((Rect)(ref val)).height), text, _outlineStyle);
GUI.Label(new Rect(((Rect)(ref val)).x + num2, ((Rect)(ref val)).y - num2, ((Rect)(ref val)).width, ((Rect)(ref val)).height), text, _outlineStyle);
GUI.Label(new Rect(((Rect)(ref val)).x - num2, ((Rect)(ref val)).y + num2, ((Rect)(ref val)).width, ((Rect)(ref val)).height), text, _outlineStyle);
GUI.Label(new Rect(((Rect)(ref val)).x + num2, ((Rect)(ref val)).y + num2, ((Rect)(ref val)).width, ((Rect)(ref val)).height), text, _outlineStyle);
GUI.Label(val, text, _labelStyle);
}
}
}
private void DrawDiagnosticsWindow()
{
//IL_0041: Unknown result type (might be due to invalid IL or missing references)
//IL_0052: Expected O, but got Unknown
//IL_00db: 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_00f6: Expected O, but got Unknown
//IL_00f1: Unknown result type (might be due to invalid IL or missing references)
//IL_00f6: Unknown result type (might be due to invalid IL or missing references)
//IL_0164: Unknown result type (might be due to invalid IL or missing references)
//IL_016a: Invalid comparison between Unknown and I4
//IL_00c3: Unknown result type (might be due to invalid IL or missing references)
//IL_00c8: Unknown result type (might be due to invalid IL or missing references)
float num = ((_benchmarkResults.Count > 0 || _benchmarkRunning) ? 560f : 360f);
if (_diagnosticTextChanged)
{
_diagnosticWindowHeight = 30f + GUI.skin.label.CalcHeight(new GUIContent(_diagnosticText), num - 16f);
_diagnosticTextChanged = false;
}
float diagnosticWindowHeight = _diagnosticWindowHeight;
((Rect)(ref _diagnosticWindowRect)).width = num;
((Rect)(ref _diagnosticWindowRect)).height = diagnosticWindowHeight;
if (!_diagnosticWindowPlaced)
{
float num2 = ((_diagnosticWindowY.Value < 0f) ? ((float)Screen.height - diagnosticWindowHeight - 10f) : _diagnosticWindowY.Value);
_diagnosticWindowRect = new Rect(_diagnosticWindowX.Value, num2, num, diagnosticWindowHeight);
_diagnosticWindowPlaced = true;
}
_diagnosticWindowRect = GUI.Window(1346519857, _diagnosticWindowRect, new WindowFunction(DrawDiagnosticsWindowContents), "PiP performance diagnostics");
((Rect)(ref _diagnosticWindowRect)).x = Mathf.Clamp(((Rect)(ref _diagnosticWindowRect)).x, 0f, Mathf.Max(0f, (float)Screen.width - num));
((Rect)(ref _diagnosticWindowRect)).y = Mathf.Clamp(((Rect)(ref _diagnosticWindowRect)).y, 0f, Mathf.Max(0f, (float)Screen.height - diagnosticWindowHeight));
if ((int)Event.current.rawType == 1 && (!Mathf.Approximately(_diagnosticWindowX.Value, ((Rect)(ref _diagnosticWindowRect)).x) || !Mathf.Approximately(_diagnosticWindowY.Value, ((Rect)(ref _diagnosticWindowRect)).y)))
{
_diagnosticWindowX.Value = ((Rect)(ref _diagnosticWindowRect)).x;
_diagnosticWindowY.Value = ((Rect)(ref _diagnosticWindowRect)).y;
}
}
private string BuildDiagnosticsText()
{
//IL_01bb: Unknown result type (might be due to invalid IL or missing references)
bool num = IsPipShowing();
string text = (_isPipEnabled ? "enabled" : "disabled");
string text2 = (num ? "active" : "inactive");
string text3 = (_hasDiagnosticAverage ? ($"10s avg: {_averageFps:F1} FPS | {_averageFrameTimeMs:F2} ms (max {_averageMaxFrameTimeMs:F2} ms)\n" + $"10s avg Mod Update: {_averageUpdateTimeMs:F3} ms | Mod GUI: {_averageOnGuiTimeMs:F3} ms") : $"10s avg: collecting... ({_diagnosticWindowSeconds:F0}/10s)\n");
string arg = ((_maxFps.Value > 0) ? _maxFps.Value.ToString() : "unlimited");
string text4 = $"Frame: {_lastFrameTimeMs:F2} ms | Mod Update: {_lastUpdateTimeMs:F3} ms | Mod GUI: {_lastOnGuiTimeMs:F3} ms\n" + text3 + "\nPiP: " + text + " | Camera: " + text2 + "\n" + $"Render: {_renderScale.Value:P0} | Distance: {_renderDistance.Value:F0} | Max FPS: {arg}\n" + "Shadows: " + OnOff(_renderShadows.Value) + " | Depth/opaque textures: " + OnOff(_renderDepthOpaqueTextures.Value);
text4 = (string.IsNullOrEmpty(_benchmarkStatus) ? (text4 + $"\n\nPress {_benchmarkKey.Value} to benchmark PiP settings.") : (text4 + "\n\n" + _benchmarkStatus));
if (_benchmarkResults.Count != _diagnosticResultsCount)
{
_diagnosticResultsCount = _benchmarkResults.Count;
_diagnosticResultsText = ((_benchmarkResults.Count > 0) ? ("\n" + string.Join("\n", FormatBenchmarkResults())) : "");
}
return text4 + _diagnosticResultsText;
}
private static string OnOff(bool value)
{
if (!value)
{
return "off";
}
return "on";
}
private void DrawDiagnosticsWindowContents(int windowId)
{
//IL_0032: Unknown result type (might be due to invalid IL or missing references)
long timestamp = Stopwatch.GetTimestamp();
GUI.Label(new Rect(8f, 20f, ((Rect)(ref _diagnosticWindowRect)).width - 16f, ((Rect)(ref _diagnosticWindowRect)).height - 24f), _diagnosticText);
GUI.DragWindow();
_onGuiTicks += Stopwatch.GetTimestamp() - timestamp;
}
private void CreateBallCamera()
{
//IL_0006: Unknown result type (might be due to invalid IL or missing references)
//IL_0010: Expected O, but got Unknown
_ballCamObj = new GameObject("PiPBallCamera");
_ballCam = _ballCamObj.AddComponent<Camera>();
_ballCam.depth = 999f;
_ballCam.cullingMask = -33;
Object.DontDestroyOnLoad((Object)(object)_ballCamObj);
UpdateBallCameraSettings();
}
private Rect GetPipViewportRect()
{
//IL_0052: Unknown result type (might be due to invalid IL or missing references)
float num = _pipSize.Value / 100f;
float num2 = Mathf.Clamp01(_pipPositionX.Value / 100f) * (1f - num);
float num3 = Mathf.Clamp01(_pipPositionY.Value / 100f) * (1f - num);
return new Rect(num2, num3, num, num);
}
private Rect GetPipScreenRect()
{
//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_0045: Unknown result type (might be due to invalid IL or missing references)
Rect pipViewportRect = GetPipViewportRect();
return new Rect((float)Screen.width * ((Rect)(ref pipViewportRect)).x, (float)Screen.height * (1f - ((Rect)(ref pipViewportRect)).yMax), (float)Screen.width * ((Rect)(ref pipViewportRect)).width, (float)Screen.height * ((Rect)(ref pipViewportRect)).height);
}
private void UpdateBallCameraSettings()
{
//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_0172: Unknown result type (might be due to invalid IL or missing references)
//IL_0177: Unknown result type (might be due to invalid IL or missing references)
//IL_0182: Unknown result type (might be due to invalid IL or missing references)
//IL_0198: Expected O, but got Unknown
//IL_01b2: Unknown result type (might be due to invalid IL or missing references)
//IL_00ca: Unknown result type (might be due to invalid IL or missing references)
//IL_00cf: Unknown result type (might be due to invalid IL or missing references)
//IL_00d7: Unknown result type (might be due to invalid IL or missing references)
//IL_00dc: Unknown result type (might be due to invalid IL or missing references)
//IL_00eb: 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_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_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_008a: 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)
if (!Mathf.Approximately(_ballCam.farClipPlane, _renderDistance.Value))
{
_ballCam.farClipPlane = _renderDistance.Value;
}
UniversalAdditionalCameraData universalAdditionalCameraData = CameraExtensions.GetUniversalAdditionalCameraData(_ballCam);
if ((Object)(object)universalAdditionalCameraData != (Object)null)
{
if (universalAdditionalCameraData.renderShadows != _renderShadows.Value)
{
universalAdditionalCameraData.renderShadows = _renderShadows.Value;
}
CameraOverrideOption val = (CameraOverrideOption)(_renderDepthOpaqueTextures.Value ? 2 : 0);
if (universalAdditionalCameraData.requiresDepthOption != val)
{
universalAdditionalCameraData.requiresDepthOption = val;
}
if (universalAdditionalCameraData.requiresColorOption != val)
{
universalAdditionalCameraData.requiresColorOption = val;
}
}
if (_renderScale.Value >= 0.999f && _maxFps.Value <= 0)
{
ReleaseBallCameraTexture();
Rect pipViewportRect = GetPipViewportRect();
if (_ballCam.rect != pipViewportRect)
{
_ballCam.rect = pipViewportRect;
}
return;
}
Rect pipScreenRect = GetPipScreenRect();
int num = Mathf.Max(1, Mathf.RoundToInt(((Rect)(ref pipScreenRect)).width * _renderScale.Value));
int num2 = Mathf.Max(1, Mathf.RoundToInt(((Rect)(ref pipScreenRect)).height * _renderScale.Value));
if (!((Object)(object)_ballCamTexture != (Object)null) || num != _renderTextureWidth || num2 != _renderTextureHeight)
{
ReleaseBallCameraTexture();
_renderTextureWidth = num;
_renderTextureHeight = num2;
_ballCamTexture = new RenderTexture(num, num2, 24)
{
name = "PiPBallCameraTexture",
antiAliasing = Mathf.Max(1, QualitySettings.antiAliasing)
};
_ballCam.rect = new Rect(0f, 0f, 1f, 1f);
_ballCam.targetTexture = _ballCamTexture;
}
}
private void ReleaseBallCameraTexture()
{
if (!((Object)(object)_ballCamTexture == (Object)null))
{
if ((Object)(object)_ballCam != (Object)null && (Object)(object)_ballCam.targetTexture == (Object)(object)_ballCamTexture)
{
_ballCam.targetTexture = null;
}
_ballCamTexture.Release();
Object.Destroy((Object)(object)_ballCamTexture);
_ballCamTexture = null;
}
}
private void OnDestroy()
{
ReleaseBallCameraTexture();
if ((Object)(object)_ballCamObj != (Object)null)
{
Object.Destroy((Object)(object)_ballCamObj);
_ballCamObj = null;
_ballCam = null;
}
}
}
namespace PiPBallCam
{
public static class MyPluginInfo
{
public const string PLUGIN_GUID = "SBG-PiPBallCam";
public const string PLUGIN_NAME = "Picture-in-Picture Ball Camera";
public const string PLUGIN_VERSION = "1.2.1";
}
}
namespace System.Runtime.CompilerServices
{
[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
internal sealed class IgnoresAccessChecksToAttribute : Attribute
{
public IgnoresAccessChecksToAttribute(string assemblyName)
{
}
}
}