RacesOfValheim/JotunnModStub/Trol/TrolTotemBehaviour.cs
Ferdinando c7cbd6bece chore(release): v1.4.18 - Valheim hotfix flight fix, 1.0 shop fixes, Fenrir speed
Drake flight resolves ZInput.GetJoyLeftStickY at runtime, since the
hotfix dropped its bool parameter. Faction merchant TradeItems now set
the 1.0 fields StoreGui dereferences (m_tooltip, m_buyPlayerEffects),
and the Dvergar trader discount clones the whole TradeItem instead of
rebuilding four fields. Trol totem refusals return true so vanilla's
$msg_cantuseon no longer covers them. The Fenrir curse speed modifier
is the bonus alone (SE_Stats adds it), not 1 + bonus. New Discord link.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-18 17:10:24 +02:00

292 lines
12 KiB
C#

using System;
using System.Collections.Generic;
using HarmonyLib;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The totem's logic: five warband slots, bought with coin, disbanded on demand.
///
/// Slots count GROUPS, not bodies - a six-greydwarf patrol is one slot, and it stays one slot as its
/// members die. Each hired creature carries the group's id in its own ZDO, so the count survives a
/// reload and corrects itself when a whole band is wiped, with nothing tallied anywhere.
///
/// E opens the vanilla store with a warband column in it, built in TrolTotemStore. It replaced a
/// hold-to-cycle gesture on the Switch that fired faster than anyone could read it.
/// Factions/FactionMerchantSellPanel.cs is the blueprint that made it possible without guessing at a
/// single UI field name.
///
/// There is no disband button and no rack of slots: a warband that dies is dead, and a butcher knife
/// already dismisses one that has outlived its use. The count is the only bookkeeping there is.
/// </summary>
public class TrolTotemBehaviour : MonoBehaviour
{
public Switch m_switch;
public GameObject m_yagluthHead;
private const string KeyUpgraded = "RoV_trolTotemUpgraded";
private const string KeyNextGroup = "RoV_trolTotemNextGroup";
private ZNetView m_nview;
private void Awake()
{
RaisedThrall.RegisterStation(transform);
m_nview = GetComponent<ZNetView>();
if (m_nview == null || m_nview.GetZDO() == null) return;
if (m_switch != null)
{
m_switch.m_onUse = OnUse;
m_switch.m_onHover = Hover;
}
m_nview.Register<string>("RoV_TrolHire", RPC_Hire);
m_nview.Register("RoV_TrolUpgrade", RPC_Upgrade);
InvokeRepeating("UpdateHeads", 0.5f, 2f);
}
private void OnDestroy()
{
RaisedThrall.UnregisterStation(transform);
}
/// <summary>Both heads are mounted; the tier decides which one is looking at you.</summary>
private void UpdateHeads()
{
// Tier one is a plain totem; the king's head only appears once it has been earned.
if (m_yagluthHead != null) m_yagluthHead.SetActive(IsUpgraded());
}
// ---------------------------------------------------------------- interaction
private bool OnUse(Switch caller, Humanoid user, ItemDrop.ItemData item)
{
Player player = user as Player;
if (player == null) return false;
if (!TrolRace.IsTrol())
{
player.Message(MessageHud.MessageType.Center, "The head will not shout for you.");
// With an item in hand, false makes Humanoid.UseItem cover this message with its
// generic "$msg_cantuseon"; true tells it the use was handled here.
return item != null;
}
// Yagluth's drop in hand upgrades it: a new head, and two more warbands on the list.
if (item != null && item.m_dropPrefab != null && item.m_dropPrefab.name == TrolTotem.UpgradeItem)
{
return TryUpgrade(player, item);
}
if (item != null)
{
player.Message(MessageHud.MessageType.Center, "$msg_wontwork");
return true;
}
return OpenStore(player);
}
// Every refusal still returns true: this only runs from an item use, where false would
// make Humanoid.UseItem replace our message with the generic "$msg_cantuseon".
private bool TryUpgrade(Player player, ItemDrop.ItemData item)
{
if (IsUpgraded())
{
player.Message(MessageHud.MessageType.Center, "It has already had one.");
return true;
}
if (BossProgressionManager.GetCurrentProgressionState() < TrolTotem.UpgradeProgressionState)
{
player.Message(MessageHud.MessageType.Center, "Not until the one it belonged to has fallen.");
return true;
}
player.GetInventory().RemoveItem(item, 1);
m_nview.InvokeRPC("RoV_TrolUpgrade");
player.Message(MessageHud.MessageType.Center, "The totem wears a king now.");
return true;
}
/// <summary>
/// Opens the vanilla store window, with the warband column hung off it by
/// TrolTotemStore. A Trader has to be present for StoreGui.Show to have anything to show; the
/// totem's own sells nothing, which is how "does not buy from the player" is expressed.
/// </summary>
private bool OpenStore(Player player)
{
Trader trader = GetComponent<Trader>();
if (trader == null || StoreGui.instance == null)
{
player.Message(MessageHud.MessageType.Center, "The head has nothing to say.");
return false;
}
// Nothing is handed to the panel here on purpose: TrolTotemStore reads the totem back out of
// StoreGui's own m_trader when it repaints, so the window cannot end up drawing one totem's
// warbands while showing another's - and there is no static left over to go stale.
StoreGui.instance.Show(trader);
return true;
}
// ---------------------------------------------------------------- what the store calls
/// <summary>Hire by id, from a row the player clicked. Every check TryHire makes still applies.</summary>
public void HireFromStore(string troopId)
{
Player player = Player.m_localPlayer;
if (player == null) return;
TrolTotem.Troop troop = TrolTotem.Find(troopId);
if (troop == null) return;
if (troop.NeedsUpgrade && !IsUpgraded()) return;
if (CountGroups() >= TrolTotem.MaxTroops)
{
player.Message(MessageHud.MessageType.Center, "Five warbands is all it can shout for.");
return;
}
Inventory inventory = player.GetInventory();
if (inventory == null) return;
if (CountCoins(inventory) < troop.Price)
{
player.Message(MessageHud.MessageType.Center, "$msg_notenoughmoney");
return;
}
TakeCoins(inventory, troop.Price);
m_nview.InvokeRPC("RoV_TrolHire", troop.Id);
player.Message(MessageHud.MessageType.Center, $"{troop.Display} answers.");
}
private const string CoinsPrefab = "Coins";
private static int CountCoins(Inventory inventory)
{
int total = 0;
foreach (ItemDrop.ItemData item in inventory.GetAllItems())
{
if (item != null && item.m_dropPrefab != null && item.m_dropPrefab.name == CoinsPrefab)
{
total += item.m_stack;
}
}
return total;
}
private static void TakeCoins(Inventory inventory, int amount)
{
foreach (ItemDrop.ItemData item in new List<ItemDrop.ItemData>(inventory.GetAllItems()))
{
if (amount <= 0) return;
if (item == null || item.m_dropPrefab == null || item.m_dropPrefab.name != CoinsPrefab) continue;
int take = Mathf.Min(amount, item.m_stack);
inventory.RemoveItem(item, take);
amount -= take;
}
}
// ---------------------------------------------------------------- hiring
private void RPC_Hire(long sender, string troopId)
{
if (!m_nview.IsOwner()) return;
TrolTotem.Troop troop = TrolTotem.Find(troopId);
if (troop == null || CountGroups() >= TrolTotem.MaxTroops) return;
if (troop.NeedsUpgrade && !IsUpgraded()) return;
int next = m_nview.GetZDO().GetInt(KeyNextGroup) + 1;
m_nview.GetZDO().Set(KeyNextGroup, next);
string group = troopId + "#" + next;
foreach (KeyValuePair<string, int> member in troop.Members)
{
string hired = TrolTotem.HiredNameFor(member.Key);
if (hired == null) continue;
GameObject prefab = ZNetScene.instance != null ? ZNetScene.instance.GetPrefab(hired) : null;
if (prefab == null)
{
Jotunn.Logger.LogWarning($"[Trol] No '{hired}' in ZNetScene; part of {troop.Display} did not arrive.");
continue;
}
for (int i = 0; i < member.Value; i++) SpawnOne(prefab, group);
}
}
private void SpawnOne(GameObject prefab, string group)
{
Vector3 offset = UnityEngine.Random.insideUnitSphere * 3f;
offset.y = 0f;
Vector3 position = transform.position + offset + Vector3.up * 0.5f;
GameObject spawned = Instantiate(prefab, position, Quaternion.Euler(0f, UnityEngine.Random.Range(0, 360), 0f));
ZNetView nview = spawned.GetComponent<ZNetView>();
if (nview != null && nview.IsValid()) nview.GetZDO().Set(TrolTotem.KeyGroup, group);
RaisedThrall thrall = spawned.GetComponent<RaisedThrall>();
if (thrall != null) thrall.Bind(transform.position);
}
private void RPC_Upgrade(long sender)
{
if (!m_nview.IsOwner()) return;
m_nview.GetZDO().Set(KeyUpgraded, true);
}
// ---------------------------------------------------------------- state
public bool IsUpgraded() => m_nview != null && m_nview.IsValid() && m_nview.GetZDO().GetBool(KeyUpgraded, false);
private static string GroupOf(RaisedThrall thrall)
{
ZNetView nview = thrall != null ? thrall.GetComponent<ZNetView>() : null;
if (nview == null || !nview.IsValid()) return null;
string group = nview.GetZDO().GetString(TrolTotem.KeyGroup, "");
return string.IsNullOrEmpty(group) ? null : group;
}
/// <summary>
/// Live warbands, counted as distinct groups rather than as bodies. This is the whole of the
/// five-slot mechanic now that the rack is gone: nothing is stored, the count is the truth, and it
/// corrects itself the moment a band is wiped out.
/// </summary>
public int CountGroups()
{
HashSet<string> groups = new HashSet<string>();
foreach (RaisedThrall thrall in RaisedThrall.BoundTo(transform.position))
{
string group = GroupOf(thrall);
if (group != null) groups.Add(group);
}
return groups.Count;
}
private string Hover()
{
string body = $"warbands {CountGroups()}/{TrolTotem.MaxTroops}";
if (!IsUpgraded()) body += "\n(a Yagluth drop in hand buys a king's head, and two more bands)";
// The roster lives in the window now, not in the hover - so this only has to get the player
// to open it. The hold gesture it used to advertise was unreadable: it cycled faster than
// anyone could see what was selected.
body += "\n[<color=yellow><b>$KEY_Use</b></color>] Call the warbands";
return Localization.instance.Localize($"{TrolTotem.PieceDisplayName} ({body})");
}
}
}