RacesOfValheim/JotunnModStub/Skadi/SkadiRace.cs
kanym 0f5b5e4868 feat(skadi): each dragon form flies and cools down on its own terms
The Drake and the Moder shared one set of flight numbers, so once the
Moder lost its time limit at the Queen the Drake had no reason left.
Now the Drake is the scout: quick to turn, fast, free to fly, but it
will not take off while encumbered. The Moder is the freighter: slow to
turn, 3 stamina a second to beat its wings, and it lifts a heavy pack at
25% extra cost.

"Skadi - Directed Flight" becomes "Skadi - Dragon Forms", with every
flight number per form plus the bat's Flight Stamina, While Encumbered,
Encumbered Extra Stamina Cost, Max Duration, Duration Per State and
Cooldown. Duration and cooldown default to -1, which keeps the
boss-tier table.

Each form also gets its own cooldown effect and icon, so a cooldown on
one form no longer blocks another. Suggested by Dissolution.
2026-11-02 15:58:17 +01:00

1014 lines
46 KiB
C#

using System;
using System.Collections;
using UnityEngine;
using Jotunn.Managers;
using Jotunn.Entities;
namespace RacesOfValheim
{
public class SkadiRace : MonoBehaviour
{
public static SkadiRace Instance;
public static SE_SkadiStats skadiCurseSE;
public static SE_FormCooldown skadiCdSE;
public static SE_SkadiForm skadiFormSE;
private float auraTimer = 0f;
private float lastSpellTime = 0f;
private GameObject currentTransformation;
private bool isTransformed = false;
private bool isTransformingSequence = false;
private SkadiProgression.FormRules activeRules = null;
// Time.time at which a timed form drops; 0 means the current form has no time limit.
private float formExpireTime = 0f;
private float lastAuraTime = 0f;
private GameObject frostAuraVFX = null;
// Cold Spell tuning. Damage is 15 + 8 per progression state, so it runs from roughly 31 at
// Eikthyr to 79 at Fader - deliberately a notch under the melee options of the other races
// at each tier, which is the trade for hitting at range on a short cooldown.
//
// All values below read from SkadiConfig (BepInEx Config, see SkadiConfig.cs) rather than
// being fixed constants, so they can be retuned from Configuration Manager without a
// rebuild - see CONFIGURATION-MANAGER-HOWTO.md.
public const string SPELL_COOLDOWN_SE = "SE_SkadiSpellCooldown";
public const string ATTACK_COOLDOWN_SE = "SE_SkadiAttackCooldown";
private static float SPELL_STAMINA_COST => SkadiConfig.SpellStaminaCost.Value;
private static float SPELL_COOLDOWN => SkadiConfig.SpellCooldown.Value;
private static float IMPROVED_SPELL_COOLDOWN => SkadiConfig.ImprovedSpellCooldown.Value;
private static float SPELL_BASE_DAMAGE => SkadiConfig.SpellBaseDamage.Value;
private static float SPELL_DAMAGE_PER_STATE => SkadiConfig.SpellDamagePerState.Value;
private static int IMPROVED_SPELL_SHARDS => SkadiConfig.ImprovedSpellShards.Value;
// The improved cast spreads 1.6 casts worth of damage over its shards: wider, not stronger.
private static float IMPROVED_SPELL_DAMAGE_BUDGET => SkadiConfig.ImprovedSpellDamageBudget.Value;
private void Awake()
{
Instance = this;
}
public void CreateModAssets()
{
// The reagent goes first: the faction merchant catalogue resolves its entries by prefab
// name, so Greater Frost Heart has to exist before a Fenring_Cultist is ever set up as a
// bench.
SkadiFrostHeart.Register();
SkadiGolem.Register();
var se = ScriptableObject.CreateInstance<SE_SkadiStats>();
se.name = "SE_SkadiStats";
se.m_name = "$rov_se_skadi_stats_name";
// Icon
GameObject drakeTrophy = PrefabManager.Cache.GetPrefab<ItemDrop>("TrophyHatchling")?.gameObject;
if (drakeTrophy != null)
{
ItemDrop trophyDrop = drakeTrophy.GetComponent<ItemDrop>();
if (trophyDrop != null && trophyDrop.m_itemData.m_shared.m_icons.Length > 0)
{
se.m_icon = trophyDrop.m_itemData.m_shared.m_icons[0];
}
}
CustomStatusEffect skadiStats = new CustomStatusEffect(se, fixReference: false);
ItemManager.Instance.AddStatusEffect(skadiStats);
skadiCurseSE = skadiStats.StatusEffect as SE_SkadiStats;
// Timed forms and their cooldown are Moder's, so they carry her trophy rather than the
// drake one used for the passive blessing.
Sprite dragonIcon = GetItemIcon("TrophyDragonQueen") ?? GetItemIcon("TrophyHatchling");
// One cooldown per form, so a Drake cooldown set in the config never holds the Moder
// back, nor the other way round. The Moder keeps the original name.
skadiCdSE = RegisterFormCooldown(SkadiProgression.FormType.Moder, "$rov_se_skadi_formcd_name", dragonIcon);
RegisterFormCooldown(SkadiProgression.FormType.Drake, "$rov_se_skadi_drakecd_name", GetItemIcon("TrophyHatchling") ?? dragonIcon);
RegisterFormCooldown(SkadiProgression.FormType.SkeletonDragon, "$rov_se_skadi_fadercd_name", GetItemIcon("TrophyFader") ?? dragonIcon);
skadiFormSE = ScriptableObject.CreateInstance<SE_SkadiForm>();
skadiFormSE.name = "SE_SkadiForm";
skadiFormSE.m_name = "$rov_se_skadi_form_name";
skadiFormSE.m_tooltip = "$rov_se_skadi_form_tooltip";
skadiFormSE.m_icon = dragonIcon;
ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(skadiFormSE, fixReference: false));
// Per-ability cooldowns. Each gets its own icon so a spell on cooldown reads
// differently from a dragon attack on cooldown at a glance.
var spellCd = ScriptableObject.CreateInstance<SE_SkadiAbilityCooldown>();
spellCd.name = SPELL_COOLDOWN_SE;
spellCd.m_name = "$rov_se_skadi_coldspellcd_name";
spellCd.m_tooltip = "$rov_se_skadi_coldspellcd_tooltip";
spellCd.m_icon = GetItemIcon("StaffIceShards") ?? dragonIcon;
ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(spellCd, fixReference: false));
var attackCd = ScriptableObject.CreateInstance<SE_SkadiAbilityCooldown>();
attackCd.name = ATTACK_COOLDOWN_SE;
attackCd.m_name = "$rov_se_skadi_dragonattackcd_name";
attackCd.m_tooltip = "$rov_se_skadi_dragonattackcd_tooltip";
attackCd.m_icon = GetItemIcon("TrophyHatchling") ?? dragonIcon;
ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(attackCd, fixReference: false));
}
// Drives the HUD countdown: Valheim prints the remaining time on any status effect whose
// m_ttl is set, so the cooldown only has to exist for the icon to tick down by itself.
public static void ApplyCooldownIcon(string effectName, float seconds)
{
if (Player.m_localPlayer == null || seconds <= 0f) return;
int hash = effectName.GetStableHashCode();
SEMan seman = Player.m_localPlayer.GetSEMan();
seman.RemoveStatusEffect(hash, true);
seman.AddStatusEffect(hash, true);
StatusEffect se = seman.GetStatusEffect(hash);
if (se != null) se.m_ttl = seconds;
}
private static SE_FormCooldown RegisterFormCooldown(SkadiProgression.FormType form, string displayName, Sprite icon)
{
SE_FormCooldown cd = ScriptableObject.CreateInstance<SE_FormCooldown>();
cd.name = CooldownSEName(form);
cd.m_name = displayName;
cd.m_icon = icon;
ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(cd, fixReference: false));
return cd;
}
private static string CooldownSEName(SkadiProgression.FormType form)
{
switch (form)
{
case SkadiProgression.FormType.Drake: return "SE_SkadiCooldown_Drake";
case SkadiProgression.FormType.SkeletonDragon: return "SE_SkadiCooldown_Fader";
default: return "SE_SkadiCooldown";
}
}
private static Sprite GetItemIcon(string prefabName)
{
GameObject trophy = PrefabManager.Cache.GetPrefab<ItemDrop>(prefabName)?.gameObject;
ItemDrop drop = trophy != null ? trophy.GetComponent<ItemDrop>() : null;
if (drop != null && drop.m_itemData.m_shared.m_icons.Length > 0)
{
return drop.m_itemData.m_shared.m_icons[0];
}
return null;
}
public bool IsSkadi()
{
return IsLocalSkadi();
}
/// <summary>
/// The same check, reachable without an Instance - which the golem and the cave-building
/// watcher both need, since they run from static context.
/// </summary>
public static bool IsLocalSkadi()
{
return Player.m_localPlayer != null &&
Player.m_localPlayer.m_customData.ContainsKey("Race") &&
Player.m_localPlayer.m_customData["Race"] == "Skadi";
}
private void Update()
{
if (!IsSkadi()) return;
if (Player.m_localPlayer.IsDead() && isTransformed)
{
ExecuteReversion();
}
var rules = SkadiProgression.GetRules(BossProgressionManager.GetCurrentProgressionState());
// Update the stats SE
if (skadiCurseSE != null)
{
int auraHash = skadiCurseSE.name.GetStableHashCode();
SEMan seman = Player.m_localPlayer.GetSEMan();
skadiCurseSE.UpdateStats(rules);
if (!seman.HaveStatusEffect(auraHash))
{
seman.AddStatusEffect(auraHash, true);
}
// SEMan.AddStatusEffect stores a Clone() of the prototype, so updating
// skadiCurseSE alone only changed the copy that gets stamped out at the next add:
// the aura already running on the player kept whatever tier it was born with.
// Beating a boss mid-session left the old frost modifier and eitr regen in place
// until the effect was re-added (race reselection or a relog) - most visibly at
// the Queen, where Immune never replaced Resistant. Refresh the live one as well;
// UpdateStats is a no-op unless the tier actually moved a value.
SE_SkadiStats liveAura = seman.GetStatusEffect(auraHash) as SE_SkadiStats;
if (liveAura != null) liveAura.UpdateStats(rules);
}
if (rules.FrostAura)
{
EnsureFrostAuraVFX(true);
if (Time.time - lastAuraTime >= SkadiConfig.AuraTickInterval.Value)
{
ApplyColdAura();
lastAuraTime = Time.time;
}
}
else
{
EnsureFrostAuraVFX(false);
}
if (rules.EitrRegenMultiplier > 1f && !Player.m_localPlayer.IsDead())
{
try
{
var eitrTimerField = HarmonyLib.Traverse.Create(Player.m_localPlayer).Field("m_eitrRegenTimer");
if (eitrTimerField.FieldExists())
{
float currentTimer = eitrTimerField.GetValue<float>();
if (currentTimer > 0f)
{
float bonus = rules.EitrRegenMultiplier - 1f;
if (bonus > 0f && bonus < 1f)
{
float targetTime = 1f - bonus;
float requiredSpeed = 1f / targetTime;
float additionalSpeed = requiredSpeed - 1f;
eitrTimerField.SetValue(currentTimer - (additionalSpeed * Time.deltaTime));
}
}
}
}
catch (Exception e)
{
// Ignore, to prevent breaking the rest of the Update loop
}
}
if (rules.ColdSpell && RaceInput.Allowed)
{
HandleColdSpell(rules);
}
else if (ColdSpellKeyPressed())
{
ColdSpellBail(!rules.ColdSpell
? $"the tier does not grant it - state {BossProgressionManager.GetCurrentProgressionState()}, needs 2"
: "RaceInput.Allowed is false - a GUI has the input");
}
if (isTransformingSequence) return;
// Forms with a DurationMinutes budget drop on their own once it runs out, which is
// also what starts their cooldown - without this the timed tiers never expired.
if (isTransformed && formExpireTime > 0f && Time.time >= formExpireTime)
{
formExpireTime = 0f;
Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_skadi_dragon_form_fades"));
RunFormRoutine(RevertToHumanRoutine());
return;
}
// Form keys and the debug dump are ability input: they stay inert while a GUI has focus.
if (!RaceInput.Allowed) return;
int state = BossProgressionManager.GetCurrentProgressionState();
if (SkadiConfig.DrakeFormKey.Value.IsDownIgnoringHeldKeys()) { TryTransformWithRules(SkadiProgression.GetGKeyRules(state)); return; }
if (SkadiConfig.ModerFormKey.Value.IsDownIgnoringHeldKeys()) { TryTransformWithRules(SkadiProgression.GetHKeyRules(state)); return; }
if (SkadiConfig.FaderFormKey.Value.IsDownIgnoringHeldKeys()) { TryTransformWithRules(SkadiProgression.GetJKeyRules(state)); return; }
}
private void DumpPrefabDebugInfo(string prefabName)
{
GameObject prefab = Jotunn.Managers.PrefabManager.Cache.GetPrefab<GameObject>(prefabName);
if (prefab == null)
{
Jotunn.Logger.LogWarning($"{prefabName} prefab not found!");
return;
}
Jotunn.Logger.LogInfo($"=== {prefabName.ToUpper()} DEBUG INFO ===");
Animator anim = prefab.GetComponentInChildren<Animator>();
if (anim != null)
{
Jotunn.Logger.LogInfo("--- Animator Parameters ---");
foreach (UnityEngine.AnimatorControllerParameter param in anim.parameters)
{
Jotunn.Logger.LogInfo($"Param: {param.name} (Type: {param.type})");
}
}
Humanoid humanoid = prefab.GetComponent<Humanoid>();
if (humanoid != null)
{
Jotunn.Logger.LogInfo("--- Weapons (Default Items) ---");
if (humanoid.m_defaultItems != null)
{
foreach (GameObject item in humanoid.m_defaultItems)
{
if (item == null) continue;
ItemDrop drop = item.GetComponent<ItemDrop>();
if (drop != null)
{
var attack = drop.m_itemData.m_shared.m_attack;
Jotunn.Logger.LogInfo($"Weapon Prefab: {item.name}");
Jotunn.Logger.LogInfo($" - Attack Anim: {attack.m_attackAnimation}");
if (attack.m_attackProjectile != null)
Jotunn.Logger.LogInfo($" - Projectile: {attack.m_attackProjectile.name}");
}
}
}
Jotunn.Logger.LogInfo("--- Random Weapons ---");
if (humanoid.m_randomWeapon != null)
{
foreach (var item in humanoid.m_randomWeapon)
{
if (item == null) continue;
ItemDrop drop = item.GetComponent<ItemDrop>();
if (drop != null)
{
var attack = drop.m_itemData.m_shared.m_attack;
Jotunn.Logger.LogInfo($"Random Weapon Prefab: {item.name}");
Jotunn.Logger.LogInfo($" - Attack Anim: {attack.m_attackAnimation}");
if (attack.m_attackProjectile != null)
Jotunn.Logger.LogInfo($" - Projectile: {attack.m_attackProjectile.name}");
}
}
}
}
ZSFX[] sfxs = prefab.GetComponentsInChildren<ZSFX>(true);
Jotunn.Logger.LogInfo("--- Sounds (ZSFX) ---");
foreach (ZSFX sfx in sfxs)
{
Jotunn.Logger.LogInfo($"Sound: {sfx.gameObject.name}");
}
Jotunn.Logger.LogInfo($"=== END {prefabName.ToUpper()} DEBUG INFO ===");
}
/// <summary>
/// Whether the Cold Spell's own key went down this frame, read raw and with no gate at all.
/// Only for the diagnostics below: five different conditions can swallow this spell and every
/// one of them is silent, so "it does nothing" was impossible to tell apart from "it was
/// never pressed".
/// </summary>
private static bool ColdSpellKeyPressed()
{
KeyCode key = SkadiConfig.ColdSpellKey.Value.MainKey;
return key != KeyCode.None && Input.GetKeyDown(key);
}
private static readonly System.Collections.Generic.HashSet<string> coldSpellBails =
new System.Collections.Generic.HashSet<string>();
/// <summary>One step of the cast, said before it is taken. Once per distinct step.</summary>
private static void ColdSpellStep(string step)
{
if (coldSpellBails.Add("step:" + step))
{
Jotunn.Logger.LogInfo($"[Skadi] Cold Spell: {step}.");
}
}
/// <summary>
/// What a borrowed prefab actually is. The root flag matters for the same reason it did on
/// the Skeleton's fire aura: a parented object is a node inside somebody else's hierarchy,
/// not a prefab, and spawning one on its own is how this mod has crashed before.
/// </summary>
private static string Describe(GameObject prefab)
{
if (prefab == null) return "null";
string path = prefab.name;
for (Transform t = prefab.transform.parent; t != null; t = t.parent) path = t.name + "/" + path;
var parts = new System.Collections.Generic.List<string>();
foreach (Component comp in prefab.GetComponents<Component>())
{
if (comp != null && !(comp is Transform)) parts.Add(comp.GetType().Name);
}
return $"{path}' root={prefab.transform.parent == null} carries=[{string.Join(", ", parts.ToArray())}]";
}
/// <summary>Says why a press did not become a cast, once per reason per session.</summary>
private static void ColdSpellBail(string reason)
{
if (coldSpellBails.Add(reason))
{
Jotunn.Logger.LogInfo($"[Skadi] Cold Spell key pressed but not cast: {reason}.");
}
}
private void HandleColdSpell(SkadiProgression.FormRules rules)
{
bool pressed = ColdSpellKeyPressed();
if (Player.m_localPlayer == null || Player.m_localPlayer.IsDead())
{
if (pressed) ColdSpellBail("the player is dead");
return;
}
if (isTransformed)
{
if (pressed) ColdSpellBail("you are in a dragon form");
return;
}
// Hammer, hoe or cultivator in hand: every build button is vanilla's. Middle mouse is
// Remove on the keyboard, and on the pad JoySecondaryAttack shares its physical button
// with JoyRemove (Classic) or JoyPlace (Alt2) - read off ZInput.AddGamepad*Buttons - so
// each piece built or removed also cast the spell and drained the stamina for it.
if (Player.m_localPlayer.InPlaceMode())
{
if (pressed) ColdSpellBail("a hammer, hoe or cultivator is in hand");
return;
}
// Middle Mouse Button to cast, by default - rebindable via SkadiConfig.ColdSpellKey.
// On a gamepad, the secondary attack button (the pad's own middle-mouse equivalent) -
// but only bare-handed: the pad has no separate spell key, so with a weapon or a tool
// that button belongs to the item's own secondary attack, as it does in vanilla.
if (SkadiConfig.ColdSpellKey.Value.IsDownIgnoringHeldKeys() ||
(RaceInput.PadAttackDown(2) && PadCastsColdSpell(Player.m_localPlayer)))
{
// The improved cast is a burst rather than a rapid-fire, so it waits longer.
float cooldown = rules.ImprovedColdSpell ? IMPROVED_SPELL_COOLDOWN : SPELL_COOLDOWN;
if (Time.time - lastSpellTime < cooldown)
{
ColdSpellBail($"it is on cooldown - {cooldown - (Time.time - lastSpellTime):F1}s left of {cooldown:F0}s");
return;
}
// Stamina, never eitr: the spell unlocks at Eikthyr but eitr food only exists from
// the Mistlands onward, so the old HaveEitr gate left it unusable for five tiers.
if (!Player.m_localPlayer.HaveStamina(SPELL_STAMINA_COST))
{
Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_skadi_not_enough_stamina"));
return;
}
Player.m_localPlayer.UseStamina(SPELL_STAMINA_COST);
lastSpellTime = Time.time;
ApplyCooldownIcon(SPELL_COOLDOWN_SE, cooldown);
var zanim = HarmonyLib.Traverse.Create(Player.m_localPlayer).Field<ZSyncAnimation>("m_zanim").Value;
if (zanim != null)
{
// "galdr_cast" is not one of the triggers Valheim actually defines, so it
// never fired and the unarmed kick stayed. "gpower" is the guardian power
// raise: both arms up, which reads as casting rather than a leg swing.
RaceInput.SuppressGuardianPowerBriefly();
zanim.SetTrigger("gpower");
}
if (coldSpellBails.Add("cast")) Jotunn.Logger.LogInfo("[Skadi] Cold Spell cast.");
StartCoroutine(ColdSpellKickCoroutine(rules));
}
else if (pressed)
{
// The key physically went down and the wrapper still said no. That is the last place
// left for this to fail, and the only one with no condition of its own above it.
ColdSpellBail($"'{SkadiConfig.ColdSpellKey.Value.MainKey}' went down but " +
"IsDownIgnoringHeldKeys refused it");
}
}
/// <summary>
/// Whether the pad's secondary attack button casts the Cold Spell right now: out of build
/// mode and with nothing in either hand. Shared with SkadiAttackPatch, which swallows the
/// unarmed kick under exactly the same condition.
/// </summary>
public static bool PadCastsColdSpell(Player player) => RaceInput.EmptyHanded(player);
private IEnumerator ColdSpellKickCoroutine(SkadiProgression.FormRules rules)
{
// Wait for the cast animation to reach the release point
yield return new WaitForSeconds(0.4f);
if (Player.m_localPlayer == null || Player.m_localPlayer.IsDead()) yield break;
// EVERY STEP BELOW IS SAID BEFORE IT IS TAKEN, once per session. Casting this spell exits
// the process outright - no exception, no stack, the log simply stops - which is the same
// signature as sfx_fenring_howl, the sound that cannot be spawned either. The only reason
// we know where either one dies is that the line before it had already been flushed.
ColdSpellStep("resolving 'StaffIceShards'");
GameObject staffPrefab = PrefabManager.Cache.GetPrefab<GameObject>("StaffIceShards");
if (staffPrefab == null)
{
ColdSpellStep("'StaffIceShards' did not resolve - no shards fired");
yield break;
}
ItemDrop staffDrop = staffPrefab.GetComponent<ItemDrop>();
if (staffDrop == null)
{
ColdSpellStep("'StaffIceShards' has no ItemDrop - no shards fired");
yield break;
}
// NOT described here, deliberately, and this is an experiment rather than a style choice.
// Describe() reads the prefab's components, and reading them may be what forces a
// soft-referenced asset to finish loading - which would mean the diagnostic was quietly
// fixing the crash it was added to measure. Both descriptions now run AFTER the shards
// are spawned, so nothing touches either prefab before the Instantiate that was dying.
// If the crash comes back, the touch was the fix and becomes a real one. If it does not,
// the crash was never about loading.
string projName = rules.ImprovedColdSpell ? "hatchling_cold_projectile" : null;
GameObject projPrefab = null;
if (projName != null)
{
projPrefab = PrefabManager.Cache.GetPrefab<GameObject>(projName);
}
if (projPrefab == null)
{
projPrefab = staffDrop.m_itemData.m_shared.m_attack.m_attackProjectile; // Default Staff of Frost projectile
}
if (projPrefab == null)
{
ColdSpellStep("no projectile prefab at all - no shards fired");
yield break;
}
ColdSpellStep("projectile chosen from " +
(projName != null ? $"'{projName}' or the staff" : "the staff"));
int count = rules.ImprovedColdSpell ? IMPROVED_SPELL_SHARDS : 1;
// The staff prefab is borrowed for its projectile visuals and velocity only. Its damage
// is Mistlands-tier, which the spell used to hand out in full from Eikthyr onward, and
// once per shard - so the improved cast was a ten times nuke rather than a wider one.
// Scale with progression instead, and split one budget across the shards.
int state = BossProgressionManager.GetCurrentProgressionState();
float castDamage = SPELL_BASE_DAMAGE + SPELL_DAMAGE_PER_STATE * state;
if (count > 1) castDamage *= IMPROVED_SPELL_DAMAGE_BUDGET;
float shardDamage = castDamage / count;
for (int i = 0; i < count; i++)
{
if (Player.m_localPlayer == null || Player.m_localPlayer.IsDead()) break;
// Spawn from chest height, forward
Vector3 lookDir = Player.m_localPlayer.GetLookDir();
// Add a small spread for the improved blast
if (rules.ImprovedColdSpell && i > 0)
{
lookDir = Quaternion.Euler(UnityEngine.Random.Range(-5f, 5f), UnityEngine.Random.Range(-5f, 5f), 0f) * lookDir;
}
Vector3 spawnPos = Player.m_localPlayer.transform.position + Vector3.up * 1.4f + lookDir * 0.6f;
ColdSpellStep($"instantiating shard {i + 1} of {count}");
GameObject projInstance = Instantiate(projPrefab, spawnPos, Quaternion.LookRotation(lookDir));
ColdSpellStep("shard instantiated");
// Described only now that a shard has survived being spawned, so the reading itself
// cannot be what made the spawning safe. See the note above the staff lookup.
if (i == 0)
{
ColdSpellStep($"staff was '{Describe(staffPrefab)}");
ColdSpellStep($"projectile was '{Describe(projPrefab)}");
}
Projectile proj = projInstance.GetComponent<Projectile>();
if (proj != null)
{
HitData hitData = new HitData();
hitData.m_damage.m_frost = shardDamage;
hitData.SetAttacker(Player.m_localPlayer);
// Before Setup, which is what copies the skill and its amount onto the
// projectile. Same split as the damage budget above, and for the same reason.
SkadiMagicSkill.TagCast(hitData, count);
proj.Setup(Player.m_localPlayer, lookDir * staffDrop.m_itemData.m_shared.m_attack.m_projectileVel, -1f, hitData, staffDrop.m_itemData, null);
}
if (count > 1) yield return new WaitForSeconds(0.05f);
}
}
private void EnsureFrostAuraVFX(bool enable)
{
if (Player.m_localPlayer == null) return;
if (enable)
{
if (frostAuraVFX == null)
{
frostAuraVFX = new GameObject("SkadiFrostAuraVFX");
frostAuraVFX.transform.SetParent(Player.m_localPlayer.transform, false);
frostAuraVFX.transform.localPosition = new Vector3(0, 1f, 0); // Center of player
ParticleSystem ps = frostAuraVFX.AddComponent<ParticleSystem>();
var main = ps.main;
main.duration = 5f;
main.loop = true;
main.startLifetime = 3f;
main.startSpeed = 0.2f; // Slow moving
main.startSize = new ParticleSystem.MinMaxCurve(0.005f, 0.01f); // 1cm max
main.startColor = new Color(0.7f, 0.9f, 1f, 0.4f); // Light blue, semi-transparent
main.maxParticles = 300;
main.simulationSpace = ParticleSystemSimulationSpace.World; // Leaves a trail when walking
var emission = ps.emission;
emission.rateOverTime = 90; // Dense mist
var shape = ps.shape;
shape.shapeType = ParticleSystemShapeType.Sphere;
shape.radius = 3f; // 3 meters radius
var colorOverLifetime = ps.colorOverLifetime;
colorOverLifetime.enabled = true;
Gradient grad = new Gradient();
grad.SetKeys(
new GradientColorKey[] { new GradientColorKey(Color.white, 0.0f), new GradientColorKey(Color.white, 1.0f) },
new GradientAlphaKey[] { new GradientAlphaKey(0.0f, 0.0f), new GradientAlphaKey(1.0f, 0.2f), new GradientAlphaKey(1.0f, 0.8f), new GradientAlphaKey(0.0f, 1.0f) }
);
colorOverLifetime.color = grad;
var renderer = frostAuraVFX.GetComponent<ParticleSystemRenderer>();
// Steal material from an existing Valheim effect
GameObject freezingVfx = Jotunn.Managers.PrefabManager.Cache.GetPrefab<GameObject>("vfx_Freezing");
if (freezingVfx != null)
{
ParticleSystemRenderer origRenderer = freezingVfx.GetComponentInChildren<ParticleSystemRenderer>();
if (origRenderer != null)
{
renderer.material = origRenderer.material;
}
}
}
if (!frostAuraVFX.activeSelf)
{
frostAuraVFX.SetActive(true);
}
}
else
{
if (frostAuraVFX != null && frostAuraVFX.activeSelf)
{
frostAuraVFX.SetActive(false);
}
}
}
private void ApplyColdAura()
{
if (Player.m_localPlayer == null) return;
Vector3 center = Player.m_localPlayer.transform.position;
// Once per tick, not once per enemy - see SkadiMagicSkill.RaiseForAuraTick.
bool burnedSomething = false;
foreach (Character c in Character.GetAllCharacters())
{
if (c == Player.m_localPlayer) continue;
if (c.IsTamed() || c.IsPlayer()) continue;
// Same guard as the Skeleton's fire aura and the Aswid's drain: an always-on aura
// that burns the race's own kin would, with RaceGrudge in place, keep every wolf,
// drake and dverger permanently angry at a Skadi who never attacked anything.
if (!BaseAI.IsEnemy(Player.m_localPlayer, c)) continue;
if (Vector3.Distance(center, c.transform.position) <= SkadiConfig.AuraRadius.Value)
{
HitData hit = new HitData();
hit.m_damage.m_frost = SkadiConfig.AuraDamagePerTick.Value;
hit.m_point = c.transform.position;
hit.m_dir = (c.transform.position - center).normalized;
hit.SetAttacker(Player.m_localPlayer);
c.ApplyDamage(hit, true, false);
burnedSomething = true;
}
}
if (burnedSomething) SkadiMagicSkill.RaiseForAuraTick();
}
private void TryTransformWithRules(SkadiProgression.FormRules rules)
{
if (rules == null || rules.Form == SkadiProgression.FormType.None) return;
if (isTransformed)
{
RunFormRoutine(RevertToHumanRoutine());
return;
}
if (rules.CooldownMinutes > 0)
{
var cdSE = Player.m_localPlayer.GetSEMan().GetStatusEffect(CooldownSEName(rules.Form).GetStableHashCode());
if (cdSE != null)
{
float m_time = HarmonyLib.Traverse.Create(cdSE).Field<float>("m_time").Value;
float remaining = cdSE.m_ttl - m_time;
if (remaining < 0) remaining = 0;
int rMin = Mathf.FloorToInt(remaining / 60f);
int rSec = Mathf.FloorToInt(remaining % 60f);
Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_skadi_dragon_form_cooldown", rMin, (rSec).ToString("00")));
return;
}
}
activeRules = rules;
RunFormRoutine(TransformRoutine(rules));
}
private Vector3 GetFormScale(SkadiProgression.FormType form)
{
if (form == SkadiProgression.FormType.Moder) return Vector3.one * SkadiConfig.ModerScale.Value;
if (form == SkadiProgression.FormType.SkeletonDragon) return Vector3.one * SkadiConfig.FaderScale.Value;
return Vector3.one * SkadiConfig.DrakeScale.Value; // Drake
}
// Same lookup, keyed by the prefab name the ZDO actually carries ("RacesOfValheim_SkadiForm"),
// so Skadi_MultiplayerVisuals_Patch can size a remote observer's copy of the form the same way
// the transforming player's own client does. Without this the remote instance was left at the
// prefab's raw Visual scale (1x) no matter which form or config value was in play - Moder's
// ModerScale nerf, in particular, only ever applied on the transformed player's own screen.
public static Vector3 GetFormScaleForPrefab(string prefabName)
{
if (prefabName == "Dragon") return Vector3.one * SkadiConfig.ModerScale.Value;
if (prefabName == "Fader") return Vector3.one * SkadiConfig.FaderScale.Value;
return Vector3.one * SkadiConfig.DrakeScale.Value; // Hatchling
}
private IEnumerator TransformRoutine(SkadiProgression.FormRules rules)
{
isTransformingSequence = true;
ZSyncAnimation zAnim = Player.m_localPlayer.GetComponent<ZSyncAnimation>();
if (zAnim != null)
{
RaceInput.SuppressGuardianPowerBriefly();
zAnim.SetTrigger("gpower");
}
yield return new WaitForSeconds(1.1f);
SpawnPoofEffect();
ExecuteTransformation(rules);
if (currentTransformation != null)
{
float elapsed = 0f;
float duration = 0.5f;
Vector3 endScale = GetFormScale(rules.Form);
Vector3 startScale = endScale * 0.5f;
currentTransformation.transform.localScale = startScale;
while (elapsed < duration)
{
if (currentTransformation == null) break;
currentTransformation.transform.localScale = Vector3.Lerp(startScale, endScale, elapsed / duration);
elapsed += Time.deltaTime;
yield return null;
}
if (currentTransformation != null) currentTransformation.transform.localScale = endScale;
}
isTransformingSequence = false;
}
private System.Collections.IEnumerator RevertToHumanRoutine()
{
isTransformingSequence = true;
if (Player.m_localPlayer.GetComponent<ZNetView>() != null) {
Player.m_localPlayer.GetComponent<ZNetView>().GetZDO().Set("Skadi_Form", "");
}
if (currentTransformation != null)
{
DrakeFormBehavior drakeBehavior = currentTransformation.GetComponent<DrakeFormBehavior>();
if (drakeBehavior != null) drakeBehavior.enabled = false;
float elapsed = 0f;
float duration = 0.5f;
Vector3 startScale = currentTransformation.transform.localScale;
float endMultiplier = 0.5f;
Vector3 endScale = startScale * endMultiplier;
while (elapsed < duration)
{
if (currentTransformation == null) break;
currentTransformation.transform.localScale = Vector3.Lerp(startScale, endScale, elapsed / duration);
elapsed += Time.deltaTime;
yield return null;
}
}
SpawnPoofEffect();
yield return new WaitForSeconds(0.1f);
ExecuteReversion();
isTransformingSequence = false;
}
private void SpawnPoofEffect()
{
if (Player.m_localPlayer == null) return;
Vector3 pos = Player.m_localPlayer.transform.position + Vector3.up;
// _medium, not a bare "vfx_corpse_destruction": that name is not in the game, so this
// resolved to nothing and the swap into a drake happened in plain view. See
// FenrirRace.SpawnPoofEffect for the same fix.
GameObject smoke = PrefabManager.Cache.GetPrefab<GameObject>("vfx_corpse_destruction_medium");
if (smoke != null) Instantiate(smoke, pos, Quaternion.identity);
GameObject sparks = PrefabManager.Cache.GetPrefab<GameObject>("vfx_HitSparks");
if (sparks != null) Instantiate(sparks, pos, Quaternion.identity);
}
private void ExecuteTransformation(SkadiProgression.FormRules rules)
{
Transform playerVisual = Player.m_localPlayer.transform.Find("Visual");
string prefabName = "";
switch (rules.Form)
{
case SkadiProgression.FormType.Drake: prefabName = "Hatchling"; break;
case SkadiProgression.FormType.Moder: prefabName = "Dragon"; break;
case SkadiProgression.FormType.SkeletonDragon: prefabName = "Fader"; break;
}
if (Player.m_localPlayer.GetComponent<ZNetView>() != null) {
Player.m_localPlayer.GetComponent<ZNetView>().GetZDO().Set("Skadi_Form", prefabName);
}
GameObject prefab = PrefabManager.Cache.GetPrefab<GameObject>(prefabName);
// Sync to ZDO
ZNetView nview = Player.m_localPlayer.GetComponent<ZNetView>();
if (nview != null && nview.IsValid())
{
nview.GetZDO().Set("RacesOfValheim_SkadiForm", prefabName);
}
if (prefab != null && playerVisual != null)
{
PlayerVisualHider.Hide(playerVisual, "skadi-local-form");
Transform visual = prefab.transform.Find("Visual");
if (visual != null)
{
currentTransformation = Instantiate(visual.gameObject, Player.m_localPlayer.transform);
if (prefabName == "Hatchling")
{
currentTransformation.transform.localPosition = new Vector3(0f, -1.0f, 0f);
}
else if (prefabName == "Fader")
{
// Turn Fader into a Frost Skeleton Dragon
foreach (Renderer r in currentTransformation.GetComponentsInChildren<Renderer>())
{
if (r.material != null)
{
r.material.SetColor("_Color", new Color(0.6f, 0.8f, 1f, 1f));
if (r.material.HasProperty("_EmissionColor"))
{
r.material.SetColor("_EmissionColor", new Color(0f, 0.5f, 1f, 1f));
}
}
}
}
else
{
currentTransformation.transform.localPosition = Vector3.zero;
}
currentTransformation.transform.localRotation = Quaternion.identity;
// Keep AnimEvent so native sounds (footsteps, attack shouts) play correctly!
DrakeFormBehavior behavior = currentTransformation.AddComponent<DrakeFormBehavior>();
behavior.Initialize(rules);
if (prefabName == "Hatchling") Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_skadi_are_drake"));
else if (prefabName == "Dragon") Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_skadi_are_moder"));
else if (prefabName == "Fader") Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_skadi_are_fader"));
isTransformed = true;
StartFormTimer(rules);
}
}
}
// Drives both the expiry check in Update and the HUD icon: the status effect exists purely
// so Valheim draws Moder's trophy with its own countdown next to the minimap.
private void StartFormTimer(SkadiProgression.FormRules rules)
{
int hash = "SE_SkadiForm".GetStableHashCode();
SEMan seman = Player.m_localPlayer.GetSEMan();
seman.RemoveStatusEffect(hash, true);
if (rules.DurationMinutes <= 0f)
{
formExpireTime = 0f;
return;
}
float seconds = rules.DurationMinutes * 60f;
formExpireTime = Time.time + seconds;
seman.AddStatusEffect(hash, true);
StatusEffect se = seman.GetStatusEffect(hash);
if (se != null) se.m_ttl = seconds;
}
// The one transform or revert routine in flight, if any, so ResetRace can stop it.
private Coroutine formRoutine;
private void RunFormRoutine(System.Collections.IEnumerator routine)
{
formRoutine = StartCoroutine(routine);
}
/// <summary>
/// Drops the drake form on the spot for ResetRace. Update bails out on its first line for
/// anyone who is not a Skadi, so once the race changes nothing in this class ever looks at
/// the form again - a Skadi reset in drake form stayed a drake for good. No message and no
/// cooldown here, unlike ExecuteReversion.
/// </summary>
/// <returns>True if there was a form to drop.</returns>
public bool HardResetForReset()
{
Player player = Player.m_localPlayer;
if (player == null) return false;
if (formRoutine != null)
{
StopCoroutine(formRoutine);
formRoutine = null;
}
bool hadForm = isTransformed || isTransformingSequence || currentTransformation != null;
if (hadForm)
{
if (currentTransformation != null) Destroy(currentTransformation);
currentTransformation = null;
foreach (var f in player.GetComponentsInChildren<DrakeFormBehavior>(true)) Destroy(f.gameObject);
ZNetView nview = player.GetComponent<ZNetView>();
if (nview != null && nview.IsValid())
{
nview.GetZDO().Set("Skadi_Form", "");
nview.GetZDO().Set("RacesOfValheim_SkadiForm", "");
}
PlayerVisualHider.Show(player.transform.Find("Visual"), "skadi-reset");
player.GetSEMan().RemoveStatusEffect("SE_SkadiForm".GetStableHashCode(), true);
}
isTransformed = false;
isTransformingSequence = false;
formExpireTime = 0f;
activeRules = null;
return hadForm;
}
private void ExecuteReversion()
{
Transform playerVisual = Player.m_localPlayer.transform.Find("Visual");
if (currentTransformation != null) Destroy(currentTransformation);
// Sync to ZDO
ZNetView nview = Player.m_localPlayer.GetComponent<ZNetView>();
if (nview != null && nview.IsValid())
{
nview.GetZDO().Set("RacesOfValheim_SkadiForm", "");
}
var forms1 = Player.m_localPlayer.GetComponentsInChildren<DrakeFormBehavior>(true);
foreach (var f in forms1) Destroy(f.gameObject);
PlayerVisualHider.Show(playerVisual, "skadi-local-revert");
isTransformed = false;
formExpireTime = 0f;
Player.m_localPlayer.GetSEMan().RemoveStatusEffect("SE_SkadiForm".GetStableHashCode(), true);
Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_skadi_returned_human_form"));
if (activeRules != null && activeRules.CooldownMinutes > 0)
{
int cdHash = CooldownSEName(activeRules.Form).GetStableHashCode();
Player.m_localPlayer.GetSEMan().AddStatusEffect(cdHash, true);
var cdSE = Player.m_localPlayer.GetSEMan().GetStatusEffect(cdHash);
if (cdSE != null) cdSE.m_ttl = activeRules.CooldownMinutes * 60f;
}
activeRules = null;
}
}
}