Please disclose if any significant portion of your mod was created using AI tools by adding the 'AI Generated' category. Failing to do so may result in the mod being removed from Thunderstore.
Decompiled source of TerretaSoundsRepo v0.5.0
REPO_TerretaSoundsRepo.dll
Decompiled 2 weeks agousing System; using System.Collections; 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 System.Text; using BepInEx; using BepInEx.Configuration; using BepInEx.Logging; using HarmonyLib; using Microsoft.CodeAnalysis; using TerretaSoundsRepo.Core; using TerretaSoundsRepo.Modules; using UnityEngine; using UnityEngine.SceneManagement; [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("REPO_TerretaSoundsRepo")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("0.5.0.0")] [assembly: AssemblyInformationalVersion("0.5.0+5e1bd47c38e71888de28e0e933b2ccd9f22c8406")] [assembly: AssemblyProduct("REPO_TerretaSoundsRepo")] [assembly: AssemblyTitle("REPO_TerretaSoundsRepo")] [assembly: AssemblyVersion("0.5.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 TerretaSoundsRepo { internal static class BuildInfo { public const string Version = "0.5.0"; } internal static class GameApi { private static readonly Dictionary<(Type, string), MemberInfo> Cache = new Dictionary<(Type, string), MemberInfo>(); private static bool _resolved; private static Component _localPlayer; private static Transform _localPlayerEyes; private static float _nextLocalPlayerLookup; private static MethodInfo _onScreen; private static bool _onScreenResolved; private const int SharedWindowMs = 250; private static Type _photonViewType; private static bool _photonViewResolved; private static PropertyInfo _serverTimestamp; private static bool _serverTimestampResolved; private static MethodInfo _isMultiplayer; private static bool _isMultiplayerResolved; public static Type Hunter { get; private set; } public static Type Sound { get; private set; } public static Type EnemyParent { get; private set; } public static Type Player { get; private set; } public static void Resolve() { if (!_resolved) { _resolved = true; Hunter = TypeByName("EnemyHunter"); Sound = TypeByName("Sound"); EnemyParent = TypeByName("EnemyParent"); Player = TypeByName("PlayerAvatar"); TerretaSoundsPlugin.LogInfo("[TerretaSounds] game types → EnemyHunter=" + ((Hunter != null) ? "OK" : "NO") + " · Sound=" + ((Sound != null) ? "OK" : "NO") + " · EnemyParent=" + ((EnemyParent != null) ? "OK" : "NO") + " · PlayerAvatar=" + ((Player != null) ? "OK" : "NO")); } } public static Type TypeByName(string name) { try { Type type = AccessToolsType(name); if (type != null) { return type; } Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies(); foreach (Assembly assembly in assemblies) { try { type = assembly.GetType(name, throwOnError: false); if (type != null) { return type; } } catch { } } } catch (Exception ex) { TerretaSoundsPlugin.LogWarn("[TerretaSounds] looking up type " + name + ": " + ex.Message); } return null; } private static Type AccessToolsType(string name) { try { return AccessTools.TypeByName(name); } catch { return null; } } public static object Get(object instance, string name) { if (instance == null || string.IsNullOrEmpty(name)) { return null; } MemberInfo memberInfo = FindMember(instance.GetType(), name); if (memberInfo == null) { return null; } try { if (memberInfo is FieldInfo fieldInfo) { return fieldInfo.GetValue(instance); } if (memberInfo is PropertyInfo { CanRead: not false } propertyInfo) { return propertyInfo.GetValue(instance); } } catch { } return null; } private static MemberInfo FindMember(Type type, string name) { (Type, string) key = (type, name); if (Cache.TryGetValue(key, out var value)) { return value; } MemberInfo memberInfo = null; Type type2 = type; while (type2 != null && memberInfo == null) { try { memberInfo = type2.GetField(name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); if ((object)memberInfo == null) { memberInfo = type2.GetProperty(name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); } } catch { } type2 = type2.BaseType; } Cache[key] = memberInfo; return memberInfo; } public static object GetByNameParts(object instance, string typePart, string namePart) { List<KeyValuePair<string, object>> soundFields = GetSoundFields(instance, new string[1] { namePart }); if (soundFields.Count <= 0) { return null; } return soundFields[0].Value; } public static List<KeyValuePair<string, object>> GetSoundFields(object instance, IReadOnlyList<string> nameParts) { List<KeyValuePair<string, object>> list = new List<KeyValuePair<string, object>>(); if (instance == null || nameParts == null || nameParts.Count == 0) { return list; } foreach (KeyValuePair<string, object> item in AllSoundFields(instance)) { if (ContainsAnyPart(item.Key, nameParts)) { list.Add(item); } } return list; } public static List<KeyValuePair<string, object>> AllSoundFields(object instance) { List<KeyValuePair<string, object>> list = new List<KeyValuePair<string, object>>(); if (instance == null) { return list; } for (Type type = instance.GetType(); type != null; type = type.BaseType) { FieldInfo[] fields; try { fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); } catch { continue; } FieldInfo[] array = fields; foreach (FieldInfo fieldInfo in array) { if ((fieldInfo.FieldType?.Name ?? string.Empty).IndexOf("Sound", StringComparison.OrdinalIgnoreCase) < 0) { continue; } try { object value = fieldInfo.GetValue(instance); if (value != null) { list.Add(new KeyValuePair<string, object>(fieldInfo.Name, value)); } } catch { } } } return list; } private static bool ContainsAnyPart(string name, IReadOnlyList<string> parts) { for (int i = 0; i < parts.Count; i++) { string value = parts[i]; if (!string.IsNullOrEmpty(value) && name.IndexOf(value, StringComparison.OrdinalIgnoreCase) >= 0) { return true; } } return false; } public static List<object> EnemyCandidates(object character) { List<object> list = new List<object>(); if (character == null) { return list; } list.Add(character); object obj = Get(character, "enemy"); if (IsUsable(obj, character)) { list.Add(obj); return list; } for (Type type = character.GetType(); type != null; type = type.BaseType) { FieldInfo[] fields; try { fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); } catch { continue; } FieldInfo[] array = fields; foreach (FieldInfo fieldInfo in array) { string text = fieldInfo.FieldType?.Name ?? string.Empty; if (text.IndexOf("Enemy", StringComparison.OrdinalIgnoreCase) >= 0 && text.IndexOf("Parent", StringComparison.OrdinalIgnoreCase) < 0) { object value; try { value = fieldInfo.GetValue(character); } catch { continue; } if (IsUsable(value, character)) { list.Add(value); } } } if (list.Count > 1) { break; } } return list; } public static List<object> SoundCandidates(object character, IReadOnlyList<Type> excludedTypes = null) { List<object> list = new List<object>(); AddUnique(list, character); AddUnique(list, Get(character, "enemy")); AddUnique(list, Get(character, "Enemy")); Component val = (Component)((character is Component) ? character : null); if (val != null) { try { MonoBehaviour[] componentsInChildren = val.gameObject.GetComponentsInChildren<MonoBehaviour>(true); foreach (MonoBehaviour value in componentsInChildren) { if (!IsExcludedType(value, excludedTypes)) { AddUnique(list, value); } } } catch { } try { Transform parent = val.transform.parent; if ((Object)(object)parent != (Object)null) { MonoBehaviour[] componentsInChildren = ((Component)parent).GetComponents<MonoBehaviour>(); foreach (MonoBehaviour value2 in componentsInChildren) { if (!IsExcludedType(value2, excludedTypes)) { AddUnique(list, value2); } } } } catch { } } return list; } private static bool IsExcludedType(object value, IReadOnlyList<Type> excludedTypes) { if (excludedTypes == null || excludedTypes.Count == 0) { return false; } Type type = value.GetType(); for (int i = 0; i < excludedTypes.Count; i++) { if (excludedTypes[i].IsAssignableFrom(type)) { return true; } } return false; } private static void AddUnique(List<object> list, object value) { Object val = (Object)((value is Object) ? value : null); if ((val != null && val == (Object)null) || value == null) { return; } for (int i = 0; i < list.Count; i++) { if (list[i] == value) { return; } } list.Add(value); } private static bool IsUsable(object value, object character) { if (value != null) { return value != character; } return false; } public static Transform TransformOf(object instance) { if (instance == null) { return null; } try { Component val = (Component)((instance is Component) ? instance : null); if (val != null) { return val.transform; } GameObject val2 = (GameObject)((instance is GameObject) ? instance : null); if (val2 != null) { return val2.transform; } } catch { } return null; } public static Transform FollowTransformOf(object character) { if (character == null) { return null; } try { object obj = Get(character, "CenterTransform") ?? Get(character, "centerTransform"); Transform val = (Transform)((obj is Transform) ? obj : null); if (val != null) { return val; } object instance = Get(character, "enemy") ?? Get(character, "Enemy"); object obj2 = Get(instance, "CenterTransform") ?? Get(instance, "centerTransform"); Transform val2 = (Transform)((obj2 is Transform) ? obj2 : null); if (val2 != null) { return val2; } Transform val3 = TransformOf(instance); if ((Object)(object)val3 != (Object)null) { return val3; } return TransformOf(character); } catch { } return null; } public static Vector3 PositionOf(object character) { //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Unknown result type (might be due to invalid IL or missing references) Transform val = FollowTransformOf(character); if ((Object)(object)val == (Object)null) { return Vector3.zero; } try { return val.position; } catch { return Vector3.zero; } } public static int PlayerPositions(List<Vector3> buffer) { //IL_005f: Unknown result type (might be due to invalid IL or missing references) buffer.Clear(); if (Player == null) { Player = TypeByName("PlayerAvatar"); } if (Player != null) { try { Object[] array = FindObjects(Player); if (array != null) { Object[] array2 = array; foreach (Object obj in array2) { Component val = (Component)(object)((obj is Component) ? obj : null); if (val != null && (Object)(object)val != (Object)null) { buffer.Add(val.transform.position); } } } } catch { } } if (buffer.Count == 0) { CollectFromGameDirector(buffer); } return buffer.Count; } private static void CollectFromGameDirector(List<Vector3> buffer) { //IL_008a: Unknown result type (might be due to invalid IL or missing references) try { Type type = TypeByName("GameDirector"); if (type == null) { return; } object obj = GetStatic(type, "instance") ?? GetStatic(type, "Instance"); if (obj == null || !((Get(obj, "PlayerList") ?? Get(obj, "playerList")) is IEnumerable enumerable)) { return; } foreach (object item in enumerable) { Component val = (Component)((item is Component) ? item : null); if (val != null && (Object)(object)val != (Object)null) { buffer.Add(val.transform.position); } } } catch { } } private static object GetStatic(Type type, string name) { try { FieldInfo field = type.GetField(name, BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); if (field != null) { return field.GetValue(null); } PropertyInfo property = type.GetProperty(name, BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic); if (property != null && property.CanRead) { return property.GetValue(null); } } catch { } return null; } private static Component LocalPlayer() { if ((Object)(object)_localPlayer != (Object)null) { return _localPlayer; } float unscaledTime = Time.unscaledTime; if (unscaledTime < _nextLocalPlayerLookup) { return null; } _nextLocalPlayerLookup = unscaledTime + 2f; if (Player == null) { Player = TypeByName("PlayerAvatar"); } if (Player == null) { return null; } try { Object[] array = FindObjects(Player); if (array != null) { Object[] array2 = array; bool flag = default(bool); foreach (Object obj in array2) { Component val = (Component)(object)((obj is Component) ? obj : null); if (val != null && !((Object)(object)val == (Object)null)) { object obj2 = Get(val, "isLocal"); int num; if (obj2 is bool) { flag = (bool)obj2; num = 1; } else { num = 0; } if (((uint)num & (flag ? 1u : 0u)) != 0) { _localPlayer = val; _localPlayerEyes = null; return val; } } } } } catch { } try { Type type = TypeByName("GameDirector"); object instance = ((type == null) ? null : (GetStatic(type, "instance") ?? GetStatic(type, "Instance"))); if ((Get(instance, "PlayerList") ?? Get(instance, "playerList")) is IEnumerable enumerable) { bool flag2 = default(bool); foreach (object item in enumerable) { Component val2 = (Component)((item is Component) ? item : null); if (val2 != null && !((Object)(object)val2 == (Object)null)) { object obj2 = Get(val2, "isLocal"); int num2; if (obj2 is bool) { flag2 = (bool)obj2; num2 = 1; } else { num2 = 0; } if (((uint)num2 & (flag2 ? 1u : 0u)) != 0) { _localPlayer = val2; _localPlayerEyes = null; return val2; } } } } } catch { } return null; } public static bool TryGetLocalPlayerPosition(out Vector3 position) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0066: Unknown result type (might be due to invalid IL or missing references) //IL_006b: Unknown result type (might be due to invalid IL or missing references) position = Vector3.zero; Component val = LocalPlayer(); if ((Object)(object)val == (Object)null) { return false; } try { Transform val2 = _localPlayerEyes; if ((Object)(object)val2 == (Object)null) { val2 = (_localPlayerEyes = TransformOf(Get(Get(val, "PlayerVisionTarget"), "VisionTransform")) ?? TransformOf(val)); } if ((Object)(object)val2 == (Object)null) { return false; } position = val2.position; return true; } catch { _localPlayer = null; _localPlayerEyes = null; return false; } } public static float LocalPlayerDistanceTo(Vector3 position) { //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) if (!TryGetLocalPlayerPosition(out var position2)) { return -1f; } return Vector3.Distance(position2, position); } public static bool IsOnScreen(Vector3 position) { //IL_0058: Unknown result type (might be due to invalid IL or missing references) if (!_onScreenResolved) { _onScreenResolved = true; try { _onScreen = TypeByName("SemiFunc")?.GetMethod("OnScreen", BindingFlags.Static | BindingFlags.Public); } catch { _onScreen = null; } } if (_onScreen == null) { return true; } try { return (bool)_onScreen.Invoke(null, new object[3] { position, 0.1f, 0.1f }); } catch { return true; } } public static bool TrySharedSeed(object character, out int seed) { seed = 0; if (!IsMultiplayer()) { return false; } int num = ViewIdOf(character); if (num == 0) { return false; } int num2 = SharedClockMilliseconds(); if (num2 <= 0) { return false; } seed = Mix(num, num2 / 250); return true; } private static bool IsMultiplayer() { if (!_isMultiplayerResolved) { _isMultiplayerResolved = true; try { _isMultiplayer = TypeByName("GameManager")?.GetMethod("Multiplayer", BindingFlags.Static | BindingFlags.Public); } catch { _isMultiplayer = null; } } if (_isMultiplayer == null) { return true; } try { return (bool)_isMultiplayer.Invoke(null, null); } catch { return true; } } private static int ViewIdOf(object character) { if (character == null) { return 0; } object obj = Get(character, "photonView") ?? Get(character, "PhotonView"); if (obj == null) { object instance = Get(character, "enemy") ?? Get(character, "Enemy"); obj = Get(instance, "photonView") ?? Get(instance, "PhotonView"); } if (obj == null) { obj = FindPhotonView(character); } object obj2 = Get(obj, "ViewID"); if (obj2 is int) { return (int)obj2; } return 0; } private static object FindPhotonView(object character) { Component val = (Component)((character is Component) ? character : null); if (val == null) { return null; } if (!_photonViewResolved) { _photonViewResolved = true; try { _photonViewType = TypeByName("Photon.Pun.PhotonView") ?? TypeByName("PhotonView"); } catch { _photonViewType = null; } } if (_photonViewType == null) { return null; } try { return val.GetComponentInParent(_photonViewType); } catch { return null; } } private static int SharedClockMilliseconds() { if (!_serverTimestampResolved) { _serverTimestampResolved = true; try { _serverTimestamp = (TypeByName("Photon.Pun.PhotonNetwork") ?? TypeByName("PhotonNetwork"))?.GetProperty("ServerTimestamp", BindingFlags.Static | BindingFlags.Public); } catch { _serverTimestamp = null; } } if (_serverTimestamp != null) { try { if (_serverTimestamp.GetValue(null) is int num && num > 0) { return num; } } catch { } } try { return (int)(Time.unscaledTime * 1000f); } catch { return 0; } } private static int Mix(int a, int b) { int num = (a * -1640531535) ^ b; int num2 = (num ^ (num >>> 16)) * 2146121005; int num3 = (num2 ^ (num2 >>> 15)) * -2073254261; return num3 ^ (num3 >>> 16); } private static Object[] FindObjects(Type type) { Type typeFromHandle = typeof(Object); string[] array = new string[2] { "FindObjectsByType", "FindObjectsOfType" }; foreach (string name in array) { try { MethodInfo method = typeFromHandle.GetMethod(name, BindingFlags.Static | BindingFlags.Public, null, new Type[1] { typeof(Type) }, null); if (method != null) { return method.Invoke(null, new object[1] { type }) as Object[]; } } catch { } } return null; } } internal static class ModuleHooks { public static void Apply(Harmony harmony) { //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Expected O, but got Unknown //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_0038: Expected O, but got Unknown HarmonyMethod postfix = new HarmonyMethod(AccessTools.Method(typeof(ModuleHooks), "OnRegister", (Type[])null, (Type[])null)); HarmonyMethod postfix2 = new HarmonyMethod(AccessTools.Method(typeof(ModuleHooks), "OnAttack", (Type[])null, (Type[])null)); int num = 0; bool flag = false; HashSet<string> patched = new HashSet<string>(StringComparer.Ordinal); foreach (ModuleState item in ModuleRegistry.All) { foreach (string registerMethod in item.Module.RegisterMethods) { Patch(harmony, item, item.GameType, registerMethod, postfix, required: false, patched); } foreach (string attackMethod in item.Module.AttackMethods) { Patch(harmony, item, item.GameType, attackMethod, postfix2, required: true, patched); } if (item.Module is ICompanionModule { CompanionRegisterMethods: { } companionRegisterMethods }) { foreach (Type companionType in item.CompanionTypes) { foreach (string item2 in companionRegisterMethods) { Patch(harmony, item, companionType, item2, postfix, required: false, patched); } } } flag |= item.Config.UseSoundHook && (item.Module.AttackSoundFields.Count > 0 || item.Module.IsFallback || item.Module.AttackOnly || item.CompanionTypes.Count > 0); } if (flag) { num = PatchSoundPlay(harmony); } TerretaSoundsPlugin.LogInfo($"[TerretaSounds] hooks ready · modules={ModuleRegistry.All.Count} " + $"· Sound hooks x{num}"); } private static void Patch(Harmony harmony, ModuleState state, Type type, string methodName, HarmonyMethod postfix, bool required, HashSet<string> patched) { try { MethodInfo methodInfo = AccessTools.Method(type, methodName, (Type[])null, (Type[])null); if (methodInfo == null) { string message = "[TerretaSounds] " + state.Module.Id + ": cannot find " + type.Name + "." + methodName + " in this game version."; if (required) { TerretaSoundsPlugin.LogWarn(message); } else { TerretaSoundsPlugin.LogInfo(message); } } else { string item = type.FullName + "." + methodName; if (patched.Add(item)) { harmony.Patch((MethodBase)methodInfo, (HarmonyMethod)null, postfix, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); TerretaSoundsPlugin.LogInfo("[TerretaSounds] " + state.Module.Id + ": hook OK → " + type.Name + "." + methodName); } } } catch (Exception ex) { TerretaSoundsPlugin.LogWarn("[TerretaSounds] " + state.Module.Id + ": could not patch " + type.Name + "." + methodName + ": " + ex.Message); } } private static int PatchSoundPlay(Harmony harmony) { //IL_003a: Unknown result type (might be due to invalid IL or missing references) //IL_0040: Expected O, but got Unknown //IL_0056: Unknown result type (might be due to invalid IL or missing references) //IL_005d: Expected O, but got Unknown Type type = GameApi.TypeByName("Sound"); if (type == null) { TerretaSoundsPlugin.LogInfo("[TerretaSounds] Sound type not found: no fallback hook."); return 0; } int num = 0; int num2 = 0; try { HarmonyMethod val = new HarmonyMethod(AccessTools.Method(typeof(ModuleHooks), "OnSoundPlay", (Type[])null, (Type[])null)); HarmonyMethod val2 = new HarmonyMethod(AccessTools.Method(typeof(ModuleHooks), "OnSoundPlayLoop", (Type[])null, (Type[])null)); MethodInfo[] methods = type.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); foreach (MethodInfo methodInfo in methods) { if (methodInfo.IsGenericMethod || methodInfo.IsAbstract) { continue; } if (methodInfo.Name == "PlayLoop") { ParameterInfo[] parameters = methodInfo.GetParameters(); if (parameters.Length == 0 || parameters[0].ParameterType != typeof(bool)) { continue; } } HarmonyMethod val3; if (methodInfo.Name == "Play") { val3 = val; } else { if (!(methodInfo.Name == "PlayLoop")) { continue; } val3 = val2; } try { harmony.Patch((MethodBase)methodInfo, (HarmonyMethod)null, val3, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); if (methodInfo.Name == "Play") { num++; } else { num2++; } } catch (Exception ex) { TerretaSoundsPlugin.LogWarn("[TerretaSounds] could not patch Sound." + methodInfo.Name + "(" + Describe(methodInfo) + "): " + ex.Message); } } TerretaSoundsPlugin.LogInfo($"[TerretaSounds] Sound.Play x{num} · Sound.PlayLoop x{num2}"); } catch (Exception ex2) { TerretaSoundsPlugin.LogWarn("[TerretaSounds] could not patch Sound.Play: " + ex2.Message); } return num + num2; } private static string Describe(MethodInfo method) { ParameterInfo[] parameters = method.GetParameters(); string[] array = new string[parameters.Length]; for (int i = 0; i < parameters.Length; i++) { array[i] = parameters[i].ParameterType.Name; } return string.Join(", ", array); } private static void OnRegister(object __instance, MethodBase __originalMethod) { Guard("register", delegate { ModuleRegistry.OnRegistered(__instance, __originalMethod); }); } private static void OnAttack(object __instance, MethodBase __originalMethod) { Guard("attack", delegate { ModuleRegistry.OnAttacked(__instance, __originalMethod); }); } private static void OnSoundPlay(object __instance) { Guard("Sound.Play", delegate { ModuleRegistry.OnSoundPlayed(__instance); }); } private static void OnSoundPlayLoop(object __instance, object[] __args) { if (__args == null || __args.Length == 0) { return; } object obj = __args[0]; if (obj is bool) { bool playing = (bool)obj; Guard("Sound.PlayLoop", delegate { ModuleRegistry.OnSoundLoopPlayed(__instance, playing); }); } } private static void Guard(string hook, Action action) { try { action(); } catch (Exception ex) { TerretaSoundsPlugin.LogWarn("[TerretaSounds] error in " + hook + ": " + ex.Message); } } } [BepInPlugin("com.Terreta.REPO.Sounds", "TerretaSoundsRepo", "0.5.0")] public sealed class TerretaSoundsPlugin : BaseUnityPlugin { public const string Guid = "com.Terreta.REPO.Sounds"; public const string Name = "TerretaSoundsRepo"; public const string Version = "0.5.0"; internal const string SfxFolderName = "TerretaSoundsRepo"; internal static ManualLogSource Log; internal static TerretaSoundsPlugin Instance; internal static ConfigEntry<float> CfgGlobalVolume; internal static ConfigEntry<float> CfgMinDistance; internal static ConfigEntry<float> CfgMaxDistance; internal static ConfigEntry<float> CfgGlobalCooldown; internal static ConfigEntry<float> CfgSameSoundCooldown; internal static ConfigEntry<bool> CfgVerbose; internal static SfxPlayer Player; private Harmony _harmony; private const int AudioSchemaVersion = 2; internal static bool Verbose => CfgVerbose?.Value ?? false; internal static float Volume => CfgGlobalVolume?.Value ?? 1f; internal static float SameSoundCooldown => Mathf.Max(0f, CfgSameSoundCooldown?.Value ?? 5f); private void Awake() { //IL_0113: Unknown result type (might be due to invalid IL or missing references) //IL_011d: Expected O, but got Unknown Log = ((BaseUnityPlugin)this).Logger; Instance = this; BindGlobalConfig(); GameApi.Resolve(); Player = SfxPlayer.Create(CfgMinDistance.Value, CfgMaxDistance.Value, CfgGlobalCooldown.Value); LogInfo("[TerretaSounds] audio channel: one voice at a time · global cooldown " + $"{CfgGlobalCooldown.Value:0.##}s · same-sound cooldown " + $"{CfgSameSoundCooldown.Value:0.##}s · hearing " + $"{CfgMinDistance.Value:0.#}-{CfgMaxDistance.Value:0.#} m per client " + $"· pool {12}"); string directoryName = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); int num = ModuleRegistry.Initialise(ModuleCatalog.Create(), ((BaseUnityPlugin)this).Config, directoryName, "TerretaSoundsRepo", Volume); if (num == 0) { LogError("[TerretaSounds] no active modules. Check that the game types exist and that there are WAVs in 'BepInEx/plugins/TerretaSoundsRepo/'."); return; } _harmony = new Harmony("com.Terreta.REPO.Sounds"); ModuleHooks.Apply(_harmony); foreach (ModuleState item in ModuleRegistry.All) { LogInfo("[TerretaSounds] " + item.Module.DisplayName + " (" + item.GameType.Name + "): " + item.Module.Sounds.Describe()); } LogInfo("[TerretaSounds] v0.5.0 loaded on R.E.P.O. " + SafeGameVersion() + " " + $"· {num} character module(s)"); } private void BindGlobalConfig() { CfgGlobalVolume = ((BaseUnityPlugin)this).Config.Bind<float>("Audio", "Volume", 1f, "Default volume for the characters. Each one can be tuned in its own section; the clips are already normalized to -1 dBFS."); CfgMinDistance = ((BaseUnityPlugin)this).Config.Bind<float>("Audio", "MinDistance", 3f, "Distance at which a sound plays at 100 %."); CfgMaxDistance = ((BaseUnityPlugin)this).Config.Bind<float>("Audio", "MaxDistance", 45f, "Distance at which a sound can no longer be heard. Nothing is played when this client's player is beyond it, so lower it to keep voices close and stop hearing monsters from the other side of the map. Off-screen voices (behind you or behind a wall) fade out at 55 % of this value and play quieter."); CfgGlobalCooldown = ((BaseUnityPlugin)this).Config.Bind<float>("Audio", "GlobalCooldown", 2f, "Minimum seconds between two sounds, counting every character. A clip always blocks the channel until it finishes (plus a 0.35 s gap), so sounds never overlap. Raise it for less chatter, lower it to hear more phrases."); CfgSameSoundCooldown = ((BaseUnityPlugin)this).Config.Bind<float>("Audio", "SameSoundCooldown", 5f, "Minimum seconds before the SAME enemy sound can trigger another phrase (attack-only characters: APM wildcard, Cleanup Crew, Headman). Some enemies repeat one sound while an action lasts (the Tick sucks about once per second) and in multiplayer the same attack can reach this client twice (local call + network RPC). The first play speaks; the repeats are ignored. 0 disables the filter."); CfgVerbose = ((BaseUnityPlugin)this).Config.Bind<bool>("Debug", "VerboseLog", false, "Writes every played sound to the console."); ConfigEntry<int> val = ((BaseUnityPlugin)this).Config.Bind<int>("Audio", "ConfigSchemaVersion", 1, "Internal: do not edit. Used to migrate values from older versions."); if (val.Value < 2) { CfgMinDistance.Value = 3f; CfgMaxDistance.Value = 45f; val.Value = 2; try { ((BaseUnityPlugin)this).Config.Save(); } catch { } LogInfo("[TerretaSounds] audio config migrated: hearing range 3-45 m (voices no longer reach players far from the enemy)."); } } internal static bool TryPlay(AudioClip clip, object character, float volume) { string reason; return TryPlay(clip, character, volume, out reason); } internal static bool TryPlay(AudioClip clip, object character, float volume, out string reason) { //IL_0035: Unknown result type (might be due to invalid IL or missing references) reason = null; if ((Object)(object)clip == (Object)null) { reason = "no clip"; return false; } try { if ((Object)(object)Player == (Object)null) { reason = "no player"; return false; } return Player.TryPlay(clip, GameApi.PositionOf(character), volume, GameApi.FollowTransformOf(character), out reason); } catch (Exception ex) { LogWarn("[TerretaSounds] could not play '" + ((Object)clip).name + "': " + ex.Message); reason = ex.Message; return false; } } internal static void LogInfo(string message) { SafeLog(delegate(ManualLogSource log) { log.LogInfo((object)message); }); } internal static void LogWarn(string message) { SafeLog(delegate(ManualLogSource log) { log.LogWarning((object)message); }); } internal static void LogError(string message) { SafeLog(delegate(ManualLogSource log) { log.LogError((object)message); }); } private static void SafeLog(Action<ManualLogSource> write) { try { if (Log != null) { write(Log); } } catch { } } private static string SafeGameVersion() { try { return Application.version; } catch { return "unknown"; } } private void Update() { try { ModuleRegistry.Tick(); } catch (Exception ex) { LogWarn("[TerretaSounds] polling failed: " + ex.Message); } } private void OnDestroy() { try { Harmony harmony = _harmony; if (harmony != null) { harmony.UnpatchSelf(); } } catch { } } } public sealed class SfxPlayer : MonoBehaviour { public const int PoolSize = 12; private const float GapSeconds = 0.35f; private const float OffscreenVolume = 0.6f; private const float OffscreenRange = 0.55f; private readonly List<AudioSource> _sources = new List<AudioSource>(); private readonly List<Transform> _followers = new List<Transform>(); private int _cursor; private float _minDistance = 3f; private float _maxDistance = 90f; private float _busyUntil; private float _globalCooldown = 2f; private static SfxPlayer _instance; public static SfxPlayer Create(float minDistance, float maxDistance, float globalCooldown) { //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Expected O, but got Unknown if ((Object)(object)_instance != (Object)null) { TerretaSoundsPlugin.LogWarn("[TerretaSounds] audio player already exists: reusing it so voices cannot overlap."); return _instance; } GameObject val = new GameObject("TerretaSoundsSfx"); Object.DontDestroyOnLoad((Object)val); SfxPlayer sfxPlayer = val.AddComponent<SfxPlayer>(); sfxPlayer._minDistance = Mathf.Max(0.1f, minDistance); sfxPlayer._maxDistance = Mathf.Max(sfxPlayer._minDistance + 0.1f, maxDistance); sfxPlayer._globalCooldown = Mathf.Max(0f, globalCooldown); sfxPlayer.BuildPool(); _instance = sfxPlayer; return sfxPlayer; } private void BuildPool() { //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Unknown result type (might be due to invalid IL or missing references) for (int i = 0; i < 12; i++) { GameObject val = new GameObject($"Voice{i:00}"); val.transform.SetParent(((Component)this).transform, false); AudioSource val2 = val.AddComponent<AudioSource>(); val2.playOnAwake = false; val2.loop = false; val2.spatialBlend = 1f; val2.rolloffMode = (AudioRolloffMode)1; val2.minDistance = _minDistance; val2.maxDistance = _maxDistance; val2.dopplerLevel = 0f; val2.spread = 0f; val2.priority = 16; _sources.Add(val2); _followers.Add(null); } } public bool TryPlay(AudioClip clip, Vector3 position, float volume, Transform follow, out string reason) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_0051: Unknown result type (might be due to invalid IL or missing references) //IL_00e6: Unknown result type (might be due to invalid IL or missing references) reason = null; if ((Object)(object)clip == (Object)null || _sources.Count == 0) { reason = "no clip"; return false; } float num = GameApi.LocalPlayerDistanceTo(position); if (num >= 0f && num > _maxDistance) { reason = $"out of range ({num:0} m)"; return false; } bool flag = GameApi.IsOnScreen(position); if (!flag && num >= 0f && num > _maxDistance * 0.55f) { reason = $"out of range behind geometry ({num:0} m)"; return false; } float unscaledTime = Time.unscaledTime; if (unscaledTime < _busyUntil || AnySourcePlaying()) { reason = "channel busy"; return false; } AudioSource val = NextSource(); int num2 = _sources.IndexOf(val); if (num2 >= 0 && num2 < _followers.Count) { _followers[num2] = follow; } ((Component)val).transform.position = position; val.clip = clip; val.volume = Mathf.Clamp01(volume) * (flag ? 1f : 0.6f); val.minDistance = _minDistance; val.maxDistance = (flag ? _maxDistance : (_maxDistance * 0.55f)); val.Play(); _busyUntil = unscaledTime + Mathf.Max(clip.length + 0.35f, _globalCooldown); return true; } private void LateUpdate() { //IL_006a: Unknown result type (might be due to invalid IL or missing references) //IL_0048: Unknown result type (might be due to invalid IL or missing references) for (int i = 0; i < _sources.Count && i < _followers.Count; i++) { AudioSource val = _sources[i]; if (!val.isPlaying) { _followers[i] = null; continue; } Transform val2 = _followers[i]; if ((Object)(object)val2 != (Object)null) { try { ((Component)val).transform.position = val2.position; } catch { _followers[i] = null; } } float num = GameApi.LocalPlayerDistanceTo(((Component)val).transform.position); if (num >= 0f && num > val.maxDistance) { val.Stop(); _followers[i] = null; } } } private bool AnySourcePlaying() { foreach (AudioSource source in _sources) { if (source.isPlaying) { return true; } } return false; } private AudioSource NextSource() { foreach (AudioSource source in _sources) { if (!source.isPlaying) { return source; } } AudioSource obj = _sources[_cursor % _sources.Count]; _cursor = (_cursor + 1) % _sources.Count; obj.Stop(); return obj; } public void StopAll() { for (int i = 0; i < _sources.Count; i++) { _sources[i].Stop(); if (i < _followers.Count) { _followers[i] = null; } } } private void OnDestroy() { StopAll(); if (_instance == this) { _instance = null; } } } internal static class WavLoader { public static AudioClip Load(string clipName, byte[] bytes) { if (bytes == null || bytes.Length < 44) { throw new InvalidDataException("WAV too short."); } if (!Matches(bytes, 0, "RIFF") || !Matches(bytes, 8, "WAVE")) { throw new InvalidDataException("Invalid RIFF/WAVE header."); } int num = 0; int num2 = 0; int num3 = 0; int num4 = 0; int num5 = -1; int num6 = 0; int num7 = 12; while (num7 + 8 <= bytes.Length) { string text = Encoding.ASCII.GetString(bytes, num7, 4); int num8 = BitConverter.ToInt32(bytes, num7 + 4); int num9 = num7 + 8; if (num8 < 0) { break; } if (text == "fmt " && num9 + 16 <= bytes.Length) { num4 = BitConverter.ToInt16(bytes, num9); num = BitConverter.ToInt16(bytes, num9 + 2); num2 = BitConverter.ToInt32(bytes, num9 + 4); num3 = BitConverter.ToInt16(bytes, num9 + 14); } else if (text == "data") { num5 = num9; num6 = Math.Min(num8, bytes.Length - num9); break; } num7 = num9 + num8 + num8 % 2; } if (num <= 0 || num2 <= 0 || num3 <= 0 || num5 < 0 || num6 <= 0) { throw new InvalidDataException("WAV without a valid fmt/data chunk."); } int num10 = num3 / 8; if (num10 <= 0) { throw new InvalidDataException($"Unsupported bits per sample: {num3}."); } int num11 = num6 / (num10 * num); if (num11 <= 0) { throw new InvalidDataException("WAV without samples."); } float[] array = new float[num11 * num]; if (num4 == 3 && num3 == 32) { for (int i = 0; i < array.Length; i++) { array[i] = BitConverter.ToSingle(bytes, num5 + i * 4); } } else if (num4 == 1 && num3 == 16) { for (int j = 0; j < array.Length; j++) { array[j] = (float)BitConverter.ToInt16(bytes, num5 + j * 2) / 32768f; } } else if (num4 == 1 && num3 == 24) { for (int k = 0; k < array.Length; k++) { int num12 = num5 + k * 3; int num13 = (bytes[num12] << 8) | (bytes[num12 + 1] << 16) | (bytes[num12 + 2] << 24); array[k] = (float)num13 / 2.1474836E+09f; } } else if (num4 == 1 && num3 == 32) { for (int l = 0; l < array.Length; l++) { array[l] = (float)BitConverter.ToInt32(bytes, num5 + l * 4) / 2.1474836E+09f; } } else { if (num4 != 1 || num3 != 8) { throw new InvalidDataException($"Unsupported WAV format (format={num4}, bits={num3})."); } for (int m = 0; m < array.Length; m++) { array[m] = (float)(bytes[num5 + m] - 128) / 128f; } } AudioClip obj = AudioClip.Create(clipName, num11, num, num2, false); if (!obj.SetData(array, 0)) { throw new InvalidOperationException("AudioClip.SetData returned false."); } return obj; } private static bool Matches(byte[] bytes, int offset, string ascii) { if (offset + ascii.Length > bytes.Length) { return false; } for (int i = 0; i < ascii.Length; i++) { if (bytes[offset + i] != ascii[i]) { return false; } } return true; } } } namespace TerretaSoundsRepo.Modules { internal sealed class ApmModule : ICharacterModule { public string Id => "apm"; public string DisplayName => "APM (other enemies)"; public string GameTypeName => "EnemyParent"; public string EnemyNameMatch => null; public bool IsFallback => true; public bool AttackOnly => true; public IReadOnlyList<string> ReservedNames { get; } = Array.Empty<string>(); public IReadOnlyList<string> RegisterMethods { get; } = new string[4] { "Awake", "Start", "OnSpawn", "Update" }; public IReadOnlyList<string> AttackMethods { get; } = Array.Empty<string>(); public IReadOnlyList<string> AttackSoundFields { get; } = Array.Empty<string>(); public float DefaultHeaderRadius => 0f; public float DefaultAttackCooldown => 1f; public float DefaultChaseRadius => 0f; public float DefaultChaseInterval => 0f; public SfxSet Sounds { get; set; } } internal sealed class CleanupCrewModule : ICharacterModule, ICompanionModule { public string Id => "llados"; public string DisplayName => "Cleanup Crew"; public string GameTypeName => "EnemyParent"; public string EnemyNameMatch => "cleanup"; public bool IsFallback => false; public bool AttackOnly => true; public IReadOnlyList<string> ReservedNames { get; } = Array.Empty<string>(); public IReadOnlyList<string> RegisterMethods { get; } = new string[4] { "Awake", "Start", "OnSpawn", "Update" }; public IReadOnlyList<string> AttackMethods { get; } = Array.Empty<string>(); public IReadOnlyList<string> AttackSoundFields { get; } = Array.Empty<string>(); public IReadOnlyList<string> CompanionTypeNames { get; } = new string[1] { "EnemyBombThrowerHead" }; public IReadOnlyList<string> CompanionRegisterMethods { get; } = new string[2] { "Awake", "Update" }; public IReadOnlyList<string> CompanionSoundFields { get; } = new string[1] { "soundLaugh" }; public float DefaultHeaderRadius => 0f; public float DefaultAttackCooldown => 0.5f; public float DefaultChaseRadius => 0f; public float DefaultChaseInterval => 0f; public SfxSet Sounds { get; set; } } internal sealed class HeadmanModule : ICharacterModule { public string Id => "xokas"; public string DisplayName => "Headman"; public string GameTypeName => "EnemyParent"; public string EnemyNameMatch => "headman"; public bool IsFallback => false; public bool AttackOnly => true; public IReadOnlyList<string> ReservedNames { get; } = Array.Empty<string>(); public IReadOnlyList<string> RegisterMethods { get; } = new string[4] { "Awake", "Start", "OnSpawn", "Update" }; public IReadOnlyList<string> AttackMethods { get; } = Array.Empty<string>(); public IReadOnlyList<string> AttackSoundFields { get; } = Array.Empty<string>(); public float DefaultHeaderRadius => 0f; public float DefaultAttackCooldown => 0.5f; public float DefaultChaseRadius => 0f; public float DefaultChaseInterval => 0f; public SfxSet Sounds { get; set; } } internal sealed class HuntsmanModule : ICharacterModule { public string Id => "huntsman"; public string DisplayName => "Huntsman"; public string GameTypeName => "EnemyHunter"; public string EnemyNameMatch => null; public bool IsFallback => false; public bool AttackOnly => false; public IReadOnlyList<string> ReservedNames { get; } = new string[2] { "huntsman", "hunter" }; public IReadOnlyList<string> RegisterMethods { get; } = new string[4] { "Awake", "OnSpawn", "UpdateState", "UpdateStateRPC" }; public IReadOnlyList<string> AttackMethods { get; } = new string[1] { "ShootRPC" }; public IReadOnlyList<string> AttackSoundFields { get; } = new string[2] { "soundShoot", "soundShootGlobal" }; public float DefaultHeaderRadius => 22f; public float DefaultAttackCooldown => 0.25f; public float DefaultChaseRadius => 0f; public float DefaultChaseInterval => 0f; public SfxSet Sounds { get; set; } } internal static class ModuleCatalog { public static IReadOnlyList<ICharacterModule> Create() { return new List<ICharacterModule> { new HuntsmanModule(), new CleanupCrewModule(), new HeadmanModule(), new ApmModule() }; } } } namespace TerretaSoundsRepo.Core { internal static class EnemyNameFilter { public static bool Matches(string name, string match, IReadOnlyList<string> claimedNames, bool isFallback) { if (string.IsNullOrEmpty(name)) { return false; } if (isFallback && ContainsAny(name, claimedNames)) { return false; } if (string.IsNullOrEmpty(match)) { return true; } return ContainsAny(name, SplitTerms(match)); } public static string[] SplitTerms(string match) { if (string.IsNullOrEmpty(match)) { return Array.Empty<string>(); } string[] array = match.Split('|'); List<string> list = new List<string>(array.Length); string[] array2 = array; for (int i = 0; i < array2.Length; i++) { string text = array2[i].Trim(); if (text.Length > 0) { list.Add(text); } } return list.ToArray(); } public static bool ContainsAny(string name, IReadOnlyList<string> terms) { for (int i = 0; i < terms.Count; i++) { string value = terms[i]; if (!string.IsNullOrEmpty(value) && name.IndexOf(value, StringComparison.OrdinalIgnoreCase) >= 0) { return true; } } return false; } public static string Describe(string match, bool isFallback) { if (!string.IsNullOrEmpty(match)) { return match; } if (!isFallback) { return "no filter"; } return "everything unclaimed"; } } internal interface ICharacterModule { string Id { get; } string DisplayName { get; } string GameTypeName { get; } string EnemyNameMatch { get; } bool IsFallback { get; } bool AttackOnly { get; } IReadOnlyList<string> ReservedNames { get; } IReadOnlyList<string> RegisterMethods { get; } IReadOnlyList<string> AttackMethods { get; } IReadOnlyList<string> AttackSoundFields { get; } float DefaultHeaderRadius { get; } float DefaultChaseRadius { get; } float DefaultChaseInterval { get; } float DefaultAttackCooldown { get; } SfxSet Sounds { get; set; } } internal interface ICompanionModule { IReadOnlyList<string> CompanionTypeNames { get; } IReadOnlyList<string> CompanionRegisterMethods { get; } IReadOnlyList<string> CompanionSoundFields { get; } } internal sealed class ModuleConfig { private const int SchemaVersion = 3; public ConfigEntry<bool> Enabled { get; private set; } public ConfigEntry<string> EnemyName { get; private set; } public ConfigEntry<float> HeaderRadius { get; private set; } public ConfigEntry<float> ChaseRadius { get; private set; } public ConfigEntry<float> ChaseInterval { get; private set; } public ConfigEntry<float> AttackCooldown { get; private set; } public ConfigEntry<float> Volume { get; private set; } public ConfigEntry<bool> DetectAttackBySound { get; private set; } public bool IsEnabled => Enabled?.Value ?? true; public string NameMatch => EnemyName?.Value ?? string.Empty; public float Radius => HeaderRadius?.Value ?? 0f; public float Chase => ChaseRadius?.Value ?? 0f; public float PhraseInterval => ChaseInterval?.Value ?? 0f; public float Cooldown => AttackCooldown?.Value ?? 0f; public float Level => Volume?.Value ?? 1f; public bool UseSoundHook => DetectAttackBySound?.Value ?? true; public static ModuleConfig Bind(ICharacterModule module, ConfigFile config, float globalVolume) { ModuleConfig moduleConfig = new ModuleConfig(); string text = "Character: " + module.DisplayName; moduleConfig.Enabled = config.Bind<bool>(text, "Enabled", true, "Enables the sounds of " + module.DisplayName + "."); moduleConfig.HeaderRadius = config.Bind<float>(text, "HeaderRadius", module.DefaultHeaderRadius, module.AttackOnly ? "Ignored: this character only speaks on its attacks (no proximity header)." : ("Distance (m) at which " + module.DisplayName + " has to get close to a player for its header to play, once per map. 0 disables it.")); moduleConfig.EnemyName = config.Bind<string>(text, "EnemyName", module.EnemyNameMatch ?? string.Empty, module.IsFallback ? "Extra filter on the enemy's internal name. Empty = every enemy that does not already have a module of its own (Huntsman, Cleanup Crew, Headman...). Several words can be separated with '|'." : "Text the enemy's internal name must contain for this character to play. Several words can be separated with '|'. Empty = no filter. With VerboseLog enabled, the console writes the name of every enemy that spawns, so you can fine-tune it."); moduleConfig.ChaseRadius = config.Bind<float>(text, "ChaseRadius", module.DefaultChaseRadius, module.AttackOnly ? "Ignored: this character only speaks on its attacks (no proximity phrases)." : ("Distance (m) at which " + module.DisplayName + " counts as chasing a player and starts dropping phrases. 0 disables them.")); moduleConfig.ChaseInterval = config.Bind<float>(text, "PhraseInterval", module.DefaultChaseInterval, module.AttackOnly ? "Ignored: this character only speaks on its attacks (no proximity phrases)." : "Seconds between chase phrases of the same enemy (a ±25 % jitter is applied so several heads do not talk in unison)."); moduleConfig.AttackCooldown = config.Bind<float>(text, "AttackCooldown", module.DefaultAttackCooldown, "Minimum seconds between two attack sounds of the same enemy (avoids duplicates between hooks)."); moduleConfig.Volume = config.Bind<float>(text, "Volume", globalVolume, "Volume for this character (0-1)."); ConfigEntry<int> val = config.Bind<int>(text, "ConfigSchemaVersion", 1, "Internal: do not edit. Used to migrate values from older versions."); bool flag = false; if (val.Value < 3) { if (module.IsFallback || module.AttackOnly) { moduleConfig.HeaderRadius.Value = module.DefaultHeaderRadius; moduleConfig.ChaseRadius.Value = module.DefaultChaseRadius; moduleConfig.ChaseInterval.Value = module.DefaultChaseInterval; } val.Value = 3; flag = true; TerretaSoundsPlugin.LogInfo($"[TerretaSounds] {module.Id}: config migrated to schema {3}."); } moduleConfig.DetectAttackBySound = config.Bind<bool>(text, "DetectAttackBySound", true, module.AttackOnly ? "Required: this character only speaks through the game's attack sounds. Leave it on." : "Extra hook on the game's attack sound. Leave it on unless you hear doubled sounds."); if (flag && module.AttackOnly && !moduleConfig.DetectAttackBySound.Value) { moduleConfig.DetectAttackBySound.Value = true; TerretaSoundsPlugin.LogInfo("[TerretaSounds] " + module.Id + ": DetectAttackBySound re-enabled (attack-only)."); } if (flag) { try { config.Save(); } catch { } } return moduleConfig; } } internal static class ModuleRegistry { private const float ProximityInterval = 0.25f; private const float PlayerScanInterval = 0.5f; private static readonly List<ModuleState> States = new List<ModuleState>(); private static readonly Dictionary<Type, List<ModuleState>> ByType = new Dictionary<Type, List<ModuleState>>(); private static readonly List<Vector3> Players = new List<Vector3>(); private static float _nextPlayerScan; private static int _mapToken = int.MinValue; private static bool _initialised; private static readonly HashSet<object> ActiveLoops = new HashSet<object>(); public static IReadOnlyList<ModuleState> All => States; public static int Initialise(IReadOnlyList<ICharacterModule> modules, ConfigFile config, string pluginDirectory, string pluginFolder, float globalVolume) { if (_initialised) { return States.Count; } _initialised = true; GameApi.Resolve(); List<string> claimedNames = ClaimedNames(modules); foreach (ICharacterModule module in modules) { try { ModuleState moduleState = CreateState(module, config, pluginDirectory, pluginFolder, globalVolume, claimedNames); if (moduleState == null) { continue; } TerretaSoundsPlugin.LogInfo($"[TerretaSounds] module '{module.Id}': header={moduleState.Config.Radius:0.#}m " + $"chase={moduleState.Config.Chase:0.#}m " + $"cooldown={moduleState.Config.Cooldown:0.##}s"); States.Add(moduleState); if (!ByType.TryGetValue(moduleState.GameType, out var value)) { value = new List<ModuleState>(); ByType[moduleState.GameType] = value; } value.Add(moduleState); foreach (Type companionType in moduleState.CompanionTypes) { if (!ByType.TryGetValue(companionType, out var value2)) { value2 = new List<ModuleState>(); ByType[companionType] = value2; } if (!value2.Contains(moduleState)) { value2.Add(moduleState); } } } catch (Exception ex) { TerretaSoundsPlugin.LogWarn("[TerretaSounds] module '" + module.Id + "' disabled: " + ex.Message); } } return States.Count; } private static List<string> ClaimedNames(IReadOnlyList<ICharacterModule> modules) { List<string> list = new List<string>(); foreach (ICharacterModule module in modules) { if (module.IsFallback) { continue; } string[] array = EnemyNameFilter.SplitTerms(module.EnemyNameMatch); foreach (string item in array) { list.Add(item); } foreach (string item2 in module.ReservedNames ?? Array.Empty<string>()) { string text = item2?.Trim(); if (!string.IsNullOrEmpty(text)) { list.Add(text); } } } return list; } private static ModuleState CreateState(ICharacterModule module, ConfigFile config, string pluginDirectory, string pluginFolder, float globalVolume, IReadOnlyList<string> claimedNames) { Type type = GameApi.TypeByName(module.GameTypeName); if (type == null) { TerretaSoundsPlugin.LogWarn("[TerretaSounds] module '" + module.Id + "': cannot find type '" + module.GameTypeName + "' in this game version."); return null; } string text = pluginFolder + "/" + module.Id; List<string> embeddedPrefixes = new List<string> { "Sfx." + module.Id + "." }; SfxSet sfxSet = SfxSet.Load(pluginDirectory, text, embeddedPrefixes, TerretaSoundsPlugin.Log, module.DisplayName); if (sfxSet.IsEmpty) { TerretaSoundsPlugin.LogWarn("[TerretaSounds] module '" + module.Id + "': no clips. Drop WAVs into 'BepInEx/plugins/" + text + "/'."); return null; } if (!sfxSet.IsEmpty && (Object)(object)sfxSet.Header == (Object)null) { string text2 = ((module.DefaultChaseRadius > 0f) ? "chase phrases" : "attack sounds only"); TerretaSoundsPlugin.LogInfo("[TerretaSounds] module '" + module.Id + "': no header, " + text2 + "."); } module.Sounds = sfxSet; ModuleConfig config2 = ModuleConfig.Bind(module, config, globalVolume); IReadOnlyList<Type> companionTypes = ResolveCompanionTypes(module); IReadOnlyList<string> companionSoundFields = (module as ICompanionModule)?.CompanionSoundFields ?? Array.Empty<string>(); return new ModuleState(module, type, config2, claimedNames, companionTypes, companionSoundFields); } private static IReadOnlyList<Type> ResolveCompanionTypes(ICharacterModule module) { if (!(module is ICompanionModule { CompanionTypeNames: not null } companionModule) || companionModule.CompanionTypeNames.Count == 0) { return Array.Empty<Type>(); } List<Type> list = new List<Type>(); foreach (string companionTypeName in companionModule.CompanionTypeNames) { Type type = GameApi.TypeByName(companionTypeName); if (type == null) { TerretaSoundsPlugin.LogWarn("[TerretaSounds] module '" + module.Id + "': cannot find companion type '" + companionTypeName + "'."); } else { list.Add(type); } } return list; } public static void OnRegistered(object character, MethodBase original) { List<ModuleState> list = StatesFor(original) ?? StatesForType(character); if (list == null) { return; } foreach (ModuleState item in list) { item.GetOrCreate(character); } } public static void OnAttacked(object character, MethodBase original) { List<ModuleState> list = StatesFor(original) ?? StatesForType(character); if (list == null) { return; } foreach (ModuleState item in list) { PlayAttack(item, character, "hook:" + original?.Name, null); } } public static void OnSoundPlayed(object sound) { if (sound == null) { return; } foreach (ModuleState state in States) { if (state.AttackSounds.Contains(sound) && state.SoundOwners.TryGetValue(sound, out var value)) { PlayAttack(state, value.Character, "Sound.Play", sound); break; } } } public static void OnSoundLoopPlayed(object sound, bool playing) { if (sound != null) { if (!playing) { ActiveLoops.Remove(sound); } else if (IsRegisteredSound(sound) && ActiveLoops.Add(sound)) { OnSoundPlayed(sound); } } } private static bool IsRegisteredSound(object sound) { foreach (ModuleState state in States) { if (state.AttackSounds.Contains(sound)) { return true; } } return false; } private static List<ModuleState> StatesFor(MethodBase original) { Type type = original?.DeclaringType; if (type == null) { return null; } if (!ByType.TryGetValue(type, out var value)) { return null; } return value; } private static List<ModuleState> StatesForType(object character) { if (character == null) { return null; } Type type = character.GetType(); while (type != null) { if (ByType.TryGetValue(type, out var value)) { return value; } type = type.BaseType; } return null; } private static void PlayAttack(ModuleState state, object character, string hook, object triggerSound) { if (character == null || !state.Config.IsEnabled) { return; } ModuleState.Instance orCreate = state.GetOrCreate(character); if (orCreate == null) { return; } float unscaledTime = Time.unscaledTime; float num = Math.Max(0f, state.Config.Cooldown); if (unscaledTime - orCreate.LastAttack < num) { return; } float num2 = ((state.Module.IsFallback || state.Module.AttackOnly) ? TerretaSoundsPlugin.SameSoundCooldown : 0f); if (triggerSound != null && num2 > 0f && orCreate.LastSoundTrigger.TryGetValue(triggerSound, out var value) && unscaledTime - value < num2) { if (TerretaSoundsPlugin.Verbose) { TerretaSoundsPlugin.LogInfo("[" + state.Module.Id + "] " + hook + " skipped " + $"(same sound {unscaledTime - value:0.0}s ago)"); } return; } AudioClip val = PickAttackClip(state, character); if (!((Object)(object)val == (Object)null)) { orCreate.LastAttack = unscaledTime; orCreate.LastSeen = unscaledTime; if (triggerSound != null) { orCreate.LastSoundTrigger[triggerSound] = unscaledTime; } string reason; bool flag = TerretaSoundsPlugin.TryPlay(val, character, state.Config.Level, out reason); if (TerretaSoundsPlugin.Verbose) { TerretaSoundsPlugin.LogInfo(flag ? ("[" + state.Module.Id + "] " + ((Object)val).name + " ← " + hook) : ("[" + state.Module.Id + "] " + ((Object)val).name + " skipped ← " + hook + " (" + reason + ")")); } } } private static AudioClip PickAttackClip(ModuleState state, object character) { SfxSet sounds = state.Module.Sounds; if (sounds == null) { return null; } if (!GameApi.TrySharedSeed(character, out var seed)) { return sounds.Next(); } return sounds.Pick(seed); } public static void Tick() { if (States.Count == 0) { return; } RefreshMap(); bool flag = false; bool flag2 = false; bool flag3 = false; foreach (ModuleState state in States) { flag |= PendingHeader(state); flag2 |= ChaseActive(state); flag3 |= state.HasUnregisteredInstances; } if (flag3) { float unscaledTime = Time.unscaledTime; foreach (ModuleState state2 in States) { state2.RetryPendingSounds(unscaledTime); } } if (!flag && !flag2) { return; } float unscaledTime2 = Time.unscaledTime; if (unscaledTime2 >= _nextPlayerScan || Players.Count == 0) { _nextPlayerScan = unscaledTime2 + 0.5f; if (GameApi.PlayerPositions(Players) == 0) { return; } } foreach (ModuleState state3 in States) { bool flag4 = PendingHeader(state3); bool flag5 = ChaseActive(state3); if (flag4 || flag5) { TickState(state3, unscaledTime2, flag4, flag5); } } } private static bool PendingHeader(ModuleState state) { if (!state.Module.IsFallback && !state.Module.AttackOnly && state.Config.IsEnabled && state.Config.Radius > 0f && (Object)(object)state.Module.Sounds?.Header != (Object)null && !state.HeaderPlayedThisMap) { return state.Instances.Count > 0; } return false; } private static bool ChaseActive(ModuleState state) { if (!state.Module.IsFallback && !state.Module.AttackOnly && state.Config.IsEnabled && state.Config.Chase > 0f && state.Config.PhraseInterval > 0f && state.Module.Sounds != null && state.Module.Sounds.Count > 0) { return state.Instances.Count > 0; } return false; } private static void TickState(ModuleState state, float now, bool header, bool chase) { float num = Math.Max(1f, state.Config.Radius); float num2 = Math.Max(1f, state.Config.Chase); float interval = Math.Max(0.5f, state.Config.PhraseInterval); foreach (ModuleState.Instance value in state.Instances.Values) { if (ModuleState.IsAlive(value.Character)) { if (now >= value.NextProximityCheck) { value.NextProximityCheck = now + 0.25f; value.NearestPlayer = NearestDistance(value.Character); } if (header && !state.HeaderPlayedThisMap && value.NearestPlayer <= num) { PlayHeader(state, value, now); } if (chase && value.NearestPlayer <= num2 && now >= value.NextChasePhrase && (!state.Module.IsFallback || now >= state.NextGlobalChase)) { PlayChasePhrase(state, value, now, interval); } } } } private static float NearestDistance(object character) { //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_001c: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Unknown result type (might be due to invalid IL or missing references) Vector3 val = GameApi.PositionOf(character); float num = float.MaxValue; foreach (Vector3 player in Players) { float num2 = Vector3.Distance(val, player); if (num2 < num) { num = num2; } } return num; } private static void PlayHeader(ModuleState state, ModuleState.Instance instance, float now) { if (!TerretaSoundsPlugin.TryPlay(state.Module.Sounds.Header, instance.Character, state.Config.Level, out var reason)) { if (TerretaSoundsPlugin.Verbose) { TerretaSoundsPlugin.LogInfo("[" + state.Module.Id + "] header skipped (" + reason + ")"); } } else { state.HeaderPlayedThisMap = true; instance.LastSeen = now; if (TerretaSoundsPlugin.Verbose) { TerretaSoundsPlugin.LogInfo("[" + state.Module.Id + "] header ← proximity"); } } } private static void PlayChasePhrase(ModuleState state, ModuleState.Instance instance, float now, float interval) { AudioClip val = state.Module.Sounds.Next(); if (!((Object)(object)val == (Object)null)) { instance.NextChasePhrase = now + interval * Random.Range(0.8f, 1.3f); instance.LastSeen = now; state.NextGlobalChase = instance.NextChasePhrase; string reason; bool flag = TerretaSoundsPlugin.TryPlay(val, instance.Character, state.Config.Level, out reason); if (TerretaSoundsPlugin.Verbose) { TerretaSoundsPlugin.LogInfo(flag ? ("[" + state.Module.Id + "] " + ((Object)val).name + " ← chase " + $"({instance.NearestPlayer:0.0} m)") : ("[" + state.Module.Id + "] " + ((Object)val).name + " skipped ← chase (" + reason + ")")); } } } private static void RefreshMap() { int num; try { num = MapToken(); } catch { return; } if (num == _mapToken) { return; } _mapToken = num; foreach (ModuleState state in States) { state.HeaderPlayedThisMap = false; } TerretaSoundsPlugin.LogInfo($"[TerretaSounds] new map ({num}): headers armed."); } private static int MapToken() { //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Unknown result type (might be due to invalid IL or missing references) int sceneCount = SceneManager.sceneCount; int num = sceneCount * 486187739; for (int i = 0; i < sceneCount; i++) { Scene sceneAt = SceneManager.GetSceneAt(i); num = num * 31 + ((Scene)(ref sceneAt)).handle; } int num2 = num * 31; Scene activeScene = SceneManager.GetActiveScene(); return num2 + ((Scene)(ref activeScene)).handle; } } internal sealed class ModuleState { public sealed class Instance { public object Character; public float LastAttack = -9999f; public float LastSeen; public float NextProximityCheck; public bool SoundsRegistered; public int SoundLookupAttempts; public float NextSoundRetry; public float NearestPlayer = float.PositiveInfinity; public float NextChasePhrase; public readonly Dictionary<object, float> LastSoundTrigger = new Dictionary<object, float>(ReferenceComparer.Instance); } private sealed class ReferenceComparer : IEqualityComparer<object> { public static readonly ReferenceComparer Instance = new ReferenceComparer(); public new bool Equals(object x, object y) { return x == y; } public int GetHashCode(object obj) { return RuntimeHelpers.GetHashCode(obj); } } private const float InitialTime = -9999f; private const float ForgetAfterSeconds = 180f; public bool HeaderPlayedThisMap; private readonly string[] _claimedNames; public float NextGlobalChase; private readonly HashSet<string> SeenNames = new HashSet<string>(StringComparer.OrdinalIgnoreCase); private bool _nameFieldWarned; private readonly HashSet<string> _soundLoggedTypes = new HashSet<string>(StringComparer.Ordinal); private static readonly string[] NonAttackSoundParts = new string[37] { "hurt", "death", "die", "idle", "walk", "move", "footstep", "step", "spawn", "despawn", "notice", "land", "stun", "breath", "gasp", "teleport", "impact", "noise", "talk", "crack", "breaker", "jingle", "song", "bell", "wheel", "rattle", "squeak", "glitch", "release", "open", "close", "ground", "wall", "recharge", "confuse", "refuse", "scramble" }; private static readonly string[] AttackSoundParts = new string[47] { "attack", "shoot", "bite", "punch", "slam", "stab", "scratch", "swing", "throw", "spit", "explos", "kill", "laser", "claw", "kick", "ram", "peck", "bomb", "rocket", "projectile", "hit", "chomp", "thrust", "puke", "lunge", "grab", "melee", "smash", "charge", "swipe", "slash", "chop", "zap", "scare", "scream", "yell", "tongue", "gas", "pickaxe", "cleaver", "mace", "implosion", "fuse", "clap", "suck", "dropkick", "headdetach" }; private const float SoundRetrySeconds = 2f; private const float SlowSoundRetrySeconds = 30f; private const int MaxSoundLookupAttempts = 15; public ICharacterModule Module { get; } public Type GameType { get; } public ModuleConfig Config { get; } public IReadOnlyList<Type> CompanionTypes { get; } public IReadOnlyList<string> CompanionSoundFields { get; } public Dictionary<int, Instance> Instances { get; } = new Dictionary<int, Instance>(); public Dictionary<object, Instance> SoundOwners { get; } = new Dictionary<object, Instance>(ReferenceComparer.Instance); public HashSet<object> AttackSounds { get; } = new HashSet<object>(ReferenceComparer.Instance); public bool HasUnregisteredInstances { get { foreach (Instance value in Instances.Values) { if (!value.SoundsRegistered) { return true; } } return false; } } public ModuleState(ICharacterModule module, Type gameType, ModuleConfig config, IReadOnlyList<string> claimedNames = null, IReadOnlyList<Type> companionTypes = null, IReadOnlyList<string> companionSoundFields = null) { Module = module; GameType = gameType; Config = config; _claimedNames = ((claimedNames == null) ? Array.Empty<string>() : ToArray(claimedNames)); CompanionTypes = companionTypes ?? Array.Empty<Type>(); CompanionSoundFields = companionSoundFields ?? Array.Empty<string>(); } public bool IsCompanion(object character) { if (character == null) { return false; } for (int i = 0; i < CompanionTypes.Count; i++) { if (CompanionTypes[i].IsInstanceOfType(character)) { return true; } } return false; } private static string[] ToArray(IReadOnlyList<string> values) { string[] array = new string[values.Count]; for (int i = 0; i < array.Length; i++) { array[i] = values[i]; } return array; } public Instance GetOrCreate(object character) { if (character == null) { return null; } int? num = IdOf(character); if (!num.HasValue) { return null; } if (Instances.TryGetValue(num.Value, out var value)) { value.Character = character; value.LastSeen = Time.unscaledTime; if (!value.SoundsRegistered && value.LastSeen >= value.NextSoundRetry) { RegisterSounds(value); } return value; } if (!IsCompanion(character) && !MatchesName(character)) { return null; } float num2 = Config?.PhraseInterval ?? 0f; float unscaledTime = Time.unscaledTime; Instance instance = new Instance { Character = character, LastSeen = unscaledTime, NextChasePhrase = ((num2 > 0f) ? (unscaledTime + Random.Range(0f, num2)) : 0f) }; Instances[num.Value] = instance; PruneIfNeeded(); if (!instance.SoundsRegistered) { RegisterSounds(instance); } return instance; } private static int? IdOf(object character) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) try { return ((Object)character).GetInstanceID(); } catch { try { return RuntimeHelpers.GetHashCode(character); } catch { return null; } } } private bool MatchesName(object character) { string text = Config?.NameMatch; bool isFallback = Module.IsFallback; if (!isFallback && string.IsNullOrEmpty(text)) { return true; } string text2 = GameApi.Get(character, "enemyName") as string; if (string.IsNullOrEmpty(text2)) { if (!_nameFieldWarned) { _nameFieldWarned = true; string text3 = (Module.IsFallback ? "The wildcard needs that name to know which enemies get APM, so it stays silent until it can be read." : "Adjust 'EnemyName' or check the game version: the module stays silent."); TerretaSoundsPlugin.LogWarn("[TerretaSounds] " + Module.Id + ": cannot read 'enemyName' on '" + character.GetType().Name + "'. " + text3); } return false; } if (TerretaSoundsPlugin.Verbose && SeenNames.Add(text2)) { TerretaSoundsPlugin.LogInfo("[" + Module.Id + "] enemy seen: '" + text2 + "' (filter '" + EnemyNameFilter.Describe(text, isFallback) + "')"); } return EnemyNameFilter.Matches(text2, text, _claimedNames, isFallback); } private void RegisterSounds(Instance instance) { instance.SoundLookupAttempts++; if (IsCompanion(instance.Character) && CompanionSoundFields.Count > 0) { RegisterCompanionSounds(instance); return; } if (Module.IsFallback || Module.AttackOnly) { RegisterAttackSoundsByName(instance); return; } if (Module.AttackSoundFields.Count == 0) { instance.SoundsRegistered = true; return; } bool flag = false; foreach (string attackSoundField in Module.AttackSoundFields) { object sound = GameApi.Get(instance.Character, attackSoundField); flag |= TryRegister(sound, instance); } if (!flag) { flag |= TryRegister(GameApi.GetByNameParts(instance.Character, "Sound", "shoot"), instance); } instance.SoundsRegistered = flag; if (!flag) { float num = ((instance.SoundLookupAttempts >= 15) ? 30f : 2f); instance.NextSoundRetry = Time.unscaledTime + num; } } private void RegisterCompanionSounds(Instance instance) { bool flag = false; foreach (string companionSoundField in CompanionSoundFields) { flag |= TryRegister(GameApi.Get(instance.Character, companionSoundField), instance); } instance.SoundsRegistered = flag; if (!flag) { float num = ((instance.SoundLookupAttempts >= 15) ? 30f : 2f); instance.NextSoundRetry = Time.unscaledTime + num; return; } string name = instance.Character.GetType().Name; if (_soundLoggedTypes.Add("ok:" + name)) { TerretaSoundsPlugin.LogInfo("[" + Module.Id + "] companion voice on '" + name + "': " + string.Join(", ", CompanionSoundFields)); } } public void RetryPendingSounds(float now) { foreach (Instance value in Instances.Values) { if (!value.SoundsRegistered && !(now < value.NextSoundRetry) && IsAlive(value.Character)) { RegisterSounds(value); } } } private void RegisterAttackSoundsByName(Instance instance) { List<object> list = GameApi.SoundCandidates(instance.Character, IsCompanion(instance.Character) ? null : CompanionTypes); bool flag = false; List<string> list2 = new List<string>(); foreach (object item in list) { foreach (KeyValuePair<string, object> soundField in GameApi.GetSoundFields(item, AttackSoundParts)) { if (!SoundNameContains(soundField.Key, NonAttackSoundParts)) { list2.Add(soundField.Key); flag |= TryRegister(soundField.Value, instance); } } } instance.SoundsRegistered = flag; if (!flag) { float num = ((instance.SoundLookupAttempts >= 15) ? 30f : 2f); instance.NextSoundRetry = Time.unscaledTime + num; } string name = instance.Character.GetType().Name; if (flag) { if (_soundLoggedTypes.Add("ok:" + name)) { TerretaSoundsPlugin.LogInfo($"[{Module.Id}] attack sounds on '{name}' (hosts={list.Count}): " + string.Join(", ", list2)); } } else { if (flag || instance.SoundLookupAttempts < 15 || !_soundLoggedTypes.Add("none:" + name)) { return; } List<string> list3 = new List<string>(); foreach (object item2 in list) { foreach (KeyValuePair<string, object> item3 in GameApi.AllSoundFields(item2)) { list3.Add(item2.GetType().Name + "." + item3.Key); } } TerretaSoundsPlugin.LogInfo($"[{Module.Id}] no attack sounds on '{name}' (hosts={list.Count}); " + "Sound fields: " + ((list3.Count > 0) ? string.Join(", ", list3) : "none")); } } private static bool SoundNameContains(string name, IReadOnlyList<string> parts) { for (int i = 0; i < parts.Count; i++) { if (!string.IsNullOrEmpty(parts[i]) && name.IndexOf(parts[i], StringComparison.OrdinalIgnoreCase) >= 0) { return true; } } return false; } private bool TryRegister(object sound, Instance instance) { if (sound == null) { return false; } if (sound is Array array) { bool flag = false; { foreach (object item in array) { flag |= TryRegister(item, instance); } return flag; } } AttackSounds.Add(sound); if (!SoundOwners.ContainsKey(sound)) { SoundOwners[sound] = instance; } return true; } public static bool IsAlive(object character) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Expected O, but got Unknown if (character == null) { return false; } try { return (Object)character != (Object)null; } catch { return false; } } private void PruneIfNeeded() { if (Instances.Count < 32) { return; } float unscaledTime = Time.unscaledTime; List<int> list = new List<int>(); foreach (KeyValuePair<int, Instance> instance in Instances) { if (!IsAlive(instance.Value.Character) || unscaledTime - instance.Value.LastSeen > 180f) { list.Add(instance.Key); } } foreach (int item in list) { if (!Instances.TryGetValue(item, out var value)) { continue; } Instances.Remove(item); List<object> list2 = new List<object>(); foreach (KeyValuePair<object, Instance> soundOwner in SoundOwners) { if (soundOwner.Value == value) { list2.Add(soundOwner.Key); } } foreach (object item2 in list2) { UnregisterSound(item2, value); } } } private void UnregisterSound(object sound, Instance instance) { if (sound != null) { AttackSounds.Remove(sound); if (SoundOwners.TryGetValue(sound, out var value) && value == instance) { SoundOwners.Remove(sound); } } } } internal sealed class SfxSet { private readonly List<AudioClip> _pool = new List<AudioClip>(); private readonly List<int> _bag = new List<int>(); private readonly Random _random; private int _lastIndex = -1; public AudioClip Header { get; private set; } public int Count => _pool.Count; public bool IsEmpty { get { if (_pool.Count == 0) { return (Object)(object)Header == (Object)null; } return false; } } private SfxSet(int seed) { _random = new Random(seed); } public static SfxSet Load(string pluginDirectory, string folderName, IReadOnlyList<string> embeddedPrefixes, ManualLogSource log, string tag) { SfxSet sfxSet = new SfxSet(Environment.TickCount); string text = FindExternalFolder(pluginDirectory, folderName); if (text != null) { int num = sfxSet.LoadFromDirectory(text, log, tag); if (num > 0) { if (log != null) { log.LogInfo((object)$"[TerretaSounds] {tag}: {num} SFX from '{text}'."); } sfxSet.Sort(); return sfxSet; } } foreach (string embeddedPrefix in embeddedPrefixes) { int num2 = sfxSet.LoadFromAssembly(Assembly.GetExecutingAssembly(), embeddedPrefix, log, tag); if (num2 > 0) { if (log != null) { log.LogInfo((object)$"[TerretaSounds] {tag}: {num2} embedded SFX ({embeddedPrefix})."); } break; } } sfxSet.Sort(); return sfxSet; } private static string FindExternalFolder(string pluginDirectory, string folderName) { List<string> list = new List<string>(); if (!string.IsNullOrEmpty(pluginDirectory)) { list.Add(Path.Combine(pluginDirectory, folderName)); } try { string pluginPath = Paths.PluginPath; if (!string.IsNullOrEmpty(pluginPath)) { list.Add(Path.Combine(pluginPath, folderName)); } } catch { } foreach (string item in list.Distinct<string>(StringComparer.OrdinalIgnoreCase)) { try { if (Directory.Exists(item) && Directory.EnumerateFiles(item, "*.wav", SearchOption.TopDirectoryOnly).Any()) { return item; } } catch { } } return null; } private int LoadFromDirectory(string directory, ManualLogSource log, string tag) { int num = 0; foreach (string item in Directory.EnumerateFiles(directory, "*.wav", SearchOption.TopDirectoryOnly).OrderBy<string, string>((string path) => path, StringComparer.OrdinalIgnoreCase)) { try { AudioClip clip = WavLoader.Load(Path.GetFileNameWithoutExtension(item), File.ReadAllBytes(item)); Add(clip); num++; } catch (Exception ex) { if (log != null) { log.LogWarning((object)("[TerretaSounds] " + tag + ": could not read '" + Path.GetFileName(item) + "': " + ex.Message)); } } } return num; } private int LoadFromAssembly(Assembly assembly, string prefix, ManualLogSource log, string tag) { int num = 0; string[] manifestResourceNames = assembly.GetManifestResourceNames(); foreach (string text in manifestResourceNames) { if (!text.StartsWith(prefix, StringComparison.OrdinalIgnoreCase) || !text.EndsWith(".wav", StringComparison.OrdinalIgnoreCase)) { continue; } try { using Stream stream = assembly.GetManifestResourceStream(text); if (stream != null) { using MemoryStream memoryStream = new MemoryStream(); stream.CopyTo(memoryStream); string clipName = text.Substring(prefix.Length, text.Length - prefix.Length - 4); Add(WavLoader.Load(clipName, memoryStream.ToArray())); num++; } } catch (Exception ex) { if (log != null) { log.LogWarning((object)("[TerretaSounds] " + tag + ": could not read '" + text + "': " + ex.Message)); } } } return num; } private void Add(AudioClip clip) { if (!((Object)(object)clip == (Object)null)) { if (IsHeader(((Object)clip).name)) { Header = clip; } else { _pool.Add(clip); } } } private void Sort() { _pool.Sort((AudioClip a, AudioClip b) => string.CompareOrdinal(((Object)a).name, ((Object)b).name)); } private static bool IsHeader(string name) { if (name.IndexOf("header", StringComparison.OrdinalIgnoreCase) < 0 && name.IndexOf("cabecera", StringComparison.OrdinalIgnoreCase) < 0) { return name.IndexOf("theme", StringComparison.OrdinalIgnoreCase) >= 0; } return true; } public AudioClip Next() { if (_pool.Count == 0) { return null; } if (_pool.Count == 1) { return _pool[0]; } if (_bag.Count == 0) { RefillBag(); } int num = _bag[_bag.Count - 1]; _bag.RemoveAt(_bag.Count - 1); if (num == _lastIndex && _bag.Count > 0) { int index = _random.Next(_bag.Count); int num2 = _bag[index]; _bag[index] = num; num = num2; } _lastIndex = num; return _pool[num]; } public AudioClip Pick(int seed) { if (_pool.Count == 0) { return null; } int index = (_lastIndex = (int)((uint)seed % (uint)_pool.Count)); return _pool[index]; } private void RefillBag() { _bag.Clear(); for (int i = 0; i < _pool.Count; i++) { _bag.Add(i); } for (int num = _bag.Count - 1; num > 0; num--) { int index = _random.Next(num + 1); int value = _bag[num]; _bag[num] = _bag[index]; _bag[index] = value; } } public string Describe() { return string.Format("header={0} · sounds={1}", ((Object)(object)Header != (Object)null) ? "yes" : "no", Count); } } }