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,455 @@
using System.Collections.Generic;
using HarmonyLib;
using Jotunn.Configs;
using Jotunn.Entities;
using Jotunn.Managers;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The Dvergar's station: a contract bank. Coin goes on the table, a crew signs on.
///
/// The Trol's war totem is the twin of this file and the two should be read together - same five
/// group slots, same empty Trader driving vanilla's store window, same "a dead band is money spent".
/// What is NOT shared is deliberate: the dvergr are hired professionals rather than a shouted-for
/// warband, and everything different here follows from that one sentence.
///
/// - they are TAMED and answer the follow command, like every servant in this mod (RaisedThrall);
/// - they knit their own wounds shut, the sentry's regeneration reused whole;
/// - they are NOT merchants, which costs no code at all: FactionMerchantSetupPatch matches the
/// exact prefab name and these clones are DvergarMerc_*. This is the same mechanism that made
/// every tameable wolf in the world a shop window until the catalogue stopped listing "Wolf",
/// read from the other side;
/// - they keep their race's truce. A hired crew walking into a dvergr outpost does not start a
/// war with the shopkeeper - see DvergarMercenaryTrucePatch at the bottom, which is the one
/// rule in this file that has no counterpart on the totem;
/// - they can be given drink, later. Nothing here is needed for that: a rune barrel will buff
/// whatever RaisedThrall is bound to this bank's anchor, so the mercenaries need no hook of
/// their own and this file does not have to be reopened to add one.
///
/// The seekers in the low bands are not allies, they are LEASHED. A dvergr contract sends you two
/// workers and their beasts, which is also why the truce has to cover them: wild dvergr shoot
/// seekers on sight, and a firefight started by a brood at your heel would be retaliation damage,
/// which IsEnemy has no say over once it has begun.
/// </summary>
public static class DvergarBanco
{
public const string PieceName = "DvergarContractBank";
public const string PieceDisplayName = "Contract Bank";
public const string RaceId = DvergarConfig.RaceId;
/// <summary>The Queen's drop, mapped to state 7 in BossProgressionManager. Mistlands money for
/// a mistlands station: the dvergr do not take Yagluth's leavings seriously.</summary>
public const string UpgradeItem = "QueenDrop";
public const int UpgradeProgressionState = 7; // The Queen
public const int MaxTroops = 5;
/// <summary>Written into each hired creature's ZDO so the bank can tell its crews apart -
/// five slots means counting contracts, not bodies.</summary>
public const string KeyGroup = "RoV_dvergarGroup";
public const float LeashRange = 12f;
public const float WitherSeconds = 60f;
public const float HomeCheckRange = 25f;
/// <summary>No cap: a signed contract walks out as a contract.</summary>
public const int MaxFollowers = -1;
// One per square kilometre. Looser than the Fenrir's pen (2.59 km2) because a bank does not
// grow anything on its own, stricter than the Trol's totem, which has no limit at all and
// should probably get one once it is out of test.
public const int MaxBanksInRange = 1;
public const float DensityAreaKm2 = 1f;
// ---------------------------------------------------------------- the look, in metres
/// <summary>A cartography table, slightly cut down. The dvergr write smaller than we do.</summary>
private const float TableScale = 0.8f;
/// <summary>
/// How high the coin pile sits, in the piece's own space and BEFORE TableScale is applied.
/// Unlike the totem's head this is not measured: the table keeps its own vanilla mesh, so
/// there is no borrowed holder to call ModelBorrow.HeightOf on. If the pile floats or sinks,
/// this is the ONE number to touch.
/// </summary>
private const float PileHeight = 1.05f;
private const float PileSize = 0.45f;
public class Troop
{
public string Id;
public string Display;
public int Price;
public bool NeedsUpgrade;
/// <summary>Trophy of whoever leads the crew - the face it wears in the rack.</summary>
public string Icon;
/// <summary>Vanilla creature prefab -> how many of it.</summary>
public KeyValuePair<string, int>[] Members;
}
// Anchored at the same 400-2000 as the Trol's totem, and laddered against ITS bands rather
// than against head count: one Dverger is worth rather more than six greydwarves, so the
// bodies come down as the coin goes up and the seekers make up the difference at the bottom.
//
// The top band is knowingly stronger than the totem's two thousand coin fuling war band. It
// sits behind the Queen and it dies for good; if it proves too much in play, the lever is to
// drop the support mage out of it before touching the price.
public static readonly Troop[] Troops =
{
new Troop
{
Id = "escort", Display = "Escort", Price = 400, NeedsUpgrade = false, Icon = "TrophyDvergr",
Members = new[]
{
new KeyValuePair<string, int>("Dverger", 1),
new KeyValuePair<string, int>("SeekerBrood", 2),
}
},
new Troop
{
Id = "yard_patrol", Display = "Yard Patrol", Price = 700, NeedsUpgrade = false, Icon = "TrophyDvergr",
Members = new[]
{
new KeyValuePair<string, int>("Dverger", 2),
new KeyValuePair<string, int>("SeekerBrood", 2),
}
},
new Troop
{
Id = "fire_crew", Display = "Fire Crew", Price = 1000, NeedsUpgrade = false, Icon = "TrophyDvergr",
Members = new[]
{
new KeyValuePair<string, int>("Dverger", 1),
new KeyValuePair<string, int>("DvergerMageFire", 1),
new KeyValuePair<string, int>("SeekerBrood", 3),
}
},
new Troop
{
Id = "runic_crew", Display = "Runic Crew", Price = 1500, NeedsUpgrade = true, Icon = "TrophyDvergr",
Members = new[]
{
new KeyValuePair<string, int>("Dverger", 2),
new KeyValuePair<string, int>("DvergerMageIce", 1),
new KeyValuePair<string, int>("DvergerMageSupport", 1),
}
},
new Troop
{
Id = "ash_guard", Display = "Ash Guard", Price = 2000, NeedsUpgrade = true, Icon = "TrophySeekerBrute",
Members = new[]
{
new KeyValuePair<string, int>("DvergerAshlands", 2),
new KeyValuePair<string, int>("DvergerMageSupport", 1),
new KeyValuePair<string, int>("SeekerBrute", 1),
}
},
};
public static Troop Find(string id)
{
foreach (Troop troop in Troops) if (troop.Id == id) return troop;
return null;
}
/// <summary>
/// What this player actually pays, after the Dvergar's own trader discount.
///
/// It reads the LOCAL player's tier, which is correct rather than convenient: the coin comes
/// out of that player's own inventory, on that player's own client, and a contract bank is not
/// a shared till. The discount table stops at 25% at state 7 (DvergarConfig.cs), which is the
/// same state that unlocks the two upgraded bands - so the top of the list can never be
/// discounted before it can be bought, and no separate ceiling is needed.
/// </summary>
public static int PriceFor(Troop troop)
{
if (troop == null) return 0;
float discount = Mathf.Clamp01(DvergarProgression.Current.TraderBuyDiscount);
return Mathf.Max(1, Mathf.RoundToInt(troop.Price * (1f - discount)));
}
/// <summary>Every distinct creature the bank can hire, so their clones exist before anyone signs.</summary>
private static readonly Dictionary<string, string> HiredPrefabs = new Dictionary<string, string>();
public static string HiredNameFor(string vanillaPrefab) =>
HiredPrefabs.TryGetValue(vanillaPrefab, out string name) ? name : null;
/// <summary>The mercenary prefabs, by name, so the truce can recognise its own cheaply.</summary>
private static readonly HashSet<string> HiredNames = new HashSet<string>();
public static bool IsHiredName(string prefabName) =>
!string.IsNullOrEmpty(prefabName) && HiredNames.Contains(prefabName);
public static void Register()
{
HashSet<string> sources = new HashSet<string>();
foreach (Troop troop in Troops)
{
foreach (KeyValuePair<string, int> member in troop.Members) sources.Add(member.Key);
}
foreach (string source in sources) RegisterHired(source);
RegisterPiece();
PieceDensityLimit.Register(PieceName,
PieceDensityLimit.RadiusForArea(DensityAreaKm2), MaxBanksInRange,
"There is already {0} contract bank within a day's walk. One ledger per valley.");
}
// ---------------------------------------------------------------- the hired
/// <summary>
/// One signed mercenary: the vanilla creature, tamed, leashed, healing, and worth nothing dead.
///
/// CharacterDrop is destroyed for the reason it always is here, and it matters more on this
/// chain than on any other: dvergr and seekers both carry loot that SELLS. A mercenary that
/// dropped its own parts would make the bank a way of turning coin into more coin.
/// </summary>
private static void RegisterHired(string source)
{
string prefabName = "DvergarMerc_" + source;
GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(prefabName, source);
if (prefab == null)
{
Jotunn.Logger.LogWarning($"[Dvergar] Could not clone {source}; that crew member cannot be hired. " +
"The rest of its band still signs on without it.");
return;
}
BaseAI ai = prefab.GetComponent<BaseAI>();
if (ai != null) ai.m_randomMoveRange = LeashRange;
foreach (CharacterDrop drops in prefab.GetComponentsInChildren<CharacterDrop>(true))
{
if (drops != null) Object.DestroyImmediate(drops);
}
RaisedThrall thrall = prefab.AddComponent<RaisedThrall>();
thrall.m_kind = prefabName;
thrall.m_commandingRace = RaceId;
thrall.m_maxFollowers = MaxFollowers;
thrall.m_witherSeconds = WitherSeconds;
thrall.m_homeCheckRange = HomeCheckRange;
thrall.m_refusalMessage = "Your name is not on the contract.";
// Ten seconds unhurt, then two percent a second - the sentry's regeneration, shared with
// the Trol's troops and the Fenrir's pack. A dead mercenary still stays dead.
prefab.AddComponent<SkeletonSentryBehaviour>();
PrefabManager.Instance.AddPrefab(prefab);
HiredPrefabs[source] = prefabName;
HiredNames.Add(prefabName);
}
// ---------------------------------------------------------------- the bank
private static void RegisterPiece()
{
GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(PieceName, "piece_cartographytable");
if (prefab == null)
{
Jotunn.Logger.LogWarning("[Dvergar] Could not clone piece_cartographytable; the contract bank " +
"is not registered.");
return;
}
// EVERY behaviour goes except the three that make it a building, and the blanket sweep is
// the point rather than laziness: the cartography table's MapTable is Interactable AND
// Hoverable, so it takes the E key before our own Switch ever sees it and opens the shared
// map instead of the ledger. That is the same bug as the barrel's Container on the Fenrir
// trough and the Trader on the vanilla wolf, and stripping by capability instead of by
// type name means it cannot come back if a future patch renames or adds a component.
//
// Unlike the Trol's totem the renderers are KEPT: the table is the look, there is nothing
// borrowed underneath it.
foreach (MonoBehaviour behaviour in prefab.GetComponentsInChildren<MonoBehaviour>(true))
{
if (behaviour == null) continue;
if (behaviour is Piece || behaviour is ZNetView || behaviour is WearNTear) continue;
Object.DestroyImmediate(behaviour);
}
AswidBloodRefinery.StripOffensive(prefab, PieceName);
prefab.transform.localScale = Vector3.one * TableScale;
DvergarBancoBehaviour bank = prefab.AddComponent<DvergarBancoBehaviour>();
foreach (Switch existing in prefab.GetComponentsInChildren<Switch>(true))
{
if (existing != null) Object.DestroyImmediate(existing);
}
bank.m_switch = prefab.AddComponent<Switch>();
bank.m_switch.m_name = PieceDisplayName;
// An empty catalogue IS the design: the bank sells crews and buys nothing. Every list is
// filled in even though this trader never talks, because a Trader added with AddComponent
// comes up with all of them null and Trader.Interact walks into Say(m_randomStartTrade)
// if the player's E happens to reach it instead of our Switch.
//
// The empty list would also throw out of StoreGui.FillList on its last instruction - that
// is fixed once and for everyone by StoreGuiEmptyCatalogueGuardPatch over in
// Trol/TrolTotemStore.cs, which is generic and is deliberately NOT copied here.
Trader trader = prefab.GetComponent<Trader>() ?? prefab.AddComponent<Trader>();
trader.m_name = PieceDisplayName;
trader.m_items = new List<Trader.TradeItem>();
trader.m_useItems = new List<Trader.TraderUseItem>();
trader.m_randomTalk = new List<string>();
trader.m_randomGreets = new List<string>();
trader.m_randomGoodbye = new List<string>();
trader.m_randomStartTrade = new List<string>();
trader.m_randomBuy = new List<string>();
trader.m_randomSell = new List<string>();
trader.m_randomGiveItemNo = new List<string>();
trader.m_randomUseItemAlreadyRecieved = new List<string>();
trader.m_randomTalkConditionals = new List<Trader.ConditionalDialog>();
// The mark of a bank that has been paid: a heap of coin on the table, hidden until the
// Queen has fallen and the ledger has been rewritten.
//
// 'treasure_pile' is the player's own choice of prop and is NOT verified against this
// build - nothing else in the project references it. ModelBorrow is null-safe by
// construction, so a wrong name costs exactly one warning in the log and an empty holder;
// if that warning appears, 'Coins' is the fallback and this is a one-string change.
bank.m_coinPile = ModelBorrow.Attach(prefab.transform, "BankCoinPile", "treasure_pile",
new Vector3(0f, PileHeight, 0f), Quaternion.identity,
PileSize, "Dvergar");
bank.m_coinPile.SetActive(false);
Piece piece = prefab.GetComponent<Piece>() ?? prefab.AddComponent<Piece>();
piece.m_craftingStation = null; // a bank is built where the work is, not at a bench
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("TrophyDvergr");
Piece template = PrefabManager.Cache.GetPrefab<Piece>("piece_workbench");
if (template != null && template.m_placeEffect != null) piece.m_placeEffect = template.m_placeEffect;
// Coin in the RECIPE, and that is the whole reason this chain needs no gate item bought
// from a merchant the way the other three do: the Dvergar pay for everything, so the
// station opens by being paid for rather than by being unlocked.
PieceManager.Instance.AddPiece(new CustomPiece(prefab, fixReference: false, new PieceConfig
{
Name = PieceDisplayName,
Description = "A ledger, a seal and a heap of coin. Sign here and someone else does the dying.",
PieceTable = PieceTables.Hammer,
Category = PieceCategories.Crafting,
Icon = BorrowIcon("TrophyDvergr"),
Requirements = new[]
{
new RequirementConfig("BlackMarble", 10, 0, true),
new RequirementConfig("YggdrasilWood", 5, 0, true),
new RequirementConfig("Sap", 2, 0, true),
new RequirementConfig("Coins", 100, 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();
}
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;
return icons != null && icons.Length > 0 ? icons[0] : null;
}
}
[HarmonyPatch(typeof(Player), "OnSpawned")]
public static class DvergarBancoKnownPatch
{
public static void Postfix(Player __instance)
{
if (__instance != Player.m_localPlayer) return;
DvergarBanco.EnsureKnown(__instance);
}
}
/// <summary>
/// The race lock, caught at placement so the marble and the coin are not spent before the refusal.
/// The same shape as TrolTotemRaceLockPatch - the second station in the mod that refuses the hammer
/// outright, because hiring dvergr with dvergr money is the race's identity and not a tool it owns.
/// </summary>
[HarmonyPatch(typeof(Player), "PlacePiece",
new[] { typeof(Piece), typeof(Vector3), typeof(Quaternion), typeof(bool) })]
public static class DvergarBancoRaceLockPatch
{
public static bool Prefix(Player __instance, Piece __0)
{
if (__instance != Player.m_localPlayer || __0 == null) return true;
if (Utils.GetPrefabName(__0.gameObject) != DvergarBanco.PieceName) return true;
if (DvergarRace.IsDvergar()) return true;
__instance.Message(MessageHud.MessageType.Center, "The contract is in runic. You do not sign it.");
return false;
}
}
/// <summary>
/// A hired crew keeps its employer's truce.
///
/// Without this the station fights itself: a Dvergar player is at peace with the mountain's dvergr
/// (FactionHostilityPatch), and those dvergr are where the player BUYS - so walking into an outpost
/// with an escort would mean the escort killing the shopkeeper. Taming a creature puts it in the
/// player faction, which makes it an enemy of everything the player is merely not fighting.
///
/// One condition covers the whole band, seekers included, because every hired body is a RaisedThrall
/// carrying the same commanding race - so the leashed brood at your heel is as welcome in an outpost
/// as the dvergr holding its chain, even though wild dvergr shoot seekers on sight. That was the
/// player's call and it is the only reason a bank is usable in the mistlands at all: retaliation
/// damage does not go through IsEnemy, so one shot fired by an outpost would have escalated into a
/// war this patch could no longer stop.
///
/// A postfix that only ever says "not enemies", layered on top of the older hostility patch on the
/// same method exactly as that one layers on RaceHostilityManager. It cannot make anything hostile
/// that was not already.
/// </summary>
[HarmonyPatch(typeof(BaseAI), nameof(BaseAI.IsEnemy), new System.Type[] { typeof(Character), typeof(Character) })]
public static class DvergarMercenaryTrucePatch
{
/// <summary>The mountain's dvergr, by prefab name. The same roster FactionHostilityPatch uses
/// for the player's own truce - kept as its own copy so a change to one is a deliberate change
/// to that one, since these two lists answer different questions.</summary>
private static readonly HashSet<string> WildDvergr = new HashSet<string>
{
"Dverger", "DvergerMageFire", "DvergerMageIce", "DvergerMageSupport", "DvergerAshlands",
};
public static void Postfix(Character a, Character b, ref bool __result)
{
if (!__result) return; // already not enemies, nothing to add
if (a == null || b == null) return;
if (IsTruce(a, b) || IsTruce(b, a)) __result = false;
}
/// <summary>True if <paramref name="mercenary"/> is one of ours and <paramref name="other"/> is
/// a wild dvergr.</summary>
private static bool IsTruce(Character mercenary, Character other)
{
RaisedThrall thrall = mercenary.GetComponent<RaisedThrall>();
if (thrall == null || thrall.m_commandingRace != DvergarBanco.RaceId) return false;
return WildDvergr.Contains(Utils.GetPrefabName(other.gameObject));
}
}
}

View file

@ -0,0 +1,290 @@
using System.Collections.Generic;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The bank's logic: five contracts, bought with coin, and no way to cancel one.
///
/// Slots count CREWS, not bodies - a fire crew of five is one slot, and it stays one slot as its
/// members die. Each hired body carries its crew's id in its own ZDO, so the count survives a reload
/// and corrects itself when a whole crew is wiped, with nothing tallied anywhere.
///
/// This is TrolTotemBehaviour's twin and was written from it. The differences are all consequences
/// of one thing - these are paid professionals rather than a shouted-for warband:
/// - the price a player pays is discounted by their own Dvergar tier (DvergarBanco.PriceFor);
/// - the upgrade is the Queen's drop rather than Yagluth's, and it puts coin on the table
/// instead of a head on a post.
/// If a bug is found in one of the two files, look for it in the other before assuming it is local.
/// </summary>
public class DvergarBancoBehaviour : MonoBehaviour
{
public Switch m_switch;
public GameObject m_coinPile;
private const string KeyUpgraded = "RoV_dvergarBankUpgraded";
private const string KeyNextGroup = "RoV_dvergarBankNextGroup";
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_DvergarHire", RPC_Hire);
m_nview.Register("RoV_DvergarUpgrade", RPC_Upgrade);
InvokeRepeating("UpdatePile", 0.5f, 2f);
}
private void OnDestroy()
{
RaisedThrall.UnregisterStation(transform);
}
/// <summary>The coin is mounted from the start; the tier decides whether it is there to see.</summary>
private void UpdatePile()
{
if (m_coinPile != null) m_coinPile.SetActive(IsUpgraded());
}
// ---------------------------------------------------------------- interaction
private bool OnUse(Switch caller, Humanoid user, ItemDrop.ItemData item)
{
Player player = user as Player;
if (player == null) return false;
if (!DvergarRace.IsDvergar())
{
player.Message(MessageHud.MessageType.Center, "The ledger is not written for you.");
return false;
}
// The Queen's drop in hand rewrites the ledger: coin on the table, and two more crews.
if (item != null && item.m_dropPrefab != null && item.m_dropPrefab.name == DvergarBanco.UpgradeItem)
{
return TryUpgrade(player, item);
}
if (item != null)
{
player.Message(MessageHud.MessageType.Center, "$msg_wontwork");
return false;
}
return OpenStore(player);
}
private bool TryUpgrade(Player player, ItemDrop.ItemData item)
{
if (IsUpgraded())
{
player.Message(MessageHud.MessageType.Center, "It has already had one.");
return false;
}
if (BossProgressionManager.GetCurrentProgressionState() < DvergarBanco.UpgradeProgressionState)
{
player.Message(MessageHud.MessageType.Center, "Not while she still sits under the mist.");
return false;
}
player.GetInventory().RemoveItem(item, 1);
m_nview.InvokeRPC("RoV_DvergarUpgrade");
player.Message(MessageHud.MessageType.Center, "The ledger is rewritten. Better names sign it now.");
return true;
}
/// <summary>
/// Opens the vanilla store window, with the crew column hung off it by DvergarBancoStore. A
/// Trader has to be present for StoreGui.Show to have anything to show; this one's catalogue is
/// empty, which is how "hires crews, buys nothing" is expressed.
/// </summary>
private bool OpenStore(Player player)
{
Trader trader = GetComponent<Trader>();
if (trader == null || StoreGui.instance == null)
{
player.Message(MessageHud.MessageType.Center, "The ledger is shut.");
return false;
}
// Nothing is handed to the panel: DvergarBancoStore reads the bank back out of StoreGui's
// own m_trader when it repaints, so the window cannot draw one bank's crews 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>Sign a crew by id, from a row the player clicked. Every check TryHire made applies.</summary>
public void HireFromStore(string troopId)
{
Player player = Player.m_localPlayer;
if (player == null) return;
DvergarBanco.Troop troop = DvergarBanco.Find(troopId);
if (troop == null) return;
if (troop.NeedsUpgrade && !IsUpgraded()) return;
if (CountGroups() >= DvergarBanco.MaxTroops)
{
player.Message(MessageHud.MessageType.Center, "Five contracts is all the ledger holds.");
return;
}
Inventory inventory = player.GetInventory();
if (inventory == null) return;
// Priced here and NOT on the way in from the row: the button only draws a number, and the
// player's tier could have changed since the window was opened.
int price = DvergarBanco.PriceFor(troop);
if (CountCoins(inventory) < price)
{
player.Message(MessageHud.MessageType.Center, "$msg_notenoughmoney");
return;
}
TakeCoins(inventory, price);
m_nview.InvokeRPC("RoV_DvergarHire", troop.Id);
player.Message(MessageHud.MessageType.Center, $"{troop.Display} signs on.");
}
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;
DvergarBanco.Troop troop = DvergarBanco.Find(troopId);
if (troop == null || CountGroups() >= DvergarBanco.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 = DvergarBanco.HiredNameFor(member.Key);
if (hired == null) continue;
GameObject prefab = ZNetScene.instance != null ? ZNetScene.instance.GetPrefab(hired) : null;
if (prefab == null)
{
Jotunn.Logger.LogWarning($"[Dvergar] No '{hired}' in ZNetScene; part of {troop.Display} " +
"did not turn up for work.");
continue;
}
for (int i = 0; i < member.Value; i++) SpawnOne(prefab, group);
}
}
private void SpawnOne(GameObject prefab, string group)
{
Vector3 offset = Random.insideUnitSphere * 3f;
offset.y = 0f;
Vector3 position = transform.position + offset + Vector3.up * 0.5f;
GameObject spawned = Instantiate(prefab, position, Quaternion.Euler(0f, Random.Range(0, 360), 0f));
ZNetView nview = spawned.GetComponent<ZNetView>();
if (nview != null && nview.IsValid()) nview.GetZDO().Set(DvergarBanco.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(DvergarBanco.KeyGroup, "");
return string.IsNullOrEmpty(group) ? null : group;
}
/// <summary>
/// Live crews, counted as distinct groups rather than as bodies. Nothing is stored: the count
/// is the truth, and it corrects itself the moment a crew 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 = $"contracts {CountGroups()}/{DvergarBanco.MaxTroops}";
// Said in as many words: a player who cannot see their own discount will read the lower
// number in the window as a mistake.
float discount = Mathf.Clamp01(DvergarProgression.Current.TraderBuyDiscount);
if (discount > 0f) body += $"\nyour seal is worth {Mathf.RoundToInt(discount * 100f)}% off";
if (!IsUpgraded()) body += "\n(what the Queen left behind buys two more crews)";
body += "\n[<color=yellow><b>$KEY_Use</b></color>] Read the ledger";
return Localization.instance.Localize($"{DvergarBanco.PieceDisplayName} ({body})");
}
}
}

View file

@ -0,0 +1,211 @@
using System.Collections.Generic;
using System.Text;
using HarmonyLib;
using TMPro;
using UnityEngine;
using UnityEngine.UI;
namespace RacesOfValheim
{
/// <summary>
/// The contract bank's window: the merchant's own store, with a column of hireable crews in it.
///
/// TWINNED WITH Trol/TrolTotemStore.cs. This is a copy of that file, taken deliberately rather than
/// refactored into something shared, so the Trol's totem is not touched while it is in test - the
/// two are the same panel drawn from a different roster. A FIX TO ONE BELONGS IN THE OTHER; when
/// the totem is settled they should collapse into one panel driven by a common station interface.
///
/// Two things are deliberately NOT copied across:
/// - StoreGuiEmptyCatalogueGuardPatch, which is what stops vanilla FillList throwing on an empty
/// catalogue and taking every postfix down with it. It is generic - it fires for any trader with
/// nothing to sell - so it already covers this bank, and a second copy would just be a second
/// prefix on the same method doing the same work.
/// - the slot rack. There was one on the totem and it was removed at the player's call: a crew
/// that dies is dead, and a butcher knife already dismisses one that has outlived its use.
///
/// The two columns cannot collide. Each one clears itself at the top of its own Refresh and only
/// switches on when the trader the window belongs to carries ITS behaviour, so at most one is ever
/// drawn - a bank is not a totem.
/// </summary>
public static class DvergarBancoStore
{
private static RectTransform _crewList;
private static readonly List<GameObject> _rows = new List<GameObject>();
/// <summary>
/// The bank the open window belongs to, read back out of StoreGui's own m_trader rather than
/// pushed in before Show(). Same field the factions sell panel and the totem's column read.
/// </summary>
public static DvergarBancoBehaviour ActiveBank(StoreGui gui)
{
Trader trader = FactionMerchantRuntime.GetActiveTrader(gui);
return trader != null ? trader.GetComponent<DvergarBancoBehaviour>() : null;
}
// ---------------------------------------------------------------- build
public static void Create(StoreGui gui)
{
if (gui == null || gui.m_listRoot == null)
{
Jotunn.Logger.LogWarning("[Dvergar] StoreGui has no m_listRoot; the contract bank's window " +
"cannot be built.");
return;
}
if (_crewList != null) return;
GameObject clone = Object.Instantiate(gui.m_listRoot.gameObject, gui.m_listRoot.parent);
clone.name = "DvergarCrewList";
_crewList = clone.GetComponent<RectTransform>();
_crewList.anchoredPosition = gui.m_listRoot.anchoredPosition;
// The clone carries whatever rows the vanilla list held at Awake. Usually none, but a
// leftover would sit under ours forever, so it starts empty by construction.
foreach (Transform child in _crewList) Object.Destroy(child.gameObject);
_crewList.gameObject.SetActive(false);
}
public static void Clear()
{
foreach (GameObject row in _rows) if (row != null) Object.Destroy(row);
_rows.Clear();
if (_crewList != null) _crewList.gameObject.SetActive(false);
}
// ---------------------------------------------------------------- fill
public static void Refresh(StoreGui gui)
{
Clear();
DvergarBancoBehaviour bank = ActiveBank(gui);
if (bank == null) return; // an ordinary merchant, or the Trol's totem. Not ours.
if (_crewList == null)
{
Jotunn.Logger.LogWarning("[Dvergar] The contract bank's column was never built (did the patch " +
"on StoreGui.Awake fail?), so nothing can be drawn into it.");
return;
}
_crewList.gameObject.SetActive(true);
int row = 0;
int hidden = 0;
foreach (DvergarBanco.Troop troop in DvergarBanco.Troops)
{
if (troop.NeedsUpgrade && !bank.IsUpgraded()) { hidden++; continue; }
BuildRow(gui, bank, troop, row++);
}
float baseSize = Traverse.Create(gui).Field("m_itemlistBaseSize").GetValue<float>();
_crewList.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical,
Mathf.Max(baseSize, row * gui.m_itemSpacing));
Jotunn.Logger.LogInfo($"[Dvergar] Contract bank window: {row} crews on offer, {hidden} still behind " +
$"the Queen, {bank.CountGroups()}/{DvergarBanco.MaxTroops} contracts live.");
}
private static void BuildRow(StoreGui gui, DvergarBancoBehaviour bank, DvergarBanco.Troop troop, int rowIndex)
{
GameObject element = Object.Instantiate(gui.m_listElement, _crewList);
element.SetActive(true);
RectTransform rt = (RectTransform)element.transform;
float offset = (_crewList.rect.width - rt.rect.width) / 2f;
rt.anchoredPosition = new Vector2(offset, rowIndex * -gui.m_itemSpacing - offset);
Sprite icon = TrophyIcon(troop.Icon);
Image iconImage = element.transform.Find("icon").GetComponent<Image>();
if (icon != null) iconImage.sprite = icon;
else Jotunn.Logger.LogWarning($"[Dvergar] No icon on '{troop.Icon}' for {troop.Display}; the row " +
"keeps whatever the cloned element was showing.");
element.transform.Find("name").GetComponent<TMP_Text>().text = troop.Display;
// The DISCOUNTED price, because that is what will actually leave the player's pocket.
TMP_Text price = FindDescendant<TMP_Text>(element.transform, "price");
if (price != null) price.text = DvergarBanco.PriceFor(troop).ToString();
UITooltip tooltip = element.GetComponent<UITooltip>();
if (tooltip != null) tooltip.Set(troop.Display, Composition(troop), gui.m_tooltipAnchor, default(Vector2));
string id = troop.Id;
element.GetComponent<Button>().onClick.AddListener(() =>
{
bank.HireFromStore(id);
Traverse.Create(gui).Method("FillList").GetValue(); // repaints the column
});
_rows.Add(element);
}
/// <summary>Who actually turns up, so two thousand coin is not spent blind.</summary>
private static string Composition(DvergarBanco.Troop troop)
{
StringBuilder text = new StringBuilder();
foreach (KeyValuePair<string, int> member in troop.Members)
{
if (text.Length > 0) text.Append('\n');
text.Append(member.Value).Append(" x ").Append(CreatureName(member.Key));
}
int full = troop.Price;
int paid = DvergarBanco.PriceFor(troop);
if (paid < full) text.Append("\n\nList price ").Append(full).Append(" - your seal takes it to ").Append(paid).Append('.');
text.Append("\n\nThey answer the follow command, knit their own wounds shut, keep your truce with " +
"the mountain's dvergr, drop nothing, and do not come back. A dead crew is money spent.");
return text.ToString();
}
private static string CreatureName(string prefabName)
{
Character character = Jotunn.Managers.PrefabManager.Cache.GetPrefab<Character>(prefabName);
if (character == null || string.IsNullOrEmpty(character.m_name)) return prefabName;
return Localization.instance.Localize(character.m_name);
}
// ---------------------------------------------------------------- helpers
private static Sprite TrophyIcon(string prefabName)
{
if (string.IsNullOrEmpty(prefabName)) return null;
ItemDrop drop = Jotunn.Managers.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;
return icons != null && icons.Length > 0 ? icons[0] : null;
}
private static T FindDescendant<T>(Transform root, string childName) where T : Component
{
foreach (T candidate in root.GetComponentsInChildren<T>(true))
{
if (candidate.gameObject.name == childName) return candidate;
}
return null;
}
}
[HarmonyPatch(typeof(StoreGui), "Awake")]
public static class DvergarBancoStoreSetupPatch
{
public static void Postfix(StoreGui __instance) => DvergarBancoStore.Create(__instance);
}
[HarmonyPatch(typeof(StoreGui), "FillList")]
public static class DvergarBancoStoreFillPatch
{
public static void Postfix(StoreGui __instance) => DvergarBancoStore.Refresh(__instance);
}
[HarmonyPatch(typeof(StoreGui), "Hide")]
public static class DvergarBancoStoreHidePatch
{
public static void Postfix() => DvergarBancoStore.Clear();
}
}

