Merge branch 'fix-cultist-fire': Cultist fire from the hands, forms stagger

This commit is contained in:
kanym 2026-10-29 15:46:33 +01:00
commit a2737dc245
5 changed files with 334 additions and 48 deletions

View file

@ -326,11 +326,30 @@ namespace RacesOfValheim
GameObject instance = Object.Instantiate(fireVfx, MouthPoint(player), player.transform.rotation, player.transform);
instance.AddComponent<CultistFlameFollow>().Player = player;
// The vanilla effect is one throw, not a held breath: its emitters do not loop (2 s) and
// a TimedDestruction removes it after 5 s, so a long hold went on draining eitr with no
// fire. It loops here and lives until StopFire takes it down.
TimedDestruction timer = instance.GetComponent<TimedDestruction>();
if (timer != null)
{
timer.CancelInvoke();
Object.Destroy(timer);
}
// Aumentiamo la durata delle particelle del 20%
foreach (ParticleSystem ps in instance.GetComponentsInChildren<ParticleSystem>())
{
var main = ps.main;
main.startLifetimeMultiplier *= 1.2f;
main.loop = true;
}
// The roar of the fire, the same one-throw story: set before its ZSFX first plays.
foreach (ZSFX sfx in instance.GetComponentsInChildren<ZSFX>())
{
sfx.m_fadeOutOnAwake = false;
AudioSource source = sfx.GetComponent<AudioSource>();
if (source != null) source.loop = true;
}
return instance;
}
@ -429,6 +448,8 @@ namespace RacesOfValheim
private ZNetView nview;
private string lastAttack;
private GameObject flames;
private bool breathing;
private float breathStarted;
private readonly FormLocomotion locomotion = new FormLocomotion();
// The flames hang off the player, not this model, so they outlive it unless taken down.
@ -469,18 +490,31 @@ namespace RacesOfValheim
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)
// The flag is up for the whole hold, wind-up included, as on the owner's side; the
// flames come at the same point of the same clip (CultistBreathClip). Only the cultist
// ever sets the flag, so no other form can grow flames here.
if (fire && !breathing)
{
flames = FenrirAttackSync.SpawnFlames(player);
breathing = true;
breathStarted = Time.time;
// 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; }
if (fire)
{
CultistBreathClip.Hold(formAnim);
if (flames == null && CultistBreathClip.FlamesDue(formAnim, breathStarted))
flames = FenrirAttackSync.SpawnFlames(player);
}
else if (breathing)
{
breathing = false;
CultistBreathClip.Release(formAnim, player);
if (flames != null) { Destroy(flames); flames = null; }
}
foreach (AnimatorControllerParameter p in formAnim.parameters)
{
@ -726,7 +760,7 @@ namespace RacesOfValheim
private void ExecuteClawDamage(float baseDamage)
{
if (Player.m_localPlayer == null) return;
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;
@ -841,36 +875,29 @@ namespace RacesOfValheim
// 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))
// Fire attack on Right Click, held.
bool wantFire = canAct && RaceInput.AttackHeld(1) && !Player.m_localPlayer.IsStaggering();
if (wantFire && Player.m_localPlayer.GetEitr() <= 0f)
{
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();
}
// 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();
wantFire = false;
}
if (wantFire)
{
if (!isShootingFire) StartFire();
else UpdateFire();
}
else if (isShootingFire)
{
StopFire();
}
if (canAct && FenrirConfig.HowlKey.Value.IsDownIgnoringHeldKeys())
if (canAct && !isShootingFire && FenrirConfig.HowlKey.Value.IsDownIgnoringHeldKeys())
{
StartCoroutine(HowlRoutine());
}
@ -943,31 +970,54 @@ namespace RacesOfValheim
ModText.Get("rov_msg_fenrir_only_breath_comes_out_fire"));
}
// The breath runs on the flame clip (CultistBreathClip): pressed, the clip starts; the flames,
// the eitr drain and the damage begin at its own Hit point; released, the clip is cut.
private bool flaming;
private float fireStarted;
/// <summary>True while the local Cultist holds its breath attack, wind-up included. Read by
/// Cultist_BreathFacesCamera_Patch.</summary>
public static bool LocalBreathing { get; private set; }
private void StartFire()
{
if (Player.m_localPlayer == null || isShootingFire) return;
isShootingFire = true;
LocalBreathing = true;
// Planted while it breathes, as the vanilla Cultist is: its controller has no walking
// version of the cast, so a moving Cultist slid along in the casting pose.
// Fenrir_FormHoldStill_Patch holds the player; turning to the camera still works.
FenrirForms.LocalAttacking = true;
flaming = false;
fireStarted = Time.time;
fireTimer = 0f;
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);
CultistBreathClip.Hold(cultistAnim);
if (!flaming)
{
if (!CultistBreathClip.FlamesDue(cultistAnim, fireStarted)) return;
flaming = true;
if (fireEffectInstance == null) fireEffectInstance = FenrirAttackSync.SpawnFlames(Player.m_localPlayer);
}
Player.m_localPlayer.UseEitr(FenrirConfig.CultistFireEitrDrainPerSecond.Value * Time.deltaTime);
fireTimer += Time.deltaTime;
if (fireTimer >= 0.2f) // Damage tick every 0.2s
{
@ -980,14 +1030,20 @@ namespace RacesOfValheim
private void OnDestroy()
{
if (isShootingFire) FenrirAttackSync.PublishFire(false);
if (isShootingFire) FenrirForms.LocalAttacking = false;
LocalBreathing = false;
}
private void StopFire()
{
isShootingFire = false;
LocalBreathing = false;
FenrirForms.LocalAttacking = false;
flaming = false;
cultistAnim.ResetTrigger("attack_flames");
FenrirAttackSync.PublishFire(false);
CultistBreathClip.Release(cultistAnim, Player.m_localPlayer);
if (fireEffectInstance != null)
{
Destroy(fireEffectInstance);
@ -1161,7 +1217,7 @@ namespace RacesOfValheim
private void ExecuteClawDamage(float baseDamage)
{
if (Player.m_localPlayer == null) return;
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;
@ -1375,7 +1431,7 @@ namespace RacesOfValheim
private void ExecuteBiteDamage(float baseDamage)
{
if (Player.m_localPlayer == null) return;
if (Player.m_localPlayer == null || FormStagger.AttackInterrupted) return;
Vector3 playerPos = Player.m_localPlayer.transform.position;
// Il lupo è basso, abbassiamo l'altezza dell'attacco
@ -1584,7 +1640,7 @@ namespace RacesOfValheim
private void ExecuteBiteDamage(float baseDamage)
{
if (Player.m_localPlayer == null) return;
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;
@ -1702,29 +1758,158 @@ namespace RacesOfValheim
}
/// <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.
/// The Cultist's breath, timed by its own clip. fenring_cultist_animator's attack_flames state
/// plays "Flame Spell Attack" (read offline with UnityPy, bundle c4210710): 3.5 s, the hands
/// light at 1.094 s (TrailOn), the vanilla flames come at 1.245 s (Hit) and are taken down at
/// 3.193 s. The state leaves for Movement only when the clip ends, so a short click used to
/// leave the Cultist standing with its arms up for the rest of the 3.5 s, breathing nothing.
///
/// Now the flames wait for the clip's Hit point, the arms are held in the casting pose for as
/// long as the button is, and letting go blends straight back to Movement. Shared by the
/// owner's Cultist and every onlooker's copy, so both play the same breath.
/// </summary>
internal static class CultistBreathClip
{
private static readonly int State = Animator.StringToHash("Base Layer.attack_flames");
private const string MovementState = "Base Layer.Movement";
// The clip's Hit event, where the vanilla Cultist's flames come out.
private const float FlamesAt = 1.245f;
// The throw itself: the Animator stops here while held. After it the vanilla Cultist lowers
// its arms while its fire flies on alone, so a pin at 2.6 s held an idle-looking pose.
private const float PinAt = 1.3f;
private const float Fade = 0.25f;
/// <summary>Seconds into the flame clip, or -1 while the Animator is in another state.</summary>
private static float ClipTime(Animator anim)
{
AnimatorStateInfo info = anim.IsInTransition(0) ? anim.GetNextAnimatorStateInfo(0) : anim.GetCurrentAnimatorStateInfo(0);
return info.fullPathHash == State ? info.normalizedTime * info.length : -1f;
}
/// <summary>True once the clip has reached its Hit point. If the clip never started (another
/// state took the Animator), the same delay counted from the press stands in for it.</summary>
public static bool FlamesDue(Animator anim, float started)
{
float t = ClipTime(anim);
return t >= FlamesAt || (t < 0f && Time.time - started >= FlamesAt + 0.2f);
}
/// <summary>
/// Holds the arms in the casting pose: once the clip reaches PinAt it is put back there every
/// frame. Not with Animator.speed = 0, which is what the troll's pin uses: the creature's own
/// CharacterAnimEvent sits on this model and sets speed back to 1 on every physics step while
/// the player is not in a vanilla attack, so the clip ran on to its end and the Cultist went
/// back to idle with the fire still pouring out.
/// </summary>
public static void Hold(Animator anim)
{
if (anim.IsInTransition(0)) return;
AnimatorStateInfo info = anim.GetCurrentAnimatorStateInfo(0);
if (info.fullPathHash != State || info.length <= 0f) return;
if (info.normalizedTime * info.length >= PinAt) anim.Play(State, 0, PinAt / info.length);
}
/// <summary>Blends out of the clip, unless a stagger has taken over (FormStagger has fired
/// the form's own).</summary>
public static void Release(Animator anim, Player player)
{
if (anim == null) return;
if (ClipTime(anim) >= 0f && (player == null || !player.IsStaggering()))
anim.CrossFadeInFixedTime(MovementState, Fade, 0);
}
}
/// <summary>
/// Keeps the Cultist's breath in its hands, where the vanilla Cultist casts it from. fx_fenring_flames
/// has two emitters, "flames_world left" and "flames_world right", set 1.2 to 1.6 m ahead of
/// its own origin; spawned at the creature, the fire began that far in front of it. Each
/// emitter goes on its hand bone (fenring_cultist rig: .../LeftForeArm/LeftHand and the right
/// one), pointing where the player faces, so the two streams leave the palms and run forward.
/// The embers and the light sit between the hands. Placed every LateUpdate, after the form's
/// Animator has moved the arms. The same on every client's copy.
///
/// A form without hand bones keeps the whole effect at its mouth, as before.
/// </summary>
internal class CultistFlameFollow : MonoBehaviour
{
// Ahead of the palm, so the stream does not start inside the hand.
private const float AheadOfHand = 0.15f;
// The light, further ahead along the stream.
private const float LightAhead = 1.5f;
public Player Player;
private Transform mouth;
private Transform mouth, leftHand, rightHand;
private Transform leftFlames, rightFlames, embers, light;
private bool partsFound;
private float nextLook;
private void LateUpdate()
{
if (Player == null) return;
if (!partsFound)
{
partsFound = true;
leftFlames = transform.Find("flames_world left");
rightFlames = transform.Find("flames_world right");
embers = transform.Find("FireEmbers");
light = transform.Find("Point light");
}
// The form can be rebuilt under the same flames; look again now and then if lost.
if (mouth == null && Time.time >= nextLook)
if ((leftHand == null || rightHand == null || mouth == null) && Time.time >= nextLook)
{
nextLook = Time.time + 0.5f;
leftHand = FindBone(Player, "LeftHand");
rightHand = FindBone(Player, "RightHand");
mouth = FenrirAttackSync.FindMouth(Player);
}
transform.SetPositionAndRotation(FenrirAttackSync.MouthPoint(Player, mouth), Player.transform.rotation);
Quaternion facing = Player.transform.rotation;
transform.SetPositionAndRotation(FenrirAttackSync.MouthPoint(Player, mouth), facing);
if (leftHand == null || rightHand == null || leftFlames == null || rightFlames == null) return;
Vector3 forward = Player.transform.forward;
Vector3 left = leftHand.position + forward * AheadOfHand;
Vector3 right = rightHand.position + forward * AheadOfHand;
leftFlames.SetPositionAndRotation(left, facing);
rightFlames.SetPositionAndRotation(right, facing);
Vector3 between = (left + right) * 0.5f;
if (embers != null) embers.SetPositionAndRotation(between, facing);
if (light != null) light.position = between + forward * LightAhead;
}
private static Transform FindBone(Player player, string name)
{
foreach (Transform child in player.transform)
{
if (child.name == "Visual" || !child.gameObject.activeInHierarchy) continue;
foreach (Transform t in child.GetComponentsInChildren<Transform>())
{
if (t.name == name) return t;
}
}
return null;
}
}
/// <summary>
/// Turns the Cultist toward the camera while it breathes fire, as vanilla turns a player who
/// blocks or draws a bow: Player.AlwaysRotateCamera answers true for those, and Character then
/// turns the body to the look direction at its own turn speed. The breath is not a vanilla
/// attack, so the body stayed facing wherever the movement keys had left it.
/// </summary>
[HarmonyPatch(typeof(Player), "AlwaysRotateCamera")]
public static class Cultist_BreathFacesCamera_Patch
{
public static void Postfix(Player __instance, ref bool __result)
{
if (!__result && __instance == Player.m_localPlayer && CultistFormBehavior.LocalBreathing) __result = true;
}
}

View file

@ -373,10 +373,14 @@ namespace RacesOfValheim
/// the equipment modifier, status effects (meads, race passives), then up to a third off with
/// the attack's skill. Without enough, the attack does not start and the stamina bar flashes,
/// as it does for a weapon. A cost of 0 is free and always goes through.
/// A staggered player cannot attack at all, and an attack that may start is marked for
/// FormStagger, so a stagger before its hit cancels it.
/// </summary>
/// <returns>True if the attack may start; the stamina is already spent.</returns>
public static bool TrySpendStamina(Player player, float baseCost, Skills.SkillType skill)
{
if (player != null && player.IsStaggering()) return false;
FormStagger.MarkAttack();
if (player == null || baseCost <= 0f) return true;
float cost = baseCost * (1f + player.GetEquipmentAttackStaminaModifier());

View file

@ -0,0 +1,95 @@
using System.Collections.Generic;
using HarmonyLib;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// A staggered player in a form plays the form's own stagger.
///
/// Vanilla staggers a character with SetTrigger("stagger") on its own Animator (Character.RPC_Stagger),
/// and that Animator belongs to the hidden human. The form's Animator never heard of it, so the
/// True Form troll stood idle while the player could not move. A tester saw it.
///
/// Every creature worn as a form has the vanilla stagger ready to play (read offline with
/// scripts/dump_controller.py, bundle c4210710): a "stagger" trigger and an AnyState -> Stagger
/// transition in troll_animator, fenring_animator, fenring_cultist_animator, wolf_animator,
/// ulv_animator, SeekerBrute_animator (the Sverm Ravager) and bat_animator (the Aswid bat).
/// gd_king_animator (the Muspell) and hatchling_animator (the Skadi drake) have none, and are
/// left alone by the parameter check.
///
/// The cue is Character.IsStaggering(), which reads the player's Animator state. The player's
/// triggers are replicated, so this holds for onlookers' copies of the form too, with nothing
/// published of its own. Fired once, as the stagger starts.
///
/// A stagger also cancels the local form's attack, as it cancels a weapon's in vanilla. The
/// form's 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 1.5 s later. MarkAttack is called as an
/// attack starts, and AttackInterrupted tells the hit whether a stagger began since.
/// </summary>
internal static class FormStagger
{
private const string Trigger = "stagger";
private static readonly AccessTools.FieldRef<Character, Animator> AnimatorRef =
AccessTools.FieldRefAccess<Character, Animator>("m_animator");
private static readonly HashSet<int> staggering = new HashSet<int>();
private static readonly List<Animator> animators = new List<Animator>();
// Staggers of the local player so far, and the count when the current attack started.
private static int localStaggers;
private static int attackMark;
public static void MarkAttack() => attackMark = localStaggers;
/// <summary>True if the local player has been staggered since the last MarkAttack.</summary>
public static bool AttackInterrupted => localStaggers != attackMark;
public static void Tick(Player player)
{
int id = player.GetInstanceID();
if (!player.IsStaggering())
{
staggering.Remove(id);
return;
}
if (!staggering.Add(id)) return;
if (player == Player.m_localPlayer) localStaggers++;
Animator own = AnimatorRef(player);
RuntimeAnimatorController ownController = own != null ? own.runtimeAnimatorController : null;
player.GetComponentsInChildren(false, animators);
foreach (Animator anim in animators)
{
// The human's own Animator staggers already, and so does anything driven by a copy of
// its controller (a VRM model).
if (anim == own || anim.runtimeAnimatorController == null) continue;
if (anim.runtimeAnimatorController == ownController) continue;
if (!anim.isActiveAndEnabled || !HasTrigger(anim)) continue;
anim.SetTrigger(Trigger);
}
animators.Clear();
}
private static bool HasTrigger(Animator anim)
{
foreach (AnimatorControllerParameter p in anim.parameters)
{
if (p.type == AnimatorControllerParameterType.Trigger && p.name == Trigger) return true;
}
return false;
}
[HarmonyPatch(typeof(Player), "LateUpdate")]
public static class Player_LateUpdate_FormStagger_Patch
{
public static void Postfix(Player __instance)
{
FormStagger.Tick(__instance);
}
}
}
}

View file

@ -744,7 +744,7 @@ namespace RacesOfValheim
wasGrounded = grounded;
if (!RaceInput.Allowed || !grounded) return;
if (!RaceInput.Allowed || !grounded || player.IsStaggering()) return;
// Right click rams, left click bites, middle click slams. All three read the device
// directly (mouse, or its gamepad counterpart - see RaceInput.AttackDown) rather than
@ -782,6 +782,7 @@ namespace RacesOfValheim
float radius, bool slam, bool lunge)
{
isAttacking = true;
FormStagger.MarkAttack();
bool played = StartAttackState(profile);
if (rootMotion != null) rootMotion.Active = lunge;
@ -791,6 +792,7 @@ namespace RacesOfValheim
yield return FollowAttackState(stateName, played, 0f, () =>
{
if (FormStagger.AttackInterrupted) return;
if (slam) Slam(profile, radius, leftY, rightY, dropSamples);
else ExecuteDamage(profile, radius);
}, () =>

View file

@ -211,7 +211,7 @@ namespace RacesOfValheim
yield return null;
}
if (player != null && !player.IsDead())
if (player != null && !player.IsDead() && !FormStagger.AttackInterrupted)
{
float scale = transform.localScale.x;
int landed;