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>
This commit is contained in:
Ferdinando 2026-08-08 14:58:43 +02:00
commit 5c5b8c34d2
20 changed files with 3784 additions and 17 deletions

View file

@ -0,0 +1,516 @@
using HarmonyLib;
using Jotunn.Configs;
using Jotunn.Entities;
using Jotunn.Managers;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The Fenrir station: a trough that keeps a standing pack, in three ranks.
///
/// Seventh of the per-race chains, and the same family as the Draugh's body pile and the
/// Skeleton's bone pile - meat goes in, a roster fills up, and a death is a slot that refills
/// itself. The ranks fill in order and each one waits for the one below it to be full:
///
/// 10 wolves, one every two minutes
/// then 6 ulv, one every three
/// upgraded: 15 wolves, 10 ulv, and 5 fenrir on top
///
/// CORRECTION, and the reason this file was rewritten: the first two versions bred the pack
/// instead of raising it - the trough rewrote what the animals in its circle gave birth to, and
/// the ranks were meant to fill through vanilla's own Procreation. It cannot work. Cubs are a
/// different prefab from adults, so they either count towards the cap - and then the pen jams at
/// its first litter, because vanilla stops breeding at four head - or they do not, and then
/// nothing stops the pen breeding until it is shoulder to shoulder. There is no third option,
/// and the whole ladder of chances and forced rungs went with it. What is left is smaller, has
/// no cache to prime, no private fields to reach into, and cannot overshoot.
///
/// It is still not a spawner of the kind the guide warns against (4.9b), and the difference is
/// the same one the Skeleton's pile has: nothing here is free or immediate. The pack is paid for
/// in meat, arrives one animal at a time over the better part of an hour, and dies for good if
/// the trough does - so it is a herd you keep, not a button you press before a fight.
/// </summary>
public static class FenrirMangiatoia
{
// ─── Names ───────────────────────────────────────────────────────────
public const string PieceName = "FenrirPackTrough";
public const string PieceDisplayName = "Pack Trough";
public const string UlvsblodName = "Ulvsblod";
public const string UlvsblodDisplayName = "Ulvsblod";
public const string GreaterUlvsblodName = "GreaterUlvsblod";
public const string GreaterUlvsblodDisplayName = "Greater Ulvsblod";
public const int UlvsblodPrice = 500;
public const int GreaterUlvsblodPrice = 1500;
public const string WolfName = "FenrirPack_Wolf";
public const string UlvName = "FenrirPack_Ulv";
public const string FenrirName = "FenrirPack_Fenrir";
public const string WolfDisplayName = "Pack Wolf";
public const string UlvDisplayName = "Ulv";
public const string FenrirDisplayName = "Fenrir";
public const string KindWolf = "FenrirPackWolf";
public const string KindUlv = "FenrirPackUlv";
public const string KindFenrir = "FenrirPackFenrir";
public const string RaceId = "Fenrir";
// Moder needs no state check of her own: her drop is IN the recipe, so a trough cannot be
// built without her having fallen. Yagluth's is checked as well as spent, because the
// upgrade is bought with coin and a drop rather than built.
public const string ModerDrop = "DragonTear";
public const string YagluthDrop = "YagluthDrop";
public const int UpgradeProgressionState = 6; // Yagluth
// ─── The roster ──────────────────────────────────────────────────────
public const int WolfSlots = 10;
public const int UlvSlots = 6;
public const int FenrirSlots = 0; // none at all until upgraded
public const int WolfSlotsUpgraded = 15;
public const int UlvSlotsUpgraded = 10;
public const int FenrirSlotsUpgraded = 5;
/// <summary>
/// How long each rank takes to put one more up. Local seconds, and only while the zone is
/// loaded: a pack that rebuilt itself in an unloaded zone would mean walking away was the
/// fastest way to raise one.
///
/// The fenrir's five minutes is the one number here nobody specified. It is set longest
/// because it is the rank worth waiting for; it is one constant.
/// </summary>
public const float WolfSeconds = 120f;
public const float UlvSeconds = 180f;
public const float FenrirSeconds = 300f;
/// <summary>
/// What one of each costs out of the tank, on AswidBloodRefinery.FleshValue's scale - the
/// same one three other chains use, so a lox steak already counts for more than a neck tail
/// without a second table.
///
/// Anchored to the Draugh's hundred-per-thrall rather than picked: a fenrir is worth one of
/// those, and the ranks below it step down from there.
/// </summary>
public const float WolfCost = 25f;
public const float UlvCost = 50f;
public const float FenrirCost = 100f;
/// <summary>The tank. Four fenrir deep, so a full pack is several trips and not one.</summary>
public const float TankCap = 400f;
public const float TickSeconds = 5f;
// ─── Behaviour ───────────────────────────────────────────────────────
// Five minutes. Long enough to notice the mistake and rebuild, short enough that the wither
// is really doing its job. The trough cannot be broken by accident anyway - it is immune to
// pickaxes - so losing a pack is always a deliberate act.
public const float OrphanWitherSeconds = 300f;
public const float HomeCheckRange = 45f;
public const float LeashRange = 15f;
// No cap, and that is a balance decision rather than an oversight: this chain sits AFTER the
// mountain - Moder to build it, Yagluth for the fenrir at all - and five fenrir is a small
// number next to what the other races field by then.
public const int MaxFollowers = -1;
// One per square mile. 2.59 km2, and stricter than every other station in the mod because of
// what stands around this one.
public const int MaxTroughsInRange = 1;
public const float DensityAreaKm2 = 2.59f;
// ─── Looks ───────────────────────────────────────────────────────────
private const float TroughScale = 1.1f;
/// <summary>
/// A fenrir is a Fenring, and the player's own race turns INTO a Fenring at tier 4. If the
/// two are the same size they are the same silhouette in a melee. This is the only number
/// written over a vanilla creature's own, and it is a legibility fix, not a stat.
/// </summary>
private const float FenrirScale = 1.6f;
private static readonly Color TroughTint = new Color(0.42f, 0.36f, 0.30f, 1f);
private static readonly Color UlvsblodTint = new Color(0.55f, 0.10f, 0.12f, 1f);
private static readonly Color GreaterUlvsblodTint = new Color(0.30f, 0.16f, 0.42f, 1f);
public static void Register()
{
RegisterUlvsblod(UlvsblodName, UlvsblodDisplayName, UlvsblodTint,
"Wolf blood, kept warm by something that should not be able to keep anything warm. " +
"The Fenring sell it and do not explain it.");
RegisterUlvsblod(GreaterUlvsblodName, GreaterUlvsblodDisplayName, GreaterUlvsblodTint,
"Older blood, and further down the line. A trough given one of these starts raising " +
"something worse than ulv.");
RegisterPackAnimal(WolfName, "Wolf", WolfDisplayName, KindWolf,
"It answers to the blood of the wolf, not to you.", 1f);
RegisterPackAnimal(UlvName, "Ulv", UlvDisplayName, KindUlv,
"It answers to the blood of the wolf, not to you.", 1f);
RegisterPackAnimal(FenrirName, "Fenring", FenrirDisplayName, KindFenrir,
"Only the blood of the wolf commands this one.", FenrirScale);
RegisterPiece();
PieceDensityLimit.Register(PieceName,
PieceDensityLimit.RadiusForArea(DensityAreaKm2), MaxTroughsInRange,
"There is already {0} of these within a day's walk. A pack needs room.");
}
// ---------------------------------------------------------------- items
private static void RegisterUlvsblod(string prefabName, string displayName, Color tint, string description)
{
GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(prefabName, "Bloodbag");
if (prefab == null)
{
Jotunn.Logger.LogWarning($"[Fenrir] Could not clone Bloodbag; {displayName} not registered.");
return;
}
Recolour(prefab, tint);
ItemDrop drop = prefab.GetComponent<ItemDrop>();
if (drop == null) return;
ItemDrop.ItemData.SharedData shared = drop.m_itemData.m_shared;
shared.m_name = displayName;
shared.m_description = description;
shared.m_itemType = ItemDrop.ItemData.ItemType.Material;
shared.m_weight = 1f;
shared.m_maxStackSize = 10;
// A Bloodbag is food in vanilla. Left alone, someone eats the gate item.
shared.m_food = 0f;
shared.m_foodStamina = 0f;
shared.m_foodRegen = 0f;
shared.m_foodBurnTime = 0f;
ItemManager.Instance.AddItem(new CustomItem(prefab, fixReference: false));
}
// ---------------------------------------------------------------- the pack
/// <summary>
/// One rank of the pack: a vanilla creature, born tame, leashed to the trough that raised it,
/// and carrying nothing on death.
///
/// Everything it is - health, damage, resistances, speed - stays exactly as vanilla has it.
/// The only number written over is the fenrir's scale, and only so it cannot be mistaken for
/// a transformed player at a glance.
///
/// No Procreation on any of them, deliberately: the trough raises the pack, the pack does not
/// raise itself. That is the whole correction this file was rewritten for.
///
/// The CharacterDrop goes for the usual reason and one of this chain's own: a slot refills
/// itself forever, so an animal that dropped its pelt would not be a farm but a mint.
/// </summary>
private static void RegisterPackAnimal(string prefabName, string source, string displayName,
string kind, string refusal, float scale)
{
GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(prefabName, source);
if (prefab == null)
{
Jotunn.Logger.LogWarning($"[Fenrir] Could not clone {source}; {displayName} not registered.");
return;
}
Character character = prefab.GetComponent<Character>();
if (character != null) character.m_name = displayName;
if (scale != 1f) prefab.transform.localScale = Vector3.one * scale;
BaseAI ai = prefab.GetComponent<BaseAI>();
if (ai != null) ai.m_randomMoveRange = LeashRange;
// A raised pack does not breed. Vanilla gives the Ulv and the Fenring none anyway; the
// wolf comes with one, and it goes.
foreach (Procreation breeding in prefab.GetComponentsInChildren<Procreation>(true))
{
if (breeding != null) Object.DestroyImmediate(breeding);
}
foreach (CharacterDrop drops in prefab.GetComponentsInChildren<CharacterDrop>(true))
{
if (drops != null) Object.DestroyImmediate(drops);
}
// Vanilla gives the Ulv and the Fenring no Tameable at all. Without one they are tamed
// animals that cannot be named or handled like one, so the wolf's is copied across.
if (prefab.GetComponent<Tameable>() == null)
{
GameObject wolf = PrefabManager.Cache.GetPrefab<GameObject>("Wolf");
Tameable source_tame = wolf != null ? wolf.GetComponent<Tameable>() : null;
if (source_tame != null) CopyPublicFields(source_tame, prefab.AddComponent<Tameable>(), prefabName);
}
// "Ten seconds unhurt, then 2% a second" - the same one the Trol's troops already use.
// The postfix that resets its clock on a hit looks for the component, not for a skeleton.
prefab.AddComponent<SkeletonSentryBehaviour>();
RaisedThrall thrall = prefab.AddComponent<RaisedThrall>();
thrall.m_kind = kind;
thrall.m_commandingRace = RaceId;
thrall.m_maxFollowers = MaxFollowers;
thrall.m_witherSeconds = OrphanWitherSeconds;
thrall.m_homeCheckRange = HomeCheckRange;
thrall.m_refusalMessage = refusal;
PrefabManager.Instance.AddPrefab(prefab);
Jotunn.Logger.LogInfo($"[Fenrir] {prefabName} from '{source}': tamed, leashed, no drops, no breeding.");
}
/// <summary>True if the trough takes this as meat. Any flesh, by the scale three chains share.</summary>
public static bool IsMeat(string prefabName)
{
return !string.IsNullOrEmpty(prefabName) && AswidBloodRefinery.FleshValue(prefabName) > 0;
}
public static float FeedValue(string prefabName)
{
int flesh = AswidBloodRefinery.FleshValue(prefabName);
return flesh > 0 ? flesh : 0f;
}
// ---------------------------------------------------------------- piece
private static void RegisterPiece()
{
// A barrel, because a trough is a barrel that someone left open. piece_chest_barrel is
// free - the taken list names piece_chest_wood, which is the Trenta's.
GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(PieceName, "piece_chest_barrel");
if (prefab == null)
{
Jotunn.Logger.LogWarning("[Fenrir] Could not clone piece_chest_barrel; the trough is not registered.");
return;
}
// The barrel's Container is itself the Hoverable AND the Interactable, so a chest would
// swallow both the click that feeds the trough and the hover text that carries the
// roster. The model stays; the chest goes.
foreach (Container container in prefab.GetComponentsInChildren<Container>(true))
{
if (container != null) Object.DestroyImmediate(container);
}
AswidBloodRefinery.StripOffensive(prefab, PieceName);
FenrirMangiatoiaBehaviour behaviour = prefab.AddComponent<FenrirMangiatoiaBehaviour>();
foreach (Switch existing in prefab.GetComponentsInChildren<Switch>(true))
{
if (existing != null) Object.DestroyImmediate(existing);
}
behaviour.m_switch = prefab.AddComponent<Switch>();
behaviour.m_switch.m_name = PieceDisplayName;
prefab.transform.localScale = Vector3.one * TroughScale;
Recolour(prefab, TroughTint);
// Ten silver ingots in the recipe, and a pickaxe that does literally nothing to it.
// "Silver hit points" is not a thing - WearNTear.MaterialType has no silver - but an
// immunity is more precise than a big number anyway: a stray swing while mining out a pen
// cannot cost a pack, and the hammer still takes it down deliberately, because removing a
// piece in Valheim does not go through damage at all.
WearNTear wear = prefab.GetComponent<WearNTear>();
if (wear != null)
{
wear.m_damages.m_pickaxe = HitData.DamageModifier.Immune;
wear.m_materialType = WearNTear.MaterialType.Iron;
Jotunn.Logger.LogInfo($"[Fenrir] Trough health {wear.m_health} (inherited), pickaxe immune.");
}
Piece piece = prefab.GetComponent<Piece>() ?? prefab.AddComponent<Piece>();
piece.m_craftingStation = null;
piece.m_resources = new Piece.Requirement[0];
piece.m_name = PieceDisplayName;
piece.m_canBeRemoved = true;
piece.m_groundPiece = true;
piece.m_groundOnly = true;
piece.m_icon = BorrowIcon("TrophyFenring");
Piece template = PrefabManager.Cache.GetPrefab<Piece>("piece_workbench");
if (template != null && template.m_placeEffect != null) piece.m_placeEffect = template.m_placeEffect;
PieceManager.Instance.AddPiece(new CustomPiece(prefab, fixReference: false, new PieceConfig
{
Name = PieceDisplayName,
Description = "Fill it with meat and the pack comes. One at a time, and it remembers its dead.",
PieceTable = PieceTables.Hammer,
Category = PieceCategories.Crafting,
Icon = BorrowIcon("TrophyFenring"),
Requirements = new[]
{
new RequirementConfig(UlvsblodName, 1, 0, true),
new RequirementConfig("Silver", 10, 0, true),
new RequirementConfig(ModerDrop, 1, 0, true),
new RequirementConfig("FineWood", 20, 0, true),
}
}));
}
public static void EnsureKnown(Player player)
{
if (player == null) return;
GameObject prefab = PrefabManager.Instance.GetPrefab(PieceName);
Piece piece = prefab != null ? prefab.GetComponent<Piece>() : null;
if (piece == null) return;
Traverse traverse = Traverse.Create(player);
traverse.Method("AddKnownPiece", piece).GetValue();
traverse.Method("UpdateAvailablePiecesList").GetValue();
}
// ---------------------------------------------------------------- helpers
/// <summary>
/// Copies every public instance field from one component to another of the same type. Private
/// ones are left alone - they are the caches Awake fills in.
/// </summary>
private static void CopyPublicFields<T>(T source, T target, string label) where T : Component
{
if (source == null || target == null) return;
int copied = 0;
foreach (System.Reflection.FieldInfo field in typeof(T).GetFields(
System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance))
{
field.SetValue(target, field.GetValue(source));
copied++;
}
Jotunn.Logger.LogInfo($"[Fenrir] {label}: {copied} {typeof(T).Name} values taken from the vanilla Wolf.");
}
private static Sprite BorrowIcon(string prefabName)
{
ItemDrop drop = PrefabManager.Cache.GetPrefab<ItemDrop>(prefabName);
Sprite[] icons = drop != null && drop.m_itemData != null && drop.m_itemData.m_shared != null
? drop.m_itemData.m_shared.m_icons
: null;
if (icons != null && icons.Length > 0 && icons[0] != null) return icons[0];
Jotunn.Logger.LogWarning($"[Fenrir] Could not borrow the icon from '{prefabName}'.");
return null;
}
private static void Recolour(GameObject root, Color tint)
{
foreach (Renderer renderer in root.GetComponentsInChildren<Renderer>(true))
{
if (renderer == null || renderer is ParticleSystemRenderer) continue;
foreach (Material material in renderer.materials)
{
if (material == null) continue;
material.color = tint;
if (material.HasProperty("_Color")) material.SetColor("_Color", tint);
}
}
}
}
[HarmonyPatch(typeof(Player), "OnSpawned")]
public static class FenrirMangiatoiaKnownPatch
{
public static void Postfix(Player __instance)
{
if (__instance != Player.m_localPlayer) return;
FenrirMangiatoia.EnsureKnown(__instance);
}
}
/// <summary>
/// [DEBUG] The pack, without the hour it takes to raise one.
///
/// A full roster is 30 animals at two to five minutes each, which is most of an afternoon, and
/// the things worth looking at - what a rank looks like, whether a slot refills after a death,
/// whether the upgrade opens the third rank - are all at the far end of it.
/// </summary>
public class FenrirPackSpawnCommand : ConsoleCommand
{
public override string Name => "fenrirpack";
public override string Help =>
"[DEBUG] fenrirpack now [count] - the nearest trough raises its next animals immediately. " +
"'fenrirpack fill' tops up its meat; 'fenrirpack [wolf|ulv|fenrir] [count]' puts animals " +
"in front of you directly, roster or no roster.";
public override void Run(string[] args)
{
Player player = Player.m_localPlayer;
if (player == null)
{
Console.instance.Print("You must be in-game.");
return;
}
string what = args.Length > 0 ? args[0].ToLowerInvariant() : "wolf";
if (what == "fill") { FenrirMangiatoiaBehaviour.FillNearby(player); return; }
if (what == "now")
{
// No number given means "as many as the roster still wants" - 30 is past the biggest
// possible roster, so the loop stops when NextShort says the pack is whole.
int wanted = 30;
if (args.Length > 1 && !int.TryParse(args[1], out wanted)) wanted = 30;
FenrirMangiatoiaBehaviour.ForceNearby(player, Mathf.Clamp(wanted, 1, 30));
return;
}
string prefabName;
switch (what)
{
case "wolf": prefabName = FenrirMangiatoia.WolfName; break;
case "ulv": prefabName = FenrirMangiatoia.UlvName; break;
case "fenrir": prefabName = FenrirMangiatoia.FenrirName; break;
default:
Console.instance.Print($"'{what}'? wolf, ulv, fenrir - or now / fill.");
return;
}
int count = 2;
if (args.Length > 1 && !int.TryParse(args[1], out count)) count = 2;
count = Mathf.Clamp(count, 1, 30);
GameObject prefab = ZNetScene.instance != null ? ZNetScene.instance.GetPrefab(prefabName) : null;
if (prefab == null)
{
Console.instance.Print($"No '{prefabName}' in ZNetScene - the chain did not register.");
return;
}
// Bound to a trough if there is one in reach, so they count against its roster exactly as
// if it had raised them. Loose otherwise, which is its own useful test.
FenrirMangiatoiaBehaviour trough = FenrirMangiatoiaBehaviour.NearestTo(player.transform.position);
for (int i = 0; i < count; i++)
{
float angle = i * Mathf.PI * 2f / count;
Vector3 ring = new Vector3(Mathf.Cos(angle), 0f, Mathf.Sin(angle)) * 3f;
Vector3 position = player.transform.position + player.transform.forward * 3f + ring + Vector3.up * 0.5f;
GameObject spawned = Object.Instantiate(prefab, position, Quaternion.identity);
Character character = spawned.GetComponent<Character>();
if (character != null) character.SetTamed(true);
MonsterAI ai = spawned.GetComponent<MonsterAI>();
if (ai != null) ai.MakeTame();
RaisedThrall thrall = spawned.GetComponent<RaisedThrall>();
if (thrall != null && trough != null) thrall.Bind(trough.transform.position);
}
Console.instance.Print(trough != null
? $"{count} {prefabName}, bound to the trough {Mathf.RoundToInt(Vector3.Distance(player.transform.position, trough.transform.position))}m away."
: $"{count} {prefabName}, bound to nothing - no trough within range.");
}
}
}

View file

@ -0,0 +1,468 @@
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})");
}
}
}

View file

@ -30,6 +30,11 @@ namespace RacesOfValheim {
public void CreateModAssets()
{
// The pack trough and its bloodline. Registered here because the faction merchant
// catalogue resolves its entries by prefab name, so both Ulvsblod have to exist before a
// Fenring is ever set up as a bench.
FenrirMangiatoia.Register();
curseSE = ScriptableObject.CreateInstance<SE_FenrirCurse>();
curseSE.name = "SE_FenrirCurse";
curseSE.m_name = "Fenrir's Blood";