RacesOfValheim/JotunnModStub/Trenta/TrentaAbilities.cs
kanym 14648aaf62 feat(trenta): make ability numbers and keybinds BepInEx-configurable
Adds TrentaConfigManagement.cs rather than reusing the TrentaConfig name,
same reasoning as DvergarConfigManagement: that existing class holds
identity constants that must never change (RaceId, status effect and
prefab names), hand-tuned cosmetic placement numbers (skin colour, crown
position), and design-time tables (HealthBonusByState, the per-biome
AwakenedSeedFoods list) left alone under the same boundary drawn for
every other race's progression table.

Only the genuine ability knobs move: Photosynthesis, Purple Rain, Last
Stand/Thorns, Homecoming Portal, Hornet's Nest, Muspell, and the vegan
food duration bonus each get a Configuration Manager section, plus the
three transform/ability keybinds (Purple Rain, Portal, Muspell).
TrentaConfig's fields for those now forward to TrentaConfigManagement
(same const-to-property trick used for Skadi and Dvergar), so every
existing call site kept working unchanged except the three keybind
consumers in TrentaAbilities, which now read the live configured key.

Fixes a BepInEx startup crash caught while testing: the Hornet's Nest
section name used a straight ASCII apostrophe, which
ConfigDefinition.CheckInvalidConfigChars rejects outright (section/key
names may not contain = \n \t \ " ' [ ]). Switched to the typographic
apostrophe (U+2019), which reads the same and isn't on the forbidden list.

Config sections stay bound alphabetically by race (Aswid, Draugh,
Dvergar, Fenrir, Furling, Skadi, Skeleton, Trenta) in
RacesOfValheim.Awake().
2026-08-06 15:20:10 +02:00

328 lines
16 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.IsDown())
{
TryPurpleRain(player);
}
if (state >= TrentaConfig.PortalUnlockState && TrentaConfigManagement.PortalKey.Value.IsDown())
{
TryOpenPortal(player);
}
if (state >= TrentaConfig.MuspellUnlockState && TrentaConfigManagement.MuspellKey.Value.IsDown())
{
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);
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 = TrentaConfig.PurpleRainPoisonDamage;
hitData.SetAttacker(player);
hitData.m_dir = Vector3.zero;
character.Damage(hitData);
}
else
{
character.Heal(TrentaConfig.PurpleRainHealAmount, true);
}
}
}
/// <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;
GameObject source = PrefabManager.Cache.GetPrefab<GameObject>(TrentaConfig.PurpleRainVfxSourcePrefab)
?? PrefabManager.Cache.GetPrefab<GameObject>("vfx_smoke");
if (source != null)
{
ParticleSystemRenderer sourceRenderer = source.GetComponentInChildren<ParticleSystemRenderer>(true);
if (sourceRenderer != null) cachedVfxMaterial = sourceRenderer.material;
}
}
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);
}
}
}