View file

@ -0,0 +1,309 @@
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using HarmonyLib;
using Jotunn.Configs;
using Jotunn.Entities;
using Jotunn.Managers;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The rune barrel: drink for a hired crew.
///
/// Second half of the Dvergar chain and the answer to "can they be given potions". They can, and it
/// costs the mercenaries nothing of their own - a creature carries an SEMan exactly like a player
/// does, so the barrel pours a vanilla consumable's own status effect straight into whoever is
/// standing around it. Nothing new had to be added to DvergarBanco.cs for this to work, which was
/// the whole point of choosing a barrel over a hand-held flask: the buff is something you PREPARE
/// before walking out, not a button you press mid-fight.
///
/// WHAT ACTUALLY WORKS IS NOT A DESIGN DECISION, IT IS A FACT ABOUT EACH POTION. A mead that heals
/// over time heals a dvergr; a mead that regenerates stamina does nothing at all, because a creature
/// has no stamina bar to fill. The barrel therefore refuses nothing and promises nothing - it pours
/// what you put in it. `dumppotions` at the bottom of this file is how the two lists were told
/// apart: it reads every consumable in ObjectDB and reports, by reflection, what its effect actually
/// carries, so no guess about a field name is involved.
///
/// The serving code is race-agnostic on purpose - it drinks to any RaisedThrall in range, whoever
/// raised it - but the piece itself is locked to the Dvergar like the bank. If another chain ever
/// wants a barrel of its own, the lock is the only line that has to change.
/// </summary>
public static class DvergarBotte
{
public const string PieceName = "DvergarRuneBarrel";
public const string PieceDisplayName = "Rune Barrel";
public const string RaceId = DvergarConfig.RaceId;
/// <summary>How many drinks it holds. One dose is one mercenary served, so twenty is four
/// rounds for a full five-crew bank and a reason to keep brewing.</summary>
public const int MaxDoses = 20;
/// <summary>
/// Who is close enough to be handed a cup. Deliberately a range around the BARREL rather than
/// "everyone bound to the bank": a crew that is out across the map following its master is not
/// at the table, and buffing it from three biomes away would make the barrel a remote control.
/// </summary>
public const float ServeRange = 30f;
private const float BarrelScale = 0.7f;
/// <summary>Dvergr brass and verdigris, so it does not read as the Fenrir's trough - which is
/// the same barrel, tinted brown and rather bigger.</summary>
private static readonly Color BarrelTint = new Color(0.30f, 0.42f, 0.40f, 1f);
public static void Register()
{
GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(PieceName, "piece_chest_barrel");
if (prefab == null)
{
Jotunn.Logger.LogWarning("[Dvergar] Could not clone piece_chest_barrel; the rune barrel is " +
"not registered.");
return;
}
// The barrel's Container is both the Hoverable and the Interactable, so a chest would
// swallow the click that fills it and the hover text that reports it. Same strip as the
// Fenrir trough, and the same reason.
foreach (Container container in prefab.GetComponentsInChildren<Container>(true))
{
if (container != null) Object.DestroyImmediate(container);
}
AswidBloodRefinery.StripOffensive(prefab, PieceName);
DvergarBotteBehaviour barrel = prefab.AddComponent<DvergarBotteBehaviour>();
foreach (Switch existing in prefab.GetComponentsInChildren<Switch>(true))
{
if (existing != null) Object.DestroyImmediate(existing);
}
barrel.m_switch = prefab.AddComponent<Switch>();
barrel.m_switch.m_name = PieceDisplayName;
prefab.transform.localScale = Vector3.one * BarrelScale;
Recolour(prefab, BarrelTint);
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("MeadHealthMinor") ?? BorrowIcon("TrophyDvergr");
Piece template = PrefabManager.Cache.GetPrefab<Piece>("piece_workbench");
if (template != null && template.m_placeEffect != null) piece.m_placeEffect = template.m_placeEffect;
// Cheap on purpose. The barrel is not the cost - the potions poured into it are, forever.
PieceManager.Instance.AddPiece(new CustomPiece(prefab, fixReference: false, new PieceConfig
{
Name = PieceDisplayName,
Description = "Pour a brew in and the crew drinks. What it does to them is whatever it " +
"would have done to you - if they have the parts for it.",
PieceTable = PieceTables.Hammer,
Category = PieceCategories.Crafting,
Icon = BorrowIcon("MeadHealthMinor") ?? BorrowIcon("TrophyDvergr"),
Requirements = new[]
{
new RequirementConfig("FineWood", 10, 0, true),
new RequirementConfig("BlackMarble", 5, 0, true),
new RequirementConfig("Sap", 1, 0, true),
}
}));
}
// ---------------------------------------------------------------- what a brew is
/// <summary>
/// The status effect a consumable would hand to whoever drank it, or null if the item is not a
/// drink at all. This is the ONLY test the barrel makes: anything with an effect on it can go
/// in, and whether that effect means anything to a dvergr is the potion's business, not ours.
/// </summary>
public static StatusEffect BrewEffect(string prefabName)
{
if (string.IsNullOrEmpty(prefabName)) return null;
ItemDrop drop = PrefabManager.Cache.GetPrefab<ItemDrop>(prefabName);
if (drop == null || drop.m_itemData == null || drop.m_itemData.m_shared == null) return null;
return drop.m_itemData.m_shared.m_consumeStatusEffect;
}
public static bool IsBrew(string prefabName) => BrewEffect(prefabName) != null;
public static string BrewDisplayName(string prefabName)
{
ItemDrop drop = PrefabManager.Cache.GetPrefab<ItemDrop>(prefabName);
if (drop == null || drop.m_itemData == null || drop.m_itemData.m_shared == null) return prefabName;
return Localization.instance.Localize(drop.m_itemData.m_shared.m_name);
}
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
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;
return icons != null && icons.Length > 0 ? icons[0] : 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 DvergarBotteKnownPatch
{
public static void Postfix(Player __instance)
{
if (__instance != Player.m_localPlayer) return;
DvergarBotte.EnsureKnown(__instance);
}
}
[HarmonyPatch(typeof(Player), "PlacePiece",
new[] { typeof(Piece), typeof(Vector3), typeof(Quaternion), typeof(bool) })]
public static class DvergarBotteRaceLockPatch
{
public static bool Prefix(Player __instance, Piece __0)
{
if (__instance != Player.m_localPlayer || __0 == null) return true;
if (Utils.GetPrefabName(__0.gameObject) != DvergarBotte.PieceName) return true;
if (DvergarRace.IsDvergar()) return true;
__instance.Message(MessageHud.MessageType.Center, "You do not know what goes in it.");
return false;
}
}
/// <summary>
/// [DEBUG] Every drinkable in the game, and what its effect ACTUALLY carries.
///
/// Written because "which potions work on a mercenary" cannot be answered from the names: two meads
/// with almost the same label can be a heal-over-time and a stamina regen, and only one of those
/// means anything to a creature. Reading the effect is the answer, and reading it BY REFLECTION is
/// what makes this command safe to write without knowing a single field name of this build's
/// StatusEffect classes - a renamed or missing field is one line that does not print, not a
/// compile error and not a wrong answer.
///
/// dumppotions every consumable with an effect
/// dumppotions mead only the ones whose prefab name contains "mead"
/// </summary>
public class DumpPotionsCommand : ConsoleCommand
{
public override string Name => "dumppotions";
public override string Help =>
"[DEBUG] Lists every consumable with a status effect and what that effect carries, so it " +
"can be told whether a mercenary would feel it. Optional filter: dumppotions <substring>.";
public override void Run(string[] args)
{
if (ObjectDB.instance == null)
{
Console.instance.Print("ObjectDB is not up yet - be in a world.");
return;
}
string filter = args.Length > 0 ? args[0].ToLowerInvariant() : null;
int found = 0;
foreach (GameObject item in ObjectDB.instance.m_items)
{
if (item == null) continue;
if (filter != null && !item.name.ToLowerInvariant().Contains(filter)) continue;
ItemDrop drop = item.GetComponent<ItemDrop>();
if (drop == null || drop.m_itemData == null || drop.m_itemData.m_shared == null) continue;
StatusEffect effect = drop.m_itemData.m_shared.m_consumeStatusEffect;
if (effect == null) continue;
found++;
Jotunn.Logger.LogInfo($"[Potion] {item.name} ({effect.GetType().Name} '{effect.name}')" +
$"\n {Describe(effect)}");
}
string message = found == 0
? "No consumable carried a status effect - check the filter."
: $"{found} drinkable(s) written to the log with everything their effect carries.";
Console.instance.Print(message);
Jotunn.Logger.LogInfo($"[Potion] {message}");
}
/// <summary>
/// Every public field of the effect that is not at its default, as "name=value". Reflection
/// rather than a hand-written list of fields: this build's StatusEffect subclasses are whatever
/// they are, and the whole point of the command is to find that out instead of assuming it.
/// </summary>
private static string Describe(StatusEffect effect)
{
StringBuilder text = new StringBuilder();
foreach (FieldInfo field in effect.GetType().GetFields(BindingFlags.Public | BindingFlags.Instance))
{
object value = field.GetValue(effect);
if (IsDefault(value)) continue;
// Collections and objects are reported as "present" rather than dumped - what matters
// is whether the effect has any, not what is in them.
string printed;
if (value is float f) printed = f.ToString("0.###");
else if (value is int || value is bool || value is string) printed = value.ToString();
else if (value is System.Collections.ICollection collection) printed = $"[{collection.Count}]";
else printed = value.GetType().Name;
if (text.Length > 0) text.Append(", ");
text.Append(field.Name).Append('=').Append(printed);
}
return text.Length > 0 ? text.ToString() : "(carries nothing - a flavour effect only)";
}
private static bool IsDefault(object value)
{
if (value == null) return true;
if (value is float f) return Mathf.Approximately(f, 0f);
if (value is int i) return i == 0;
if (value is bool b) return !b;
if (value is string s) return string.IsNullOrEmpty(s);
if (value is System.Collections.ICollection collection) return collection.Count == 0;
// A Unity object reference that has been destroyed compares equal to null.
if (value is Object unityObject) return unityObject == null;
return false;
}
}
}

