RacesOfValheim/JotunnModStub/Skadi/DrakeFormBehavior.cs
kanym b0d18b0654 feat(text): on-screen messages come from translation files
Every message the mod puts in the middle or corner of the screen now reads
its text through ModText.Get, and messages.json holds 191 texts in English
and Italian. Values computed in code become $1, $2 in the text, so a
translator can put them wherever the sentence needs them. Branching
messages get one key per branch.

A few messages travel through a field before they are shown: thralls'
refusals and the building limits now hold a token or key there. Boss and
form names inside messages use tokens too, the bosses the game's own, so
"The Elder" arrives translated.

ModText.Get now localizes each argument before inserting it. A token
argument left for a later pass ran into the text after it: "$1's power"
became the unknown token "enemy_eikthyr's".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-26 20:30:03 +02:00

608 lines
29 KiB
C#

using UnityEngine;
using System.Collections;
using Jotunn.Managers;
namespace RacesOfValheim
{
public class DrakeFormBehavior : MonoBehaviour
{
// Single active instance, read by SkadiDirectedFlightPatch to feed a
// look-direction-based m_moveDir into Character.UpdateFlying every frame.
public static DrakeFormBehavior Active { get; private set; }
private Animator anim;
private bool isFlying = false;
private bool isLanding = false;
private float lastAttackTime = 0f;
public bool IsFlying => isFlying;
// Read by RacesVisualController on other clients so they can keep this character airborne.
public const string FlyingKey = "RacesOfValheim_SkadiFlying";
/// <summary>
/// Time.time until which a breath is still streaming. Read by SkadiReverseFacingPatch to
/// hold the body on the aim for the duration.
///
/// A deadline rather than a bool on purpose: the attack coroutine has several early exits
/// (a missing prefab, not enough stamina) and can be cut short outright when the form is
/// destroyed mid-breath, so a flag would leak set and pin the body forever. A timestamp
/// cannot leak - it expires on its own however the coroutine ends.
/// </summary>
private static float breathingUntil = -1f;
public static bool IsBreathing => Time.time < breathingUntil;
private void SetFlying(bool value)
{
HarmonyLib.Traverse.Create(Player.m_localPlayer).Field("m_flying").SetValue(value);
ZNetView nview = Player.m_localPlayer.GetComponent<ZNetView>();
if (nview != null && nview.IsValid()) nview.GetZDO().Set(FlyingKey, value);
}
// Time.time of the last powered/grounded moment. SkadiDirectedFlightPatch holds the form
// level for a short window past this before letting it start sinking.
public float LastPoweredTime;
private SkadiProgression.FormRules formRules;
public void Initialize(SkadiProgression.FormRules rules)
{
this.formRules = rules;
}
// formRules is a snapshot taken when the form was entered, so a progression change while
// still transformed (defeating a boss, or the increaseprogression debug command) wouldn't
// grant the attack until the player reverted and transformed again. Re-read the rules for
// the form we're currently in so the unlock applies as soon as the tier is reached.
private bool CanAttackNow()
{
if (formRules == null) return false;
int state = BossProgressionManager.GetCurrentProgressionState();
SkadiProgression.FormRules live = null;
switch (formRules.Form)
{
case SkadiProgression.FormType.Drake: live = SkadiProgression.GetGKeyRules(state); break;
case SkadiProgression.FormType.Moder: live = SkadiProgression.GetHKeyRules(state); break;
case SkadiProgression.FormType.SkeletonDragon: live = SkadiProgression.GetJKeyRules(state); break;
}
return live != null && live.Form == formRules.Form && live.CanAttackInForm;
}
// Read from SkadiConfig (BepInEx Config) rather than fixed constants, so dragon-form
// attacks can be retuned from Configuration Manager - see CONFIGURATION-MANAGER-HOWTO.md.
private static float ATTACK_COOLDOWN => SkadiConfig.FormAttackCooldown.Value;
// Ranged volleys charge per projectile rather than a flat fee, so the 20- and 60-shard
// breaths cost what they are worth instead of the same as a three-shard drake spit.
// Stamina rather than eitr, for the same reason the Cold Spell uses it: eitr food only
// exists from the Mistlands on, while the drake form arrives at the Elder, so an eitr
// cost left the earliest dragon tiers with no attack they could actually pay for.
private static float STAMINA_PER_PROJECTILE => SkadiConfig.StaminaPerProjectile.Value;
// Ceiling so the widest breath stays castable: 60 shards would otherwise ask 90 stamina.
private static float MAX_VOLLEY_STAMINA => SkadiConfig.MaxVolleyStamina.Value;
// Melee costs nothing at all - it is the baseline attack that has to work at every tier,
// including the long stretch where the player has no eitr whatsoever.
private static float MELEE_RADIUS => SkadiConfig.MeleeRadius.Value;
private static float MODER_MELEE_DAMAGE => SkadiConfig.ModerMeleeDamage.Value;
private static float FADER_MELEE_DAMAGE => SkadiConfig.FaderMeleeDamage.Value;
private static float FADER_SPIN_DAMAGE => SkadiConfig.FaderSpinDamage.Value;
private static float FADER_SPIN_RADIUS => SkadiConfig.FaderSpinRadius.Value;
private void Start()
{
Active = this;
anim = GetComponentInChildren<Animator>();
if (Player.m_localPlayer != null)
{
SetFlying(false);
}
}
// Read by RemoteSkadiAnimator (SkadiPatches.cs) so other clients' copy of the form actually
// plays the bite/claw/breath clip instead of just locomotion. The suffix is a running count,
// not just the trigger name, because the same attack (e.g. two bites in a row) has to look
// like a NEW event to a remote client diffing the ZDO string - an unchanged value never
// re-triggers a Unity Animator trigger parameter.
public const string AttackTriggerKey = "RacesOfValheim_SkadiAttackTrigger";
private static int attackTriggerSeq = 0;
/// <summary>
/// Animator.SetTrigger on a name the controller does not have is silently ignored by Unity,
/// so a wrong trigger looks exactly like "the animation did not play" with nothing in the
/// log. Check before setting, while the form's real trigger names are still being pinned
/// down against the live prefabs.
/// </summary>
private void SetAttackTrigger(string trigger)
{
if (anim == null) return;
foreach (AnimatorControllerParameter p in anim.parameters)
{
if (p.type == AnimatorControllerParameterType.Trigger && p.name == trigger)
{
anim.SetTrigger(trigger);
ZNetView nview = Player.m_localPlayer?.GetComponent<ZNetView>();
if (nview != null && nview.IsValid())
{
attackTriggerSeq++;
nview.GetZDO().Set(AttackTriggerKey, trigger + "#" + attackTriggerSeq);
}
return;
}
}
Jotunn.Logger.LogWarning($"[SkadiFormDebug] {formRules?.Form}: no trigger named '{trigger}' on this animator.");
}
private void Update()
{
if (Player.m_localPlayer == null || Player.m_localPlayer.IsDead()) return;
// Handle Flight Toggle (Right Mouse by default, rebindable) - Disabled for Fader.
// On a pad it is the Block button, Right Mouse's vanilla partner (RaceInput.PadAttackDown(1)):
// the left trigger in the Classic layout. Free here - neither drake nor Moder has a
// button-1 attack; the only one is Fader's spin, and Fader never flies.
if (RaceInput.Allowed &&
(SkadiConfig.FlightToggleKey.Value.IsDownIgnoringHeldKeys() || RaceInput.PadAttackDown(1)) &&
formRules != null && formRules.Form != SkadiProgression.FormType.SkeletonDragon)
{
if (!isFlying && !isLanding)
{
isFlying = true;
LastPoweredTime = Time.time;
SetFlying(true);
}
else if (isFlying && !isLanding)
{
isLanding = true;
isFlying = false;
SetFlying(false);
}
else if (isLanding)
{
// Cancel landing, resume flight
isLanding = false;
isFlying = true;
LastPoweredTime = Time.time;
SetFlying(true);
}
}
if (isLanding)
{
// Prevent fall damage by keeping maxAirAltitude equal to current height
var altitudeField = HarmonyLib.Traverse.Create(Player.m_localPlayer).Field("m_maxAirAltitude");
if (altitudeField.FieldExists())
{
altitudeField.SetValue(Player.m_localPlayer.transform.position.y);
}
if (Player.m_localPlayer.IsOnGround())
{
isLanding = false;
}
}
// Sync Animator
if (anim != null)
{
bool grounded = !isFlying && !isLanding && Player.m_localPlayer.IsOnGround();
// Use standard Valheim monster animator parameters
anim.SetBool("onGround", grounded);
anim.SetBool("flying", isFlying || isLanding);
Vector3 vel = Player.m_localPlayer.GetVelocity();
vel.y = 0f;
float speed = vel.magnitude;
anim.SetFloat("forward_speed", speed);
}
// Handle Attack - each trigger is a rebindable SkadiConfig keybind; the button id
// passed into PerformAttackCoroutine (0/1/2) still selects which attack runs, exactly
// as it did when these were raw mouse-button checks. The same id also picks the
// gamepad button (RaceInput.PadAttackDown), which stays fixed even if the key is rebound.
if (CanAttackNow() && RaceInput.Allowed)
{
if (SkadiConfig.PrimaryAttackKey.Value.IsDownIgnoringHeldKeys() || RaceInput.PadAttackDown(0))
{
if (HasAttackForButton(0) && Time.time - lastAttackTime >= ATTACK_COOLDOWN)
{
StartCoroutine(PerformAttackCoroutine(0));
}
}
else if (SkadiConfig.BreathAttackKey.Value.IsDownIgnoringHeldKeys() || RaceInput.PadAttackDown(2))
{
if (Time.time - lastAttackTime >= ATTACK_COOLDOWN)
{
StartCoroutine(PerformAttackCoroutine(2));
}
}
else if ((SkadiConfig.SpinAttackKey.Value.IsDownIgnoringHeldKeys() || RaceInput.PadAttackDown(1)) && formRules.Form == SkadiProgression.FormType.SkeletonDragon) // Fader Spin
{
if (Time.time - lastAttackTime >= ATTACK_COOLDOWN)
{
StartCoroutine(PerformAttackCoroutine(1));
}
}
}
}
// Airborne Moder keeps the same hand as the ground: the ranged breath is Middle Mouse, and
// Left Mouse has no attack in the air (its ground bite and claws cannot reach from up
// there). Checked before the cooldown so a stray left click does not eat the next volley.
private bool HasAttackForButton(int button)
{
if (formRules == null) return false;
bool airborne = isFlying || isLanding;
if (airborne && formRules.Form == SkadiProgression.FormType.Moder && button != 2)
{
return false;
}
return true;
}
private bool TrySpendVolleyStamina(int projCount)
{
float cost = Mathf.Min(STAMINA_PER_PROJECTILE * projCount, MAX_VOLLEY_STAMINA);
if (!Player.m_localPlayer.HaveStamina(cost))
{
Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_skadi_not_enough_stamina"));
return false;
}
Player.m_localPlayer.UseStamina(cost);
return true;
}
private IEnumerator PerformAttackCoroutine(int button)
{
lastAttackTime = Time.time;
SkadiRace.ApplyCooldownIcon(SkadiRace.ATTACK_COOLDOWN_SE, ATTACK_COOLDOWN);
if (formRules.Form == SkadiProgression.FormType.Drake)
{
if (button == 2) yield break; // Drake only uses LMB
if (!TrySpendVolleyStamina(3)) yield break;
if (anim != null) anim.SetTrigger("attack");
// Delay to match animation spit timing
yield return new WaitForSeconds(0.3f);
GameObject projPrefab = PrefabManager.Cache.GetPrefab<GameObject>("hatchling_cold_projectile");
if (projPrefab == null) yield break;
ItemDrop staffDrop = PrefabManager.Cache.GetPrefab<GameObject>("StaffIceShards")?.GetComponent<ItemDrop>();
if (staffDrop == null) yield break;
float vel = staffDrop.m_itemData.m_shared.m_attack.m_projectileVel;
for (int i = 0; i < 3; i++)
{
Vector3 spawnPos = Player.m_localPlayer.GetEyePoint() + Player.m_localPlayer.GetLookDir() * 1.5f;
Vector3 targetDir = Player.m_localPlayer.GetLookDir();
Vector3 right = Vector3.Cross(Vector3.up, targetDir);
targetDir += right * UnityEngine.Random.Range(-0.1f, 0.1f) + Vector3.up * UnityEngine.Random.Range(-0.1f, 0.1f);
targetDir.Normalize();
GameObject projInstance = Instantiate(projPrefab, spawnPos, Quaternion.LookRotation(targetDir));
Projectile proj = projInstance.GetComponent<Projectile>();
if (proj != null)
{
HitData hitData = new HitData();
hitData.m_damage = staffDrop.m_itemData.m_shared.m_damages;
hitData.SetAttacker(Player.m_localPlayer);
// The Drake breath is a fixed three-shard volley, so one third each.
SkadiMagicSkill.TagCast(hitData, 3);
proj.Setup(Player.m_localPlayer, targetDir * vel, -1f, hitData, staffDrop.m_itemData, null);
}
yield return new WaitForSeconds(0.2f);
}
}
else if (formRules.Form == SkadiProgression.FormType.Moder)
{
string attackTrigger = "attack_bite";
string projName = null;
int projCount = 1;
float projDelay = 0.5f;
bool isMelee = true;
if (isFlying || isLanding)
{
// Air attack (Ice Barrage)
attackTrigger = "attack_iceball";
projName = "dragon_ice_projectile";
projCount = 16;
projDelay = 0.8f;
isMelee = false;
}
else
{
if (button == 2)
{
// Ground MMB (Breath)
attackTrigger = "attack_breath";
projName = "hatchling_cold_projectile"; // Use cold explosion projectiles for a breath stream
projCount = 20;
projDelay = 0.5f; // Wait for the head to lower before breathing
isMelee = false;
}
else
{
// Ground LMB (Bite/Claw)
attackTrigger = UnityEngine.Random.value > 0.5f ? "attack_bite" : (UnityEngine.Random.value > 0.5f ? "attack_claw_left" : "attack_claw_right");
isMelee = true;
projDelay = 0.5f;
}
}
if (!isMelee && !TrySpendVolleyStamina(projCount)) yield break;
// Committed for the same reason as Fader's below: a 16- or 20-projectile volley
// lasts long enough for the camera to swing away from where the animation is
// still breathing.
// Grounded, the same as Fader's below: the head is held on the aim and the breath
// comes out of it. In the air the flight patch already steers the body, so this
// stays out of its way and the volley simply follows the same muzzle.
if (!isMelee && !isFlying && !isLanding)
{
breathingUntil = Time.time + projDelay + projCount * 0.05f + 0.5f;
}
SetAttackTrigger(attackTrigger);
yield return new WaitForSeconds(projDelay);
if (isMelee)
{
ExecuteMeleeDamage(MODER_MELEE_DAMAGE, MELEE_RADIUS);
}
if (!isMelee && projName != null)
{
GameObject projPrefab = PrefabManager.Cache.GetPrefab<GameObject>(projName);
if (projPrefab == null) yield break;
ItemDrop staffDrop = PrefabManager.Cache.GetPrefab<GameObject>("StaffIceShards")?.GetComponent<ItemDrop>();
if (staffDrop == null) yield break;
float vel = staffDrop.m_itemData.m_shared.m_attack.m_projectileVel;
for (int i = 0; i < projCount; i++)
{
Vector3 targetDir = Player.m_localPlayer.transform.forward;
Vector3 spawnPos = Player.m_localPlayer.GetEyePoint() + targetDir * 3.0f;
if (projCount > 1)
{
Vector3 right = Vector3.Cross(Vector3.up, targetDir);
targetDir += right * UnityEngine.Random.Range(-0.3f, 0.3f) + Vector3.up * UnityEngine.Random.Range(-0.3f, 0.3f);
targetDir.Normalize();
}
GameObject projInstance = Instantiate(projPrefab, spawnPos, Quaternion.LookRotation(targetDir));
Projectile proj = projInstance.GetComponent<Projectile>();
if (proj != null)
{
HitData hitData = new HitData();
hitData.m_damage = staffDrop.m_itemData.m_shared.m_damages;
hitData.SetAttacker(Player.m_localPlayer);
SkadiMagicSkill.TagCast(hitData, projCount);
proj.Setup(Player.m_localPlayer, targetDir * vel, -1f, hitData, staffDrop.m_itemData, null);
}
if (projCount > 1) yield return new WaitForSeconds(0.05f);
}
}
}
else if (formRules.Form == SkadiProgression.FormType.SkeletonDragon)
{
string attackTrigger = "attack_bite";
string projName = null;
int projCount = 1;
float projDelay = 0.5f;
bool isMelee = true;
float meleeDamage = FADER_MELEE_DAMAGE;
float meleeRadius = MELEE_RADIUS;
// No airborne branch here: the flight toggle in Update excludes SkeletonDragon,
// so this form never leaves the ground and any air attack would be unreachable.
if (button == 2)
{
// Ground MMB (Frost Breath stream)
attackTrigger = "attack_flamebreath";
projName = "hatchling_cold_projectile";
projCount = 60; // Tripled!
projDelay = 0.5f;
isMelee = false;
}
else if (button == 1)
{
// Ground RMB (Spin) - hits all around rather than in a forward arc
attackTrigger = "attack_Spin";
isMelee = true;
projDelay = 0.5f;
meleeDamage = FADER_SPIN_DAMAGE;
meleeRadius = FADER_SPIN_RADIUS;
}
else
{
// Ground LMB (Melee mix - bite/claws)
float rand = UnityEngine.Random.value;
if (rand < 0.33f) attackTrigger = "attack_bite";
else if (rand < 0.66f) attackTrigger = "attack_ClawL";
else attackTrigger = "attack_ClawR";
isMelee = true;
projDelay = 0.5f;
}
if (!isMelee && !TrySpendVolleyStamina(projCount)) yield break;
// A breath is a stream, not a shot: 60 shards at 0.05 s each runs for about three
// seconds. Reading GetLookDir() fresh inside that loop let the ice track the
// crosshair live while the model's own breath VFX - baked into the animation, and
// so always leaving the muzzle - stayed with the body, which only turns at
// m_turnSpeed. Sweep the camera mid-breath and the two ended up pointing opposite
// ways. The direction is committed here instead, and the body is turned onto it.
// The breath follows the muzzle rather than a direction captured when the key went
// down. The model's own breath VFX is part of the animation and always leaves the
// mouth, so any direction the projectiles keep on their own drifts away from it -
// locking it at the press just swapped which of the two lagged. Pinning the body
// to the aim for the duration (breathingUntil, read by SkadiReverseFacingPatch)
// lets the mouse steer the head, and the projectiles below simply come out of
// wherever it has turned to, so ice and VFX cannot separate.
if (!isMelee)
{
breathingUntil = Time.time + projDelay + projCount * 0.05f + 0.5f;
}
SetAttackTrigger(attackTrigger);
yield return new WaitForSeconds(projDelay);
if (isMelee)
{
ExecuteMeleeDamage(meleeDamage, meleeRadius);
}
if (!isMelee && projName != null)
{
GameObject projPrefab = PrefabManager.Cache.GetPrefab<GameObject>(projName);
if (projPrefab == null) yield break;
ItemDrop staffDrop = PrefabManager.Cache.GetPrefab<GameObject>("StaffIceShards")?.GetComponent<ItemDrop>();
if (staffDrop == null) yield break;
float vel = staffDrop.m_itemData.m_shared.m_attack.m_projectileVel;
for (int i = 0; i < projCount; i++)
{
Vector3 targetDir = Player.m_localPlayer.transform.forward;
Vector3 spawnPos = Player.m_localPlayer.GetEyePoint() + targetDir * 4.0f;
if (projCount > 1)
{
Vector3 right = Vector3.Cross(Vector3.up, targetDir);
targetDir += right * UnityEngine.Random.Range(-0.2f, 0.2f) + Vector3.up * UnityEngine.Random.Range(-0.2f, 0.2f);
targetDir.Normalize();
}
GameObject projInstance = Instantiate(projPrefab, spawnPos, Quaternion.LookRotation(targetDir));
Projectile proj = projInstance.GetComponent<Projectile>();
HitData hitData = new HitData();
hitData.m_damage = staffDrop.m_itemData.m_shared.m_damages;
// Convert Fire to Frost
hitData.m_damage.m_frost += hitData.m_damage.m_fire;
hitData.m_damage.m_fire = 0f;
hitData.SetAttacker(Player.m_localPlayer);
SkadiMagicSkill.TagCast(hitData, projCount);
if (proj != null)
{
proj.Setup(Player.m_localPlayer, targetDir * vel, -1f, hitData, staffDrop.m_itemData, null);
}
// Turn fire VFX to blue/frost
foreach (ParticleSystem ps in projInstance.GetComponentsInChildren<ParticleSystem>())
{
var main = ps.main;
main.startColor = new Color(0.4f, 0.8f, 1f, 1f); // Ice blue
}
foreach (Light l in projInstance.GetComponentsInChildren<Light>())
{
l.color = new Color(0.4f, 0.8f, 1f, 1f);
}
if (projCount > 1) yield return new WaitForSeconds(0.05f);
}
}
}
}
// The dragon forms never go through Humanoid.StartAttack - SkadiAttackPatch blocks it, and
// they carry no weapon - so the bite, claw and spin animations landed no damage at all and
// simply burned eitr. Sweep for targets the way FenrirBehaviors does for its claws.
private void ExecuteMeleeDamage(float baseDamage, float radius)
{
if (Player.m_localPlayer == null) return;
Vector3 playerPos = Player.m_localPlayer.transform.position;
Vector3 forward = Player.m_localPlayer.transform.forward;
Vector3 attackPoint = playerPos + forward * 2f + Vector3.up * 1f;
// Spin sweeps all around; the directional attacks stay in a forward arc.
bool fullCircle = radius >= FADER_SPIN_RADIUS;
float totalDamage = baseDamage + Player.m_localPlayer.GetSkillLevel(Skills.SkillType.Unarmed);
if (fullCircle) attackPoint = playerPos + Vector3.up * 1f;
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, radius, layerMask);
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) continue;
Character characterTarget = target as Character;
if (characterTarget != null && characterTarget == Player.m_localPlayer) continue;
GameObject targetObj = (target as MonoBehaviour)?.gameObject;
if (targetObj != null)
{
if (hitObjects.Contains(targetObj)) continue;
hitObjects.Add(targetObj);
}
Vector3 targetCenter = hit.bounds.center;
Vector3 dirToTarget = (targetCenter - playerPos).normalized;
if (!fullCircle && Vector3.Angle(forward, dirToTarget) >= 70f) continue;
Vector3 eyePos = playerPos + Vector3.up * 1.5f;
if (Physics.Linecast(eyePos, targetCenter, out RaycastHit rayHit, LayerMask.GetMask("Default", "static_solid", "terrain", "piece"))) continue;
HitData hitData = new HitData();
// Frost-flavoured maul; SkadiDamagePatch tops this up with the per-tier frost bonus.
hitData.m_damage.m_blunt = totalDamage * 0.6f;
hitData.m_damage.m_frost = totalDamage * 0.4f;
hitData.m_pushForce = 40f;
hitData.m_point = targetCenter;
hitData.m_dir = dirToTarget;
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);
target.Damage(hitData);
}
}
private void OnDestroy()
{
if (Active == this) Active = null;
if (Player.m_localPlayer != null)
{
SetFlying(false);
}
}
}
}