RacesOfValheim/JotunnModStub/Skadi/DrakeFormBehavior.cs
kanym 5350ebda5d Add the Race Menu Ward; WIP on remote Trol/Skadi visuals
Race Menu Ward: a buildable ward (2 wood, hammer/Misc, no crafting station)
that manages your race outside the debug console - reset the race, switch
between the server's boss progression and your own, and advance that personal
progression by offering a boss's secondary drop to it. One is placed near the
sacrificial stones on first load of a world, by the host only.

BossProgressionManager grows a personal mode alongside the world one. The tier
is stored on the character rather than the world, so a personal tier travels
with the player between servers instead of being tied to whichever world
unlocked it. resetrace and the ward now share RacesOfValheim.ResetRace so both
paths clean up identical state.

Also in progress, and NOT yet working: remote Trol sizing and remote Skadi
flight. Both are computed from the observer instead of the observed -

- Remote Trols are scaled from the observing player's own progression, and
  never show True Form, because SE_TrolTrueForm only exists on the transformed
  player's client. Each Trol now publishes its state and True Form flag onto
  its own ZDO for others to read.
- Remote Skadi dragons sink to the terrain regardless of the altitude being
  replicated: Character.m_flying is only ever set on the flying player's
  client, so observers run grounded motion under gravity. Flight is mirrored
  through the ZDO and the remote copy's rigidbody gravity is disabled while it
  lasts.

Neither has fixed the symptom yet, so both paths keep a throttled diagnostic
log reporting what each observer actually computes. Committed to get the
instrumentation onto the branch, not because it works.

Packaging no longer hardcodes another machine's desktop path: Thunderstore and
Nexus zips go to dist/ on Release builds only, and the DLL is copied into
Valheim only when VALHEIM_INSTALL actually points at a plugins folder.
2026-08-02 08:45:47 +02:00

512 lines
23 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";
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;
}
private const float ATTACK_COOLDOWN = 3f;
// 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 const float STAMINA_PER_PROJECTILE = 1.5f;
// Ceiling so the widest breath stays castable: 60 shards would otherwise ask 90 stamina.
private const float MAX_VOLLEY_STAMINA = 85f;
// 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 const float MELEE_RADIUS = 3f;
private const float MODER_MELEE_DAMAGE = 90f;
private const float FADER_MELEE_DAMAGE = 120f;
private const float FADER_SPIN_DAMAGE = 100f;
private const float FADER_SPIN_RADIUS = 5f;
private void Start()
{
Active = this;
anim = GetComponentInChildren<Animator>();
if (Player.m_localPlayer != null)
{
SetFlying(false);
}
}
private void Update()
{
if (Player.m_localPlayer == null || Player.m_localPlayer.IsDead()) return;
// Handle Flight Toggle (RMB) - Disabled for Fader
if (RaceInput.Allowed && Input.GetMouseButtonDown(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
if (CanAttackNow() && RaceInput.Allowed)
{
if (Input.GetMouseButtonDown(0))
{
if (HasAttackForButton(0) && Time.time - lastAttackTime >= ATTACK_COOLDOWN)
{
StartCoroutine(PerformAttackCoroutine(0));
}
}
else if (Input.GetMouseButtonDown(2)) // MMB
{
if (Time.time - lastAttackTime >= ATTACK_COOLDOWN)
{
StartCoroutine(PerformAttackCoroutine(2));
}
}
else if (Input.GetMouseButtonDown(1) && formRules.Form == SkadiProgression.FormType.SkeletonDragon) // RMB for 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, "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);
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;
if (anim != null) anim.SetTrigger(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 spawnPos = Player.m_localPlayer.GetEyePoint() + Player.m_localPlayer.GetLookDir() * 3.0f;
Vector3 targetDir = Player.m_localPlayer.GetLookDir();
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);
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;
if (anim != null) anim.SetTrigger(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 spawnPos = Player.m_localPlayer.GetEyePoint() + Player.m_localPlayer.GetLookDir() * 4.0f;
Vector3 targetDir = Player.m_localPlayer.GetLookDir();
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);
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);
}
}
}
}