RacesOfValheim/JotunnModStub/Trenta/TrentaMuspell.cs
kanym b0d18b0654 feat(text): on-screen messages come from translation files
Every message the mod puts in the middle or corner of the screen now reads
its text through ModText.Get, and messages.json holds 191 texts in English
and Italian. Values computed in code become $1, $2 in the text, so a
translator can put them wherever the sentence needs them. Branching
messages get one key per branch.

A few messages travel through a field before they are shown: thralls'
refusals and the building limits now hold a token or key there. Boss and
form names inside messages use tokens too, the bosses the game's own, so
"The Elder" arrives translated.

ModText.Get now localizes each argument before inserting it. A token
argument left for a later pass ran into the text after it: "$1's power"
became the unknown token "enemy_eikthyr's".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-26 20:30:03 +02:00

387 lines
17 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;
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;
// 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
{
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("Armature/root/spine1/spine2/spine3/head");
}
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);
}
}
}