RacesOfValheim/JotunnModStub/Fenrir/FenrirMangiatoiaBehaviour.cs
Ferdinando 5c5b8c34d2 feat(races): Skadi hollow chain, plus the pending Dvergar and Fenrir ones
Three per-race item chains had accumulated uncommitted. They land
together because FactionMerchantCatalog.cs carries hunks from all
three and cannot be split without interactive staging.

Skadi (new this session):
- SkadiNokkel - "Skadis Nokkel", a StaffSkeleton clone recoloured to
  ice, stripped of its eitr and health costs and of the skeleton
  summon, opening an ice-blue portal to a troll cave the player
  claims as their own. Crafted at the forge after Moder from a
  1500-coin Greater Frost Heart, a DragonTear and a TrophySkeleton.
- SkadiFrostHeart - the bought leg of that recipe, sold by the
  Cultist bench.
- SkadiHollow / SkadiHollowPortal - claims one existing TrollCave02
  in the Black Forest, half a world radius out and south of the
  equator, and opens a linked local portal pair to it.
- RaceCaveBuilding - Skadi and Trol may build inside any troll cave.

Two facts worth keeping, both paid for the hard way:
- a troll cave counts as a DUNGEON, so the flag that refuses a piece
  there is the per-piece Piece.m_allowedInDungeons, not the
  per-location Location.m_noBuild. Player.m_placementStatus names the
  exact refusal reason and is now logged.
- Object.DestroyImmediate is forbidden inside an animation event
  callback, and a staff cast runs in one - it fails silently there.

Also carried in, from earlier sessions and unverified in game:
- Dvergar contract bank and barrel (DvergarBanco*, DvergarBotte*)
- Fenrir Ulvsblod trough (FenrirMangiatoia*)
- the Wolf -> Ulv merchant bench move, so tameable wolves stop
  answering the E key with a shop window

Status: compiles clean with no new warnings. The Skadi chain has NOT
been confirmed working in game - the most recent fix to the troll
cave detection is still untested.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-08 14:58:43 +02:00

468 lines
19 KiB
C#

