RacesOfValheim/JotunnModStub/Trol/TrolRace.cs
kanym bca47beda6 Ignore race ability input while a GUI has focus
UnityEngine.Input reads the device directly, so abilities bound to keys
or mouse buttons kept firing with the map, the inventory, a chest, the
chat or a menu open - clicking an item in a container also swung the
transformed attack.

Route that input through Player.TakeInput, which is what Valheim runs
its own controls through and already reports false for those states
(InventoryGui covers the backpack and chests alike). Aswid's transform
keys were the only place already doing this; the shared helper replaces
that one-off and covers Skadi's cold spell, form keys, flight toggle,
form attacks and flight boost, Fenrir's form keys and the attacks of all
four form behaviors, Trol's rock throw and true form, and Aswid's devour
toggle.

Cultist fire is a held button, so it is gated per read rather than
around the block: opening a GUI mid-stream now falls through to
StopFire() instead of leaving the flames running.
2026-08-01 13:25:02 +02:00

395 lines
17 KiB
C#

using BepInEx;
using HarmonyLib;
using UnityEngine;
using System.Collections.Generic;
using Jotunn.Managers;
using Jotunn.Entities;
namespace RacesOfValheim
{
public class TrolRace : MonoBehaviour
{
private static TrolRace _instance;
public static TrolRace Instance
{
get
{
if (_instance == null)
{
GameObject go = new GameObject("TrolRace");
_instance = go.AddComponent<TrolRace>();
DontDestroyOnLoad(go);
}
return _instance;
}
}
public static bool IsTrol()
{
if (Player.m_localPlayer == null) return false;
ZNetView nview = Player.m_localPlayer.GetComponent<ZNetView>();
if (nview != null && nview.IsValid())
return nview.GetZDO().GetString("RacesOfValheim_Race", "") == "Trol";
return Player.m_localPlayer.m_customData.TryGetValue("Race", out string r) && r == "Trol";
}
public void CreateModAssets()
{
Jotunn.Logger.LogInfo("Initializing Trol Race...");
TrolStatusEffects.RegisterStatusEffects();
// No custom projectile needed anymore
string[] logNames = new string[] {
"beech_log", "beech_log_half",
"pine_log", "pine_log_half",
"birch_log", "birch_log_half",
"oak_log", "oak_log_half",
"FirTree_log", "FirTree_log_half",
"yggdrasil_shoot_log", "yggdrasil_shoot_log_half",
"AshTree_log", "AshTree_log_half",
"DeadTree_log", "DeadTree_log_half",
"SwampTree1_log", "SwampTree1_log_half",
"SwampTree2_log", "SwampTree2_log_half"
};
foreach (string logName in logNames)
{
GameObject logPrefab = PrefabManager.Cache.GetPrefab<GameObject>(logName);
if (logPrefab != null)
{
Jotunn.Configs.ItemConfig config = new Jotunn.Configs.ItemConfig();
config.Name = "Giant's Log";
config.Description = "A massive tree log wielded as a weapon.";
CustomItem customWep = new CustomItem("TrolWeapon_" + logName, "MaceIron", config);
if (customWep != null && customWep.ItemPrefab != null)
{
Transform attach = customWep.ItemPrefab.transform.Find("attach");
if (attach != null)
{
foreach (Transform child in attach)
{
Destroy(child.gameObject);
}
GameObject newVisual = new GameObject("TrolWeaponVisual");
newVisual.transform.SetParent(attach);
newVisual.transform.localScale = new Vector3(0.4f, 0.4f, 0.4f);
// Valheim logs are aligned along Y. Rotate Y to point along Z (forward).
newVisual.transform.localRotation = Quaternion.Euler(90, 0, 0);
// Offset along the local Z axis to grab it by the end instead of the middle
newVisual.transform.localPosition = new Vector3(0, 0, 1.5f);
MeshRenderer[] renderers = logPrefab.GetComponentsInChildren<MeshRenderer>(true);
foreach (var r in renderers)
{
if (r.name.ToLower().Contains("lod")) continue;
GameObject part = new GameObject(r.gameObject.name);
part.transform.SetParent(newVisual.transform);
part.transform.localPosition = r.transform.localPosition;
part.transform.localRotation = r.transform.localRotation;
part.transform.localScale = r.transform.localScale;
var mf = part.AddComponent<MeshFilter>();
var origMf = r.GetComponent<MeshFilter>();
if (origMf != null) mf.sharedMesh = origMf.sharedMesh;
var mr = part.AddComponent<MeshRenderer>();
mr.sharedMaterials = r.sharedMaterials;
}
}
ItemDrop itemDrop = customWep.ItemPrefab.GetComponent<ItemDrop>();
itemDrop.m_itemData.m_shared.m_maxDurability = 6f;
itemDrop.m_itemData.m_shared.m_useDurability = true;
itemDrop.m_itemData.m_shared.m_useDurabilityDrain = 1f;
itemDrop.m_itemData.m_shared.m_destroyBroken = false;
itemDrop.m_itemData.m_shared.m_weight = 0f;
itemDrop.m_itemData.m_shared.m_equipDuration = 0.1f;
// It uses MaceIron base, so its skill is Clubs, which automatically gets our damage buffs!
ItemManager.Instance.AddItem(customWep);
}
}
}
}
public bool isTransforming = false;
private bool wasTrueFormActive = false;
private void Update()
{
if (!IsTrol()) return;
if (RaceInput.Allowed)
{
if (Input.GetKeyDown(KeyCode.G))
{
TryThrowRock();
}
if (Input.GetKeyDown(KeyCode.H))
{
TryTrueForm();
}
}
// Check log durability
ItemDrop.ItemData rightItem = HarmonyLib.Traverse.Create(Player.m_localPlayer).Field<ItemDrop.ItemData>("m_rightItem").Value;
if (rightItem != null && rightItem.m_dropPrefab != null && rightItem.m_dropPrefab.name.StartsWith("TrolWeapon_"))
{
if (rightItem.m_durability <= 0f)
{
string logName = rightItem.m_dropPrefab.name.Substring("TrolWeapon_".Length);
GameObject logPrefab = PrefabManager.Cache.GetPrefab<GameObject>(logName);
if (logPrefab != null)
{
DropOnDestroyed dod = logPrefab.GetComponent<DropOnDestroyed>();
if (dod != null && dod.m_dropWhenDestroyed != null)
{
var drops = dod.m_dropWhenDestroyed.GetDropList();
foreach (var drop in drops)
{
Vector3 offset = UnityEngine.Random.insideUnitSphere * 0.5f;
offset.y = 0.5f;
UnityEngine.Object.Instantiate(drop, Player.m_localPlayer.transform.position + offset, Quaternion.identity);
}
}
}
// Message removed
Player.m_localPlayer.UnequipItem(rightItem);
Player.m_localPlayer.GetInventory().RemoveItem(rightItem);
}
}
// Auto-revert True Form check
bool isTrueFormActive = Player.m_localPlayer.GetSEMan().HaveStatusEffect("SE_TrolTrueForm".GetStableHashCode());
if (wasTrueFormActive && !isTrueFormActive && !isTransforming)
{
StartCoroutine(RevertTrueFormRoutine());
}
wasTrueFormActive = isTrueFormActive;
}
private void TryTrueForm()
{
if (BossProgressionManager.GetCurrentProgressionState() < 5) return; // Requires Moder
if (Player.m_localPlayer.GetSEMan().HaveStatusEffect("SE_TrolTrueForm".GetStableHashCode()))
{
if (BossProgressionManager.GetCurrentProgressionState() >= 7)
{
GameObject hoverObj = Player.m_localPlayer.GetHoverObject();
if (hoverObj != null)
{
TreeLog log = hoverObj.GetComponentInParent<TreeLog>();
if (log != null)
{
TrolLogWeapon.GrabLog(Player.m_localPlayer, log);
}
}
}
return;
}
var cdSE = Player.m_localPlayer.GetSEMan().GetStatusEffect("SE_TrolTrueFormCooldown".GetStableHashCode());
if (cdSE != null)
{
float m_time = HarmonyLib.Traverse.Create(cdSE).Field<float>("m_time").Value;
int remaining = (int)(cdSE.m_ttl - m_time);
return;
}
if (!isTransforming)
{
StartCoroutine(TransformToTrueFormRoutine());
}
}
private System.Collections.IEnumerator TransformToTrueFormRoutine()
{
isTransforming = true;
Player.m_localPlayer.GetSEMan().AddStatusEffect("SE_TrolTrueForm".GetStableHashCode(), true);
Player.m_localPlayer.GetSEMan().RemoveStatusEffect("SE_TrolThrowRockCooldown".GetStableHashCode(), true);
float duration = 1.5f;
float elapsed = 0f;
GameObject visual = HarmonyLib.Traverse.Create(Player.m_localPlayer).Field("m_visual").GetValue<GameObject>();
if (visual != null)
{
Vector3 startScale = visual.transform.localScale;
float trueFormScale = BossProgressionManager.GetCurrentProgressionState() >= 7 ? 2.5f : 2.0f;
Vector3 targetScale = new Vector3(trueFormScale, trueFormScale, trueFormScale);
while (elapsed < duration)
{
visual.transform.localScale = Vector3.Lerp(startScale, targetScale, elapsed / duration);
elapsed += Time.deltaTime;
yield return null;
}
visual.transform.localScale = targetScale;
}
isTransforming = false;
}
private System.Collections.IEnumerator RevertTrueFormRoutine()
{
isTransforming = true;
float duration = 1.5f;
float elapsed = 0f;
GameObject visual = HarmonyLib.Traverse.Create(Player.m_localPlayer).Field("m_visual").GetValue<GameObject>();
if (visual != null)
{
Vector3 startScale = visual.transform.localScale;
float normalScale = 1.2f;
int state = BossProgressionManager.GetCurrentProgressionState();
if (state >= 6) normalScale = 1.30f;
else if (state >= 4) normalScale = 1.25f;
Vector3 targetScale = new Vector3(normalScale, normalScale, normalScale);
while (elapsed < duration)
{
visual.transform.localScale = Vector3.Lerp(startScale, targetScale, elapsed / duration);
elapsed += Time.deltaTime;
yield return null;
}
visual.transform.localScale = targetScale;
}
Player.m_localPlayer.GetSEMan().AddStatusEffect("SE_TrolTrueFormCooldown".GetStableHashCode(), true);
isTransforming = false;
}
private void TryThrowRock()
{
if (BossProgressionManager.GetCurrentProgressionState() < 3) return; // Requires The Elder
var cdSE = Player.m_localPlayer.GetSEMan().GetStatusEffect("SE_TrolThrowRockCooldown".GetStableHashCode());
if (cdSE != null)
{
return;
}
StartCoroutine(ThrowRockRoutine());
}
private System.Collections.IEnumerator ThrowRockRoutine()
{
bool isTrueForm = Player.m_localPlayer.GetSEMan().HaveStatusEffect("SE_TrolTrueForm".GetStableHashCode());
float throwRockCooldown = isTrueForm ? 15f : 60f;
var addedSE = Player.m_localPlayer.GetSEMan().AddStatusEffect("SE_TrolThrowRockCooldown".GetStableHashCode(), true);
if (addedSE != null)
{
addedSE.m_ttl = throwRockCooldown;
}
var zanim = HarmonyLib.Traverse.Create(Player.m_localPlayer).Field("m_zanim").GetValue<ZSyncAnimation>();
if (zanim != null)
{
zanim.SetTrigger("throw_bomb");
}
string logName = "";
ItemDrop.ItemData rightItem = HarmonyLib.Traverse.Create(Player.m_localPlayer).Field<ItemDrop.ItemData>("m_rightItem").Value;
bool isHoldingLog = rightItem != null && rightItem.m_dropPrefab != null && rightItem.m_dropPrefab.name.StartsWith("TrolWeapon_");
if (isHoldingLog)
{
logName = rightItem.m_dropPrefab.name.Substring("TrolWeapon_".Length);
// Remove the weapon from inventory
Player.m_localPlayer.UnequipItem(rightItem);
Player.m_localPlayer.GetInventory().RemoveItem(rightItem);
}
// Wait a moment for the animation to reach the throw point
yield return new WaitForSeconds(0.4f);
Vector3 spawnPos = Player.m_localPlayer.GetEyePoint() + Player.m_localPlayer.GetLookDir() * 1.5f;
if (isHoldingLog && !string.IsNullOrEmpty(logName))
{
// Spawn original log asset further away so it doesn't instantly collide with the player
Vector3 logSpawnPos = Player.m_localPlayer.GetEyePoint() + Player.m_localPlayer.GetLookDir() * 3.5f;
GameObject originalLogPrefab = ZNetScene.instance.GetPrefab(logName);
if (originalLogPrefab != null)
{
GameObject logInstance = UnityEngine.Object.Instantiate(originalLogPrefab, logSpawnPos, Quaternion.LookRotation(Player.m_localPlayer.GetLookDir()));
Rigidbody rb = logInstance.GetComponent<Rigidbody>();
if (rb == null) rb = logInstance.GetComponentInChildren<Rigidbody>();
if (rb != null)
{
// 3x speed to compensate for log weight/drag
rb.velocity = Player.m_localPlayer.GetLookDir() * 60f;
// Add some slight rotation tumbling
rb.angularVelocity = new Vector3(10f, 5f, 0f);
}
logInstance.AddComponent<LogImpactBreaker>();
}
}
else
{
// Default rock throw
GameObject projPrefab = ZNetScene.instance.GetPrefab("troll_throw_projectile");
if (projPrefab != null)
{
GameObject projInstance = UnityEngine.Object.Instantiate(projPrefab, spawnPos, Quaternion.LookRotation(Player.m_localPlayer.GetLookDir()));
Projectile proj = projInstance.GetComponent<Projectile>();
if (proj != null)
{
HitData hitData = new HitData();
hitData.m_damage.m_blunt = 25f; // Base troll rock
if (BossProgressionManager.GetCurrentProgressionState() >= 4)
{
hitData.m_damage.m_blunt += 10f; // Bonemass bonus
}
if (BossProgressionManager.GetCurrentProgressionState() >= 6)
{
hitData.m_damage.m_blunt += 5f; // Yagluth bonus
}
if (isTrueForm)
{
hitData.m_damage.m_blunt += 40f; // True Form bonus
}
hitData.SetAttacker(Player.m_localPlayer);
proj.Setup(Player.m_localPlayer, Player.m_localPlayer.GetLookDir() * 20f, -1f, hitData, null, null);
}
}
}
}
}
public class LogImpactBreaker : MonoBehaviour
{
private bool broken = false;
private float armTime;
private void Awake()
{
armTime = Time.time + 0.2f;
}
private void OnCollisionEnter(Collision collision)
{
if (broken || Time.time < armTime) return;
broken = true;
Destructible destructible = GetComponent<Destructible>();
if (destructible != null)
{
HitData hitData = new HitData();
hitData.m_damage.m_chop = 9999f;
hitData.m_point = collision.contacts.Length > 0 ? collision.contacts[0].point : transform.position;
destructible.Damage(hitData);
}
}
}
}