RacesOfValheim/JotunnModStub/Dvergar/DvergarBanco.cs
kanym b3edb2aed1 feat: marble Bone Servant tables, bigger centred props, fix table hover name
The Smith's and Cook's Tables clone the black marble table: the
cartography table's map is baked into its texture. Anvil or meal and a
skull sit near the centre at the table's measured height. The bank loses
its lantern and its tankard grows. The servant table hover localizes its
title, which showed as a raw token once a servant stood there.
2026-10-28 13:22:56 +01:00

484 lines
25 KiB
C#

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 = "$rov_piece_dvergar_contractbank_name";
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;
// The dressing, in the same unscaled table space as the pile. The pile owns the centre, so the
// tankard stands just clear of it, on the near side.
private static readonly Color BankWoodTint = new Color(0.62f, 0.55f, 0.5f, 1f);
private static readonly Vector3 TankardSpot = new Vector3(0.45f, PileHeight, -0.25f);
private const float TankardSize = 0.38f;
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 = "$rov_troop_dvergar_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 = "$rov_troop_dvergar_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 = "$rov_troop_dvergar_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 = "$rov_troop_dvergar_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 = "$rov_troop_dvergar_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,
"rov_msg_build_limit_dvergar_contractbank");
}
// ---------------------------------------------------------------- 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 = "$rov_msg_thrall_refusal_dvergar";
// 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;
// A counting table, not a map table: darker wood and a dvergr tankard beside the coin.
// Tinted BEFORE the tankard goes on, or it would be darkened too.
PieceLook.Tint(prefab.transform, BankWoodTint);
ModelBorrow.Attach(prefab.transform, "BankTankard", "Tankard_dvergr",
TankardSpot, Quaternion.identity, TankardSize, "Dvergar", activeOnly: true);
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;
// DISABLED ON PURPOSE, and it is the line that keeps the log clean. Trader was written for
// Haldor, who is a creature with an animator and a LookAt rig: Trader.Update() calls
// m_animator.SetBool("Stand", ...) and m_lookAt.ResetTarget() with no null check on every
// frame no player is nearby, and Trader.Start() calls InvokeRepeating("RandomTalk", 0, 0)
// on a component nobody authored in the editor. On a table both of those are null, so the
// bank threw a NullReferenceException every frame from the moment it was built. A disabled
// component runs neither, and StoreGui needs neither: Show() only reads fields off the
// Trader and asks it for its item list, and GetComponent finds it disabled just the same.
// This is the same fix SvermHiveStore.Mount already carries for the Hive Market.
trader.enabled = false;
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;
// Neither flag, like the Bone Pile. m_groundPiece made Player.UpdatePlacementGhost switch
// the ghost off outright wherever the aim was not terrain - floors, rocks, a troll cave's
// mesh floor - so players saw no ghost at all and could not tell why. A station belongs
// in a house or a cave as much as outside.
piece.m_groundPiece = false;
piece.m_groundOnly = false;
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 = "$rov_piece_dvergar_contractbank_desc",
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>
// Valheim 1.0 appended a 'bool cheated' parameter to this overload. The type array has to
// match it exactly or the patch silently fails to bind and PatchAll throws.
[HarmonyPatch(typeof(Player), "PlacePiece",
new[] { typeof(Piece), typeof(Vector3), typeof(Quaternion), typeof(bool), 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, ModText.Get("rov_msg_dvergar_contract_runic_do_not_sign"));
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));
}
}
}