using System;
using System.Collections.Generic;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The trough's logic: one rank at a time, one animal at a time, paid for in meat.
///
/// Same shape as DraughSpawnerBehaviour and SkeletonBonePileBehaviour, and deliberately so - all
/// the state in the ZDO, owner-only accounting, and a roster that is COUNTED rather than tallied.
/// Counting fresh on every tick is what makes "when one dies its slot comes back" need no code at
/// all: a death, a despawn, or a player killing his own wolf all correct themselves.
///
/// The ranks fill in order - wolves, then ulv, then fenrir - and whichever rank is short is the
/// one the clock is running for. That is also what "the timer for that one restarts" means: a
/// wolf dying while the trough is working on ulv moves the clock back to the wolf rank, because
/// the lowest short rank always wins.
///
/// HONEST LIMIT, the same one the Skeleton's pile carries: RaisedThrall.BoundTo can only see
/// LOADED creatures. A pack that is off across the map following its owner does not count, and a
/// trough left alone will fill the slots it thinks are empty. The wither is what stops that
/// becoming permanent - a trough only sustains one pack - but a player who ferries animals away
/// and comes back can hold more than the roster says. Closing it properly needs the animals to
/// carry their own bookkeeping, which is the version this replaced and which cost more than it
/// was worth.
/// </summary>
public class FenrirMangiatoiaBehaviour : MonoBehaviour
{
public Switch m_switch;
private const string KeyFeed = "RoV_fenrirFeed";
private const string KeyUpgraded = "RoV_fenrirUpgraded";
private static readonly List<FenrirMangiatoiaBehaviour> Live = new List<FenrirMangiatoiaBehaviour>();
private ZNetView m_nview;
/// <summary>Seconds towards the next animal of whichever rank is currently short.</summary>
private float m_timer;
/// <summary>Which rank the clock is running for, so that a change resets it.</summary>
private string m_waitingFor;
// ---------------------------------------------------------------- life
private void Awake()
{
Live.Add(this);
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, int>("RoV_FenrirFeed", RPC_Feed);
m_nview.Register("RoV_FenrirUpgrade", RPC_Upgrade);
WearNTear wear = GetComponent<WearNTear>();
if (wear != null) wear.m_onDestroyed = (Action)Delegate.Combine(wear.m_onDestroyed, new Action(OnDestroyed));
InvokeRepeating("Tick", FenrirMangiatoia.TickSeconds, FenrirMangiatoia.TickSeconds);
}
private void OnDestroy()
{
Live.Remove(this);
RaisedThrall.UnregisterStation(transform);
}
/// <summary>The nearest loaded trough, or null if none is in reach.</summary>
public static FenrirMangiatoiaBehaviour NearestTo(Vector3 position)
{
FenrirMangiatoiaBehaviour best = null;
float bestSq = 60f * 60f;
for (int i = Live.Count - 1; i >= 0; i--)
{
FenrirMangiatoiaBehaviour trough = Live[i];
if (trough == null) { Live.RemoveAt(i); continue; }
float sq = Vector3.SqrMagnitude(trough.transform.position - position);
if (sq > bestSq) continue;
bestSq = sq;
best = trough;
}
return best;
}
/// <summary>[DEBUG] Tops up every nearby trough, so a test does not start with a meat run.</summary>
public static void FillNearby(Player player)
{
int filled = 0;
foreach (FenrirMangiatoiaBehaviour trough in Live)
{
if (trough == null || trough.m_nview == null || !trough.m_nview.IsValid()) continue;
if (Vector3.Distance(trough.transform.position, player.transform.position) > 60f) continue;
trough.m_nview.ClaimOwnership();
trough.SetFeed(FenrirMangiatoia.TankCap);
filled++;
}
Console.instance.Print(filled == 0 ? "No troughs within 60m." : $"{filled} filled to the brim.");
}
// ---------------------------------------------------------------- the tick
private void Tick()
{
if (m_nview == null || !m_nview.IsValid() || !m_nview.IsOwner()) return;
if (!NextShort(out string kind, out string prefabName, out float wait, out float cost))
{
// Nothing short: the pack is whole. The clock does not run, so a death does not get a
// head start it never earned.
m_timer = 0f;
m_waitingFor = null;
return;
}
// A rank that has just fallen short takes the clock over from the one above it, and it
// starts from zero. This is "the timer for that one restarts", and it is why a death
// costs the full wait rather than whatever happened to be left on another rank's clock.
if (m_waitingFor != kind)
{
m_waitingFor = kind;
m_timer = 0f;
}
if (GetFeed() < cost) return; // no meat, no clock
m_timer += FenrirMangiatoia.TickSeconds;
if (m_timer < wait) return;
m_timer = 0f;
if (Spawn(prefabName)) SetFeed(GetFeed() - cost);
}
/// <summary>
/// The lowest rank that is short, and what raising one of it costs and takes. Ranks fill in
/// order, so this one method is the whole scheduler.
///
/// Extracted so the debug command that forces a spawn goes through EXACTLY this, and cannot
/// quietly fill a rank out of order, past its cap, or before the upgrade opens it. A test
/// tool that skips the rule it is testing proves nothing.
///
/// Returns false when the pack is whole.
/// </summary>
private bool NextShort(out string kind, out string prefabName, out float wait, out float cost)
{
Count(out int wolves, out int ulv, out int fenrir);
if (wolves < WolfCap())
{
kind = FenrirMangiatoia.KindWolf;
prefabName = FenrirMangiatoia.WolfName;
wait = FenrirMangiatoia.WolfSeconds;
cost = FenrirMangiatoia.WolfCost;
return true;
}
if (ulv < UlvCap())
{
kind = FenrirMangiatoia.KindUlv;
prefabName = FenrirMangiatoia.UlvName;
wait = FenrirMangiatoia.UlvSeconds;
cost = FenrirMangiatoia.UlvCost;
return true;
}
if (fenrir < FenrirCap())
{
kind = FenrirMangiatoia.KindFenrir;
prefabName = FenrirMangiatoia.FenrirName;
wait = FenrirMangiatoia.FenrirSeconds;
cost = FenrirMangiatoia.FenrirCost;
return true;
}
kind = null;
prefabName = null;
wait = 0f;
cost = 0f;
return false;
}
/// <summary>
/// [DEBUG] Raises the next <paramref name="count"/> animals at once, skipping only the wait.
///
/// The meat is still charged and the tank is topped up to cover it, because a full roster is
/// far more meat than a tank holds and the point of the command is to skip the CLOCK, not the
/// economy. Everything else - which rank is next, its cap, whether the upgrade has opened the
/// third one - comes from NextShort, the same call the timer uses.
/// </summary>
public static void ForceNearby(Player player, int count)
{
FenrirMangiatoiaBehaviour trough = NearestTo(player.transform.position);
if (trough == null || trough.m_nview == null || !trough.m_nview.IsValid())
{
Console.instance.Print("No trough within 60m.");
return;
}
trough.m_nview.ClaimOwnership();
int raised = 0;
for (int i = 0; i < count; i++)
{
if (!trough.NextShort(out _, out string prefabName, out _, out float cost)) break;
if (trough.GetFeed() < cost) trough.SetFeed(FenrirMangiatoia.TankCap);
if (!trough.Spawn(prefabName)) break;
trough.SetFeed(trough.GetFeed() - cost);
raised++;
}
trough.m_timer = 0f;
Console.instance.Print(raised == 0
? "The pack is already whole."
: $"{raised} raised on the spot. The roster picked them, in its own order.");
}
/// <summary>
/// The roster, counted fresh. Never banked: a tally would have to be corrected on death, on
/// despawn and on a player killing his own, and any one of those going missing leaves a
/// trough that thinks it is full forever.
/// </summary>
private void Count(out int wolves, out int ulv, out int fenrir)
{
wolves = 0;
ulv = 0;
fenrir = 0;
foreach (RaisedThrall thrall in RaisedThrall.BoundTo(transform.position))
{
if (thrall.Kind == FenrirMangiatoia.KindWolf) wolves++;
else if (thrall.Kind == FenrirMangiatoia.KindUlv) ulv++;
else if (thrall.Kind == FenrirMangiatoia.KindFenrir) fenrir++;
}
}
private bool Spawn(string prefabName)
{
GameObject prefab = ZNetScene.instance != null ? ZNetScene.instance.GetPrefab(prefabName) : null;
if (prefab == null)
{
Jotunn.Logger.LogWarning($"[Fenrir] No '{prefabName}' in ZNetScene; the trough cannot raise anything.");
return false;
}
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));
// Bind tames it, marks whose it is, and sends it home - all three.
RaisedThrall thrall = spawned.GetComponent<RaisedThrall>();
if (thrall != null) thrall.Bind(transform.position);
return true;
}
// ---------------------------------------------------------------- interaction
private bool OnUse(Switch caller, Humanoid user, ItemDrop.ItemData item)
{
if (user == null) return false;
Inventory inventory = user.GetInventory();
if (inventory == null) return false;
if (item == null) item = FindAnyInput(inventory);
if (item == null)
{
user.Message(MessageHud.MessageType.Center, "It wants meat. Any meat.");
return false;
}
string prefabName = item.m_dropPrefab != null ? item.m_dropPrefab.name : null;
if (prefabName == null) return false;
if (prefabName == FenrirMangiatoia.GreaterUlvsblodName) return TryUpgrade(user, inventory, item);
if (!FenrirMangiatoia.IsMeat(prefabName))
{
user.Message(MessageHud.MessageType.Center, "$msg_wontwork");
return false;
}
if (GetFeed() >= FenrirMangiatoia.TankCap)
{
user.Message(MessageHud.MessageType.Center, "$msg_itsfull");
return false;
}
// A whole stack per click. A full tank is a lot of neck tails and clicking them out one
// at a time is not a mechanic.
int stack = Mathf.Max(1, item.m_stack);
user.Message(MessageHud.MessageType.Center, $"$msg_added {item.m_shared.m_name} x{stack}");
inventory.RemoveItem(item, stack);
m_nview.InvokeRPC("RoV_FenrirFeed", prefabName, stack);
return true;
}
private ItemDrop.ItemData FindAnyInput(Inventory inventory)
{
foreach (ItemDrop.ItemData candidate in inventory.GetAllItems())
{
if (candidate == null || candidate.m_dropPrefab == null) continue;
string name = candidate.m_dropPrefab.name;
if (name == FenrirMangiatoia.GreaterUlvsblodName) return candidate;
if (FenrirMangiatoia.IsMeat(name)) return candidate;
}
return null;
}
/// <summary>
/// The 1500-coin upgrade, and the second boss gate. Nothing about the trough changes to look
/// at - which is exactly why the hover text has to say it, or the next thing that happens is
/// somebody buys a second one.
/// </summary>
private bool TryUpgrade(Humanoid user, Inventory inventory, ItemDrop.ItemData item)
{
if (IsUpgraded())
{
user.Message(MessageHud.MessageType.Center, "It has already had one.");
return false;
}
if (BossProgressionManager.GetCurrentProgressionState() < FenrirMangiatoia.UpgradeProgressionState)
{
user.Message(MessageHud.MessageType.Center, "The blood will not take. Something in the plains has to fall first.");
return false;
}
if (inventory.CountItems(YagluthDropName()) < 1)
{
user.Message(MessageHud.MessageType.Center, "It wants what Yagluth left behind.");
return false;
}
inventory.RemoveItem(YagluthDropName(), 1);
inventory.RemoveItem(item, 1);
m_nview.InvokeRPC("RoV_FenrirUpgrade");
user.Message(MessageHud.MessageType.Center, "The trough takes it. The line runs deeper now.");
return true;
}
/// <summary>Inventory.RemoveItem and CountItems work on the DISPLAYED name, not the prefab.</summary>
private static string YagluthDropName()
{
ItemDrop drop = Jotunn.Managers.PrefabManager.Cache.GetPrefab<ItemDrop>(FenrirMangiatoia.YagluthDrop);
return drop != null ? drop.m_itemData.m_shared.m_name : FenrirMangiatoia.YagluthDrop;
}
// ---------------------------------------------------------------- accounting
private void RPC_Feed(long sender, string prefabName, int count)
{
if (!m_nview.IsOwner()) return;
if (count < 1) count = 1;
SetFeed(GetFeed() + FenrirMangiatoia.FeedValue(prefabName) * count);
}
private void RPC_Upgrade(long sender)
{
if (!m_nview.IsOwner()) return;
m_nview.GetZDO().Set(KeyUpgraded, true);
}
/// <summary>
/// The trough sustains the pack, so it takes the pack with it - on the wither's delay rather
/// than on the spot. Without some form of this, a trough is a duplication exploit: fill it,
/// dismantle it, rebuild it elsewhere, and keep every animal from every round.
/// </summary>
private void OnDestroyed()
{
if (m_nview == null || !m_nview.IsOwner()) return;
List<RaisedThrall> bound = RaisedThrall.BoundTo(transform.position);
foreach (RaisedThrall thrall in bound) thrall.MarkOrphaned();
if (bound.Count > 0 && Player.m_localPlayer != null)
{
Player.m_localPlayer.Message(MessageHud.MessageType.Center,
$"The trough is broken. {bound.Count} will not outlast it by long.");
}
SetFeed(0f);
}
// ---------------------------------------------------------------- state and display
public bool IsUpgraded() =>
m_nview != null && m_nview.IsValid() && m_nview.GetZDO().GetBool(KeyUpgraded, false);
private int WolfCap() => IsUpgraded() ? FenrirMangiatoia.WolfSlotsUpgraded : FenrirMangiatoia.WolfSlots;
private int UlvCap() => IsUpgraded() ? FenrirMangiatoia.UlvSlotsUpgraded : FenrirMangiatoia.UlvSlots;
private int FenrirCap() => IsUpgraded() ? FenrirMangiatoia.FenrirSlotsUpgraded : FenrirMangiatoia.FenrirSlots;
private float GetFeed() => m_nview != null && m_nview.IsValid() ? m_nview.GetZDO().GetFloat(KeyFeed) : 0f;
private void SetFeed(float value)
{
if (m_nview != null && m_nview.IsValid())
{
m_nview.GetZDO().Set(KeyFeed, Mathf.Clamp(value, 0f, FenrirMangiatoia.TankCap));
}
}
/// <summary>
/// Everything a player needs without opening a log, which is the standard this project
/// arrived at the hard way: a mechanic that cannot say whether it is working looks exactly
/// like one that is broken.
/// </summary>
private string Hover()
{
Count(out int wolves, out int ulv, out int fenrir);
string body = $"meat {Mathf.Floor(GetFeed())}/{FenrirMangiatoia.TankCap}" +
$"\nwolves {wolves}/{WolfCap()}, ulv {ulv}/{UlvCap()}";
// Said in as many words, because the upgrade is deliberately invisible on the model.
body += IsUpgraded()
? $", fenrir {fenrir}/{FenrirCap()}"
: "\nthe blood is thin here - it raises no fenrir yet";
if (m_waitingFor != null)
{
float wait = m_waitingFor == FenrirMangiatoia.KindWolf ? FenrirMangiatoia.WolfSeconds
: m_waitingFor == FenrirMangiatoia.KindUlv ? FenrirMangiatoia.UlvSeconds
: FenrirMangiatoia.FenrirSeconds;
float cost = m_waitingFor == FenrirMangiatoia.KindWolf ? FenrirMangiatoia.WolfCost
: m_waitingFor == FenrirMangiatoia.KindUlv ? FenrirMangiatoia.UlvCost
: FenrirMangiatoia.FenrirCost;
body += GetFeed() < cost
? $"\nnot enough meat for the next one ({cost} needed)"
: $"\nnext in {Mathf.Max(1, Mathf.CeilToInt(wait - m_timer))}s";
}
else
{
body += "\nthe pack is whole";
}
body += "\n[<color=yellow><b>$KEY_Use</b></color>] Fill it with meat";
return Localization.instance.Localize($"{FenrirMangiatoia.PieceDisplayName} ({body})");
}
}
}