RacesOfValheim/JotunnModStub/Fenrir/FenrirBehaviors.cs
kanym beffd0bee6 fix: a stagger cancels the form's attack
A form swing waits for its clip's hit event and lands on a timeout if none comes,
so a stagger that cut the clip short still dealt the blow. Attacks are marked as
they start (TrySpendStamina, Ravager AttackRoutine) and their hits are dropped if
a stagger began since. No attack or Cultist breath starts while staggered.
2026-10-29 13:53:04 +01:00

1731 lines
80 KiB
C#

using System.Collections;
using System.Collections.Generic;
using BepInEx;
using HarmonyLib;
using Jotunn.Configs;
using Jotunn.Entities;
using Jotunn.Managers;
using UnityEngine;
using UnityEngine.UI; // Added for UI
namespace RacesOfValheim
{
/// <summary>
/// The voice of the creature a Fenrir is wearing.
///
/// 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".
/// </summary>
internal static class FenrirCreatureSound
{
/// <summary>
/// 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.
/// </summary>
private static readonly Dictionary<string, string[]> Howls = new Dictionary<string, string[]>
{
{ "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" } },
};
/// <summary>The cue that opens the cultist's fire breath: its own fire-claw snarl.</summary>
private static readonly string[] FireRoar = { "sfx_fenring_fireclaw" };
/// <summary>
/// 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.
/// </summary>
private static readonly HashSet<string> Suspect = new HashSet<string> { "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<string> logged = new HashSet<string>();
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);
}
/// <summary>
/// State names to try when a creature has no howl trigger. 'C_Hawl' first, and that spelling
/// is not a typo here - it is the game's, on the wolf's own clip.
/// </summary>
private static readonly string[] HowlStates = { "C_Hawl", "C_Howl", "Hawl", "Howl", "Taunt" };
/// <summary>
/// The creatures whose howl ANIMATION already carries the sound, so playing a prefab as well
/// would be a second howl over the first.
///
/// ONLY THE WOLF. Its 'C_Hawl' fires an Effect event at 0.39s holding sfx_wolf_haul. The Ulv
/// is the same family on the same rig and its 'Idle Howl' carries no event at all - checked
/// with "dumpanim Ulv", which reads events=0 on that clip. Assuming the two behaved alike is
/// what made the Ulv mouth a silent howl: the animation played, the code took that as proof
/// the sound was coming, and nothing was ever spawned.
/// </summary>
private static readonly HashSet<string> HowlAnimationHasSound = new HashSet<string> { "Wolf" };
/// <summary>
/// One howl: the creature's own animation where it has one, and a sound unless that animation
/// is already bringing it. The four forms call this and nothing else.
/// </summary>
public static void Howl(Animator animator, string creature, Vector3 position)
{
string trigger;
bool animated = TryHowlAnimation(animator, creature, out trigger);
// A trigger replicates to the other clients; a state played directly does not.
if (animated && trigger != null) FenrirAttackSync.Publish(trigger);
if (!animated || !HowlAnimationHasSound.Contains(creature))
{
PlayHowl(creature, position);
}
}
/// <summary>
/// Makes the worn creature perform its own howl, and says whether it could.
///
/// WORTH KNOWING BEFORE READING THE CODE: on the wolf this brings the sound with it. Its howl
/// clip carries the sound as an animation event - 'C_Hawl' fires Effect at 0.39s holding
/// sfx_wolf_haul - and the game's own AnimationEffect, which sits beside the Animator on the
/// form, plays it. So for the wolf and the Ulv there is no sound to spawn at all: play the
/// animation and the howl comes out of it, at the instant the animation means it to.
///
/// A TRIGGER IS TRIED BEFORE A STATE, and the reason is multiplayer rather than tidiness.
/// FenrirAttackSync replicates trigger names, so a howl fired through a trigger is a howl the
/// other clients see and hear. Animator.Play is local: it works, and nobody else knows.
/// <paramref name="triggerName"/> comes back non-null exactly when the caller has something
/// worth publishing.
/// </summary>
public static bool TryHowlAnimation(Animator animator, string creature, out string triggerName)
{
triggerName = null;
if (animator == null || animator.runtimeAnimatorController == null) return false;
foreach (AnimatorControllerParameter p in animator.parameters)
{
if (p.type != AnimatorControllerParameterType.Trigger) continue;
string lower = p.name.ToLower();
if (!lower.Contains("hawl") && !lower.Contains("howl") && !lower.Contains("taunt")) continue;
animator.SetTrigger(p.name);
triggerName = p.name;
LogHowlRouteOnce(creature, $"trigger '{p.name}'");
return true;
}
foreach (string state in HowlStates)
{
int hash = Animator.StringToHash(state);
if (!animator.HasState(0, hash)) continue;
animator.Play(hash, 0);
LogHowlRouteOnce(creature, $"state '{state}', played directly - local only, " +
"no trigger exists to replicate it");
return true;
}
// Nothing matched, so say what there was to match against. A keypress that does nothing is
// the thing this whole exercise started from.
List<string> parameters = new List<string>();
foreach (AnimatorControllerParameter p in animator.parameters) parameters.Add($"{p.name}({p.type})");
LogHowlRouteOnce(creature,
"no howl trigger and no howl state. Parameters: " + string.Join(", ", parameters.ToArray()) +
". Run 'dumpanim " + creature + "' for its clip list");
return false;
}
private static void LogHowlRouteOnce(string creature, string route)
{
if (logged.Add("howl/" + creature)) Jotunn.Logger.LogInfo($"[FenrirForm] howl for '{creature}': {route}.");
}
/// <summary>Instantiates the first name that resolves and is safe. True if anything played.</summary>
private static bool Play(string[] prefabNames, Vector3 position, string label)
{
foreach (string name in prefabNames)
{
GameObject prefab = PrefabManager.Cache.GetPrefab<GameObject>(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;
}
/// <summary>
/// Spawns a sound prefab the way the game's own EffectList.Create does: a plain Instantiate.
///
/// THIS USED TO WRAP THE INSTANTIATE IN ZNetView GHOST INIT, and that was wrong. Some vanilla
/// sound and effect prefabs carry a ZNetView ("sfx_fenring_alerted" does), and the fear was
/// one persistent ZDO per play left in the save. The ones logged so far also carry
/// TimedDestruction, which ends in ZNetScene.Destroy, and that deletes the ZDO. They are
/// network effects by design, which is how other players hear them.
///
/// Ghost init does not prevent the ZDO either. Read off ZNetView.Awake: it still calls
/// CreateNewZDO and only skips ZNetScene.AddInstance. That leaves the ZDO with Created=false,
/// and ZNetScene.CreateObjectsSorted builds a second copy of the object from it. Vanilla
/// uses ghost init for zone generation, where the ZDOs are the point and the objects are not.
/// The switch that really yields no ZDO is m_forceDisableInit, which is for item icons and
/// inventory copies, not for anything meant to be seen or heard by others.
/// </summary>
public static void Spawn(GameObject prefab, Vector3 position)
{
if (prefab == null) return;
Object.Instantiate(prefab, position, Quaternion.identity);
// 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 <name>" - that is
// the moment to call ZSFX.Play() here, and not before.
}
/// <summary>
/// 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.
/// </summary>
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<string> parts = new List<string>();
foreach (Component comp in prefab.GetComponentsInChildren<Component>(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())}]");
}
/// <summary>
/// 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.
/// </summary>
private static void PlayAlertedEffects(string sourcePrefabName, Vector3 position)
{
GameObject source = PrefabManager.Cache.GetPrefab<GameObject>(sourcePrefabName);
BaseAI ai = source != null ? source.GetComponent<BaseAI>() : null;
if (ai == null || ai.m_alertedEffects == null || ai.m_alertedEffects.m_effectPrefabs == null ||
ai.m_alertedEffects.m_effectPrefabs.Length == 0)
{
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.");
}
}
}
/// <summary>
/// The attack half of somebody else's form: the owner's client publishes each trigger it fires
/// on its own copy of the Animator, RemoteFenrirAnimator replays it on the copy every other
/// client sees. The running count rides along because an unchanged ZDO string would never
/// re-fire a Unity Animator trigger when the same bite lands twice in a row - the same trick as
/// DrakeFormBehavior.AttackTriggerKey and SvermRavagerForm.AttackTriggerKey.
/// </summary>
public static class FenrirAttackSync
{
public const string Key = "RacesOfValheim_FenrirAttack";
private static int seq = 0;
// The cultist's flame is a held bool on the Animator, not a one-shot trigger, so it gets a
// key of its own: a sequence number would say "it started" but never "it stopped".
public const string FireKey = "RacesOfValheim_FenrirFire";
/// <summary>
/// The flame the cultist breathes, parented to the given player so it follows them. One
/// place for it because the owner's own copy and every onlooker's copy have to look alike.
/// </summary>
public static GameObject SpawnFlames(Player player)
{
if (player == null || ZNetScene.instance == null) return null;
// Un effetto che dura nel tempo, trovato dai log!
GameObject fireVfx = ZNetScene.instance.GetPrefab("fx_fenring_flames");
if (fireVfx == null) return null;
GameObject instance = Object.Instantiate(fireVfx, MouthPoint(player), player.transform.rotation, player.transform);
instance.AddComponent<CultistFlameFollow>().Player = player;
// Aumentiamo la durata delle particelle del 20%
foreach (ParticleSystem ps in instance.GetComponentsInChildren<ParticleSystem>())
{
var main = ps.main;
main.startLifetimeMultiplier *= 1.2f;
}
return instance;
}
// Bone names the breath leaves from, mouth first. Matched by name anywhere under the form.
private static readonly string[] MouthBones = { "Jaw", "Head" };
/// <summary>
/// Where the Cultist's breath starts: just ahead of the form's jaw (or head), so it leaves the
/// mouth at whatever size the form stands. It used to be a fixed 1.5 m above the player's
/// feet, chest height on a Cultist, which is the "fire starts too low" report. Falls back on
/// that fixed point if the form has neither bone.
/// </summary>
public static Vector3 MouthPoint(Player player) => MouthPoint(player, FindMouth(player));
public static Vector3 MouthPoint(Player player, Transform bone)
{
Transform body = player.transform;
return bone != null
? bone.position + body.forward * 0.3f
: body.position + Vector3.up * 1.5f + body.forward;
}
public static Transform FindMouth(Player player)
{
foreach (string wanted in MouthBones)
{
foreach (Transform child in player.transform)
{
if (child.name == "Visual" || !child.gameObject.activeInHierarchy) continue;
foreach (Transform t in child.GetComponentsInChildren<Transform>())
{
if (string.Equals(t.name, wanted, System.StringComparison.OrdinalIgnoreCase)) return t;
}
}
}
return null;
}
public static void PublishFire(bool on)
{
Player player = Player.m_localPlayer;
ZNetView nview = player != null ? player.GetComponent<ZNetView>() : null;
if (nview == null || !nview.IsValid()) return;
nview.GetZDO().Set(FireKey, on);
}
/// <summary>
/// Publishes a trigger, and with it the swing's sound: the candidate prefab names in the
/// order the owner's own PlaySFX would try them, or "@Creature" for a howl borrowed from
/// that creature's alert effect. Only the opening cue rides along; the impact sounds are
/// decided by what the swing hits, which an onlooker's client never works out.
/// </summary>
public static void Publish(string trigger, params string[] sfx)
{
Player player = Player.m_localPlayer;
ZNetView nview = player != null ? player.GetComponent<ZNetView>() : null;
if (nview == null || !nview.IsValid()) return;
seq++;
string payload = trigger + "#" + seq;
if (sfx != null && sfx.Length > 0) payload += "#" + string.Join("|", sfx);
nview.GetZDO().Set(Key, payload);
}
}
/// <summary>
/// The animation half of somebody else's form.
///
/// The four behaviours below drive their model's Animator from the player's own, and every
/// one of them runs on the transformed player's client only: FenrirRace.ExecuteTransformation
/// is what adds them, and they read Player.m_localPlayer throughout. RacesVisualController
/// spawns the same model on every other client from the ZDO, and used to spawn nothing else -
/// no parameter was ever written to that copy's Animator, so it sat in its controller's
/// default state and slid across the terrain. The wolf's owner saw a wolf running; everyone
/// else saw a statue on rails.
///
/// This is the piece that was missing, and it is the arrangement Skadi already uses for its
/// remote dragons (RemoteSkadiAnimator). The parameters come from the remote player's own
/// Visual Animator, which ZSyncAnimation keeps fed over the network for every character a
/// client can see - hiding the body hides renderers, not the animation - so the form walks,
/// runs, jumps and creeps exactly when the real player does.
///
/// Kept next to the four local behaviours on purpose: this mirrors the movement half of their
/// Update, and the two have to be changed together.
///
/// Attacks are triggers fired from input on the owner's client; FenrirAttackSync publishes
/// each one on the ZDO and this component replays it below.
/// </summary>
public class RemoteFenrirAnimator : MonoBehaviour
{
private Player player;
private Animator playerAnim;
private Animator formAnim;
private ZNetView nview;
private string lastAttack;
private GameObject flames;
private readonly FormLocomotion locomotion = new FormLocomotion();
// The flames hang off the player, not this model, so they outlive it unless taken down.
private void OnDestroy()
{
if (flames != null) Destroy(flames);
}
private void Update()
{
// Resolved here rather than in Start: the model is instantiated under a player who may
// still be assembling their own rig on the frame it arrives.
if (player == null) player = GetComponentInParent<Player>();
if (player == null) return;
if (formAnim == null) formAnim = GetComponent<Animator>() ?? GetComponentInChildren<Animator>();
if (playerAnim == null)
{
Transform visual = player.transform.Find("Visual");
if (visual != null) playerAnim = visual.GetComponent<Animator>();
}
if (formAnim == null || playerAnim == null) return;
ReplayAttack();
ReplayFire();
// The same helper the local behaviours use, so both views of the same wolf agree.
// Player.IsCrouching answers off the animator's current state, which is replicated, so
// it is true here too.
locomotion.Mirror(formAnim, playerAnim, player);
}
// Written every frame while the flag is set, and only when the controller has the bool: a
// wolf or a Ulv has no "attack_fire", and the ZDO key is only ever true for the cultist.
private void ReplayFire()
{
if (nview == null || !nview.IsValid()) return;
bool fire = nview.GetZDO().GetBool(FenrirAttackSync.FireKey, false);
// The breath itself: up while the flag is, gone when it drops. Only the cultist ever
// sets the flag, so no other form can grow flames here.
if (fire && flames == null)
{
flames = FenrirAttackSync.SpawnFlames(player);
// The roar that opens the breath, once per start, the same cue the owner hears.
// "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; }
foreach (AnimatorControllerParameter p in formAnim.parameters)
{
if (p.type == AnimatorControllerParameterType.Bool && p.name == "attack_fire")
{
formAnim.SetBool("attack_fire", fire);
break;
}
}
}
private void PlayAttackSound(string[] names)
{
foreach (string name in names)
{
if (name.StartsWith("@"))
{
FenrirCreatureSound.PlayHowl(name.Substring(1), player.transform.position);
return;
}
GameObject sfx = PrefabManager.Cache.GetPrefab<GameObject>(name);
if (sfx != null)
{
FenrirCreatureSound.Spawn(sfx, player.transform.position);
return;
}
}
}
private void ReplayAttack()
{
if (nview == null) nview = player.GetComponent<ZNetView>();
if (nview == null || !nview.IsValid()) return;
string current = nview.GetZDO().GetString(FenrirAttackSync.Key, "");
// First look at the ZDO only records what is already there, so a trigger left over from
// an earlier form does not replay the instant this model is built.
if (lastAttack == null) { lastAttack = current; return; }
if (string.IsNullOrEmpty(current) || current == lastAttack) return;
lastAttack = current;
string[] parts = current.Split('#');
string trigger = parts[0];
if (parts.Length > 2) PlayAttackSound(parts[2].Split('|'));
// Only the triggers this particular borrowed controller actually has: the four forms
// share none of the attack names but the taunt.
foreach (AnimatorControllerParameter p in formAnim.parameters)
{
if (p.type == AnimatorControllerParameterType.Trigger && p.name == trigger)
{
formAnim.SetTrigger(trigger);
break;
}
}
}
}
public class FenrirFormBehavior : MonoBehaviour
{
private const string FormLabel = "Fenring";
private Animator playerAnim;
private Animator fenrirAnim;
private readonly FormLocomotion locomotion = new FormLocomotion();
private float busySince = -1f;
// A property so every form tells FenrirForms.LocalAttacking too: Fenrir_FormHoldStill_Patch
// holds the player still for exactly as long as an attack clip runs.
private bool attacking;
private bool isAttacking { get => attacking; set { attacking = value; FenrirForms.LocalAttacking = value; } }
void Start()
{
playerAnim = Player.m_localPlayer.transform.Find("Visual").GetComponent<Animator>();
fenrirAnim = GetComponent<Animator>();
if (fenrirAnim == null) fenrirAnim = GetComponentInChildren<Animator>();
}
void Update()
{
if (FormAnimGuard.Stuck(isAttacking, ref busySince))
{
StopAllCoroutines();
isAttacking = false;
}
if (playerAnim == null || fenrirAnim == null) return;
// Se stiamo attaccando, l'Update smette di inviare costantemente
// "onGround", inWater, forward_speed ecc. alle variabili di base?
// Meglio continuare a sincronizzare i movimenti base.
if (!isAttacking)
{
bool isGrounded = locomotion.Mirror(fenrirAnim, playerAnim, Player.m_localPlayer);
if (isGrounded && RaceInput.Allowed)
{
if (FenrirConfig.HowlKey.Value.IsDownIgnoringHeldKeys())
{
StartCoroutine(HowlRoutine());
}
else if (RaceInput.AttackDown(1) && FormMelee.TrySpendStamina(Player.m_localPlayer, FenrirConfig.FenringHeavyClawStamina.Value, Skills.SkillType.Unarmed)) // Tasto destro (Heavy Claw)
{
StartCoroutine(ClawRoutine("attack_claw1", FenrirConfig.FenringHeavyClawDamage.Value, 1.2f, 0.5f));
}
else if (RaceInput.AttackDown(0) && FormMelee.TrySpendStamina(Player.m_localPlayer, FenrirConfig.FenringLightClawStamina.Value, Skills.SkillType.Unarmed)) // Tasto sinistro
{
StartCoroutine(ClawRoutine("attack_claw0", FenrirConfig.FenringLightClawDamage.Value, 1.0f, 0.4f));
}
else if (RaceInput.AttackDown(2) && FormMelee.TrySpendStamina(Player.m_localPlayer, FenrirConfig.FenringJumpAttackStamina.Value, Skills.SkillType.Unarmed)) // Tasto centrale
{
StartCoroutine(JumpAttackRoutine());
}
}
}
}
private void PlaySFX(params string[] prefabNames)
{
foreach (string name in prefabNames)
{
GameObject sfx = PrefabManager.Cache.GetPrefab<GameObject>(name);
if (sfx != null)
{
FenrirCreatureSound.Spawn(sfx, Player.m_localPlayer.transform.position);
return;
}
}
Jotunn.Logger.LogWarning($"[FenrirForm] Nessun suono trovato tra: {string.Join(", ", prefabNames)}");
}
private IEnumerator HowlRoutine()
{
isAttacking = true;
fenrirAnim.SetFloat("forward_speed", 0f);
fenrirAnim.SetFloat("sideway_speed", 0f);
fenrirAnim.SetTrigger("attack_taunt");
FenrirAttackSync.Publish("attack_taunt", "@Fenring");
FenrirCreatureSound.PlayHowl("Fenring", Player.m_localPlayer.transform.position);
yield return new WaitForSeconds(2.0f);
isAttacking = false;
}
private IEnumerator ClawRoutine(string triggerName, float baseDamage, float lockDuration, float dmgDelay)
{
isAttacking = true;
FormAnimGuard.LeaveHowl(fenrirAnim);
fenrirAnim.SetFloat("forward_speed", 0f);
fenrirAnim.SetFloat("sideway_speed", 0f);
fenrirAnim.SetTrigger(triggerName);
// 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);
// 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);
float remainingTimeToIdle = lockDuration - dmgDelay;
if (remainingTimeToIdle > 0)
{
yield return new WaitForSeconds(remainingTimeToIdle);
}
fenrirAnim.ResetTrigger(triggerName);
isAttacking = false;
}
private IEnumerator JumpAttackRoutine()
{
isAttacking = true;
FormAnimGuard.LeaveHowl(fenrirAnim);
fenrirAnim.SetFloat("forward_speed", 0f);
fenrirAnim.SetFloat("sideway_speed", 0f);
fenrirAnim.SetTrigger("attack_jump");
FenrirAttackSync.Publish("attack_jump");
// Aspettiamo che l'animazione si carichi (0.75s)
yield return new WaitForSeconds(0.75f);
// 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),
// muoviamo esplicitamente il personaggio fotogramma per fotogramma per 0.2 secondi
float dashDuration = 0.2f;
float elapsedDash = 0f;
while (elapsedDash < dashDuration)
{
if (Player.m_localPlayer != null)
{
Rigidbody rb = Player.m_localPlayer.GetComponent<Rigidbody>();
if (rb != null)
{
Vector3 dashVelocity = Player.m_localPlayer.transform.forward * FenrirConfig.FenringJumpDashSpeed.Value;
// Spinta verso l'alto solo nella prima metà dello scatto
if (elapsedDash < dashDuration / 2f)
{
dashVelocity += Vector3.up * FenrirConfig.FenringJumpDashUpwardSpeed.Value;
}
rb.MovePosition(rb.position + dashVelocity * Time.fixedDeltaTime);
}
}
elapsedDash += Time.fixedDeltaTime;
yield return new WaitForFixedUpdate();
}
// 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
yield return new WaitForSeconds(0.55f);
fenrirAnim.ResetTrigger("attack_jump");
isAttacking = false;
}
private void ExecuteClawDamage(float baseDamage)
{
if (Player.m_localPlayer == null || FormStagger.AttackInterrupted) return;
Vector3 playerPos = Player.m_localPlayer.transform.position;
Vector3 attackPoint = playerPos + Player.m_localPlayer.transform.forward * 1.5f + Vector3.up * 1f;
float attackRadius = FenrirConfig.FenringAttackRadius.Value;
float unarmedSkillLevel = Player.m_localPlayer.GetSkillLevel(Skills.SkillType.Unarmed);
float totalDamage = baseDamage + unarmedSkillLevel;
int layerMask = LayerMask.GetMask("Default", "static_solid", "Default_small", "piece", "piece_nonsolid", "terrain", "character", "character_net", "character_ghost", "hitbox", "character_noenv", "vehicle");
Collider[] hits = Physics.OverlapSphere(attackPoint, attackRadius, layerMask);
FormMelee.LogSwing(FormLabel, hits.Length);
System.Collections.Generic.HashSet<GameObject> hitObjects = new System.Collections.Generic.HashSet<GameObject>();
foreach (Collider hit in hits)
{
if (hit.gameObject == Player.m_localPlayer.gameObject) continue;
if (hit.attachedRigidbody != null && hit.attachedRigidbody.gameObject == Player.m_localPlayer.gameObject) continue;
IDestructible target = hit.GetComponentInParent<IDestructible>();
if (target != null)
{
Character characterTarget = target as Character;
if (characterTarget != null && characterTarget == Player.m_localPlayer) continue;
// Marked as hit only once it IS hit, further down. Marking it here let the first
// collider found decide for the whole creature: a limb outside the arc or behind
// cover ruled out a body that was squarely in the swing.
GameObject targetObj = (target as MonoBehaviour)?.gameObject;
if (targetObj != null && hitObjects.Contains(targetObj)) continue;
Vector3 targetCenter = hit.bounds.center;
Vector3 dirToTarget = (targetCenter - playerPos).normalized;
float angle = Vector3.Angle(Player.m_localPlayer.transform.forward, dirToTarget);
if (angle >= 70f) FormMelee.LogMiss(FormLabel, hit, $"outside the swing arc ({angle:0} deg)");
else
{
Vector3 eyePos = playerPos + Vector3.up * 1.5f;
if (!FormMelee.CanReach(eyePos, attackPoint, hit, target, out string cover))
{
FormMelee.LogMiss(FormLabel, hit, "no clear line, blocked by '" + cover + "'");
}
else
{
HitData hitData = new HitData();
hitData.m_damage.m_slash = totalDamage;
hitData.m_pushForce = FenrirConfig.FenringPushForce.Value;
hitData.m_point = targetCenter;
hitData.m_dir = Player.m_localPlayer.transform.forward;
hitData.m_skill = Skills.SkillType.Unarmed;
hitData.m_dodgeable = true;
hitData.m_blockable = true;
hitData.m_hitType = HitData.HitType.PlayerHit;
hitData.m_toolTier = 0;
hitData.SetAttacker(Player.m_localPlayer);
if (targetObj != null) hitObjects.Add(targetObj);
FormMelee.LogHit(FormLabel, target, totalDamage);
target.Damage(hitData);
FormMelee.GrantAdrenaline(target);
}
}
}
}
}
}
// --- CLASSE CUSTOM PER L'ATTACCO "FIRE" DEL CULTIST ---
public class CultistFormBehavior : MonoBehaviour
{
private const string FormLabel = "Cultist";
private Animator playerAnim;
private Animator cultistAnim;
private readonly FormLocomotion locomotion = new FormLocomotion();
private float busySince = -1f;
// A property so every form tells FenrirForms.LocalAttacking too: Fenrir_FormHoldStill_Patch
// holds the player still for exactly as long as an attack clip runs.
private bool attacking;
private bool isAttacking { get => attacking; set { attacking = value; FenrirForms.LocalAttacking = value; } }
private bool isShootingFire = false;
private float fireTimer = 0f;
void Start()
{
playerAnim = Player.m_localPlayer.transform.Find("Visual").GetComponent<Animator>();
cultistAnim = GetComponent<Animator>();
if (cultistAnim == null) cultistAnim = GetComponentInChildren<Animator>();
}
void Update()
{
if (FormAnimGuard.Stuck(isAttacking, ref busySince))
{
StopAllCoroutines();
isAttacking = false;
}
if (playerAnim == null || cultistAnim == null) return;
if (!isAttacking)
{
// Se tiene premuto Ctrl (Crouch), ferma il movimento per preparare l'attacco
bool isGrounded = locomotion.Mirror(cultistAnim, playerAnim, Player.m_localPlayer);
if (isGrounded)
{
// Gated per-read rather than around the block, so opening a GUI mid-stream
// still falls through to StopFire() instead of leaving the flames running.
bool canAct = RaceInput.Allowed;
// Fire attack on Right Click
if (canAct && RaceInput.AttackHeld(1) && !Player.m_localPlayer.IsStaggering())
{
if (Player.m_localPlayer.GetEitr() > 0)
{
if (!isShootingFire)
{
StartFire();
}
else
{
UpdateFire();
}
}
else
{
// Held with an empty pool. Until now this did nothing whatsoever: no
// flames, no sound, no reason given - and the form's own tier is Yagluth
// while eitr is a Mistlands thing, so a Cultist meets this before it ever
// meets the fire.
SayNoEitr();
if (isShootingFire) StopFire();
}
}
else if (isShootingFire)
{
StopFire();
}
if (canAct && FenrirConfig.HowlKey.Value.IsDownIgnoringHeldKeys())
{
StartCoroutine(HowlRoutine());
}
// Attacks on Left Click
if (canAct && RaceInput.AttackDown(0) && !isShootingFire && FormMelee.TrySpendStamina(Player.m_localPlayer, FenrirConfig.CultistClawStamina.Value, Skills.SkillType.Unarmed))
{
StartCoroutine(ClawRoutine()); // Single claw
}
// Double claw on Middle Click
else if (canAct && RaceInput.AttackDown(2) && !isShootingFire && FormMelee.TrySpendStamina(Player.m_localPlayer, FenrirConfig.CultistDoubleClawStamina.Value, Skills.SkillType.Unarmed))
{
StartCoroutine(DoubleClawRoutine());
}
}
else if (isShootingFire)
{
StopFire();
}
}
}
private void PlaySFX(params string[] prefabNames)
{
foreach (string name in prefabNames)
{
GameObject sfx = PrefabManager.Cache.GetPrefab<GameObject>(name);
if (sfx != null)
{
FenrirCreatureSound.Spawn(sfx, Player.m_localPlayer.transform.position);
return;
}
}
Jotunn.Logger.LogWarning($"[CultistForm] Nessun suono trovato tra: {string.Join(", ", prefabNames)}");
}
private IEnumerator HowlRoutine()
{
isAttacking = true;
cultistAnim.SetFloat("forward_speed", 0f);
cultistAnim.SetFloat("sideway_speed", 0f);
// Cultist ha una vera e propria animazione di "taunt"
cultistAnim.SetTrigger("attack_taunt");
FenrirAttackSync.Publish("attack_taunt", "@Fenring_Cultist");
FenrirCreatureSound.PlayHowl("Fenring_Cultist", Player.m_localPlayer.transform.position);
// Durata approssimativa dell'animazione di taunt
yield return new WaitForSeconds(2.0f);
isAttacking = false;
}
private GameObject fireEffectInstance;
private float lastNoEitrMessage = -100f;
/// <summary>
/// Says why the fire did not come. Held down rather than tapped, so it is on a timer: the
/// button is read every frame and the message would otherwise be a wall.
/// </summary>
private void SayNoEitr()
{
if (Player.m_localPlayer == null || Time.time - lastNoEitrMessage < 3f) return;
lastNoEitrMessage = Time.time;
Player.m_localPlayer.Message(MessageHud.MessageType.Center,
ModText.Get("rov_msg_fenrir_only_breath_comes_out_fire"));
}
private void StartFire()
{
if (Player.m_localPlayer == null || isShootingFire) return;
isShootingFire = true;
FormAnimGuard.LeaveHowl(cultistAnim);
cultistAnim.SetFloat("forward_speed", 0f);
cultistAnim.SetFloat("sideway_speed", 0f);
cultistAnim.SetBool("attack_fire", true);
FenrirAttackSync.PublishFire(true);
// 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");
if (fireEffectInstance == null) fireEffectInstance = FenrirAttackSync.SpawnFlames(Player.m_localPlayer);
}
private void UpdateFire()
{
Player.m_localPlayer.UseEitr(FenrirConfig.CultistFireEitrDrainPerSecond.Value * Time.deltaTime);
cultistAnim.SetFloat("forward_speed", 0f);
cultistAnim.SetFloat("sideway_speed", 0f);
fireTimer += Time.deltaTime;
if (fireTimer >= 0.2f) // Damage tick every 0.2s
{
fireTimer = 0f;
ExecuteFireDamage();
}
}
// Leaving the form mid-flame must not leave the flag up for onlookers.
private void OnDestroy()
{
if (isShootingFire) FenrirAttackSync.PublishFire(false);
}
private void StopFire()
{
isShootingFire = false;
cultistAnim.ResetTrigger("attack_flames");
FenrirAttackSync.PublishFire(false);
if (fireEffectInstance != null)
{
Destroy(fireEffectInstance);
fireEffectInstance = null;
}
}
private void ExecuteFireDamage()
{
if (Player.m_localPlayer == null) return;
Vector3 playerPos = Player.m_localPlayer.transform.position;
Vector3 attackPoint = playerPos + Player.m_localPlayer.transform.forward * 2.5f + Vector3.up * 1f;
float attackRadius = FenrirConfig.CultistFireAttackRadius.Value;
float magicSkillLevel = Player.m_localPlayer.GetSkillLevel(Skills.SkillType.ElementalMagic);
float baseFireDamage = FenrirConfig.CultistFireDamagePerTick.Value;
float totalDamage = baseFireDamage + (magicSkillLevel * FenrirConfig.CultistFireMagicSkillScaling.Value);
int layerMask = LayerMask.GetMask("Default", "static_solid", "Default_small", "piece", "piece_nonsolid", "terrain", "character", "character_net", "character_ghost", "hitbox", "character_noenv", "vehicle");
Collider[] hits = Physics.OverlapSphere(attackPoint, attackRadius, layerMask);
FormMelee.LogSwing(FormLabel, hits.Length);
System.Collections.Generic.HashSet<GameObject> hitObjects = new System.Collections.Generic.HashSet<GameObject>();
foreach (Collider hit in hits)
{
if (hit.gameObject == Player.m_localPlayer.gameObject) continue;
if (hit.attachedRigidbody != null && hit.attachedRigidbody.gameObject == Player.m_localPlayer.gameObject) continue;
IDestructible target = hit.GetComponentInParent<IDestructible>();
if (target != null)
{
Character characterTarget = target as Character;
if (characterTarget != null && characterTarget == Player.m_localPlayer) continue;
// Marked as hit only once it IS hit, further down. Marking it here let the first
// collider found decide for the whole creature: a limb outside the arc or behind
// cover ruled out a body that was squarely in the swing.
GameObject targetObj = (target as MonoBehaviour)?.gameObject;
if (targetObj != null && hitObjects.Contains(targetObj)) continue;
Vector3 targetCenter = hit.bounds.center;
Vector3 dirToTarget = (targetCenter - playerPos).normalized;
float angle = Vector3.Angle(Player.m_localPlayer.transform.forward, dirToTarget);
if (angle < 45f)
{
HitData hitData = new HitData();
hitData.m_damage.m_fire = totalDamage;
hitData.m_point = targetCenter;
hitData.m_dir = Player.m_localPlayer.transform.forward;
hitData.m_skill = Skills.SkillType.ElementalMagic;
hitData.m_dodgeable = true;
hitData.m_blockable = true;
hitData.m_hitType = HitData.HitType.PlayerHit;
hitData.SetAttacker(Player.m_localPlayer);
if (targetObj != null) hitObjects.Add(targetObj);
FormMelee.LogHit(FormLabel, target, totalDamage);
target.Damage(hitData);
FormMelee.GrantAdrenaline(target, 0.2f); // one 0.2s tick: a full hit per second of breath
if (ZNetScene.instance != null)
{
GameObject hitFx = ZNetScene.instance.GetPrefab("vfx_FireballHit");
if (hitFx != null) Instantiate(hitFx, targetCenter, Quaternion.identity);
}
}
}
}
}
private IEnumerator ClawRoutine()
{
isAttacking = true;
FormAnimGuard.LeaveHowl(cultistAnim);
cultistAnim.SetFloat("forward_speed", 0f);
cultistAnim.SetFloat("sideway_speed", 0f);
// Per il Cultista usiamo esplicitamente il trigger dell'artigliata
int baseline = FenrirForms.AttackEvents;
float started = Time.time;
cultistAnim.SetTrigger("attack_claw");
FenrirAttackSync.Publish("attack_claw", "sfx_fenring_claw_start");
// The blow lands on the clip's own Hit event (ClawAttackCultist: 0.64 s of 1.33 s), and
// the lock holds until the clip is over. A fixed 0.4 s hit and a 0.5 s lock used to land
// the damage before the claw swung and let the next click start a new one mid-swing.
yield return null;
float length = ClipLength(1.33f);
yield return WaitForHit(baseline, started);
PlaySFX("sfx_fenring_claw_start");
ExecuteClawDamage(FenrirConfig.CultistClawDamage.Value);
yield return WaitUntilClipEnds(length, started);
cultistAnim.ResetTrigger("attack_claw");
isAttacking = false;
}
// Each swipe of the double claw deals this share of Double Claw Damage. Two swipes give
// 120% of what the old single hit dealt: a little more, for a slower swing that can be cut short.
private const float DoubleClawHitShare = 0.6f;
private IEnumerator DoubleClawRoutine()
{
isAttacking = true;
FormAnimGuard.LeaveHowl(cultistAnim);
cultistAnim.SetFloat("forward_speed", 0f);
cultistAnim.SetFloat("sideway_speed", 0f);
int baseline = FenrirForms.AttackEvents;
float started = Time.time;
cultistAnim.SetTrigger("attack_claw_double");
FenrirAttackSync.Publish("attack_claw_double", "sfx_fenring_claw_start");
// DoubleClawAttackCultist carries two Hit events (0.64 s and 1.21 s of 1.83 s), one per
// swipe. It used to deal one hit at a fixed 0.6 s, so the second swipe did nothing.
yield return null;
float length = ClipLength(1.83f);
float damage = FenrirConfig.CultistDoubleClawDamage.Value * DoubleClawHitShare;
yield return WaitForHit(baseline, started);
PlaySFX("sfx_fenring_claw_start");
ExecuteClawDamage(damage);
yield return WaitForHit(baseline + 1, started, HitEventTimeout + 0.6f);
PlaySFX("sfx_fenring_claw_start");
ExecuteClawDamage(damage);
yield return WaitUntilClipEnds(length, started);
cultistAnim.ResetTrigger("attack_claw_double");
isAttacking = false;
}
// Longest a swipe waits for its Hit event before landing anyway, measured from the trigger:
// a clip that never sends one must not leave the Cultist swinging at nothing.
private const float HitEventTimeout = 1.5f;
/// <summary>Waits until the clip has sent more than <paramref name="seen"/> hit events since
/// the trigger, or until the timeout.</summary>
private IEnumerator WaitForHit(int seen, float started, float timeout = HitEventTimeout)
{
while (FenrirForms.AttackEvents <= seen && Time.time - started < timeout)
{
yield return null;
}
}
/// <summary>The attack clip's length, read a frame after its trigger, when the transition
/// into it has begun. <paramref name="fallback"/> is the clip's length in the game files.</summary>
private float ClipLength(float fallback)
{
AnimatorClipInfo[] clips = cultistAnim.IsInTransition(0)
? cultistAnim.GetNextAnimatorClipInfo(0)
: cultistAnim.GetCurrentAnimatorClipInfo(0);
if (clips != null && clips.Length > 0 && clips[0].clip != null) return clips[0].clip.length;
return fallback;
}
/// <summary>Holds the lock until the clip has played out, clamped so a wrong reading can
/// neither cut a swing short nor freeze the form.</summary>
private IEnumerator WaitUntilClipEnds(float length, float started)
{
float remaining = Mathf.Clamp(length, 0.6f, 3f) - (Time.time - started);
if (remaining > 0f) yield return new WaitForSeconds(remaining);
}
private void ExecuteClawDamage(float baseDamage)
{
if (Player.m_localPlayer == null || FormStagger.AttackInterrupted) return;
Vector3 playerPos = Player.m_localPlayer.transform.position;
Vector3 attackPoint = playerPos + Player.m_localPlayer.transform.forward * 1.5f + Vector3.up * 1f;
float attackRadius = FenrirConfig.CultistAttackRadius.Value;
float unarmedSkillLevel = Player.m_localPlayer.GetSkillLevel(Skills.SkillType.Unarmed);
float totalDamage = baseDamage + unarmedSkillLevel;
int layerMask = LayerMask.GetMask("Default", "static_solid", "Default_small", "piece", "piece_nonsolid", "terrain", "character", "character_net", "character_ghost", "hitbox", "character_noenv", "vehicle");
Collider[] hits = Physics.OverlapSphere(attackPoint, attackRadius, layerMask);
FormMelee.LogSwing(FormLabel, hits.Length);
System.Collections.Generic.HashSet<GameObject> hitObjects = new System.Collections.Generic.HashSet<GameObject>();
foreach (Collider hit in hits)
{
if (hit.gameObject == Player.m_localPlayer.gameObject) continue;
if (hit.attachedRigidbody != null && hit.attachedRigidbody.gameObject == Player.m_localPlayer.gameObject) continue;
IDestructible target = hit.GetComponentInParent<IDestructible>();
if (target != null)
{
Character characterTarget = target as Character;
if (characterTarget != null && characterTarget == Player.m_localPlayer) continue;
// Marked as hit only once it IS hit, further down. Marking it here let the first
// collider found decide for the whole creature: a limb outside the arc or behind
// cover ruled out a body that was squarely in the swing.
GameObject targetObj = (target as MonoBehaviour)?.gameObject;
if (targetObj != null && hitObjects.Contains(targetObj)) continue;
Vector3 targetCenter = hit.bounds.center;
Vector3 dirToTarget = (targetCenter - playerPos).normalized;
float angle = Vector3.Angle(Player.m_localPlayer.transform.forward, dirToTarget);
if (angle >= 70f) FormMelee.LogMiss(FormLabel, hit, $"outside the swing arc ({angle:0} deg)");
else
{
Vector3 eyePos = playerPos + Vector3.up * 1.5f;
if (!FormMelee.CanReach(eyePos, attackPoint, hit, target, out string cover))
{
FormMelee.LogMiss(FormLabel, hit, "no clear line, blocked by '" + cover + "'");
}
else
{
HitData hitData = new HitData();
hitData.m_damage.m_slash = totalDamage;
hitData.m_pushForce = FenrirConfig.CultistPushForce.Value;
hitData.m_point = targetCenter;
hitData.m_dir = Player.m_localPlayer.transform.forward;
hitData.m_skill = Skills.SkillType.Unarmed;
hitData.m_dodgeable = true;
hitData.m_blockable = true;
hitData.m_hitType = HitData.HitType.PlayerHit;
hitData.m_toolTier = 0;
hitData.SetAttacker(Player.m_localPlayer);
if (targetObj != null) hitObjects.Add(targetObj);
FormMelee.LogHit(FormLabel, target, totalDamage);
target.Damage(hitData);
FormMelee.GrantAdrenaline(target);
}
}
}
}
}
}
public class WolfFormBehavior : MonoBehaviour
{
private const string FormLabel = "Wolf";
private Animator playerAnim;
private Animator wolfAnim;
private readonly FormLocomotion locomotion = new FormLocomotion();
private float busySince = -1f;
// A property so every form tells FenrirForms.LocalAttacking too: Fenrir_FormHoldStill_Patch
// holds the player still for exactly as long as an attack clip runs.
private bool attacking;
private bool isAttacking { get => attacking; set { attacking = value; FenrirForms.LocalAttacking = value; } }
void Start()
{
playerAnim = Player.m_localPlayer.transform.Find("Visual").GetComponent<Animator>();
wolfAnim = GetComponent<Animator>();
if (wolfAnim == null) wolfAnim = GetComponentInChildren<Animator>();
}
void Update()
{
if (FormAnimGuard.Stuck(isAttacking, ref busySince))
{
StopAllCoroutines();
isAttacking = false;
}
if (playerAnim == null || wolfAnim == null) return;
if (!isAttacking)
{
bool isGrounded = locomotion.Mirror(wolfAnim, playerAnim, Player.m_localPlayer);
if (isGrounded && RaceInput.Allowed)
{
// The howl, on the same key as every other form. It used to be read only by the
// two Fenring forms, so pressing it as a wolf did nothing at all.
if (!isAttacking && FenrirConfig.HowlKey.Value.IsDownIgnoringHeldKeys())
{
StartCoroutine(WolfHowlRoutine());
}
else if (RaceInput.AttackDown(0) && FormMelee.TrySpendStamina(Player.m_localPlayer, FenrirConfig.WolfAttack1Stamina.Value, Skills.SkillType.Unarmed)) // Left Click
{
StartCoroutine(WolfAttackRoutine("attack1", FenrirConfig.WolfAttack1Damage.Value, 0.6f, 0.2f));
}
else if (RaceInput.AttackDown(1) && FormMelee.TrySpendStamina(Player.m_localPlayer, FenrirConfig.WolfAttack2Stamina.Value, Skills.SkillType.Unarmed)) // Right Click
{
StartCoroutine(WolfAttackRoutine("attack2", FenrirConfig.WolfAttack2Damage.Value, 0.8f, 0.3f));
}
else if (RaceInput.AttackDown(2) && FormMelee.TrySpendStamina(Player.m_localPlayer, FenrirConfig.WolfAttack3Stamina.Value, Skills.SkillType.Unarmed)) // Middle Click
{
StartCoroutine(WolfAttackRoutine("attack3", FenrirConfig.WolfAttack3Damage.Value, 1.0f, 0.4f));
}
}
}
}
private void PlaySFX(params string[] prefabNames)
{
foreach (string name in prefabNames)
{
GameObject sfx = PrefabManager.Cache.GetPrefab<GameObject>(name);
if (sfx != null)
{
FenrirCreatureSound.Spawn(sfx, Player.m_localPlayer.transform.position);
return;
}
}
}
/// <summary>
/// The howl on demand. For the wolf it is the animation and nothing else: 'C_Hawl' carries
/// the sound as an event, so spawning a prefab on top would be a second howl over the first.
/// FenrirCreatureSound.Howl knows which creatures those are.
/// </summary>
private IEnumerator WolfHowlRoutine()
{
isAttacking = true;
try
{
try { wolfAnim.SetFloat("forward_speed", 0f); } catch {}
try { wolfAnim.SetFloat("sideway_speed", 0f); } catch {}
FenrirCreatureSound.Howl(wolfAnim, "Wolf", Player.m_localPlayer.transform.position);
// The wolf's howl clip runs 3.13s. Held a little past it so the form does not snap back
// into a bite the instant the sound ends.
yield return new WaitForSeconds(3.3f);
}
finally
{
isAttacking = false;
}
}
private IEnumerator WolfAttackRoutine(string triggerName, float baseDamage, float lockDuration, float dmgDelay)
{
isAttacking = true;
// finally and not a plain assignment at the end: an exception anywhere below used to
// leave isAttacking true for good, and Update does nothing at all while it is.
try
{
// Out of the howl first - see FormAnimGuard.
FormAnimGuard.LeaveHowl(wolfAnim);
try { wolfAnim.SetFloat("forward_speed", 0f); } catch {}
try { wolfAnim.SetFloat("sideway_speed", 0f); } catch {}
wolfAnim.SetTrigger(triggerName);
FenrirAttackSync.Publish(triggerName, "sfx_wolf_attack");
yield return new WaitForSeconds(dmgDelay);
if (ZNetScene.instance != null)
{
GameObject attackSfx = ZNetScene.instance.GetPrefab("sfx_wolf_attack");
if (attackSfx != null)
{
FenrirCreatureSound.Spawn(attackSfx, Player.m_localPlayer.transform.position);
}
}
ExecuteBiteDamage(baseDamage);
float remainingTimeToIdle = lockDuration - dmgDelay;
if (remainingTimeToIdle > 0)
{
yield return new WaitForSeconds(remainingTimeToIdle);
}
}
finally
{
try { wolfAnim.ResetTrigger(triggerName); } catch {}
isAttacking = false;
}
}
private void ExecuteBiteDamage(float baseDamage)
{
if (Player.m_localPlayer == null || FormStagger.AttackInterrupted) return;
Vector3 playerPos = Player.m_localPlayer.transform.position;
// Il lupo è basso, abbassiamo l'altezza dell'attacco
Vector3 attackPoint = playerPos + Player.m_localPlayer.transform.forward * 1.5f + Vector3.up * 0.5f;
float attackRadius = FenrirConfig.WolfAttackRadius.Value;
float unarmedSkillLevel = Player.m_localPlayer.GetSkillLevel(Skills.SkillType.Unarmed);
float totalDamage = baseDamage + unarmedSkillLevel;
int layerMask = LayerMask.GetMask("Default", "static_solid", "Default_small", "piece", "piece_nonsolid", "terrain", "character", "character_net", "character_ghost", "hitbox", "character_noenv", "vehicle");
Collider[] hits = Physics.OverlapSphere(attackPoint, attackRadius, layerMask);
FormMelee.LogSwing(FormLabel, hits.Length);
System.Collections.Generic.HashSet<GameObject> hitObjects = new System.Collections.Generic.HashSet<GameObject>();
foreach (Collider hit in hits)
{
if (hit.gameObject == Player.m_localPlayer.gameObject) continue;
if (hit.attachedRigidbody != null && hit.attachedRigidbody.gameObject == Player.m_localPlayer.gameObject) continue;
IDestructible target = hit.GetComponentInParent<IDestructible>();
if (target != null)
{
Character characterTarget = target as Character;
if (characterTarget != null && characterTarget == Player.m_localPlayer) continue;
// Marked as hit only once it IS hit, further down. Marking it here let the first
// collider found decide for the whole creature: a limb outside the arc or behind
// cover ruled out a body that was squarely in the swing.
GameObject targetObj = (target as MonoBehaviour)?.gameObject;
if (targetObj != null && hitObjects.Contains(targetObj)) continue;
Vector3 targetCenter = hit.bounds.center;
Vector3 dirToTarget = (targetCenter - playerPos).normalized;
float angle = Vector3.Angle(Player.m_localPlayer.transform.forward, dirToTarget);
if (angle >= 70f) FormMelee.LogMiss(FormLabel, hit, $"outside the swing arc ({angle:0} deg)");
else
{
Vector3 eyePos = playerPos + Vector3.up * 1.0f;
if (!FormMelee.CanReach(eyePos, attackPoint, hit, target, out string cover))
{
FormMelee.LogMiss(FormLabel, hit, "no clear line, blocked by '" + cover + "'");
}
else
{
HitData hitData = new HitData();
hitData.m_damage.m_slash = totalDamage;
hitData.m_pushForce = FenrirConfig.WolfPushForce.Value;
hitData.m_point = targetCenter;
hitData.m_dir = Player.m_localPlayer.transform.forward;
hitData.m_skill = Skills.SkillType.Unarmed;
hitData.m_dodgeable = true;
hitData.m_blockable = true;
hitData.m_hitType = HitData.HitType.PlayerHit;
hitData.m_toolTier = 0;
hitData.SetAttacker(Player.m_localPlayer);
if (targetObj != null) hitObjects.Add(targetObj);
FormMelee.LogHit(FormLabel, target, totalDamage);
target.Damage(hitData);
FormMelee.GrantAdrenaline(target);
}
}
}
}
}
}
// --- CLASSE CUSTOM PER L'ULV ---
public class UlvFormBehavior : MonoBehaviour
{
private const string FormLabel = "Ulv";
private Animator playerAnim;
private Animator ulvAnim;
private readonly FormLocomotion locomotion = new FormLocomotion();
private float busySince = -1f;
// A property so every form tells FenrirForms.LocalAttacking too: Fenrir_FormHoldStill_Patch
// holds the player still for exactly as long as an attack clip runs.
private bool attacking;
private bool isAttacking { get => attacking; set { attacking = value; FenrirForms.LocalAttacking = value; } }
void Start()
{
playerAnim = Player.m_localPlayer.transform.Find("Visual").GetComponent<Animator>();
ulvAnim = GetComponent<Animator>();
if (ulvAnim == null) ulvAnim = GetComponentInChildren<Animator>();
}
void Update()
{
if (FormAnimGuard.Stuck(isAttacking, ref busySince))
{
StopAllCoroutines();
isAttacking = false;
}
if (Player.m_localPlayer == null || playerAnim == null || ulvAnim == null) return;
if (!isAttacking)
{
bool isGrounded = locomotion.Mirror(ulvAnim, playerAnim, Player.m_localPlayer);
if (isGrounded && RaceInput.Allowed)
{
// The howl, on the same key as every other form. It used to be read only by the
// two Fenring forms, so pressing it as a wolf did nothing at all.
if (!isAttacking && FenrirConfig.HowlKey.Value.IsDownIgnoringHeldKeys())
{
StartCoroutine(UlvHowlRoutine());
}
else if (RaceInput.AttackDown(0) && FormMelee.TrySpendStamina(Player.m_localPlayer, FenrirConfig.UlvBiteStamina.Value, Skills.SkillType.Unarmed)) // Left Click
{
StartCoroutine(UlvAttackRoutine("attack_bite", FenrirConfig.UlvBiteDamage.Value, 0.6f, 0.2f));
}
else if (RaceInput.AttackDown(1) && FormMelee.TrySpendStamina(Player.m_localPlayer, FenrirConfig.UlvHeavyBiteStamina.Value, Skills.SkillType.Unarmed)) // Right Click
{
// Right click uses bite but as a heavier attack since slash is moved to jump
StartCoroutine(UlvAttackRoutine("attack_bite", FenrirConfig.UlvHeavyBiteDamage.Value, 0.8f, 0.3f));
}
else if (RaceInput.AttackDown(2) && FormMelee.TrySpendStamina(Player.m_localPlayer, FenrirConfig.UlvJumpAttackStamina.Value, Skills.SkillType.Unarmed)) // Middle Click
{
StartCoroutine(UlvJumpAttackRoutine());
}
}
}
}
private void PlaySFX(params string[] prefabNames)
{
foreach (string name in prefabNames)
{
GameObject sfx = PrefabManager.Cache.GetPrefab<GameObject>(name);
if (sfx != null)
{
FenrirCreatureSound.Spawn(sfx, Player.m_localPlayer.transform.position);
return;
}
}
}
/// <summary>
/// The howl on demand. The Ulv animates one and carries NO sound with it - 'Idle Howl' has no
/// events at all - so unlike the wolf it needs a prefab played over the animation. Assuming
/// the two behaved alike is what left this howl silent; FenrirCreatureSound.Howl holds the
/// distinction now.
/// </summary>
private IEnumerator UlvHowlRoutine()
{
isAttacking = true;
try { ulvAnim.SetFloat("forward_speed", 0f); } catch {}
try { ulvAnim.SetFloat("sideway_speed", 0f); } catch {}
FenrirCreatureSound.Howl(ulvAnim, "Ulv", Player.m_localPlayer.transform.position);
// The Ulv's 'Idle Howl' runs 3.67s. Held a little past it so the form does not snap
// back into a bite the instant it ends.
yield return new WaitForSeconds(3.8f);
isAttacking = false;
}
private IEnumerator UlvAttackRoutine(string triggerName, float baseDamage, float lockDuration, float dmgDelay)
{
isAttacking = true;
FormAnimGuard.LeaveHowl(ulvAnim);
try { ulvAnim.SetFloat("forward_speed", 0f); } catch {}
try { ulvAnim.SetFloat("sideway_speed", 0f); } catch {}
try { ulvAnim.SetTrigger(triggerName); } catch {}
FenrirAttackSync.Publish(triggerName, "sfx_wolf_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);
if (ZNetScene.instance != null)
{
GameObject attackSfx = ZNetScene.instance.GetPrefab("sfx_wood_hit");
if (attackSfx != null)
{
FenrirCreatureSound.Spawn(attackSfx, Player.m_localPlayer.transform.position);
}
}
ExecuteBiteDamage(baseDamage);
float remainingTimeToIdle = lockDuration - dmgDelay;
if (remainingTimeToIdle > 0)
{
yield return new WaitForSeconds(remainingTimeToIdle);
}
try { ulvAnim.ResetTrigger(triggerName); } catch {}
isAttacking = false;
}
private void ExecuteBiteDamage(float baseDamage)
{
if (Player.m_localPlayer == null || FormStagger.AttackInterrupted) return;
Vector3 playerPos = Player.m_localPlayer.transform.position;
Vector3 attackPoint = playerPos + Player.m_localPlayer.transform.forward * 1.5f + Vector3.up * 0.5f;
float attackRadius = FenrirConfig.UlvAttackRadius.Value;
float unarmedSkillLevel = Player.m_localPlayer.GetSkillLevel(Skills.SkillType.Unarmed);
float totalDamage = baseDamage + unarmedSkillLevel;
int layerMask = LayerMask.GetMask("Default", "static_solid", "Default_small", "piece", "piece_nonsolid", "terrain", "character", "character_net", "character_ghost", "hitbox", "character_noenv", "vehicle");
Collider[] hits = Physics.OverlapSphere(attackPoint, attackRadius, layerMask);
FormMelee.LogSwing(FormLabel, hits.Length);
System.Collections.Generic.HashSet<GameObject> hitObjects = new System.Collections.Generic.HashSet<GameObject>();
foreach (Collider hit in hits)
{
if (hit.gameObject == Player.m_localPlayer.gameObject) continue;
if (hit.attachedRigidbody != null && hit.attachedRigidbody.gameObject == Player.m_localPlayer.gameObject) continue;
IDestructible target = hit.GetComponentInParent<IDestructible>();
if (target != null)
{
Character characterTarget = target as Character;
if (characterTarget != null && characterTarget == Player.m_localPlayer) continue;
// Marked as hit only once it IS hit, further down. Marking it here let the first
// collider found decide for the whole creature: a limb outside the arc or behind
// cover ruled out a body that was squarely in the swing.
GameObject targetObj = (target as MonoBehaviour)?.gameObject;
if (targetObj != null && hitObjects.Contains(targetObj)) continue;
Vector3 targetCenter = hit.bounds.center;
Vector3 dirToTarget = (targetCenter - playerPos).normalized;
float angle = Vector3.Angle(Player.m_localPlayer.transform.forward, dirToTarget);
if (angle >= 70f) FormMelee.LogMiss(FormLabel, hit, $"outside the swing arc ({angle:0} deg)");
else
{
Vector3 eyePos = playerPos + Vector3.up * 1.0f;
if (!FormMelee.CanReach(eyePos, attackPoint, hit, target, out string cover))
{
FormMelee.LogMiss(FormLabel, hit, "no clear line, blocked by '" + cover + "'");
}
else
{
HitData hitData = new HitData();
hitData.m_damage.m_slash = totalDamage;
hitData.m_pushForce = FenrirConfig.UlvPushForce.Value;
hitData.m_point = targetCenter;
hitData.m_dir = Player.m_localPlayer.transform.forward;
hitData.m_skill = Skills.SkillType.Unarmed;
hitData.m_dodgeable = true;
hitData.m_blockable = true;
hitData.m_hitType = HitData.HitType.PlayerHit;
hitData.m_toolTier = 0;
hitData.SetAttacker(Player.m_localPlayer);
if (targetObj != null) hitObjects.Add(targetObj);
FormMelee.LogHit(FormLabel, target, totalDamage);
target.Damage(hitData);
FormMelee.GrantAdrenaline(target);
}
}
}
}
}
private IEnumerator UlvJumpAttackRoutine()
{
isAttacking = true;
FormAnimGuard.LeaveHowl(ulvAnim);
try { ulvAnim.SetFloat("forward_speed", 0f); } catch {}
try { ulvAnim.SetFloat("sideway_speed", 0f); } catch {}
try { ulvAnim.SetTrigger("attack_slash"); } catch {}
FenrirAttackSync.Publish("attack_slash", "sfx_wolf_attack");
PlaySFX("sfx_wolf_attack");
yield return new WaitForSeconds(0.3f); // Wait 0.3s before leaping
// Leap forward (+50% range)
float leapDuration = 0.25f;
float leapSpeed = FenrirConfig.UlvLeapSpeed.Value;
float elapsed = 0f;
while (elapsed < leapDuration)
{
if (Player.m_localPlayer != null)
{
Vector3 moveDir = Player.m_localPlayer.transform.forward;
Player.m_localPlayer.transform.position += moveDir * leapSpeed * Time.deltaTime;
}
elapsed += Time.deltaTime;
yield return null;
}
if (ZNetScene.instance != null)
{
GameObject attackSfx = ZNetScene.instance.GetPrefab("sfx_wood_hit");
if (attackSfx != null)
{
FenrirCreatureSound.Spawn(attackSfx, Player.m_localPlayer.transform.position);
}
}
ExecuteBiteDamage(FenrirConfig.UlvJumpAttackDamage.Value);
yield return new WaitForSeconds(0.4f);
try { ulvAnim.ResetTrigger("attack_slash"); } catch {}
isAttacking = false;
}
}
/// <summary>
/// Keeps the Cultist's breath at its mouth: on the Jaw bone (fenring_cultist rig:
/// .../Neck/Head/Jaw), facing where the player faces. Placed every LateUpdate, after the form's
/// Animator has moved the head, rather than parented to the bone, so the flames point where the
/// player aims and not wherever the jaw happens to tilt. The same on every client's copy.
/// </summary>
internal class CultistFlameFollow : MonoBehaviour
{
public Player Player;
private Transform mouth;
private float nextLook;
private void LateUpdate()
{
if (Player == null) return;
// The form can be rebuilt under the same flames; look again now and then if lost.
if (mouth == null && Time.time >= nextLook)
{
nextLook = Time.time + 0.5f;
mouth = FenrirAttackSync.FindMouth(Player);
}
transform.SetPositionAndRotation(FenrirAttackSync.MouthPoint(Player, mouth), Player.transform.rotation);
}
}
}