RacesOfValheim/JotunnModStub/Trol/TrolRace.cs
2026-08-24 19:17:47 +02:00

426 lines
19 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;
}
}
// The ZDO copy is authoritative once it has been written - but it is written by a
// Player.OnSpawned postfix in ZdoVisualSync that Harmony registers AFTER this race's own
// OnSpawned postfix (type 363 against type 319 in the built assembly), and the player's
// ZDO is a brand new empty one every session. So on every single load there is a window
// where m_customData is the only place the race exists, and returning out of the ZDO
// branch unconditionally made that window answer "not a Trol" - which is what had
// TrolFoodManager.LoadFood wiping the 4th and 5th stomach out of the save file on reload.
//
// Same fix, same reason, as FactionHostilityPatch.GetPlayerRace: only trust the ZDO
// string when it is non-empty. An explicit "Human" written by resetrace IS non-empty and
// still wins over a stale m_customData, which is the behaviour that fix was added for.
public static bool IsTrol()
{
if (Player.m_localPlayer == null) return false;
ZNetView nview = Player.m_localPlayer.GetComponent<ZNetView>();
if (nview != null && nview.IsValid())
{
string zdoRace = nview.GetZDO().GetString("RacesOfValheim_Race", "");
if (!string.IsNullOrEmpty(zdoRace)) return zdoRace == "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();
// The war totem and every creature it can hire. Race-locked at placement, unlike every
// other station in the mod.
TrolTotem.Register();
// 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 = TrolConfig.LogWeaponMaxDurability.Value;
itemDrop.m_itemData.m_shared.m_useDurability = true;
itemDrop.m_itemData.m_shared.m_useDurabilityDrain = TrolConfig.LogWeaponDurabilityDrainPerHit.Value;
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 (TrolConfig.ThrowRockKey.Value.IsDown())
{
TryThrowRock();
}
if (TrolConfig.TrueFormKey.Value.IsDown())
{
TryTrueForm();
}
if (TrolConfig.GrabLogKey.Value.IsDown())
{
TryGrabLog();
}
}
// 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()))
{
// Grabbing a log now has its own key (TrolConfig.GrabLogKey, see TryGrabLog) -
// pressing True Form again while already transformed no longer tries to grab
// whatever you happen to be looking at.
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 void TryGrabLog()
{
if (BossProgressionManager.GetCurrentProgressionState() < 7) return;
if (!Player.m_localPlayer.GetSEMan().HaveStatusEffect("SE_TrolTrueForm".GetStableHashCode())) return;
GameObject hoverObj = Player.m_localPlayer.GetHoverObject();
if (hoverObj == null) return;
TreeLog log = hoverObj.GetComponentInParent<TreeLog>();
if (log != null)
{
TrolLogWeapon.GrabLog(Player.m_localPlayer, log);
}
}
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
? TrolConfig.TrueFormScaleAdvanced.Value
: TrolConfig.TrueFormScaleNormal.Value;
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 ? TrolConfig.ThrowRockCooldownTrueForm.Value : TrolConfig.ThrowRockCooldown.Value;
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)
{
// Compensates for log weight/drag
rb.velocity = Player.m_localPlayer.GetLookDir() * TrolConfig.ThrowLogVelocity.Value;
// 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 = TrolConfig.ThrowRockBaseDamage.Value;
if (BossProgressionManager.GetCurrentProgressionState() >= 4)
{
hitData.m_damage.m_blunt += TrolConfig.ThrowRockBonemassBonus.Value;
}
if (BossProgressionManager.GetCurrentProgressionState() >= 6)
{
hitData.m_damage.m_blunt += TrolConfig.ThrowRockYagluthBonus.Value;
}
if (isTrueForm)
{
hitData.m_damage.m_blunt += TrolConfig.ThrowRockTrueFormBonus.Value;
}
hitData.SetAttacker(Player.m_localPlayer);
proj.Setup(Player.m_localPlayer, Player.m_localPlayer.GetLookDir() * TrolConfig.ThrowRockProjectileVelocity.Value, -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);
}
}
}
}