using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using FMOD;
using FMODUnity;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using UnityEngine;
[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("CustomHitSound")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("CustomHitSound")]
[assembly: AssemblyTitle("CustomHitSound")]
[assembly: AssemblyVersion("1.0.0.0")]
[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;
}
}
}
namespace CustomHitSound
{
[BepInPlugin("com.pigpooteamelf.customhitsound", "CustomHitSound", "1.0.0")]
public class Plugin : BaseUnityPlugin
{
public const string PluginGuid = "com.pigpooteamelf.customhitsound";
public const string PluginName = "CustomHitSound";
public const string PluginVersion = "1.0.0";
internal static ManualLogSource Log;
private static string _soundPath;
private static float _lastPlayTime = -10f;
private static ConfigEntry<string> _targetClass;
private static ConfigEntry<string> _targetMethod;
private static ConfigEntry<float> _volume;
private static ConfigEntry<bool> _discoveryMode;
private static ConfigEntry<string> _discoveryKeywords;
private static ConfigEntry<string> _gameAssemblies;
private Harmony _harmony;
private static readonly Dictionary<string, int> CallCounts = new Dictionary<string, int>();
private const int MaxLogsPerMethod = 3;
private void Awake()
{
//IL_0081: Unknown result type (might be due to invalid IL or missing references)
//IL_008b: Expected O, but got Unknown
//IL_015d: Unknown result type (might be due to invalid IL or missing references)
//IL_0167: Expected O, but got Unknown
Log = ((BaseUnityPlugin)this).Logger;
_targetClass = ((BaseUnityPlugin)this).Config.Bind<string>("Hook", "TargetClass", "Hittable", "Full name of the game class whose method runs when you hit the ball.");
_targetMethod = ((BaseUnityPlugin)this).Config.Bind<string>("Hook", "TargetMethod", "HitWithGolfSwing", "Name of the method in TargetClass that runs when you hit the ball.");
_volume = ((BaseUnityPlugin)this).Config.Bind<float>("Sound", "Volume", 1f, new ConfigDescription("Hit sound volume.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 1f), Array.Empty<object>()));
_discoveryMode = ((BaseUnityPlugin)this).Config.Bind<bool>("Discovery", "Enabled", false, "Turn on to log game methods whose class names match the keywords below, to help find the hit method.");
_discoveryKeywords = ((BaseUnityPlugin)this).Config.Bind<string>("Discovery", "Keywords", "Swing,Hit,Shot,Stroke,Club,Putt", "Comma-separated words to look for in class names when Discovery is on.");
_gameAssemblies = ((BaseUnityPlugin)this).Config.Bind<string>("Discovery", "GameAssemblies", "GameAssembly,SharedAssembly", "The game's own code files (without .dll) to search.");
_soundPath = Path.Combine(Path.GetDirectoryName(((BaseUnityPlugin)this).Info.Location), "HitSound.wav");
if (File.Exists(_soundPath))
{
Log.LogInfo((object)("Found hit sound at " + _soundPath));
}
else
{
Log.LogError((object)("HitSound.wav not found next to the mod at: " + _soundPath));
}
_harmony = new Harmony("com.pigpooteamelf.customhitsound");
if (_discoveryMode.Value)
{
RunDiscovery();
}
PatchHitMethod();
}
public static void PlayHitSound()
{
if (!(Time.unscaledTime - _lastPlayTime < 0.15f))
{
_lastPlayTime = Time.unscaledTime;
FmodPlayer.Play(_soundPath, _volume.Value);
}
}
private void PatchHitMethod()
{
//IL_011f: Unknown result type (might be due to invalid IL or missing references)
//IL_012c: Expected O, but got Unknown
if (string.IsNullOrWhiteSpace(_targetClass.Value) || string.IsNullOrWhiteSpace(_targetMethod.Value))
{
Log.LogWarning((object)"No hit method set yet. Fill in [Hook] TargetClass and TargetMethod in the config file.");
return;
}
Type type = AccessTools.TypeByName(_targetClass.Value.Trim());
if (type == null)
{
Log.LogError((object)("Class '" + _targetClass.Value + "' not found in the game."));
return;
}
string name = _targetMethod.Value.Trim();
List<MethodInfo> list = (from m in AccessTools.GetDeclaredMethods(type)
where m.Name == name && !m.IsAbstract
select m).ToList();
if (list.Count == 0)
{
Log.LogError((object)("Method '" + name + "' not found in class '" + type.FullName + "'."));
return;
}
foreach (MethodInfo item in list)
{
_harmony.Patch((MethodBase)item, (HarmonyMethod)null, new HarmonyMethod(typeof(Plugin), "PlayHitSound", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
Log.LogInfo((object)("Hit sound hooked to " + type.FullName + "." + item.Name));
}
}
private void RunDiscovery()
{
//IL_007a: Unknown result type (might be due to invalid IL or missing references)
//IL_0080: Expected O, but got Unknown
string[] source = SplitList(_discoveryKeywords.Value);
HashSet<string> hashSet = new HashSet<string> { "Update", "FixedUpdate", "LateUpdate", "OnGUI", "ToString", "GetHashCode", "Equals" };
HarmonyMethod val = new HarmonyMethod(typeof(Plugin), "DiscoveryLogger", (Type[])null);
int num = 0;
string[] array = SplitList(_gameAssemblies.Value);
foreach (string asmName in array)
{
Assembly assembly = AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault((Assembly a) => a.GetName().Name == asmName);
if (assembly == null)
{
try
{
assembly = Assembly.Load(asmName);
}
catch (Exception ex)
{
Log.LogWarning((object)("Discovery: couldn't load " + asmName + ": " + ex.Message));
continue;
}
}
Type[] array2;
try
{
array2 = assembly.GetTypes();
}
catch (ReflectionTypeLoadException ex2)
{
array2 = ex2.Types.Where((Type type) => type != null).ToArray();
}
Type[] array3 = array2;
foreach (Type t in array3)
{
if (t.IsGenericTypeDefinition || t.IsInterface || !source.Any((string k) => t.Name.IndexOf(k, StringComparison.OrdinalIgnoreCase) >= 0))
{
continue;
}
MethodInfo[] methods = t.GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
foreach (MethodInfo methodInfo in methods)
{
if (!methodInfo.IsAbstract && !methodInfo.IsGenericMethodDefinition && !methodInfo.IsSpecialName && !hashSet.Contains(methodInfo.Name) && !methodInfo.Name.Contains("<") && methodInfo.GetMethodBody() != null)
{
try
{
_harmony.Patch((MethodBase)methodInfo, (HarmonyMethod)null, val, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
num++;
}
catch
{
}
}
}
}
}
Log.LogInfo((object)$"Discovery: watching {num} methods. Hit the ball, then check the log for [HIT?] lines.");
}
public static void DiscoveryLogger(MethodBase __originalMethod)
{
string text = __originalMethod.DeclaringType?.FullName + "." + __originalMethod.Name;
CallCounts.TryGetValue(text, out var value);
value++;
CallCounts[text] = value;
if (value <= 3)
{
Log.LogInfo((object)$"[HIT?] t={Time.time:0.00}s {text} (call #{value})");
}
}
private static string[] SplitList(string s)
{
return (from k in s.Split(new char[1] { ',' }, StringSplitOptions.RemoveEmptyEntries)
select k.Trim() into k
where k.Length > 0
select k).ToArray();
}
}
internal static class FmodPlayer
{
private static Sound _sound;
private static bool _loaded;
private static bool _failed;
public static void Play(string path, float volume)
{
//IL_0009: Unknown result type (might be due to invalid IL or missing references)
//IL_000e: Unknown result type (might be due to invalid IL or missing references)
//IL_008f: Unknown result type (might be due to invalid IL or missing references)
//IL_0097: Unknown result type (might be due to invalid IL or missing references)
//IL_009c: Unknown result type (might be due to invalid IL or missing references)
//IL_00a0: Unknown result type (might be due to invalid IL or missing references)
//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
//IL_00a6: 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_0028: Unknown result type (might be due to invalid IL or missing references)
//IL_002a: Unknown result type (might be due to invalid IL or missing references)
//IL_00c8: 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_00b3: Unknown result type (might be due to invalid IL or missing references)
//IL_0062: Unknown result type (might be due to invalid IL or missing references)
//IL_0038: Unknown result type (might be due to invalid IL or missing references)
if (_failed)
{
return;
}
try
{
System coreSystem = RuntimeManager.CoreSystem;
if (!_loaded)
{
RESULT val = ((System)(ref coreSystem)).createSound(path, (MODE)256, ref _sound);
if ((int)val != 0)
{
Plugin.Log.LogError((object)$"FMOD couldn't load the hit sound: {val}");
_failed = true;
return;
}
_loaded = true;
uint num = default(uint);
((Sound)(ref _sound)).getLength(ref num, (TIMEUNIT)1);
Plugin.Log.LogInfo((object)$"Hit sound loaded into FMOD ({(float)num / 1000f:0.00}s).");
}
ChannelGroup val2 = default(ChannelGroup);
((System)(ref coreSystem)).getMasterChannelGroup(ref val2);
Channel val4 = default(Channel);
RESULT val3 = ((System)(ref coreSystem)).playSound(_sound, val2, true, ref val4);
if ((int)val3 != 0)
{
Plugin.Log.LogError((object)$"FMOD couldn't play the hit sound: {val3}");
return;
}
((Channel)(ref val4)).setVolume(volume);
((Channel)(ref val4)).setPaused(false);
}
catch (Exception arg)
{
Plugin.Log.LogError((object)$"Hit sound error: {arg}");
_failed = true;
}
}
}
}