RacesOfValheim/JotunnModStub/Trenta/TrentaAbilities.cs
kanym d9bca1934f fix(skills): hand-built attacks level the skill they scale with
Form attacks and powers called Damage directly, and vanilla only raises
a skill inside Attack and Projectile.OnHit, so the skill never moved.
FormMelee.RaiseSkill pays once per swing or tick that hit a creature.

- Fenrir forms' claws and bites: Unarmed; Cultist fire: Elemental Magic
- Skadi drake melee and Trenta stomp: Unarmed
- Aswid aura: Blood Magic, 0.1 per second like the Frost Aura
- Alfar Geisli and Ljosstorm: Elemental Magic; Sameining pulse 0.1/s
- Trenta Purple Rain scales with Blood Magic (two new bonus keys) and
  levels it once per cast that reaches someone besides the caster
2026-11-06 21:21:11 +01:00

357 lines
18 KiB
C#

using System.Collections;
using System.Collections.Generic;
using HarmonyLib;
using Jotunn.Managers;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The Trenta's active abilities, driven from TrentaRace.Update. Each one reads its cost,
/// radius, duration and cooldown out of TrentaConfig.
/// </summary>
public static class TrentaAbilities
{
public static void Tick(Player player, int state)
{
// Photosynthesis is a passive trigger, not a keypress, so it runs unconditionally -
// unlike the keybound abilities below it is not gated on RaceInput.Allowed. Standing
// still with an inventory screen open is still standing still.
TickPhotosynthesis(player, state);
// Ability input is gated exactly like every other race's: RaceInput mirrors
// Player.TakeInput, so nothing fires while a map, chest or chat window has focus.
if (!RaceInput.Allowed) return;
if (state >= TrentaConfig.PurpleRainUnlockState && TrentaConfigManagement.PurpleRainKey.Value.IsDownIgnoringHeldKeys())
{
TryPurpleRain(player);
}
if (state >= TrentaConfig.PortalUnlockState && TrentaConfigManagement.PortalKey.Value.IsDownIgnoringHeldKeys())
{
TryOpenPortal(player);
}
if (state >= TrentaConfig.MuspellUnlockState && TrentaConfigManagement.MuspellKey.Value.IsDownIgnoringHeldKeys())
{
TrentaMuspell.Toggle(player);
}
// TODO: any further keybound perks, one `if (... && Input.GetKeyDown(...))` each.
}
// ─── Hornet's Nest ──────────────────────────────────────────────────
private static GameObject hornetSwarm;
/// <summary>
/// Called unconditionally from TrentaRace.Update, not from Tick above - a permanent
/// companion has to be torn down the moment it should stop existing (race change, tier
/// drop, death), and Tick only ever runs while the local player still qualifies as a
/// Queen-tier Trenta, which is exactly the case this needs to catch.
/// </summary>
public static void TickHornetsNest(Player player, bool shouldExist)
{
if (shouldExist && hornetSwarm == null)
{
hornetSwarm = TrentaHornetSwarm.Spawn(player);
}
else if (!shouldExist && hornetSwarm != null)
{
Object.Destroy(hornetSwarm);
hornetSwarm = null;
}
}
// ─── Photosynthesis ──────────────────────────────────────────────────
// Seconds of unbroken stillness accumulated so far, and the state of the heal-over-time
// window once a grant has fired. Static because only ever ticked for the local player.
private static float stillTimer = 0f;
private static bool healPhaseActive = false;
private static float healPhaseTimer = 0f;
private static int healTicksApplied = 0;
/// <summary>
/// Daylight, out from under a roof, ten unbroken seconds of standing still: the Trenta
/// gets a Rested buff (Player.SetSleeping's own duration-less grant, given a duration here
/// instead - see the long comment on Trenta_Player_EatFood_Patch-adjacent code style,
/// mirrors DvergarStatusEffects.ApplyCooldownIcon exactly) plus 10% of max health healed
/// once a second for 8 seconds.
///
/// Movement cancels whichever phase is running, on the spot, with no partial credit -
/// including movement from being knocked back by an attack, since this only ever looks at
/// whether the character actually moved, never at why. A hit that does not move the Trenta
/// does not touch either phase.
/// </summary>
private static void TickPhotosynthesis(Player player, int state)
{
bool moving = player.GetVelocity().magnitude > TrentaConfig.PhotosynthesisVelocityEpsilon;
if (healPhaseActive)
{
if (moving)
{
healPhaseActive = false;
healPhaseTimer = 0f;
healTicksApplied = 0;
return;
}
healPhaseTimer += Time.deltaTime;
int targetTicks = Mathf.Min(Mathf.FloorToInt(healPhaseTimer), TrentaConfig.PhotosynthesisHealSeconds);
while (healTicksApplied < targetTicks)
{
player.Heal(player.GetMaxHealth() * TrentaConfig.PhotosynthesisHealPercentPerSecond, true);
healTicksApplied++;
}
if (healTicksApplied >= TrentaConfig.PhotosynthesisHealSeconds)
{
healPhaseActive = false;
healPhaseTimer = 0f;
healTicksApplied = 0;
}
return; // A new stillness channel cannot start while a grant is still healing
}
bool eligible = EnvMan.instance != null && EnvMan.IsDay() &&
!Traverse.Create(player).Field<bool>("m_underRoof").Value;
if (!eligible || moving)
{
stillTimer = 0f;
return;
}
stillTimer += Time.deltaTime;
if (stillTimer < TrentaConfig.PhotosynthesisStillnessSeconds) return;
stillTimer = 0f;
float restMinutes = TrentaConfig.PhotosynthesisRestBaseMinutes +
TrentaConfig.PhotosynthesisRestMinutesPerBoss * (state - BossProgressionManager.MinState);
SEMan seman = player.GetSEMan();
seman.AddStatusEffect(SEMan.s_statusEffectRested, true);
StatusEffect rested = seman.GetStatusEffect(SEMan.s_statusEffectRested);
if (rested != null) rested.m_ttl = restMinutes * 60f;
healPhaseActive = true;
healPhaseTimer = 0f;
healTicksApplied = 0;
}
// ─── Purple Rain ─────────────────────────────────────────────────────
private static float lastPurpleRainTime = -1000f;
private static Material cachedVfxMaterial;
private static bool vfxMaterialResolved;
/// <summary>
/// A burst of toxic-purple pollen centred on the Trenta: heals everything that isn't its
/// enemy, poisons everything that is. "Ally" and "enemy" are read straight off
/// BaseAI.IsEnemy - the same check RaceHostilityManager's Trenta block feeds - so this
/// automatically covers players, tamed companions and the neutral Greyling/Greydwarf/
/// Fuling/Troll/Leech/Deathsquito list without a second, separate species list to keep in
/// sync with the first one.
/// </summary>
private static void TryPurpleRain(Player player)
{
// Muspell (state 8) shortens Purple Rain's own cooldown while transformed - read here
// rather than baked into PurpleRainCooldown, since the normal-form value still applies
// the instant the player reverts.
float cooldown = TrentaMuspell.IsTransformed ? TrentaConfig.MuspellPurpleRainCooldown : TrentaConfig.PurpleRainCooldown;
if (Time.time - lastPurpleRainTime < cooldown) return;
lastPurpleRainTime = Time.time;
TrentaStatusEffects.ApplyCooldownIcon(TrentaConfig.PurpleRainCdSE, cooldown);
// While transformed, The Elder's own root-summon gesture plays on the transformation
// clone's Animator instead - TryPlayRootSummonAnimation returns false (and does
// nothing) when not transformed, so the normal staff_summon path below still covers
// every other case unchanged.
if (!TrentaMuspell.TryPlayRootSummonAnimation())
{
var zanim = Traverse.Create(player).Field("m_zanim").GetValue<ZSyncAnimation>();
if (zanim != null)
{
// "galdr_cast" was never real, and "gpower" turned out to read as the vanilla
// Guardian Power raise (Forsaken Power), not a staff cast - both dead ends, now
// documented so nobody re-walks them. "staff_summon" is the Dead Raiser's own
// attack animation, the actual "raise the staff and call something forth" clip -
// confirmed against WeaponsAttackAnimationManager's own dump of vanilla weapon
// attack animations, since it is weapon data rather than anything hard-coded in
// the assembly's IL the way "gpower" is. Unlike gpower it is not expected to carry
// a baked side effect (per-weapon attack clips resolve their game logic through
// Humanoid.StartAttack, not through Animation Events on the clip), so no suppress
// call before it - flag it if this instead spawns a real skeleton ally.
zanim.SetTrigger("staff_summon");
}
}
SpawnPurpleRainVfx(player);
// The Trenta stands in its own rain and is healed by it too. It used to be left out, so
// a lone Trenta cast a heal that never touched anyone.
float heal = TrentaConfig.PurpleRainHealFor(player);
float poison = TrentaConfig.PurpleRainPoisonFor(player);
player.Heal(heal, true);
// Blood Magic experience once per cast that reached someone besides the caster, the
// way a vanilla staff pays per cast: healing only yourself earns nothing, or the
// skill would level by casting into an empty field on cooldown.
bool reachedSomeone = false;
HashSet<Character> hit = new HashSet<Character>();
foreach (Collider collider in Physics.OverlapSphere(player.transform.position, TrentaConfig.PurpleRainRadius))
{
if (collider == null) continue;
Character character = collider.GetComponentInParent<Character>();
if (character == null || character == player || character.IsDead() || !hit.Add(character)) continue;
if (BaseAI.IsEnemy(player, character))
{
HitData hitData = new HitData();
hitData.m_damage.m_poison = poison;
hitData.m_skill = Skills.SkillType.BloodMagic;
hitData.SetAttacker(player);
hitData.m_dir = Vector3.zero;
character.Damage(hitData);
}
else
{
character.Heal(heal, true);
}
reachedSomeone = true;
}
if (reachedSomeone) FormMelee.RaiseSkill(Skills.SkillType.BloodMagic);
}
/// <summary>
/// Builds the rain burst from scratch - mirrors SkeletonRace.EnsureFireAuraVFX, which
/// borrows only a *material* off an existing prefab and drives everything else (shape,
/// emission, gradient) itself, rather than cloning a specific child particle system
/// wholesale. The clone-a-child approach tried first came up empty: whatever the Shaman's
/// actual spit VFX is, it is not a particle system living permanently on its model (most
/// likely a separate projectile prefab spawned by its attack code instead), so there was
/// nothing there to find. Borrowing just the material sidesteps needing to know that at
/// all - it fails safe to Unity's default particle material if even that comes up empty,
/// so this always renders *something*.
/// </summary>
private static void SpawnPurpleRainVfx(Player player)
{
if (!vfxMaterialResolved)
{
vfxMaterialResolved = true;
// The "vfx_smoke" fallback that used to sit here is gone. That name is not a prefab
// in this game, so it could only ever resolve to another mod's object - and with
// Magic_Supremacy installed it resolved to a weapon trail, which is what put purple
// smoke on the Skeleton (see SkeletonVisuals.EnsureFireAura). Purple Rain is purple
// by design, so the same theft here would never have looked wrong enough to report.
//
// Losing the fallback means a miss is now a miss. Said out loud, because the resolve
// is cached for the session either way and a silent one would be invisible: 1.0
// loads creature assets lazily, so the Shaman is not guaranteed to be in memory.
GameObject source = PrefabManager.Cache.GetPrefab<GameObject>(TrentaConfig.PurpleRainVfxSourcePrefab);
if (source != null)
{
ParticleSystemRenderer sourceRenderer = source.GetComponentInChildren<ParticleSystemRenderer>(true);
if (sourceRenderer != null) cachedVfxMaterial = sourceRenderer.material;
}
else
{
Jotunn.Logger.LogWarning(
$"[Trenta] Purple Rain: '{TrentaConfig.PurpleRainVfxSourcePrefab}' not in the prefab " +
"cache; falling back to Unity's default particle material for this session.");
}
}
GameObject vfx = new GameObject("TrentaPurpleRainVFX");
vfx.transform.SetParent(player.transform, false);
vfx.transform.localPosition = new Vector3(0, 3f, 0);
ParticleSystem ps = vfx.AddComponent<ParticleSystem>();
var main = ps.main;
main.loop = false;
main.duration = 1.2f;
main.startLifetime = new ParticleSystem.MinMaxCurve(1.5f, 2.5f);
main.startSpeed = new ParticleSystem.MinMaxCurve(0.5f, 1.5f);
main.startSize = new ParticleSystem.MinMaxCurve(0.03f, 0.09f); // cherry-sized, not watermelon-sized
main.gravityModifier = 1.2f; // falls like rain rather than hanging in the air
main.simulationSpace = ParticleSystemSimulationSpace.World;
main.maxParticles = 400;
var emission = ps.emission;
emission.rateOverTime = 250f;
var shape = ps.shape;
shape.shapeType = ParticleSystemShapeType.Sphere;
shape.radius = TrentaConfig.PurpleRainRadius * 0.6f;
ParticleSystemRenderer renderer = ps.GetComponent<ParticleSystemRenderer>();
if (cachedVfxMaterial != null) renderer.material = cachedVfxMaterial;
var colorOverLifetime = ps.colorOverLifetime;
colorOverLifetime.enabled = true;
Gradient grad = new Gradient();
grad.SetKeys(
new GradientColorKey[] { new GradientColorKey(TrentaConfig.PurpleRainVfxColor, 0f), new GradientColorKey(TrentaConfig.PurpleRainVfxColor, 1f) },
new GradientAlphaKey[] { new GradientAlphaKey(0f, 0f), new GradientAlphaKey(0.85f, 0.2f), new GradientAlphaKey(0.85f, 0.7f), new GradientAlphaKey(0f, 1f) }
);
colorOverLifetime.color = grad;
ps.Play();
if (TrentaRace.Instance != null)
{
TrentaRace.Instance.StartCoroutine(DestroyAfter(vfx, 4f));
}
else
{
Object.Destroy(vfx, 4f);
}
}
private static IEnumerator DestroyAfter(GameObject obj, float seconds)
{
yield return new WaitForSeconds(seconds);
if (obj != null) Object.Destroy(obj);
}
// ─── Homecoming Portal ──────────────────────────────────────────────
private static float lastPortalTime = -100000f;
/// <summary>
/// Opens a linked portal pair (TrentaPortal.Open does the actual spawning): one where the
/// Trenta is standing, one at their respawn point - a custom spawn point if they have set
/// one by sleeping in a bed, otherwise the world's starting temple, exactly mirroring the
/// choice vanilla respawn itself makes.
/// </summary>
private static void TryOpenPortal(Player player)
{
if (Time.time - lastPortalTime < TrentaConfig.PortalCooldown) return;
PlayerProfile profile = Game.instance != null ? Game.instance.GetPlayerProfile() : null;
if (profile == null) return;
// m_originalSpawnPoint is static on PlayerProfile - one starting temple per world,
// not per profile - unlike everything else read off profile here.
Vector3 homePoint = profile.HaveCustomSpawnPoint() ? profile.GetCustomSpawnPoint() : PlayerProfile.m_originalSpawnPoint;
lastPortalTime = Time.time;
TrentaStatusEffects.ApplyCooldownIcon(TrentaConfig.PortalCdSE, TrentaConfig.PortalCooldown);
var zanim = Traverse.Create(player).Field("m_zanim").GetValue<ZSyncAnimation>();
if (zanim != null) zanim.SetTrigger("staff_summon"); // same cast as Purple Rain - see its comment for why
Vector3 castPoint = player.transform.position + player.transform.forward * TrentaConfig.PortalSpawnDistance;
TrentaPortal.Open(player, castPoint, homePoint);
}
}
}