View file

@ -0,0 +1,267 @@
using System.Collections.Generic;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The barrel's logic: one brew at a time, one dose per mercenary, poured by hand.
///
/// Two gestures on one key, and the split is the same one the bank uses:
/// - a potion USED on the barrel fills it (and tops it up, if it is the same brew);
/// - a bare E pours a round - and fills it from your pack first if it is empty, so the common
/// case is one click rather than the inventory dance. The Fenrir trough does the same thing
/// with meat, for the same reason.
///
/// Serving is MANUAL and never automatic. An automatic barrel would drink itself dry keeping a
/// buff up on a crew that is standing still doing nothing, and the whole point of a barrel over a
/// flask was that the buff is something you spend on purpose before walking out.
///
/// HONEST LIMIT, in the shape this project writes them: the round is poured by the client that
/// clicked. It claims ownership of each mercenary before adding the effect, so the effect is
/// simulated by someone who has it - but a mercenary that is not loaded on that client cannot be
/// served at all, and in multiplayer the dose count can be spent twice if two players click in the
/// same instant. Neither is worth a handshake for a barrel of mead.
/// </summary>
public class DvergarBotteBehaviour : MonoBehaviour
{
public Switch m_switch;
private const string KeyBrew = "RoV_dvergarBotteBrew";
private const string KeyDoses = "RoV_dvergarBotteDoses";
private ZNetView m_nview;
private void Awake()
{
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_DvergarBotteFill", RPC_Fill);
m_nview.Register<int>("RoV_DvergarBotteSpend", RPC_Spend);
}
// ---------------------------------------------------------------- interaction
private bool OnUse(Switch caller, Humanoid user, ItemDrop.ItemData item)
{
Player player = user as Player;
if (player == null) return false;
Inventory inventory = player.GetInventory();
if (inventory == null) return false;
// A drink handed to the barrel always fills it, whatever is already in there.
if (item != null)
{
string prefabName = item.m_dropPrefab != null ? item.m_dropPrefab.name : null;
if (!DvergarBotte.IsBrew(prefabName))
{
player.Message(MessageHud.MessageType.Center, "$msg_wontwork");
return false;
}
return Fill(player, inventory, item, prefabName);
}
// Bare hands: pour a round if there is one, otherwise go looking for something to pour.
if (GetDoses() > 0) return Serve(player);
ItemDrop.ItemData found = FindAnyBrew(inventory);
if (found == null)
{
player.Message(MessageHud.MessageType.Center, "It is empty, and so are you.");
return false;
}
return Fill(player, inventory, found, found.m_dropPrefab.name);
}
private ItemDrop.ItemData FindAnyBrew(Inventory inventory)
{
foreach (ItemDrop.ItemData candidate in inventory.GetAllItems())
{
if (candidate == null || candidate.m_dropPrefab == null) continue;
if (DvergarBotte.IsBrew(candidate.m_dropPrefab.name)) return candidate;
}
return null;
}
// ---------------------------------------------------------------- filling
/// <summary>
/// Pours a stack in. One brew at a time: a barrel holding two different meads would have to
/// decide which one a mercenary gets, and there is no answer to that which is not arbitrary.
/// </summary>
private bool Fill(Player player, Inventory inventory, ItemDrop.ItemData item, string prefabName)
{
string current = GetBrew();
if (!string.IsNullOrEmpty(current) && current != prefabName && GetDoses() > 0)
{
player.Message(MessageHud.MessageType.Center,
$"There is still {DvergarBotte.BrewDisplayName(current)} in it.");
return false;
}
int room = DvergarBotte.MaxDoses - GetDoses();
if (room <= 0)
{
player.Message(MessageHud.MessageType.Center, "$msg_itsfull");
return false;
}
int poured = Mathf.Min(room, Mathf.Max(1, item.m_stack));
inventory.RemoveItem(item, poured);
m_nview.InvokeRPC("RoV_DvergarBotteFill", prefabName, poured);
player.Message(MessageHud.MessageType.Center,
$"$msg_added {DvergarBotte.BrewDisplayName(prefabName)} x{poured}");
return true;
}
private void RPC_Fill(long sender, string prefabName, int count)
{
if (!m_nview.IsOwner()) return;
if (count < 1) return;
// A barrel that has been drunk dry forgets what it held, so the next brew can be anything.
string current = GetBrew();
if (string.IsNullOrEmpty(current) || GetDoses() <= 0) m_nview.GetZDO().Set(KeyBrew, prefabName);
else if (current != prefabName) return;
SetDoses(GetDoses() + count);
}
// ---------------------------------------------------------------- serving
/// <summary>
/// One round: every mercenary in reach gets a cup, and every cup is a dose. Whoever is out of
/// range or already dead simply is not served - there is no queue and no leftovers.
/// </summary>
private bool Serve(Player player)
{
string brew = GetBrew();
StatusEffect effect = DvergarBotte.BrewEffect(brew);
if (effect == null)
{
player.Message(MessageHud.MessageType.Center, "Whatever is in it does nothing to anyone.");
return false;
}
List<RaisedThrall> drinkers = InRange();
if (drinkers.Count == 0)
{
player.Message(MessageHud.MessageType.Center, "Nobody is at the barrel.");
return false;
}
int doses = GetDoses();
int served = 0;
foreach (RaisedThrall thrall in drinkers)
{
if (served >= doses) break;
if (Pour(thrall, effect)) served++;
}
if (served == 0)
{
player.Message(MessageHud.MessageType.Center, "Not a drop went down.");
return false;
}
m_nview.InvokeRPC("RoV_DvergarBotteSpend", served);
string what = DvergarBotte.BrewDisplayName(brew);
player.Message(MessageHud.MessageType.Center, served < drinkers.Count
? $"{served} drink {what}. The barrel runs dry."
: $"{served} drink {what}.");
return true;
}
/// <summary>
/// Hands one creature the drink. The effect object is passed the same way vanilla passes it
/// when a player swallows a potion - Humanoid.UseItem does exactly this - so whatever SEMan
/// does with the shared asset internally, it is what the game already does to itself.
/// </summary>
private static bool Pour(RaisedThrall thrall, StatusEffect effect)
{
Character character = thrall != null ? thrall.GetComponent<Character>() : null;
if (character == null || character.IsDead()) return false;
// Claimed so that the client pouring is the one simulating the effect. Without this the
// drink would tick on a machine that does not own the creature, which for a heal-over-time
// means it quietly does nothing.
ZNetView nview = character.GetComponent<ZNetView>();
if (nview != null && nview.IsValid()) nview.ClaimOwnership();
character.GetSEMan().AddStatusEffect(effect, true);
return true;
}
private List<RaisedThrall> InRange()
{
List<RaisedThrall> near = new List<RaisedThrall>();
foreach (Character character in Character.GetAllCharacters())
{
if (character == null || character.IsDead()) continue;
RaisedThrall thrall = character.GetComponent<RaisedThrall>();
if (thrall == null) continue;
if (Vector3.SqrMagnitude(character.transform.position - transform.position) >
DvergarBotte.ServeRange * DvergarBotte.ServeRange) continue;
near.Add(thrall);
}
return near;
}
private void RPC_Spend(long sender, int count)
{
if (!m_nview.IsOwner()) return;
SetDoses(GetDoses() - Mathf.Max(0, count));
}
// ---------------------------------------------------------------- state and display
private string GetBrew() =>
m_nview != null && m_nview.IsValid() ? m_nview.GetZDO().GetString(KeyBrew, "") : "";
private int GetDoses() =>
m_nview != null && m_nview.IsValid() ? m_nview.GetZDO().GetInt(KeyDoses, 0) : 0;
private void SetDoses(int value)
{
if (m_nview == null || !m_nview.IsValid()) return;
m_nview.GetZDO().Set(KeyDoses, Mathf.Clamp(value, 0, DvergarBotte.MaxDoses));
}
private string Hover()
{
int doses = GetDoses();
string brew = GetBrew();
string body;
if (doses <= 0 || string.IsNullOrEmpty(brew))
{
body = "empty\n[<color=yellow><b>$KEY_Use</b></color>] Pour a brew in";
}
else
{
int waiting = InRange().Count;
body = $"{DvergarBotte.BrewDisplayName(brew)} {doses}/{DvergarBotte.MaxDoses}" +
$"\n{waiting} at the barrel" +
$"\n[<color=yellow><b>$KEY_Use</b></color>] Pour a round";
}
return Localization.instance.Localize($"{DvergarBotte.PieceDisplayName} ({body})");
}
}
}

View file

@ -28,6 +28,14 @@ namespace RacesOfValheim
public void CreateModAssets()
{
DvergarStatusEffects.RegisterStatusEffects();
// The contract bank and every mercenary it can hire. Race-locked at placement, like the
// Trol's war totem and unlike every other station in the mod.
DvergarBanco.Register();
// The barrel the crews drink from. Separate piece, no dependency in either direction:
// it serves whatever RaisedThrall is standing near it.
DvergarBotte.Register();
}
/// <summary>