diff --git a/JotunnModStub/Fenrir/FenrirBehaviors.cs b/JotunnModStub/Fenrir/FenrirBehaviors.cs index 2d1180c..380f47c 100644 --- a/JotunnModStub/Fenrir/FenrirBehaviors.cs +++ b/JotunnModStub/Fenrir/FenrirBehaviors.cs @@ -1,4 +1,5 @@ using System.Collections; +using System.Collections.Generic; using BepInEx; using HarmonyLib; using Jotunn.Configs; @@ -10,32 +11,202 @@ using UnityEngine.UI; // Added for UI namespace RacesOfValheim { /// - /// Howl vocalisation, borrowed from the real creature instead of guessed at. Wolves and their - /// kin do not carry a standalone "sfx_wolf_howl"-style prefab that PlaySFX's - /// PrefabManager.Cache lookup could ever find - dumpdverger's own hierarchy dump for - /// Fenring_Cultist shows no ZSFX anywhere on it. + /// The voice of the creature a Fenrir is wearing. /// - /// BaseAI.m_idleSound was the first guess and was wrong in a quieter way: it is real, but it - /// is the creature's passive ambient noise (DoIdleSound, on a timer while it is doing nothing - /// in particular) - a small grunt, not a howl, and it played back sounding like whatever - /// generic "the form did something" cue the transformation itself already uses. What a - /// creature actually vocalises WHEN IT SPOTS SOMETHING is BaseAI.m_alertedEffects, fired from - /// SetAlerted(true) - reading that off the real "Fenring"/"Fenring_Cultist" prefab and calling - /// Create() plays the same aggressive bark the creature itself makes going on alert. + /// THE HISTORY MATTERS HERE, because two reasonable-sounding answers were tried and both were + /// silent, and the note that used to sit in this place asserted the second one worked. + /// + /// "sfx_wolf_howl" was the first guess. There is no such prefab in the game. + /// + /// BaseAI.m_idleSound was the second. Real, but it is the creature's ambient grunt on a timer + /// (DoIdleSound) - the wrong sound even when it plays. + /// + /// BaseAI.m_alertedEffects was the third, on the reasoning that a creature's alert bark is the + /// nearest thing it has to a howl and that these creatures carry no standalone ZSFX at all. + /// That last part is simply not true - see the table below - and calling Create() on a PREFAB's + /// EffectList produced nothing audible in testing while instantiating a sound prefab directly, + /// two lines away in the same file, worked. So the alert-list route is now the last resort + /// rather than the plan. + /// + /// What actually plays is a real prefab, instantiated the same way the claw and the landing thud + /// are. Every name below was checked against the game's own asset manifest. Note "sfx_wolf_haul", + /// which is the wolf's howl under the game's own misspelling - that single typo is most of why + /// nobody found it by searching for "howl". /// internal static class FenrirCreatureSound { + /// + /// Per creature, best first, and every name checked against the game's own asset manifest. + /// The Ulv has no vocalisation of its own in vanilla beyond sfx_ulv_death, so it borrows the + /// wolf's. "sfx_wolf_haul" is the wolf's howl under the game's own misspelling, which is most + /// of why nobody found it by searching for "howl". + /// + /// THE FENRING BORROWS THE WOLF'S HOWL. It has none of its own: its 19 clips carry no howl, + /// and its taunt fires no sound event at all. Its own "sfx_fenring_howl" is in Suspect below + /// and must not be spawned. Its alert bark stays as the second entry - that is its real voice, + /// just not an ululation. + /// + private static readonly Dictionary Howls = new Dictionary + { + { "Wolf", new[] { "sfx_wolf_haul", "sfx_wolf_alerted" } }, + { "Ulv", new[] { "sfx_wolf_haul", "sfx_wolf_alerted" } }, + { "Fenring", new[] { "sfx_wolf_haul", "sfx_fenring_alerted" } }, + { "Fenring_Cultist", new[] { "sfx_wolf_haul", "sfx_fenring_alerted" } }, + }; + + /// The cue that opens the cultist's fire breath: its own fire-claw snarl. + private static readonly string[] FireRoar = { "sfx_fenring_fireclaw" }; + + /// + /// PREFABS THAT RESOLVE AND MUST NOT BE INSTANTIATED. + /// + /// "sfx_fenring_howl" exists, resolves through the cache to a real GameObject, and takes the + /// process down with it - not an exception BepInEx can catch, a hard exit. It killed the game + /// the first time a Fenrir transformation reached it, and the only reason we know which prefab + /// did it is that its log line had been flushed a moment before. + /// + /// Best guess is that it is not a standalone sound at all but a node belonging to the + /// creature's own rig, fired by that creature's animator and meaningless off it. Described + /// here rather than deleted, because the description is what will settle that - and because a + /// name nobody records is a name somebody adds back. + /// + private static readonly HashSet Suspect = new HashSet { "sfx_fenring_howl" }; + + // Said once per name, because "the howl is silent" cost two rounds of testing to notice and + // the log said nothing either time. + private static readonly HashSet logged = new HashSet(); + public static void PlayHowl(string sourcePrefabName, Vector3 position) + { + string[] names; + if (Howls.TryGetValue(sourcePrefabName, out names) && Play(names, position, sourcePrefabName)) + { + return; + } + + // A form not in the table, or one whose whole list was refused, still gets a voice. + PlayAlertedEffects(sourcePrefabName, position); + } + + public static void PlayFireRoar(Vector3 position) + { + if (!Play(FireRoar, position, "fire roar")) PlayAlertedEffects("Fenring_Cultist", position); + } + + /// Instantiates the first name that resolves and is safe. True if anything played. + private static bool Play(string[] prefabNames, Vector3 position, string label) + { + foreach (string name in prefabNames) + { + GameObject prefab = PrefabManager.Cache.GetPrefab(name); + if (prefab == null) continue; + + // BEFORE the Instantiate, not after. Anything that goes the way sfx_fenring_howl went + // now names itself, and says what it is, while the log can still be written. + if (logged.Add(name)) Describe(label, name, prefab); + + if (Suspect.Contains(name)) continue; + + // A parented object is not a prefab, it is a node inside somebody else's hierarchy. + // Spawning one on its own is the thing this route is suspected of getting wrong. + if (prefab.transform.parent != null) continue; + + Spawn(prefab, position); + return true; + } + + return false; + } + + /// + /// Spawns a sound prefab without letting it write itself into the save. + /// + /// SOME VANILLA SOUND PREFABS CARRY A ZNetView. "sfx_fenring_alerted" is one - the Describe + /// line below printed it, which is how this was noticed. A ZNetView that wakes with no init + /// ZDO calls ZDOMan.CreateNewZDO at its position, marks itself persistent, stamps itself with + /// the prefab hash and registers with the scene. On a sound played every time somebody howls + /// or swings a claw, that is one persistent "there is a noise here" record per swing, saved + /// with the world. It is the same bug that left burnt-in torches in people's worlds; the long + /// version is on SkeletonVisuals.BorrowEffect. + /// + /// ZNetView.StartGhostInit is the game's own answer, not ours: between the two calls a + /// ZNetView comes up with no ZDO at all. Cheaper and far less invasive than stripping the + /// component off a copy, and free on the prefabs that carry no ZNetView. + /// + /// The finally matters. Leaving ghost init switched on because an Instantiate threw would + /// break every ZNetView created afterwards, for the rest of the session. + /// + public static void Spawn(GameObject prefab, Vector3 position) + { + if (prefab == null) return; + + ZNetView.StartGhostInit(); + try + { + Object.Instantiate(prefab, position, Quaternion.identity); + } + finally + { + ZNetView.FinishGhostInit(); + } + + // NOT FOLLOWED BY A Play() CALL, and that took a while to establish. ZSFX is ticked by + // CustomUpdate rather than Unity's Update, so it starts on a later frame: reading + // AudioSource.isPlaying straight after this says false for every sound there is, and + // nudging Play() in on top of a prefab whose own m_playOnAwake is already set is as + // likely to interrupt it as to help. Every sound this mod spawns self-starts. If one ever + // turns up that does not - m_playOnAwake false, checked with "dumpanim " - that is + // the moment to call ZSFX.Play() here, and not before. + } + + /// + /// What a resolved sound actually is: where it sits in its own hierarchy, and what it carries. + /// The root flag is the one to read first - see Play. + /// + private static void Describe(string label, string name, GameObject prefab) + { + string path = prefab.name; + for (Transform t = prefab.transform.parent; t != null; t = t.parent) path = t.name + "/" + path; + + List parts = new List(); + foreach (Component comp in prefab.GetComponentsInChildren(true)) + { + if (comp != null && !(comp is Transform)) parts.Add(comp.GetType().Name); + } + + Jotunn.Logger.LogInfo( + $"[FenrirForm] {label}: '{name}' -> '{path}' root={prefab.transform.parent == null} " + + $"suspect={Suspect.Contains(name)} carries=[{string.Join(", ", parts.ToArray())}]"); + } + + /// + /// The creature's alert EffectList, kept as a fallback. Not trusted as the primary any more: + /// it is what left every howl in the mod silent. + /// + private static void PlayAlertedEffects(string sourcePrefabName, Vector3 position) { GameObject source = PrefabManager.Cache.GetPrefab(sourcePrefabName); BaseAI ai = source != null ? source.GetComponent() : null; - if (ai == null || ai.m_alertedEffects == null) + if (ai == null || ai.m_alertedEffects == null || ai.m_alertedEffects.m_effectPrefabs == null || + ai.m_alertedEffects.m_effectPrefabs.Length == 0) { - Jotunn.Logger.LogWarning($"[FenrirForm] No BaseAI.m_alertedEffects found on '{sourcePrefabName}'."); + if (logged.Add(sourcePrefabName + "-alerted")) + { + Jotunn.Logger.LogWarning( + $"[FenrirForm] No sound for '{sourcePrefabName}': nothing from its table was " + + "playable and its BaseAI.m_alertedEffects is empty."); + } return; } ai.m_alertedEffects.Create(position, Quaternion.identity); + if (logged.Add(sourcePrefabName + "-alerted")) + { + Jotunn.Logger.LogWarning( + $"[FenrirForm] '{sourcePrefabName}': fell through to BaseAI.m_alertedEffects " + + $"({ai.m_alertedEffects.m_effectPrefabs.Length} effect(s)). This route has been " + + "silent before - if you hear nothing, that is why."); + } } } @@ -193,8 +364,9 @@ namespace RacesOfValheim flames = FenrirAttackSync.SpawnFlames(player); // The roar that opens the breath, once per start, the same cue the owner hears. - GameObject sfx = PrefabManager.Cache.GetPrefab("sfx_cultist_attack_fire_start"); - if (sfx != null) Instantiate(sfx, player.transform.position, Quaternion.identity); + // "sfx_cultist_attack_fire_start" was asked for here and there is no sfx_cultist_* + // prefab in the game at all; the fenring's own fire-claw snarl is the real one. + FenrirCreatureSound.PlayFireRoar(player.transform.position); } else if (!fire && flames != null) { Destroy(flames); flames = null; } @@ -221,7 +393,7 @@ namespace RacesOfValheim GameObject sfx = PrefabManager.Cache.GetPrefab(name); if (sfx != null) { - Instantiate(sfx, player.transform.position, Quaternion.identity); + FenrirCreatureSound.Spawn(sfx, player.transform.position); return; } } @@ -333,7 +505,7 @@ namespace RacesOfValheim GameObject sfx = PrefabManager.Cache.GetPrefab(name); if (sfx != null) { - Instantiate(sfx, Player.m_localPlayer.transform.position, Quaternion.identity); + FenrirCreatureSound.Spawn(sfx, Player.m_localPlayer.transform.position); return; } } @@ -365,19 +537,19 @@ namespace RacesOfValheim fenrirAnim.SetFloat("sideway_speed", 0f); fenrirAnim.SetTrigger(triggerName); - FenrirAttackSync.Publish(triggerName, "sfx_fenring_attack", "sfx_fenring_attack_claw", "sfx_wolf_attack"); - PlaySFX("sfx_fenring_attack", "sfx_fenring_attack_claw", "sfx_wolf_attack"); + // The swing. The chain here used to be "sfx_fenring_attack", "sfx_fenring_attack_claw", + // "sfx_wolf_attack", and only the last of those is a prefab in this game - so a Fenring + // has been swinging with a wolf's voice, through a fallback, while the creature's own + // sound sat there unused under a different name. + FenrirAttackSync.Publish(triggerName, "sfx_fenring_claw_start"); + PlaySFX("sfx_fenring_claw_start"); yield return new WaitForSeconds(dmgDelay); - if (ZNetScene.instance != null) - { - GameObject attackSfx = ZNetScene.instance.GetPrefab("sfx_fenring_attack"); - if (attackSfx != null) - { - Instantiate(attackSfx, Player.m_localPlayer.transform.position, Quaternion.identity); - } - } + // The hit, as opposed to the swing PlaySFX covers above. This asked for + // "sfx_fenring_attack" on its own, which is not a prefab in this game, so the claw landed + // in silence - same dead name as the jump attack's, same replacement. + PlaySFX("sfx_fenring_claw_hit"); ExecuteClawDamage(baseDamage); @@ -404,16 +576,12 @@ namespace RacesOfValheim // Aspettiamo che l'animazione si carichi (0.75s) yield return new WaitForSeconds(0.75f); - if (ZNetScene.instance != null) - { - GameObject attackSfx = ZNetScene.instance.GetPrefab("sfx_fenring_attack"); - if (attackSfx != null) - { - Instantiate(attackSfx, Player.m_localPlayer.transform.position, Quaternion.identity); - } - } + // The impact sound used to be played HERE, which is mid-air: the jump has not started + // yet, let alone landed. It now fires at the end of the dash, next to the damage. It also + // asked for "sfx_fenring_attack", which is not a prefab in this game, so it was silent + // either way. - // Invece di una singola spinta di velocità (che viene subito annullata da Valheim), + // Invece di una singola spinta di velocità (che viene subito annullata da Valheim), // muoviamo esplicitamente il personaggio fotogramma per fotogramma per 0.2 secondi float dashDuration = 0.2f; float elapsedDash = 0f; @@ -438,7 +606,9 @@ namespace RacesOfValheim yield return new WaitForFixedUpdate(); } - // Infliggiamo il danno al termine dello scatto + // Infliggiamo il danno al termine dello scatto, che è anche il momento dell'atterraggio: + // il suono d'impatto va qui, non prima dello scatto. + PlaySFX("sfx_fenring_claw_hit"); ExecuteClawDamage(FenrirConfig.FenringJumpAttackDamage.Value); // Tempo per riprendersi dall'atterraggio prima di potersi muovere di nuovo @@ -620,7 +790,7 @@ namespace RacesOfValheim GameObject sfx = PrefabManager.Cache.GetPrefab(name); if (sfx != null) { - Instantiate(sfx, Player.m_localPlayer.transform.position, Quaternion.identity); + FenrirCreatureSound.Spawn(sfx, Player.m_localPlayer.transform.position); return; } } @@ -658,7 +828,8 @@ namespace RacesOfValheim cultistAnim.SetBool("attack_fire", true); FenrirAttackSync.PublishFire(true); - PlaySFX("sfx_cultist_attack_fire_start"); + // Same cue the remote mirror plays - see the fire branch in the sync behaviour above. + FenrirCreatureSound.PlayFireRoar(Player.m_localPlayer.transform.position); cultistAnim.SetTrigger("attack_flames"); FenrirAttackSync.Publish("attack_flames"); @@ -770,11 +941,11 @@ namespace RacesOfValheim // Per il Cultista usiamo esplicitamente il trigger dell'artigliata cultistAnim.SetTrigger("attack_claw"); - FenrirAttackSync.Publish("attack_claw", "sfx_cultist_attack", "sfx_fenring_attack", "sfx_wolf_attack"); + FenrirAttackSync.Publish("attack_claw", "sfx_fenring_claw_start"); yield return new WaitForSeconds(0.4f); - PlaySFX("sfx_cultist_attack", "sfx_fenring_attack", "sfx_wolf_attack"); + PlaySFX("sfx_fenring_claw_start"); ExecuteClawDamage(FenrirConfig.CultistClawDamage.Value); @@ -796,12 +967,12 @@ namespace RacesOfValheim cultistAnim.SetFloat("sideway_speed", 0f); cultistAnim.SetTrigger("attack_claw_double"); - FenrirAttackSync.Publish("attack_claw_double", "sfx_cultist_attack_double", "sfx_cultist_attack", "sfx_fenring_attack"); + FenrirAttackSync.Publish("attack_claw_double", "sfx_fenring_claw_start"); // L'animazione double claw è più lunga, facciamo il danno un po' dopo yield return new WaitForSeconds(0.6f); - PlaySFX("sfx_cultist_attack_double", "sfx_cultist_attack", "sfx_fenring_attack"); + PlaySFX("sfx_fenring_claw_start"); ExecuteClawDamage(FenrirConfig.CultistDoubleClawDamage.Value); @@ -946,7 +1117,7 @@ namespace RacesOfValheim GameObject sfx = PrefabManager.Cache.GetPrefab(name); if (sfx != null) { - Instantiate(sfx, Player.m_localPlayer.transform.position, Quaternion.identity); + FenrirCreatureSound.Spawn(sfx, Player.m_localPlayer.transform.position); return; } } @@ -969,7 +1140,7 @@ namespace RacesOfValheim GameObject attackSfx = ZNetScene.instance.GetPrefab("sfx_wolf_attack"); if (attackSfx != null) { - Instantiate(attackSfx, Player.m_localPlayer.transform.position, Quaternion.identity); + FenrirCreatureSound.Spawn(attackSfx, Player.m_localPlayer.transform.position); } } @@ -1121,7 +1292,7 @@ namespace RacesOfValheim GameObject sfx = PrefabManager.Cache.GetPrefab(name); if (sfx != null) { - Instantiate(sfx, Player.m_localPlayer.transform.position, Quaternion.identity); + FenrirCreatureSound.Spawn(sfx, Player.m_localPlayer.transform.position); return; } } @@ -1135,17 +1306,12 @@ namespace RacesOfValheim try { ulvAnim.SetFloat("sideway_speed", 0f); } catch {} try { ulvAnim.SetTrigger(triggerName); } catch {} - FenrirAttackSync.Publish(triggerName, "sfx_ulv_attack", "sfx_wolf_attack", "sfx_fenring_attack"); + FenrirAttackSync.Publish(triggerName, "sfx_wolf_attack"); - // Scegli il suono appropriato per l'attacco - if (triggerName == "attack_bite") - { - PlaySFX("sfx_ulv_attack", "sfx_wolf_attack", "sfx_fenring_attack"); - } - else - { - PlaySFX("sfx_ulv_attack", "sfx_wolf_attack", "sfx_fenring_attack"); - } + // Un solo suono per entrambi i trigger. I due rami esistevano per scegliere fra + // "sfx_ulv_attack" e il ripiego sul lupo, ma l'Ulv non ha un prefab d'attacco in vanilla + // - c'e solo sfx_ulv_death - quindi entrambi suonavano il lupo comunque. + PlaySFX("sfx_wolf_attack"); yield return new WaitForSeconds(dmgDelay); @@ -1154,7 +1320,7 @@ namespace RacesOfValheim GameObject attackSfx = ZNetScene.instance.GetPrefab("sfx_wood_hit"); if (attackSfx != null) { - Instantiate(attackSfx, Player.m_localPlayer.transform.position, Quaternion.identity); + FenrirCreatureSound.Spawn(attackSfx, Player.m_localPlayer.transform.position); } } @@ -1241,8 +1407,8 @@ namespace RacesOfValheim try { ulvAnim.SetFloat("sideway_speed", 0f); } catch {} try { ulvAnim.SetTrigger("attack_slash"); } catch {} - FenrirAttackSync.Publish("attack_slash", "sfx_ulv_attack", "sfx_wolf_attack"); - PlaySFX("sfx_ulv_attack", "sfx_wolf_attack"); + FenrirAttackSync.Publish("attack_slash", "sfx_wolf_attack"); + PlaySFX("sfx_wolf_attack"); yield return new WaitForSeconds(0.3f); // Wait 0.3s before leaping @@ -1267,7 +1433,7 @@ namespace RacesOfValheim GameObject attackSfx = ZNetScene.instance.GetPrefab("sfx_wood_hit"); if (attackSfx != null) { - Instantiate(attackSfx, Player.m_localPlayer.transform.position, Quaternion.identity); + FenrirCreatureSound.Spawn(attackSfx, Player.m_localPlayer.transform.position); } } diff --git a/JotunnModStub/Fenrir/FenrirRace.cs b/JotunnModStub/Fenrir/FenrirRace.cs index a98f6d3..4e55a80 100644 --- a/JotunnModStub/Fenrir/FenrirRace.cs +++ b/JotunnModStub/Fenrir/FenrirRace.cs @@ -236,11 +236,16 @@ namespace RacesOfValheim { SpawnPoofEffect(); - if (ZNetScene.instance != null) - { - GameObject howlPrefab = ZNetScene.instance.GetPrefab("sfx_wolf_howl") ?? ZNetScene.instance.GetPrefab("sfx_fenring_idle"); - if (howlPrefab != null) Instantiate(howlPrefab, Player.m_localPlayer.transform.position, Quaternion.identity); - } + // The howl of the creature being turned into, read off that creature. This used to look + // for "sfx_wolf_howl" and fall back to "sfx_fenring_idle": the first is not a prefab in + // this game, and the second is real but is the creature's ambient grunt, so every + // transformation announced itself with a small idle noise. FenrirCreatureSound exists for + // exactly this - see the note at the top of FenrirBehaviors for how it reads a creature's + // own voice off BaseAI.m_alertedEffects, which is the only route the Wolf and the Ulv + // have. The two Fenring forms could do better: vanilla does ship "sfx_fenring_howl", a + // real howl rather than an alert bark, and preferring it when it exists would cost four + // lines here. + FenrirCreatureSound.PlayHowl(CreaturePrefabFor(rules.Form), Player.m_localPlayer.transform.position); yield return new WaitForSeconds(0.1f); @@ -326,18 +331,26 @@ namespace RacesOfValheim { if (sparks != null) Instantiate(sparks, pos, Quaternion.identity); } + /// + /// The vanilla creature a form is built from. One place rather than two, because the howl + /// that announces a transformation has to be read off the same creature the body comes from. + /// + private static string CreaturePrefabFor(FenrirProgression.FormType form) + { + switch (form) + { + case FenrirProgression.FormType.Wolf: return "Wolf"; + case FenrirProgression.FormType.Ulv: return "Ulv"; + case FenrirProgression.FormType.Fenring: return "Fenring"; + case FenrirProgression.FormType.Cultist: return "Fenring_Cultist"; + } + return ""; + } + private void ExecuteTransformation(FenrirProgression.FormRules rules) { Transform playerVisual = Player.m_localPlayer.transform.Find("Visual"); - string prefabName = ""; - - switch (rules.Form) - { - case FenrirProgression.FormType.Wolf: prefabName = "Wolf"; break; - case FenrirProgression.FormType.Ulv: prefabName = "Ulv"; break; - case FenrirProgression.FormType.Fenring: prefabName = "Fenring"; break; - case FenrirProgression.FormType.Cultist: prefabName = "Fenring_Cultist"; break; - } + string prefabName = CreaturePrefabFor(rules.Form); GameObject prefab = PrefabManager.Cache.GetPrefab(prefabName); @@ -363,9 +376,30 @@ namespace RacesOfValheim { currentTransformation = Instantiate(visual.gameObject, Player.m_localPlayer.transform); currentTransformation.transform.localPosition = Vector3.zero; currentTransformation.transform.localRotation = Quaternion.identity; + // DEAD LINE, kept until somebody decides what it was for. The game has no type + // called "AnimEvent" - the animation-event dispatcher is CharacterAnimEvent - and + // GetComponent(string) matches a type name in full, so this has never found + // anything and the Destroy has never run. Component animEvent = currentTransformation.GetComponent("AnimEvent"); if (animEvent != null) Destroy(animEvent); + // The creature's own animations carry their sounds as events; this is what hears + // them. On the object that owns the Animator, because that is where Unity delivers + // an animation event - for the wolf that is WolfSmooth, two levels down, not the + // Visual this method has in hand. + Animator formAnimator = currentTransformation.GetComponentInChildren(true); + if (formAnimator != null) + { + formAnimator.gameObject.AddComponent(); + Jotunn.Logger.LogInfo( + $"[FenrirForm] animation-event listener on '{formAnimator.gameObject.name}'."); + } + else + { + Jotunn.Logger.LogWarning( + "[FenrirForm] no Animator under the form; animation sounds will not play."); + } + float ttl = rules.DurationMinutes > 0 ? (rules.DurationMinutes * 60f) : 0f; if (prefabName == "Ulv") diff --git a/JotunnModStub/Fenrir/FormAnimEventSound.cs b/JotunnModStub/Fenrir/FormAnimEventSound.cs new file mode 100644 index 0000000..4fdea87 --- /dev/null +++ b/JotunnModStub/Fenrir/FormAnimEventSound.cs @@ -0,0 +1,89 @@ +using System.Collections.Generic; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// Plays the sounds Valheim wires into a creature's own animation clips, for a player wearing + /// that creature. + /// + /// THE HOWL WAS NEVER A PREFAB TO LOOK UP. It is an AnimationEvent. The wolf's animator carries a + /// clip called 'C_Hawl' whose single event, at 0.39s, calls a method named Effect and hands it the + /// sound as an object reference: + /// + /// 'C_Hawl' 3.13s loop=True events=1 + /// @0.39s Effect() ref='sfx_wolf_haul' (GameObject) + /// + /// Two things follow from that, and both are better than what the mod was doing. First, the clip + /// already plays on its own: a player in wolf form idles through 'C_Hawl' like any other idle, so + /// the howl animation costs nothing to get. Second, the sound belongs at 0.39s into that clip and + /// nowhere else, which is something no amount of instantiating a prefab on a keypress can match. + /// + /// Three names, three spellings, and that is the whole reason this took so long to find: the clip + /// is 'C_Hawl', the sound is 'sfx_wolf_haul', and the mod was looking for 'sfx_wolf_howl' - the + /// only correct spelling of the three, and the only one that does not exist. + /// + /// Unity calls Effect BY NAME on the components of the GameObject that owns the Animator, so this + /// has to sit there and the method must keep that name. + /// + internal class FormAnimEventSound : MonoBehaviour + { + private static readonly HashSet logged = new HashSet(); + + /// + /// Off whenever the game's own receiver is on this object, which in practice is always. + /// + /// A player in wolf form idles through 'C_Hawl' and howls, out loud, with no help from this + /// class - confirmed in game. AnimationEffect, which sits beside the Animator on the form + /// along with CharacterAnimEvent, is doing that already. Two receivers for one event means two + /// howls, so this stands down and stays only as cover for a form that turns out not to carry + /// one. The log says which of the two happened, once per form, so nobody has to wonder. + /// + private bool standDown; + + private void Awake() + { + standDown = GetComponent("AnimationEffect") != null; + + if (logged.Add("attach/" + name)) + { + Jotunn.Logger.LogInfo( + standDown + ? $"[FenrirForm] '{name}' already carries AnimationEffect; leaving animation sounds to it." + : $"[FenrirForm] '{name}' has no AnimationEffect; handling animation sounds here."); + } + } + + /// + /// CALLED BY UNITY from an AnimationEvent. Do not rename, and do not make it private. + /// + /// Only object references are taken, and only when they carry audio. The clips also fire + /// Effect with a string and no reference - 'Jump' does, with string='jump' - and that form + /// means "look something up", which is a different job and somebody else's. The audio test is + /// there because an animation can reference anything at all, and a form is not the place to + /// find out what spawning an arbitrary vanilla object does. + /// + public void Effect(AnimationEvent e) + { + if (standDown) return; + + GameObject prefab = e.objectReferenceParameter as GameObject; + if (prefab == null) return; + + bool audible = prefab.GetComponentInChildren(true) != null; + + if (logged.Add(prefab.name)) + { + Jotunn.Logger.LogInfo( + $"[FenrirForm] animation event Effect on '{name}' -> '{prefab.name}' " + + $"audio={audible}{(audible ? "" : ", skipped")}."); + } + + if (!audible) return; + + // Through the same ghost-init spawn as everything else here: some vanilla sound prefabs + // carry a ZNetView, and this one fires every time the animation comes round. + FenrirCreatureSound.Spawn(prefab, transform.position); + } + } +}