RacesOfValheim/JotunnModStub/Trenta/TrentaMuspell.cs
kanym 7d88bc78d0 fix(trenta): the camera rises to the Muspell's head
The form hides the player's body by shrinking its Visual to 0.001, and
RaceEyeHeight reads anything that small as hidden and leaves the eye
where it was, at a person's height. The Muspell now measures its head
height when the clone is made and hands RaceEyeHeight that height times
the form's current scale, so the camera follows the grow and shrink.
2026-09-30 12:55:15 +02:00

422 lines
18 KiB
C#

using System.Collections;
using System.Collections.Generic;
using HarmonyLib;
using Jotunn.Managers;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// Muspell (Fader): toggle with J into a half-size The Elder and back. Structured as closely
/// as possible on FenrirRace.cs's own transform/revert routines - poof, clone the target's
/// "Visual" child onto the player, shrink the player's own Visual to nothing, drive the clone
/// with its own per-form Animator-reading MonoBehaviour (MuspellFormBehavior, the same shape
/// as FenrirFormBehavior). The permanent-Burning/ignite-attacker fire mechanic was tried and
/// dropped - the flame VFX glitched with no reliable fix in reach, and the player asked for it
/// (and the fire damage that rode along with it) removed rather than chased further.
/// </summary>
public static class TrentaMuspell
{
public static bool IsTransformed { get; private set; }
private static GameObject currentTransformation;
private static bool isTransformingSequence;
/// <summary>
/// How high the form's head sits above the player's feet at a form scale of 1, measured
/// off the clone the moment it is made. Multiplied by the form's current scale it gives the
/// eye height, so the camera rides the grow and shrink tween with the model.
/// </summary>
private static float headHeightAtScaleOne;
/// <summary>
/// The eye height the Muspell wants for <paramref name="player"/>, for RaceEyeHeight.
///
/// The form hides the player's own body by shrinking its Visual to 0.001, and RaceEyeHeight
/// reads anything that small as "hidden" and leaves the eye alone - so the camera stayed at
/// a person's eye level inside something the size of a house. The form is local only, so
/// this only ever answers for the local player.
/// </summary>
public static bool TryGetEyeHeight(Player player, out float height)
{
height = 0f;
if (!IsTransformed || currentTransformation == null || headHeightAtScaleOne <= 0f) return false;
if (player == null || player != Player.m_localPlayer) return false;
height = headHeightAtScaleOne * currentTransformation.transform.localScale.y;
return true;
}
public static void Toggle(Player player)
{
if (isTransformingSequence) return;
if (IsTransformed)
{
TrentaRace.Instance.StartCoroutine(RevertRoutine(player));
}
else
{
TrentaRace.Instance.StartCoroutine(TransformRoutine(player));
}
}
/// <summary>Called from TrentaRace.Update unconditionally, the same way Hornet's Nest is -
/// a race change, a tier drop or death has to end the transformation even though nothing
/// would otherwise be left running to notice.</summary>
public static void ForceRevert(Player player)
{
if (IsTransformed && !isTransformingSequence)
{
TrentaRace.Instance.StartCoroutine(RevertRoutine(player));
}
}
/// <summary>
/// Called by Purple Rain instead of its usual staff_summon trigger whenever Muspell is
/// active - The Elder's own root-summon gesture, played on the transformation clone's
/// Animator rather than the player's. Returns false (and does nothing) if not transformed,
/// so TryPurpleRain's own fallback to staff_summon still covers the normal case.
/// </summary>
public static bool TryPlayRootSummonAnimation()
{
if (!IsTransformed || currentTransformation == null) return false;
Animator formAnim = currentTransformation.GetComponent<Animator>() ?? currentTransformation.GetComponentInChildren<Animator>();
if (formAnim == null) return false;
try { formAnim.SetTrigger(TrentaConfig.MuspellRootSummonTrigger); } catch { }
return true;
}
private static IEnumerator TransformRoutine(Player player)
{
isTransformingSequence = true;
var zanim = Traverse.Create(player).Field("m_zanim").GetValue<ZSyncAnimation>();
if (zanim != null)
{
// The transformation poof itself, not an ability cast - "gpower" (the arms-raised
// Guardian Power clip, borrowed the same way FenrirRace's own TransformIntoWolfRoutine
// borrows it for its transformation) rather than staff_summon, which is reserved for
// Purple Rain.
RaceInput.SuppressGuardianPowerBriefly();
zanim.SetTrigger("gpower");
}
yield return new WaitForSeconds(1.1f);
SpawnPoofEffect(player);
yield return new WaitForSeconds(0.1f);
ExecuteTransformation(player);
// Grows in from small rather than popping straight to 50%, the same tween
// FenrirRace uses for its own non-wolf forms.
float elapsed = 0f;
float duration = 0.5f;
Vector3 startScale = Vector3.one * (TrentaConfig.MuspellScale * 0.2f);
Vector3 endScale = Vector3.one * TrentaConfig.MuspellScale;
if (currentTransformation != null) 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 static IEnumerator RevertRoutine(Player player)
{
isTransformingSequence = true;
if (currentTransformation != null)
{
MuspellFormBehavior behavior = currentTransformation.GetComponent<MuspellFormBehavior>();
if (behavior != null) behavior.enabled = false;
float elapsed = 0f;
float duration = 0.5f;
Vector3 startScale = currentTransformation.transform.localScale;
Vector3 endScale = Vector3.one * (TrentaConfig.MuspellScale * 0.2f);
while (elapsed < duration)
{
if (currentTransformation == null) break;
currentTransformation.transform.localScale = Vector3.Lerp(startScale, endScale, elapsed / duration);
elapsed += Time.deltaTime;
yield return null;
}
}
SpawnPoofEffect(player);
yield return new WaitForSeconds(0.1f);
ExecuteReversion(player);
isTransformingSequence = false;
}
private static void SpawnPoofEffect(Player player)
{
if (player == null) return;
Vector3 pos = player.transform.position + Vector3.up;
// _large rather than the _medium the other two forms use: the Muspell is the biggest
// thing this mod turns a player into, and a body-sized puff does not cover it. A bare
// "vfx_corpse_destruction" is not a prefab in this game, so until now the Muspell was
// the one transformation with no covering effect of any kind - Fenrir and Skadi at least
// had their sparks.
GameObject smoke = PrefabManager.Cache.GetPrefab<GameObject>("vfx_corpse_destruction_large");
if (smoke != null) Object.Instantiate(smoke, pos, Quaternion.identity);
}
private static void ExecuteTransformation(Player player)
{
Transform playerVisual = player.transform.Find("Visual");
GameObject prefab = PrefabManager.Cache.GetPrefab<GameObject>(TrentaConfig.MuspellFormPrefab);
if (prefab == null || playerVisual == null)
{
Jotunn.Logger.LogWarning($"[Trenta] Muspell: could not find form prefab '{TrentaConfig.MuspellFormPrefab}'.");
return;
}
playerVisual.localScale = Vector3.one * 0.001f;
Transform visual = prefab.transform.Find("Visual") ?? prefab.transform;
currentTransformation = Object.Instantiate(visual.gameObject, player.transform);
currentTransformation.transform.localPosition = Vector3.zero;
currentTransformation.transform.localRotation = Quaternion.identity;
// Measured here, straight off the clone, before the grow tween touches its scale. The
// head is the same bone the spike volley fires from.
Transform head = currentTransformation.transform.Find(MuspellFormBehavior.HeadPath);
float cloneScale = currentTransformation.transform.localScale.y;
headHeightAtScaleOne = head != null && cloneScale > 0f
? (head.position.y - player.transform.position.y) / cloneScale
: 0f;
// Same reasoning as FenrirRace.ExecuteTransformation: the clone must never carry
// whatever AI/gameplay component made the source a functioning boss.
Component animEvent = currentTransformation.GetComponent("AnimEvent");
if (animEvent != null) Object.Destroy(animEvent);
foreach (Component ai in currentTransformation.GetComponentsInChildren<BaseAI>(true)) Object.Destroy(ai);
foreach (Component character in currentTransformation.GetComponentsInChildren<Character>(true)) Object.Destroy(character);
foreach (Component znet in currentTransformation.GetComponentsInChildren<ZNetView>(true)) Object.Destroy(znet);
currentTransformation.AddComponent<MuspellFormBehavior>();
ZNetView nview = player.GetComponent<ZNetView>();
if (nview != null && nview.IsValid())
{
nview.GetZDO().Set("RacesOfValheim_MuspellForm", true);
}
IsTransformed = true;
player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_trenta_are_muspell_ash_ember_given"));
}
private static void ExecuteReversion(Player player)
{
Transform playerVisual = player.transform.Find("Visual");
if (currentTransformation != null) Object.Destroy(currentTransformation);
currentTransformation = null;
ZNetView nview = player.GetComponent<ZNetView>();
if (nview != null && nview.IsValid())
{
nview.GetZDO().Set("RacesOfValheim_MuspellForm", false);
}
if (playerVisual != null)
{
playerVisual.localScale = Vector3.one;
playerVisual.gameObject.SetActive(true);
}
IsTransformed = false;
player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_trenta_return_rooted_form"));
}
}
/// <summary>
/// Drives the transformation clone's Animator and its two mouse-button attacks - the same
/// shape as FenrirBehaviors.cs's per-form classes (locomotion sync from the player's own
/// Animator when idle, lock-and-trigger-and-damage coroutines per attack).
/// </summary>
public class MuspellFormBehavior : MonoBehaviour
{
public const string HeadPath = "Armature/root/spine1/spine2/spine3/head";
private Animator playerAnim;
private Animator formAnim;
private Transform muzzle;
private bool isAttacking;
private void Start()
{
playerAnim = Player.m_localPlayer.transform.Find("Visual").GetComponent<Animator>();
formAnim = GetComponent<Animator>();
if (formAnim == null) formAnim = GetComponentInChildren<Animator>();
// The spike volley should leave from the Elder's own mouth, not the (now hidden)
// player's eye point underneath it.
muzzle = transform.Find(HeadPath);
}
private void Update()
{
if (playerAnim == null || formAnim == null || Player.m_localPlayer == null) return;
if (isAttacking) return;
bool isGrounded = playerAnim.GetBool("onGround");
TrySet(() => formAnim.SetBool("onGround", isGrounded));
TrySet(() => formAnim.SetBool("inWater", playerAnim.GetBool("inWater")));
if (!isGrounded || Player.m_localPlayer.IsCrouching())
{
TrySet(() => formAnim.SetFloat("forward_speed", 0f));
TrySet(() => formAnim.SetFloat("sideway_speed", 0f));
}
else
{
TrySet(() => formAnim.SetFloat("forward_speed", playerAnim.GetFloat("forward_speed")));
TrySet(() => formAnim.SetFloat("sideway_speed", playerAnim.GetFloat("sideway_speed")));
}
if (!isGrounded || !RaceInput.Allowed) return;
if (RaceInput.AttackDown(0)) // Stomp
{
StartCoroutine(StompRoutine());
}
else if (RaceInput.AttackDown(1)) // Spike volley
{
StartCoroutine(SpikeRoutine());
}
}
private static void TrySet(System.Action set)
{
try { set(); } catch { }
}
private IEnumerator StompRoutine()
{
isAttacking = true;
TrySet(() => formAnim.SetFloat("forward_speed", 0f));
TrySet(() => formAnim.SetFloat("sideway_speed", 0f));
// gd_king_stomp's own attack has m_attackRandomAnimations=2 - The Elder itself picks
// between "stomp0"/"stomp1" at random each swing, so this mirrors that instead of
// always firing the same one.
string trigger = TrentaConfig.MuspellStompTrigger + Random.Range(0, TrentaConfig.MuspellStompTriggerVariants);
TrySet(() => formAnim.SetTrigger(trigger));
yield return new WaitForSeconds(0.5f);
ExecuteMeleeDamage(TrentaConfig.MuspellStompDamage, TrentaConfig.MuspellStompRadius);
yield return new WaitForSeconds(0.5f);
TrySet(() => formAnim.ResetTrigger(trigger));
isAttacking = false;
}
private IEnumerator SpikeRoutine()
{
isAttacking = true;
TrySet(() => formAnim.SetFloat("forward_speed", 0f));
TrySet(() => formAnim.SetFloat("sideway_speed", 0f));
TrySet(() => formAnim.SetTrigger(TrentaConfig.MuspellSpikeTrigger));
yield return new WaitForSeconds(0.4f);
FireSpikeProjectile();
yield return new WaitForSeconds(0.6f);
TrySet(() => formAnim.ResetTrigger(TrentaConfig.MuspellSpikeTrigger));
isAttacking = false;
}
/// <summary>Close-range, all-around - matches Stomp being an area slam rather than a
/// directional swing.</summary>
private void ExecuteMeleeDamage(float baseDamage, float radius)
{
Player player = Player.m_localPlayer;
if (player == null) return;
Vector3 center = player.transform.position + Vector3.up;
float unarmedSkillLevel = player.GetSkillLevel(Skills.SkillType.Unarmed);
float totalDamage = baseDamage + unarmedSkillLevel;
HashSet<GameObject> hit = new HashSet<GameObject>();
foreach (Collider collider in Physics.OverlapSphere(center, radius))
{
Character target = collider.GetComponentInParent<Character>();
if (target == null || target == player || target.IsDead() || !hit.Add(target.gameObject)) continue;
if (!BaseAI.IsEnemy(player, target)) continue;
DealDamage(player, target, totalDamage, HitData.DamageType.Blunt, Vector3.zero);
}
}
/// <summary>
/// The real ranged attack - "gdking_root_projectile", the same one gd_king_shoot fires -
/// rather than an instant hitscan, so it travels, can be dodged and can miss the same way
/// the boss's own volley does. Spawn/Setup shape copied from TrolRace's own rock throw,
/// the established pattern for a custom projectile in this codebase.
/// </summary>
private void FireSpikeProjectile()
{
Player player = Player.m_localPlayer;
if (player == null) return;
GameObject projPrefab = ZNetScene.instance.GetPrefab(TrentaConfig.MuspellSpikeProjectilePrefab);
if (projPrefab == null)
{
Jotunn.Logger.LogWarning($"[Trenta] Muspell: could not find projectile prefab '{TrentaConfig.MuspellSpikeProjectilePrefab}'.");
return;
}
// Aim still follows the player's own look direction (mouse/camera), only the spawn
// point moves to the Elder clone's mouth so the shot visibly comes from the model
// that's on screen instead of the hidden player underneath it.
Vector3 origin = muzzle != null ? muzzle.position : player.GetEyePoint();
Vector3 spawnPos = origin + player.GetLookDir() * 1.5f;
GameObject projInstance = Object.Instantiate(projPrefab, spawnPos, Quaternion.LookRotation(player.GetLookDir()));
Projectile proj = projInstance.GetComponent<Projectile>();
if (proj == null) return;
float unarmedSkillLevel = player.GetSkillLevel(Skills.SkillType.Unarmed);
HitData hitData = new HitData();
hitData.m_damage.m_pierce = TrentaConfig.MuspellSpikeDamage + unarmedSkillLevel;
hitData.m_skill = Skills.SkillType.Unarmed;
hitData.SetAttacker(player);
proj.Setup(player, player.GetLookDir() * TrentaConfig.MuspellSpikeVelocity, -1f, hitData, null, null);
}
private void DealDamage(Player attacker, Character target, float amount, HitData.DamageType type, Vector3 dir)
{
HitData hitData = new HitData();
if (type == HitData.DamageType.Pierce) hitData.m_damage.m_pierce = amount;
else hitData.m_damage.m_blunt = amount;
hitData.m_point = target.GetCenterPoint();
hitData.m_dir = dir;
hitData.m_skill = Skills.SkillType.Unarmed;
hitData.m_hitType = HitData.HitType.PlayerHit;
hitData.SetAttacker(attacker);
target.Damage(hitData);
}
}
}