diff --git a/JotunnModStub/Butler/BoneServant.cs b/JotunnModStub/Butler/BoneServant.cs new file mode 100644 index 0000000..bbd9147 --- /dev/null +++ b/JotunnModStub/Butler/BoneServant.cs @@ -0,0 +1,292 @@ +using HarmonyLib; +using Jotunn.Configs; +using Jotunn.Entities; +using Jotunn.Managers; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// The two Bone Servants and their tables. Servants that work the stations around them and never + /// lift a hand against anything. + /// + /// TWO TRADES, and that was the first thing the working version asked for. One servant serving a + /// whole yard spends its life walking: with the kitchen at one edge of the circle and the furnaces + /// at the other, travel eats the margin that keeps food off the fire. So there is a SMITH for the + /// Smelter family and a COOK for cooking stations and mead, each with its own table, each with its + /// own twenty-metre circle - and the two circles may sit on top of each other, because the servants + /// never look at the same station. PieceDensityLimit counts by prefab name, so "no second table + /// within forty metres" keeps smith away from smith and cook away from cook, and needed no change + /// at all to let a smith and a cook stand side by side. + /// + /// The smith keeps the ORIGINAL prefab names, BoneServant and ServantTable. That is not tidiness - + /// it means a table already standing in a test world keeps working and keeps its servant instead of + /// becoming a missing prefab at the next load. + /// + /// TWO PREFABS EACH, forced the same way the sentry's are: a Character cannot sit in the hammer's + /// piece table, so the buildable thing is the table and the servant is instantiated by it. Unlike + /// the sentry there is no seed piece to throw away, because here the table is not scaffolding - it + /// is the anchor, the summoning point and the only interface the feature has. + /// + /// WHAT WAS DELIBERATELY NOT REUSED. The design said the servant would be a RaisedThrall, and it is + /// not. RaisedThrall brings the anchor, the leash and the withering, all of which are wanted - but + /// it also brings RaisedThrallInteractPatch, which turns E on the creature into a follow command. + /// A servant that can be told to follow you out of its own circle is a servant that stops serving, + /// and "E does nothing on the servant" was decided explicitly. So the useful half is reused as a + /// static - RaisedThrall.RegisterStation / StationStandsAt, which is what makes the table findable - + /// and the anchor and wither clock are thirty lines inside BoneServantAI. The alternative was + /// editing RaisedThrall.cs, which is shared with five other chains. + /// + public static class BoneServant + { + // The smith inherits the names the single servant had, so nothing already built is orphaned. + public const string SmithName = "BoneServant"; + public const string SmithTableName = "ServantTable"; + public const string SmithDisplay = "Bone Smith"; + public const string SmithTableDisplay = "Smith's Table"; + + public const string CookName = "BoneCook"; + public const string CookTableName = "CookTable"; + public const string CookDisplay = "Bone Cook"; + public const string CookTableDisplay = "Cook's Table"; + + /// Vanilla's guaranteed-melee skeleton: the plain one rolls its own weapon, and the + /// point here is to have none at all. + private const string ServantSource = "Skeleton_NoArcher"; + + public const float Health = 100f; + + /// Two circles of twenty metres cannot overlap if the tables are forty apart, which is + /// how the question of two servants of the SAME trade fighting over one chest was answered - by + /// making the situation impossible to build rather than by sharing state between them. + public const float TableSpacing = 40f; + + private const float TableScale = 0.8f; + + /// + /// One skull, one wishbone, eight stone - the same price for both tables. + /// + /// The skull is TrophySkeleton and NOT this mod's own CursedSkull, and that is forced rather + /// than chosen: the cursed skull is bought from the Skeleton faction's merchant, so building it + /// into the cook's price would make the cook unbuildable by the only race allowed to build it. + /// A skeleton trophy is a skull anyone can go and get. + /// + /// The wishbone is a real cost and worth knowing about: it is Bonemass's drop and the only + /// treasure-finder in the game, so a standing table keeps yours locked up. Recovered in full + /// when the table is removed, like every other recipe in this mod. + /// + private static RequirementConfig[] Recipe() + { + return new[] + { + new RequirementConfig("TrophySkeleton", 1, 0, true), + new RequirementConfig("Wishbone", 1, 0, true), + new RequirementConfig("Stone", 8, 0, true), + }; + } + + public static void Register() + { + if (RegisterServant(SmithName, SmithDisplay, ButlerFamily.Forge)) + { + RegisterTable(SmithTableName, SmithTableDisplay, SmithName, ButlerFamily.Forge, + "A slab of bone and slate, dusted with ore. Something patient waits by the fires.", + "Coal"); + + PieceDensityLimit.Register(SmithTableName, TableSpacing, 1, + "Another smith's table stands within forty paces. One smith to a yard."); + + // Two races, and it is the wider of the two locks: the Skeleton raises the dead to work + // for it, and Skadi's hold is a forge under ice. + PieceDensityLimit.RegisterGate(SmithTableName, (player, position) => + { + if (SkeletonRace.IsSkeleton() || SkadiRace.IsLocalSkadi()) return true; + + if (player != null) + { + player.Message(MessageHud.MessageType.Center, + "The bones do not answer to your blood."); + } + return false; + }); + } + + if (RegisterServant(CookName, CookDisplay, ButlerFamily.Kitchen)) + { + RegisterTable(CookTableName, CookTableDisplay, CookName, ButlerFamily.Kitchen, + "A slab of bone and slate, worn smooth. Something patient waits by the hearth.", + "CookedMeat"); + + PieceDensityLimit.Register(CookTableName, TableSpacing, 1, + "Another cook's table stands within forty paces. One cook to a yard."); + + // Skadi alone. A hearth kept by something dead is hers, not the Skeleton's. + PieceDensityLimit.RegisterGate(CookTableName, (player, position) => + { + if (SkadiRace.IsLocalSkadi()) return true; + + if (player != null) + { + player.Message(MessageHud.MessageType.Center, + "Only Skadi's hearth is kept by the dead."); + } + return false; + }); + } + } + + // ---------------------------------------------------------------- the servants + + private static bool RegisterServant(string prefabName, string displayName, ButlerFamily family) + { + GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(prefabName, ServantSource); + if (prefab == null) + { + Jotunn.Logger.LogWarning($"[Butler] Could not clone {ServantSource}; " + + $"{displayName} is not registered."); + return false; + } + + Character character = prefab.GetComponent(); + if (character != null) + { + character.m_name = displayName; + character.m_health = Health; + character.m_faction = Character.Faction.Players; + } + + // Nothing in its hands, and nothing to roll for. Belt and braces with the AI prefix: the + // code that would swing a weapon never runs, but a servant carrying a rusty sword around + // the kitchen would still look like a mistake. + Humanoid humanoid = prefab.GetComponent(); + if (humanoid != null) + { + humanoid.m_defaultItems = new GameObject[0]; + humanoid.m_randomWeapon = new GameObject[0]; + humanoid.m_randomArmor = new GameObject[0]; + humanoid.m_randomShield = new GameObject[0]; + humanoid.m_randomSets = new Humanoid.ItemSet[0]; + } + + BaseAI ai = prefab.GetComponent(); + if (ai != null) + { + ai.m_randomMoveRange = 0f; // it never wanders: every step it takes is a decision + ai.m_avoidFire = false; // it works next to kilns for a living + ai.m_afraidOfFire = false; + } + + // A servant that dropped bones would be a bone mill, exactly as with the garrison. + foreach (CharacterDrop drops in prefab.GetComponentsInChildren(true)) + { + if (drops != null) Object.DestroyImmediate(drops); + } + + // Ten seconds unhurt, then two percent a second. The sentry's regeneration, whole. + prefab.AddComponent(); + + BoneServantAI servant = prefab.AddComponent(); + servant.m_family = family; + + PrefabManager.Instance.AddPrefab(prefab); + return true; + } + + // ---------------------------------------------------------------- the tables + + private static void RegisterTable(string pieceName, string displayName, string servantPrefab, + ButlerFamily family, string description, string iconSource) + { + GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(pieceName, "piece_cartographytable"); + if (prefab == null) + { + Jotunn.Logger.LogWarning($"[Butler] Could not clone piece_cartographytable; " + + $"the {displayName} is not registered."); + return; + } + + // The MapTable trap, and it is the reason this is a blanket sweep by capability rather than + // a named DestroyImmediate: MapTable is Interactable AND Hoverable, so it takes the E key + // before our own Switch ever sees it and opens the shared map instead. Same bug as the + // barrel's Container on the Fenrir trough and the Trader on the vanilla wolf; the Dvergar + // contract bank pays for this lesson already. + foreach (MonoBehaviour behaviour in prefab.GetComponentsInChildren(true)) + { + if (behaviour == null) continue; + if (behaviour is Piece || behaviour is ZNetView || behaviour is WearNTear) continue; + Object.DestroyImmediate(behaviour); + } + + prefab.transform.localScale = Vector3.one * TableScale; + + ServantTableBehaviour table = prefab.AddComponent(); + table.m_switch = prefab.AddComponent(); + table.m_switch.m_name = displayName; + table.m_title = displayName; + table.m_servantPrefab = servantPrefab; + table.m_family = family; + + Sprite icon = BorrowIcon(iconSource) ?? BorrowIcon("TrophySkeleton"); + + Piece piece = prefab.GetComponent() ?? prefab.AddComponent(); + piece.m_craftingStation = null; + piece.m_resources = new Piece.Requirement[0]; + piece.m_name = displayName; + piece.m_canBeRemoved = true; + piece.m_groundPiece = true; + piece.m_groundOnly = true; + piece.m_icon = icon; + + Piece template = PrefabManager.Cache.GetPrefab("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 = displayName, + Description = description, + PieceTable = PieceTables.Hammer, + Category = PieceCategories.Crafting, + Icon = icon, + Requirements = Recipe(), + })); + } + + public static void EnsureKnown(Player player) + { + if (player == null) return; + + Traverse traverse = Traverse.Create(player); + LearnPiece(traverse, SmithTableName); + LearnPiece(traverse, CookTableName); + traverse.Method("UpdateAvailablePiecesList").GetValue(); + } + + private static void LearnPiece(Traverse player, string pieceName) + { + GameObject prefab = PrefabManager.Instance.GetPrefab(pieceName); + Piece piece = prefab != null ? prefab.GetComponent() : null; + if (piece == null) return; + + player.Method("AddKnownPiece", piece).GetValue(); + } + + private static Sprite BorrowIcon(string prefabName) + { + ItemDrop drop = PrefabManager.Cache.GetPrefab(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 BoneServantKnownPatch + { + public static void Postfix(Player __instance) + { + if (__instance != Player.m_localPlayer) return; + BoneServant.EnsureKnown(__instance); + } + } +} diff --git a/JotunnModStub/Butler/BoneServantAI.cs b/JotunnModStub/Butler/BoneServantAI.cs new file mode 100644 index 0000000..c6eee21 --- /dev/null +++ b/JotunnModStub/Butler/BoneServantAI.cs @@ -0,0 +1,1286 @@ +using System.Collections.Generic; +using System.Text; +using HarmonyLib; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// The Bone Servant's own head. Everything it does is here; vanilla's MonsterAI never runs on it. + /// + /// HOW IT MOVES, which was the one open question in the design and is answered here rather than in + /// the doc. Three candidates were on the table: a ghost follow-target, pinning m_patrolPoint the way + /// RaisedThrall does, and calling BaseAI.MoveTo directly. The IL settled it: + /// + /// - BaseAI has NO Update and NO FixedUpdate. UpdateAI(dt) is driven centrally by + /// MonoUpdaters.FixedUpdate over BaseAI.Instances, and that list is maintained by OnEnable / + /// OnDisable. So "disable the AI and drive MoveTo yourself" kills the only thing that would + /// call anything: a disabled BaseAI is not ticked at all. That candidate is dead. + /// - BaseAI.UpdateAI itself does almost nothing - IsOwner, UpdateTakeoffLanding, + /// UpdateRegeneration - so skipping it costs a flying check we do not need and a regeneration + /// we already have from SkeletonSentryBehaviour. + /// + /// So: a PREFIX on MonsterAI.UpdateAI that hands the tick to this class and returns false. The + /// servant keeps its place in the central tick, keeps vanilla pathing through BaseAI.MoveTo, and + /// vanilla's own AI - targeting, fleeing, wandering, attacking - never executes a single line. That + /// is also why the servant cannot fight: not because its weapon was taken (it was), but because the + /// code that would swing it is never reached. + /// + /// MoveTo(dt, point, dist, run) is private, hence the cached MethodInfo. It returns TRUE on arrival + /// (read in the IL: DistanceXZ under the threshold calls StopMoving and returns 1), which is the + /// whole arrival test - no distance maths of our own. + /// + /// THE PAYLOAD IS VIRTUAL. The servant has no inventory. Every station's input RPC takes a STRING, + /// so what it carries is a list of prefab names and counts in its own ZDO, which survives saving, + /// zone reload and - the case that matters - a change of owner mid-job in multiplayer. The one + /// thing this costs is that the goods do not exist as objects while in transit, so they have to be + /// put back into the world by hand if the servant dies holding them. That is , + /// and it is the reason nothing here can quietly delete a player's ore. + /// + public class BoneServantAI : MonoBehaviour + { + // ─── ZDO keys ──────────────────────────────────────────────────────── + public const string KeyAnchor = "RoV_butlerAnchor"; + public const string KeyOrphanAt = "RoV_butlerOrphanAt"; + public const string KeyLoad = "RoV_butlerLoad"; + public const string KeySource = "RoV_butlerSource"; + public const string KeyTarget = "RoV_butlerTarget"; + public const string KeyStatus = "RoV_butlerStatus"; + + /// Written into a STATION's ZDO: the chest whose material is in it right now, so the + /// product goes home to where the raw came from even after a reload, and even if a different + /// client collects it. + public const string KeyFedBy = "RoV_butlerFedBy"; + + // ─── numbers that are not worth a config entry ─────────────────────── + private const float PlanInterval = 1.5f; + + /// + /// How close is close enough. Measured to the piece's ORIGIN, which on a furnace or a kiln sits + /// inside a metre or so of solid collider - so anything tight enough to look like hugging the + /// thing is a distance the servant can never actually reach, and it would time out and put a + /// perfectly good station in the penalty box. Two and a half metres is roughly where a player + /// stands to use one. + /// + private const float ArriveDistance = 2.5f; + + private const float CollectRadius = 3.5f; + private const float JobTimeout = 25f; + private const float PenaltySeconds = 180f; + + /// Set aside briefly when a job was reached but achieved nothing. Without this, a job + /// that arrives and finds nothing to do is re-planned identically on the next tick and the + /// servant stands there deciding the same thing forever. + private const float ShortPenaltySeconds = 20f; + private const float FleeSeconds = 6f; + private const float WitherSeconds = 30f; + private const float HomeCheckRange = 25f; + + /// A cooking slot inside this many seconds of burning outranks everything else. Twelve + /// seconds is a walk of about twenty metres with room to spare, which is the whole radius. + private const float SpoilPanicSeconds = 12f; + + /// How long a station may sit unserved before its wait starts outweighing distance. + /// This is what stops a furnace at the edge of the circle from starving while the servant + /// shuttles between two closer ones. + private const float WaitToMetres = 0.25f; + + private const int PayloadCap = 120; + + private static readonly System.Reflection.MethodInfo MoveToMethod = + AccessTools.Method(typeof(BaseAI), "MoveTo", + new[] { typeof(float), typeof(Vector3), typeof(float), typeof(bool) }); + + private static readonly System.Reflection.FieldInfo AllPiecesField = + AccessTools.Field(typeof(Piece), "s_allPieces"); + + private static readonly System.Reflection.MethodInfo ContainerSaveMethod = + AccessTools.Method(typeof(Container), "Save"); + + private static int s_itemMask = -1; + + /// Which stations this one serves. Set on the prefab at registration, so it travels + /// with every instance the table raises. + public ButlerFamily m_family = ButlerFamily.Forge; + + private ZNetView m_nview; + private Character m_character; + private MonsterAI m_ai; + + private readonly object[] m_moveArgs = new object[4]; + private readonly List m_payload = new List(); + private readonly Dictionary m_penalties = new Dictionary(); + private readonly Dictionary m_idleSince = new Dictionary(); + + private readonly List m_stations = new List(); + private readonly List m_chests = new List(); + private float m_scannedAt = -99f; + + private Job m_job; + private float m_nextPlan; + private float m_jobDeadline; + private float m_fleeUntil; + private string m_status = ""; + + private class Load + { + public string Name; + public int Count; + } + + private class Job + { + public string Kind; // load | fuel | collect | deposit | drop + public ZDOID Target; + public Vector3 Point; + public bool Hurry; + public string Label; + } + + // ================================================================ life + + private void Awake() + { + m_nview = GetComponent(); + m_character = GetComponent(); + m_ai = GetComponent(); + + ReadPayload(); + } + + private void OnDestroy() + { + // Only a DEATH scatters the load. A zone unloading destroys this object too, and there the + // payload must stay in the ZDO where it will be read again on the way back in - dropping it + // would mint a copy every time the player walked away. + if (m_character != null && m_character.IsDead()) DropPayload(); + } + + /// Called by the table the moment it raises one. + public void Bind(Vector3 anchor) + { + if (m_nview == null || !m_nview.IsValid()) return; + + m_nview.GetZDO().Set(KeyAnchor, anchor); + + if (m_ai != null) m_ai.MakeTame(); + if (m_character != null) m_character.SetTamed(true); + } + + public Vector3? Anchor + { + get + { + if (m_nview == null || !m_nview.IsValid()) return null; + + Vector3 anchor = m_nview.GetZDO().GetVec3(KeyAnchor, Vector3.zero); + return anchor == Vector3.zero ? (Vector3?)null : anchor; + } + } + + public bool IsBoundTo(Vector3 anchor) + { + Vector3? own = Anchor; + return own != null && Vector3.SqrMagnitude(own.Value - anchor) < 0.25f; + } + + /// The one line the table's hover shows. Read from the ZDO so a client that does not + /// own the servant still sees what it is doing. + public string Status + { + get + { + if (m_nview == null || !m_nview.IsValid()) return m_status; + return m_nview.GetZDO().GetString(KeyStatus, m_status); + } + } + + private void SetStatus(string text) + { + if (text == m_status) return; + + m_status = text; + if (m_nview != null && m_nview.IsValid() && m_nview.IsOwner()) + { + m_nview.GetZDO().Set(KeyStatus, text); + } + } + + /// Hit by something: stop working and walk home. It never fights back - there is + /// nothing in this class that could. + public void NoteDamage() + { + m_fleeUntil = Time.time + FleeSeconds; + m_job = null; + } + + // ================================================================ the tick + + /// Everything. Returns what MonsterAI.UpdateAI would have returned. + public bool Tick(float dt) + { + if (m_nview == null || !m_nview.IsValid() || !m_nview.IsOwner()) return false; + if (m_character == null || m_character.IsDead()) return false; + + if (TickWither()) return true; + + if (Time.time < m_fleeUntil) + { + SetStatus("Driven off."); + GoHome(dt); + return true; + } + + if (Time.time >= m_nextPlan) + { + m_nextPlan = Time.time + PlanInterval; + Plan(); + } + + Execute(dt); + return true; + } + + /// + /// The table is gone: start the clock, and stop when it runs out. Same shape as RaisedThrall's, + /// and deliberately only asked near home - further out the table's zone is simply not loaded, so + /// "nothing there" would be a lie. + /// + private bool TickWither() + { + Vector3? anchor = Anchor; + if (anchor == null || ZNet.instance == null) return false; + + long stamp = m_nview.GetZDO().GetLong(KeyOrphanAt, 0L); + + if (stamp == 0L) + { + if (Vector3.SqrMagnitude(transform.position - anchor.Value) > + HomeCheckRange * HomeCheckRange) return false; + if (RaisedThrall.StationStandsAt(anchor.Value)) return false; + + m_nview.GetZDO().Set(KeyOrphanAt, ZNet.instance.GetTime().Ticks); + return false; + } + + if (RaisedThrall.StationStandsAt(anchor.Value)) + { + m_nview.GetZDO().Set(KeyOrphanAt, 0L); + return false; + } + + double elapsed = (ZNet.instance.GetTime() - new System.DateTime(stamp)).TotalSeconds; + if (elapsed < WitherSeconds) return false; + + HitData hit = new HitData(); + hit.m_damage.m_damage = 1E+10f; + hit.m_hitType = HitData.HitType.Undefined; + m_character.ApplyDamage(hit, true, false); + return true; + } + + // ================================================================ planning + + private void Plan() + { + Vector3? anchor = Anchor; + if (anchor == null) { m_job = null; return; } + + Scan(anchor.Value); + ExpirePenalties(); + + if (m_payload.Count > 0) { m_job = PlanDelivery(anchor.Value); return; } + + // The forge has no clock: a smelter holds its ore indefinitely and puts its own output on + // the floor, so PlanRescue would ask a question whose answer is always no. The smith is a + // four-state machine and the cook is a five-state one, and that is the whole of the + // simplification the split bought. + Job job = m_family == ButlerFamily.Kitchen ? PlanRescue() : null; + job = job ?? PlanCollect() ?? PlanLoad() ?? PlanFuel(); + + if (job != null && (m_job == null || m_job.Kind != job.Kind || m_job.Target != job.Target)) + { + m_jobDeadline = Time.time + JobTimeout; + } + m_job = job; + } + + /// + /// Everything within the radius, once every planning tick. Piece.s_allPieces is the cheap way in + /// - it is the list the game already keeps of every built piece - so there is no OverlapSphere + /// and no guessing at layer masks for the part that runs constantly. + /// + private void Scan(Vector3 anchor) + { + if (Time.time - m_scannedAt < PlanInterval * 0.5f) return; + m_scannedAt = Time.time; + + m_stations.Clear(); + m_chests.Clear(); + + List pieces = AllPiecesField != null ? AllPiecesField.GetValue(null) as List : null; + if (pieces == null) return; + + float radius = ButlerConfig.WorkRadius.Value; + float radiusSq = radius * radius; + + for (int i = 0; i < pieces.Count; i++) + { + Piece piece = pieces[i]; + if (piece == null) continue; + if (Vector3.SqrMagnitude(piece.transform.position - anchor) > radiusSq) continue; + + // A station of the other trade is not this servant's business, but it is still not a + // chest - hence the continue either way. + ButlerStation station = ButlerStation.From(piece.gameObject); + if (station != null) + { + if (station.Family == m_family) m_stations.Add(station); + continue; + } + + Container container = piece.GetComponent(); + if (container != null && IsSealed(container)) m_chests.Add(container); + } + } + + /// A chest is the servant's only if it holds the sigil. The sigil itself is never + /// counted as material and never carried away - see TakeFrom. + private static bool IsSealed(Container container) + { + if (container == null || container.IsInUse()) return false; + + Inventory inventory = container.GetInventory(); + if (inventory == null) return false; + + string sigil = SigilSharedName(); + if (string.IsNullOrEmpty(sigil)) return false; + + return inventory.CountItems(sigil) > 0; + } + + private static string s_sigilShared; + private static string s_sigilFor; + + /// Inventory.CountItems matches on the SHARED name ($item_...), not on the prefab name + /// the stations use, so the configured prefab is resolved once into the other kind of name. + private static string SigilSharedName() + { + string wanted = ButlerConfig.SigilItem.Value; + if (s_sigilFor == wanted) return s_sigilShared; + + s_sigilFor = wanted; + s_sigilShared = null; + + GameObject prefab = ObjectDB.instance != null ? ObjectDB.instance.GetItemPrefab(wanted) : null; + ItemDrop drop = prefab != null ? prefab.GetComponent() : null; + if (drop != null && drop.m_itemData != null && drop.m_itemData.m_shared != null) + { + s_sigilShared = drop.m_itemData.m_shared.m_name; + } + else + { + Jotunn.Logger.LogWarning($"[Butler] No item '{wanted}' to use as the sigil; " + + "no chest can be marked until that name is right."); + } + + return s_sigilShared; + } + + // ---------------------------------------------------------------- the five states + + /// 1. SAVE. A slot about to burn beats everything, and it is the only job it runs to. + private Job PlanRescue() + { + ButlerStation best = null; + float soonest = SpoilPanicSeconds; + + foreach (ButlerStation station in m_stations) + { + if (!station.Alive || IsPenalised(station.Id)) continue; + if (!station.HasOutput) continue; // nothing pullable yet, panic changes nothing + + float left = station.SecondsToSpoil; + if (left >= soonest) continue; + + soonest = left; + best = station; + } + + if (best == null) return null; + + return new Job + { + Kind = "collect", + Target = best.Id, + Point = best.Position, + Hurry = true, + Label = "Saving the food", + }; + } + + /// 2. COLLECT. Anything finished, and anything already lying under a station. + private Job PlanCollect() + { + ButlerStation best = null; + float bestScore = float.MaxValue; + + foreach (ButlerStation station in m_stations) + { + if (!station.Alive || IsPenalised(station.Id)) continue; + if (!station.HasOutput && !HasDropsNear(station.Position)) continue; + + float score = Vector3.Distance(transform.position, station.Position); + if (score >= bestScore) continue; + + bestScore = score; + best = station; + } + + if (best == null) return null; + + return new Job + { + Kind = "collect", + Target = best.Id, + Point = best.Position, + Label = "Collecting", + }; + } + + /// + /// 3. LOAD. Urgency, then distance - and the urgency of a station with nothing wrong with it is + /// how long it has been waiting. A metre of walking is worth four seconds of a station standing + /// idle, so the far furnace wins eventually instead of never. + /// + private Job PlanLoad() + { + ButlerStation best = null; + string bestItem = null; + Container bestChest = null; + float bestScore = float.MaxValue; + + foreach (ButlerStation station in m_stations) + { + if (!station.Alive || IsPenalised(station.Id)) continue; + if (!station.Operable || station.FreeSlots <= 0) continue; + + Container chest; + string item = FindMaterialFor(station, out chest); + if (item == null) { m_idleSince.Remove(station.Id); continue; } + + float waited = NoteIdle(station.Id); + float score = Vector3.Distance(transform.position, chest.transform.position) + + Vector3.Distance(chest.transform.position, station.Position) - + waited * WaitToMetres; + + if (score >= bestScore) continue; + + bestScore = score; + best = station; + bestItem = item; + bestChest = chest; + } + + if (best == null) return null; + + // The chest first - the station is where the payload goes afterwards, and PlanDelivery + // works that out from the target written on the load. + return new Job + { + Kind = "load", + Target = ZdoOf(bestChest), + Point = bestChest.transform.position, + Label = "Fetching " + bestItem, + }; + } + + /// 4. REFUEL. Only stations that actually have something to work on. + private Job PlanFuel() + { + foreach (ButlerStation station in m_stations) + { + if (!station.Alive || IsPenalised(station.Id)) continue; + if (!station.Operable) continue; + + int wanted = station.FuelWanted; + if (wanted <= 0) continue; + + string fuel = station.FuelPrefab; + if (string.IsNullOrEmpty(fuel)) continue; + + Container chest = FindChestWith(fuel); + if (chest == null) continue; + + return new Job + { + Kind = "fuel", + Target = ZdoOf(chest), + Point = chest.transform.position, + Label = "Fetching " + fuel, + }; + } + + return null; + } + + /// Where the load in hand is going: on to its station, or back into a chest. + private Job PlanDelivery(Vector3 anchor) + { + ZDOID target = m_nview.GetZDO().GetZDOID(KeyTarget); + if (target != ZDOID.None) + { + // NO FreeSlots CHECK HERE, and that was the first bug found in play: fuel does not go + // into a slot. A furnace filled to m_maxOre with copper has FreeSlots 0 and still wants + // coal, so gating the delivery on free slots sent the servant back to the chest with + // the coal it had just fetched - and then PlanFuel sent it out for the same coal again, + // forever. AcceptsAnything already asks the right question of both doors. + ButlerStation station = StationById(target); + if (station != null && station.Alive && station.Operable && AcceptsAnything(station)) + { + return new Job + { + Kind = "deposit_station", + Target = target, + Point = station.Position, + Label = "Loading " + Describe(), + }; + } + + // The station is gone, full or cold. The goods are ours to put back, not to hold. + m_nview.GetZDO().Set(KeyTarget, ZDOID.None); + } + + Container chest = ChestForProduct(); + if (chest != null) + { + return new Job + { + Kind = "deposit", + Target = ZdoOf(chest), + Point = chest.transform.position, + Label = "Storing " + Describe(), + }; + } + + // Every sealed chest is full. Beside the table it goes: a stalled chain is worse than a + // tidy floor, and nothing may vanish (sec. 7.3). + return new Job + { + Kind = "drop", + Target = ZDOID.None, + Point = anchor, + Label = "Nowhere to put " + Describe(), + }; + } + + // ================================================================ execution + + private void Execute(float dt) + { + if (m_job == null) + { + SetStatus(m_stations.Count == 0 ? "Nothing to serve." : "Nothing to do."); + GoHome(dt); + return; + } + + SetStatus(m_job.Label); + + if (!MoveToPoint(dt, m_job.Point, ArriveDistance, m_job.Hurry)) + { + // Doors do not open for pathfinding. A target it cannot reach goes into the penalty box + // and the servant gets on with something it can do. + if (Time.time > m_jobDeadline) + { + Penalise(m_job.Target); + Jotunn.Logger.LogInfo($"[Butler] Could not reach {m_job.Kind} target; " + + "setting it aside for a few minutes."); + m_job = null; + m_nextPlan = 0f; + } + return; + } + + bool achieved; + switch (m_job.Kind) + { + case "load": achieved = DoLoad(); break; + case "fuel": achieved = DoFuel(); break; + case "collect": achieved = DoCollect(); break; + case "deposit_station": achieved = DoDepositStation(); break; + case "deposit": achieved = DoDeposit(); break; + case "drop": DropPayload(); achieved = true; break; + default: achieved = true; break; + } + + // Arrived and nothing happened: the world moved while it walked. Set that target aside for + // twenty seconds so the next plan picks something else instead of re-deciding the same + // errand on every tick. + if (!achieved) PenaliseShort(m_job.Target); + + m_job = null; + m_nextPlan = 0f; // arriving changes the world; re-plan on the next tick rather than in 1.5 s + } + + /// At the chest: take what the chosen station will eat, and remember where it came from. + private bool DoLoad() + { + Container chest = ContainerById(m_job.Target); + if (chest == null) return false; + + // The station is chosen again here rather than carried on the job, because the walk took + // time and the world may have moved on. + ButlerStation station = null; + string item = null; + + foreach (ButlerStation candidate in m_stations) + { + if (!candidate.Alive || !candidate.Operable || candidate.FreeSlots <= 0) continue; + if (IsPenalised(candidate.Id)) continue; + + string found = FirstAccepted(candidate, chest); + if (found == null) continue; + + station = candidate; + item = found; + break; + } + + if (station == null || item == null) return false; + + int taken = TakeFrom(chest, item, station.FreeSlots); + if (taken <= 0) return false; + + AddToPayload(item, taken); + m_nview.GetZDO().Set(KeySource, ZdoOf(chest)); + m_nview.GetZDO().Set(KeyTarget, station.Id); + WritePayload(); + return true; + } + + /// At the chest, for fuel. Same shape as DoLoad, and kept separate because fuel goes in + /// through a different door and is never the thing being processed. + private bool DoFuel() + { + Container chest = ContainerById(m_job.Target); + if (chest == null) return false; + + foreach (ButlerStation station in m_stations) + { + if (!station.Alive || !station.Operable || IsPenalised(station.Id)) continue; + + int wanted = station.FuelWanted; + string fuel = station.FuelPrefab; + if (wanted <= 0 || string.IsNullOrEmpty(fuel)) continue; + + int taken = TakeFrom(chest, fuel, wanted); + if (taken <= 0) continue; + + AddToPayload(fuel, taken); + m_nview.GetZDO().Set(KeySource, ZdoOf(chest)); + m_nview.GetZDO().Set(KeyTarget, station.Id); + WritePayload(); + return true; + } + + return false; + } + + /// + /// At a station with something finished. Pull first, sweep second - and the sweep is the only + /// place the servant ever picks anything up off the ground, which is what keeps it from tidying + /// away things the player left lying about on purpose. + /// + private bool DoCollect() + { + ButlerStation station = StationById(m_job.Target); + if (station == null || !station.Alive) return false; + + int before = PayloadCount(); + SweepDrops(station.Position); + bool swept = PayloadCount() > before; + + bool pulled = false; + if (station.HasOutput) + { + station.PullOutput(transform.position); + pulled = true; + } + + if (swept) + { + // The product belongs to whoever fed the station. If nothing was written there - the + // player loaded it by hand - it goes to the nearest sealed chest instead, which is the + // "yes, it collects your work too" decision paying its own way. + ZDOID fedBy = station.Nview.GetZDO().GetZDOID(KeyFedBy); + m_nview.GetZDO().Set(KeySource, fedBy); + m_nview.GetZDO().Set(KeyTarget, ZDOID.None); + WritePayload(); + } + + return swept || pulled; + } + + /// At the station, with raw material in hand. + private bool DoDepositStation() + { + ButlerStation station = StationById(m_job.Target); + if (station == null || !station.Alive || !station.Operable) return false; + + bool loadedAny = false; + + for (int i = m_payload.Count - 1; i >= 0; i--) + { + Load load = m_payload[i]; + + while (load.Count > 0 && station.FreeSlots > 0 && station.Accepts(load.Name)) + { + station.Add(load.Name); + load.Count--; + loadedAny = true; + } + + // Fuel goes in through its own door, and only for as long as it is wanted. + if (load.Count > 0 && load.Name == station.FuelPrefab) + { + int wanted = station.FuelWanted; + while (load.Count > 0 && wanted > 0) + { + station.AddFuel(); + load.Count--; + wanted--; + loadedAny = true; + } + } + + if (load.Count <= 0) m_payload.RemoveAt(i); + } + + if (loadedAny) + { + // Whoever fed it, gets it back. + ZDOID source = m_nview.GetZDO().GetZDOID(KeySource); + if (source != ZDOID.None && station.Nview.IsValid()) + { + if (!station.Nview.IsOwner()) station.Nview.ClaimOwnership(); + station.Nview.GetZDO().Set(KeyFedBy, source); + } + } + + if (m_payload.Count == 0) m_nview.GetZDO().Set(KeyTarget, ZDOID.None); + WritePayload(); + return loadedAny; + } + + /// At a chest, with the finished goods. + private bool DoDeposit() + { + Container chest = ContainerById(m_job.Target); + if (chest == null) return false; + + ZNetView nview = chest.GetComponent(); + if (nview == null || !nview.IsValid()) return false; + if (!nview.IsOwner()) nview.ClaimOwnership(); + + Inventory inventory = chest.GetInventory(); + if (inventory == null) return false; + + bool wrote = false; + + for (int i = m_payload.Count - 1; i >= 0; i--) + { + Load load = m_payload[i]; + + GameObject prefab = ObjectDB.instance != null + ? ObjectDB.instance.GetItemPrefab(load.Name) + : null; + if (prefab == null) continue; + + // One at a time: it stacks correctly, it stops exactly when the chest is full, and the + // counts are small enough that being tidy costs nothing. + while (load.Count > 0 && inventory.CanAddItem(prefab, 1) && inventory.AddItem(prefab, 1)) + { + load.Count--; + wrote = true; + } + + if (load.Count <= 0) m_payload.RemoveAt(i); + } + + if (wrote && ContainerSaveMethod != null) ContainerSaveMethod.Invoke(chest, null); + WritePayload(); + + // Still holding something: that chest is full, so do not choose it again on the next pass. + if (m_payload.Count > 0) Penalise(m_job.Target); + return wrote; + } + + // ================================================================ moving + + /// Vanilla pathing, through the private MoveTo. True the moment it has arrived. + private bool MoveToPoint(float dt, Vector3 point, float distance, bool run) + { + if (m_ai == null || MoveToMethod == null) return true; // cannot walk: act in place + + m_moveArgs[0] = dt; + m_moveArgs[1] = point; + m_moveArgs[2] = distance; + m_moveArgs[3] = run; + + return (bool)MoveToMethod.Invoke(m_ai, m_moveArgs); + } + + private void GoHome(float dt) + { + Vector3? anchor = Anchor; + if (anchor == null) + { + if (m_ai != null) m_ai.StopMoving(); + return; + } + + MoveToPoint(dt, anchor.Value, 2.5f, false); + } + + // ================================================================ the ground + + private static int ItemMask() + { + if (s_itemMask >= 0) return s_itemMask; + + int mask = LayerMask.GetMask("item"); + s_itemMask = mask != 0 ? mask : ~0; + return s_itemMask; + } + + private bool HasDropsNear(Vector3 point) + { + Collider[] hits = Physics.OverlapSphere(point, CollectRadius, ItemMask()); + foreach (Collider hit in hits) + { + if (hit == null) continue; + ItemDrop drop = hit.GetComponentInParent(); + if (drop != null && drop.m_itemData != null) return true; + } + return false; + } + + /// + /// Picks up everything lying around a station. The drop is destroyed and its contents become + /// entries in the virtual payload, which is the same road the smelter's bars, the oven's bread + /// and the fermenter's bottles all arrive by - one pickup routine for three families. + /// + private void SweepDrops(Vector3 point) + { + Collider[] hits = Physics.OverlapSphere(point, CollectRadius, ItemMask()); + + foreach (Collider hit in hits) + { + if (hit == null) continue; + if (PayloadCount() >= PayloadCap) return; + + ItemDrop drop = hit.GetComponentInParent(); + if (drop == null || drop.m_itemData == null) continue; + + ZNetView nview = drop.GetComponent(); + if (nview == null || !nview.IsValid()) continue; + if (!nview.IsOwner()) nview.ClaimOwnership(); + + string name = drop.m_itemData.m_dropPrefab != null + ? drop.m_itemData.m_dropPrefab.name + : Utils.GetPrefabName(drop.gameObject); + if (string.IsNullOrEmpty(name)) continue; + + AddToPayload(name, Mathf.Max(1, drop.m_itemData.m_stack)); + if (ZNetScene.instance != null) ZNetScene.instance.Destroy(drop.gameObject); + } + } + + /// + /// Puts the virtual load back into the world as real objects. Called when the servant dies and + /// when there is nowhere left to put anything - the two ends of the same promise, which is that + /// nothing the player owns is ever deleted by this feature. + /// + public void DropPayload() + { + if (m_payload.Count == 0) return; + if (ObjectDB.instance == null) { m_payload.Clear(); return; } + + Vector3 at = transform.position + Vector3.up * 0.4f; + + foreach (Load load in m_payload) + { + GameObject prefab = ObjectDB.instance.GetItemPrefab(load.Name); + ItemDrop template = prefab != null ? prefab.GetComponent() : null; + if (template == null || template.m_itemData == null) continue; + + int left = load.Count; + int max = Mathf.Max(1, template.m_itemData.m_shared.m_maxStackSize); + + while (left > 0) + { + int stack = Mathf.Min(left, max); + ItemDrop.DropItem(template.m_itemData.Clone(), stack, + at + Random.insideUnitSphere * 0.3f, Quaternion.identity); + left -= stack; + } + } + + m_payload.Clear(); + WritePayload(); + } + + // ================================================================ chests + + /// + /// Takes up to of a prefab out of a chest. The sigil is skipped by name, + /// which is the one thing in here that must never be got wrong: carrying it off would unmark the + /// chest halfway through a job. + /// + private int TakeFrom(Container chest, string prefabName, int want) + { + if (chest == null || want <= 0) return 0; + if (prefabName == ButlerConfig.SigilItem.Value) return 0; + + ZNetView nview = chest.GetComponent(); + if (nview == null || !nview.IsValid()) return 0; + if (!nview.IsOwner()) nview.ClaimOwnership(); + + Inventory inventory = chest.GetInventory(); + if (inventory == null) return 0; + + List matches = new List(); + foreach (ItemDrop.ItemData item in inventory.GetAllItems()) + { + if (item == null || item.m_dropPrefab == null) continue; + if (item.m_dropPrefab.name != prefabName) continue; + matches.Add(item); + } + + int taken = 0; + foreach (ItemDrop.ItemData item in matches) + { + if (taken >= want) break; + + int amount = Mathf.Min(item.m_stack, want - taken); + if (amount <= 0) continue; + + inventory.RemoveItem(item, amount); + taken += amount; + } + + if (taken > 0 && ContainerSaveMethod != null) ContainerSaveMethod.Invoke(chest, null); + return taken; + } + + /// The first thing in any sealed chest that this station will take. + private string FindMaterialFor(ButlerStation station, out Container chest) + { + foreach (Container candidate in m_chests) + { + if (candidate == null || candidate.IsInUse()) continue; + + string item = FirstAccepted(station, candidate); + if (item == null) continue; + + chest = candidate; + return item; + } + + chest = null; + return null; + } + + private string FirstAccepted(ButlerStation station, Container chest) + { + Inventory inventory = chest != null ? chest.GetInventory() : null; + if (inventory == null) return null; + + string sigil = ButlerConfig.SigilItem.Value; + string fuel = station.FuelPrefab; + + foreach (ItemDrop.ItemData item in inventory.GetAllItems()) + { + if (item == null || item.m_dropPrefab == null) continue; + + string name = item.m_dropPrefab.name; + if (name == sigil) continue; + if (name == fuel) continue; // fuel has its own errand + if (!station.Accepts(name)) continue; + + return name; + } + + return null; + } + + private Container FindChestWith(string prefabName) + { + foreach (Container chest in m_chests) + { + if (chest == null || chest.IsInUse()) continue; + + Inventory inventory = chest.GetInventory(); + if (inventory == null) continue; + + foreach (ItemDrop.ItemData item in inventory.GetAllItems()) + { + if (item != null && item.m_dropPrefab != null && item.m_dropPrefab.name == prefabName) + { + return chest; + } + } + } + + return null; + } + + /// Where the finished goods go: the chest that fed the station, or the nearest sealed + /// one with room if that chest is gone, full, or never existed. + private Container ChestForProduct() + { + ZDOID source = m_nview.GetZDO().GetZDOID(KeySource); + + Container home = ContainerById(source); + if (home != null && !IsPenalised(source) && HasRoomFor(home)) return home; + + Container best = null; + float bestDistance = float.MaxValue; + + foreach (Container chest in m_chests) + { + if (chest == null || chest.IsInUse()) continue; + if (IsPenalised(ZdoOf(chest))) continue; + if (!HasRoomFor(chest)) continue; + + float distance = Vector3.Distance(transform.position, chest.transform.position); + if (distance >= bestDistance) continue; + + bestDistance = distance; + best = chest; + } + + return best; + } + + private bool HasRoomFor(Container chest) + { + Inventory inventory = chest != null ? chest.GetInventory() : null; + if (inventory == null || ObjectDB.instance == null) return false; + + foreach (Load load in m_payload) + { + GameObject prefab = ObjectDB.instance.GetItemPrefab(load.Name); + if (prefab != null && inventory.CanAddItem(prefab, 1)) return true; + } + + return false; + } + + // ================================================================ payload + + private bool AcceptsAnything(ButlerStation station) + { + foreach (Load load in m_payload) + { + if (station.Accepts(load.Name)) return true; + if (load.Name == station.FuelPrefab && station.FuelWanted > 0) return true; + } + return false; + } + + private void AddToPayload(string name, int count) + { + if (string.IsNullOrEmpty(name) || count <= 0) return; + + foreach (Load load in m_payload) + { + if (load.Name != name) continue; + load.Count += count; + WritePayload(); + return; + } + + m_payload.Add(new Load { Name = name, Count = count }); + WritePayload(); + } + + private int PayloadCount() + { + int total = 0; + foreach (Load load in m_payload) total += load.Count; + return total; + } + + private string Describe() + { + if (m_payload.Count == 0) return "nothing"; + if (m_payload.Count == 1) return m_payload[0].Count + "x " + m_payload[0].Name; + + return PayloadCount() + " items"; + } + + /// "Copper:8;Coal:12". Small, readable in a ZDO dump, and enough to survive a handover + /// mid-job - which is the whole reason the payload lives in the ZDO instead of in this class. + private void WritePayload() + { + if (m_nview == null || !m_nview.IsValid()) return; + + StringBuilder builder = new StringBuilder(); + foreach (Load load in m_payload) + { + if (load.Count <= 0) continue; + if (builder.Length > 0) builder.Append(';'); + builder.Append(load.Name).Append(':').Append(load.Count); + } + + m_nview.GetZDO().Set(KeyLoad, builder.ToString()); + } + + private void ReadPayload() + { + m_payload.Clear(); + if (m_nview == null || !m_nview.IsValid()) return; + + string raw = m_nview.GetZDO().GetString(KeyLoad, ""); + if (string.IsNullOrEmpty(raw)) return; + + foreach (string entry in raw.Split(';')) + { + if (string.IsNullOrEmpty(entry)) continue; + + int split = entry.LastIndexOf(':'); + if (split <= 0) continue; + + int count; + if (!int.TryParse(entry.Substring(split + 1), out count) || count <= 0) continue; + + m_payload.Add(new Load { Name = entry.Substring(0, split), Count = count }); + } + } + + // ================================================================ small change + + private static ZDOID ZdoOf(Component component) + { + ZNetView nview = component != null ? component.GetComponent() : null; + return nview != null && nview.IsValid() ? nview.GetZDO().m_uid : ZDOID.None; + } + + private Container ContainerById(ZDOID id) + { + if (id == ZDOID.None || ZNetScene.instance == null) return null; + + GameObject go = ZNetScene.instance.FindInstance(id); + return go != null ? go.GetComponent() : null; + } + + private ButlerStation StationById(ZDOID id) + { + foreach (ButlerStation station in m_stations) + { + if (station.Id == id) return station; + } + + if (id == ZDOID.None || ZNetScene.instance == null) return null; + + GameObject go = ZNetScene.instance.FindInstance(id); + return go != null ? ButlerStation.From(go) : null; + } + + private void Penalise(ZDOID id) + { + if (id == ZDOID.None) return; + m_penalties[id] = Time.time + PenaltySeconds; + } + + /// Never shortens a penalty already running: a target set aside for three minutes + /// because it could not be reached must not be let back in after twenty seconds. + private void PenaliseShort(ZDOID id) + { + if (id == ZDOID.None) return; + + float until; + float wanted = Time.time + ShortPenaltySeconds; + if (m_penalties.TryGetValue(id, out until) && until > wanted) return; + + m_penalties[id] = wanted; + } + + private bool IsPenalised(ZDOID id) + { + float until; + return m_penalties.TryGetValue(id, out until) && Time.time < until; + } + + private void ExpirePenalties() + { + if (m_penalties.Count == 0) return; + + List done = null; + foreach (KeyValuePair entry in m_penalties) + { + if (Time.time < entry.Value) continue; + if (done == null) done = new List(); + done.Add(entry.Key); + } + + if (done == null) return; + foreach (ZDOID id in done) m_penalties.Remove(id); + } + + /// Seconds this station has been waiting with work available. + private float NoteIdle(ZDOID id) + { + float since; + if (!m_idleSince.TryGetValue(id, out since)) + { + m_idleSince[id] = Time.time; + return 0f; + } + + return Time.time - since; + } + } + + /// + /// The whole of the servant's mind, in one prefix. + /// + /// Returning false skips MonsterAI.UpdateAI entirely - targeting, alerting, fleeing, wandering and + /// attacking with it - so the servant is peaceful by construction rather than by having its weapon + /// confiscated. __result is legitimate here and not the old PlacePiece trap: that one threw because + /// the patched method was VOID. This one returns bool, which is exactly what a prefix may write. + /// + /// Bound positionally (__0) so a parameter rename in a future patch cannot stop the mod from + /// applying its patches at startup. + /// + [HarmonyPatch(typeof(MonsterAI), "UpdateAI")] + public static class BoneServantUpdateAIPatch + { + public static bool Prefix(MonsterAI __instance, float __0, ref bool __result) + { + if (__instance == null) return true; + + BoneServantAI servant = __instance.GetComponent(); + if (servant == null) return true; + + __result = servant.Tick(__0); + return false; + } + } + + /// Hit and it walks home. The same postfix shape the sentry's regeneration uses, on the + /// same method, which is a shape known to work in this project. + [HarmonyPatch(typeof(Character), "Damage")] + public static class BoneServantDamagePatch + { + public static void Postfix(Character __instance) + { + if (__instance == null) return; + + BoneServantAI servant = __instance.GetComponent(); + if (servant != null) servant.NoteDamage(); + } + } +} diff --git a/JotunnModStub/Butler/ButlerConfig.cs b/JotunnModStub/Butler/ButlerConfig.cs new file mode 100644 index 0000000..c7ac2f6 --- /dev/null +++ b/JotunnModStub/Butler/ButlerConfig.cs @@ -0,0 +1,50 @@ +using BepInEx.Configuration; + +namespace RacesOfValheim +{ + /// + /// The four knobs the Bone Servant exposes, and deliberately only four. + /// + /// Butler_BoneServant.txt sec. 14 turned down "expose everything": tick cadence, safety margins, + /// penalty-box time and the spacing between tables are constants in the code, because they are + /// numbers that get tuned once during the test and then never again - and every config entry is + /// maintained forever. + /// + /// The sigil is here for a different reason from the other three. It is a PLACEHOLDER: bone + /// fragments stand in for a craftable sigil that only gets made if the feature leaves the test, + /// and being able to move the mark onto another item without a rebuild is the whole point of the + /// entry. + /// + public static class ButlerConfig + { + public static ConfigEntry SigilItem; + public static ConfigEntry WorkRadius; + public static ConfigEntry FuelThreshold; + public static ConfigEntry ResummonSeconds; + + public static void Bind(ConfigFile config) + { + const string section = "Butler - Bone Servant"; + + SigilItem = config.Bind(section, "Sigil Item", "BoneFragments", + new ConfigDescription("Prefab name of the item that marks a chest as the servant's. " + + "A chest holding at least one of these is worked from and " + + "delivered to; every other chest is left alone. The sigil itself " + + "is never taken and never processed.")); + + WorkRadius = config.Bind(section, "Work Radius", 20f, + new ConfigDescription("Metres from the Servant's Table within which chests and stations " + + "are served.", new AcceptableValueRange(5f, 40f))); + + FuelThreshold = config.Bind(section, "Fuel Threshold", 0.25f, + new ConfigDescription("Refuel a station when its fuel drops below this fraction of its " + + "maximum, and only while it has something to work on.", + new AcceptableValueRange(0f, 1f))); + + ResummonSeconds = config.Bind(section, "Resummon Cooldown", 0f, + new ConfigDescription("Seconds that must pass before a fallen servant can be raised " + + "again. Zero is free and immediate, which is what the test runs on.", + new AcceptableValueRange(0f, 600f))); + } + } +} diff --git a/JotunnModStub/Butler/ButlerStation.cs b/JotunnModStub/Butler/ButlerStation.cs new file mode 100644 index 0000000..2b47de5 --- /dev/null +++ b/JotunnModStub/Butler/ButlerStation.cs @@ -0,0 +1,496 @@ +using System; +using System.Reflection; +using HarmonyLib; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// Which servant a station belongs to. + /// + /// The split is not cosmetic, it is the answer to the one complaint the first working version drew: + /// with a kitchen at one edge of the circle and three furnaces at the other, a single servant spends + /// its life walking and the margin that keeps food off the fire gets eaten by travel. Two servants + /// with two tables in the same yard walk half as far each. + /// + /// It also cuts the AI in half along a seam that was already there. FORGE cannot spoil - a smelter + /// holds its ore forever and drops its own output - so the forge servant has no clock, never runs, + /// and never pre-empts itself. All of that machinery lives on in the KITCHEN, which is the only + /// place it was ever needed. + /// + public enum ButlerFamily + { + /// Smelter: furnace, blast furnace, charcoal kiln, windmill, spinning wheel, eitr + /// refinery. Nothing here has a deadline. + Forge, + + /// CookingStation and Fermenter: hearths, ovens and mead. The only family with a + /// clock. + Kitchen, + } + + /// + /// One working station, seen through the handful of questions the servant ever asks it. + /// + /// THREE FAMILIES, and they are not variations on a theme - they behave OPPOSITELY on output, which + /// is the single fact the whole feature is built around (Butler_BoneServant.txt sec. 5, all of it + /// read off assembly_valheim.dll with Cecil rather than guessed): + /// + /// Smelter furnace, blast furnace, charcoal kiln, windmill, spinning wheel, eitr + /// refinery. Its output FALLS ON THE GROUND BY ITSELF - UpdateSmelter runs + /// RemoveOneOre -> QueueProcessed -> SpawnProcessed with nobody asking. Nothing + /// to pull; the servant just picks the bars up. + /// CookingStation hearth, iron cooking station, stone oven. Output STAYS IN THE SLOT and keeps + /// cooking: Done at m_cookTime, Burnt at exactly twice it (verified: the IL + /// literally loads m_cookTime, pushes 2 and multiplies). This is the family that + /// can lose you food, and the only one with a clock. + /// Fermenter mead. Output stays in until the tap is opened, and never spoils. + /// + /// NOTHING HERE KNOWS WHAT A MATERIAL IS. Every family exposes IsItemAllowed(string) and + /// GetItemConversion(string), matching on the PREFAB name (m_from.gameObject.name - verified), so + /// the servant asks the station "do you take this?" instead of carrying a list of ores and crops. + /// That is what makes it serve this mod's own stations, other races' stations, and other mods' + /// stations without a line of code per station. + /// + /// WHY SO MUCH REFLECTION. Every one of those question methods is PRIVATE in this build - + /// GetQueueSize, IsItemAllowed, GetSlot, GetFuel, HaveDoneItem, IsFireLit, GetStatus, the lot - and + /// both Status enums are private nested types, so they cannot even be named in source. The + /// alternative was reimplementing each station's rules by reading its public m_conversion list, + /// which would be a second copy of vanilla's logic drifting out of step at the next patch. Calling + /// the real method through a cached MethodInfo is the smaller lie. The enum values are hard-coded + /// as ints, and they are not guesses: Cecil reports NotDone=0, Done=1, Burnt=2 and Empty=0, + /// Fermenting=1, Exposed=2, Ready=3. + /// + /// Every write goes through InvokeRPC with the name the station REGISTERED, which carries the + /// "RPC_" prefix in this build - "RPC_AddOre", not "AddOre". A wrong name here is a silent no-op, + /// which is exactly the class of bug that takes an evening to find, so the four names below were + /// read out of each Awake() rather than remembered. + /// + public abstract class ButlerStation + { + public Component Behaviour; + public ZNetView Nview; + public Transform Transform; + + public Vector3 Position { get { return Transform.position; } } + + public ZDOID Id + { + get { return Nview != null && Nview.IsValid() ? Nview.GetZDO().m_uid : ZDOID.None; } + } + + public bool Alive { get { return Behaviour != null && Nview != null && Nview.IsValid(); } } + + /// Wraps whichever of the three this object is, or null if it is not a station. + public static ButlerStation From(GameObject go) + { + if (go == null) return null; + + ZNetView nview = go.GetComponent(); + if (nview == null || !nview.IsValid()) return null; + + Smelter smelter = go.GetComponent(); + if (smelter != null) return Fill(new SmelterStation { m_smelter = smelter }, smelter, nview); + + CookingStation cooking = go.GetComponent(); + if (cooking != null) return Fill(new CookingStationStation { m_cooking = cooking }, cooking, nview); + + Fermenter fermenter = go.GetComponent(); + if (fermenter != null) return Fill(new FermenterStation { m_fermenter = fermenter }, fermenter, nview); + + return null; + } + + private static ButlerStation Fill(ButlerStation station, Component behaviour, ZNetView nview) + { + station.Behaviour = behaviour; + station.Nview = nview; + station.Transform = behaviour.transform; + return station; + } + + /// + /// Taking ownership before writing is the multiplayer rule of this feature (sec. 10), and it + /// buys a second thing that matters here: once we own the ZDO the RPC runs locally and + /// immediately, so GetQueueSize and GetFuel answer truthfully on the very next line instead of + /// a network round trip later. + /// + protected void Claim() + { + if (Nview != null && Nview.IsValid() && !Nview.IsOwner()) Nview.ClaimOwnership(); + } + + // ---------------------------------------------------------------- what the servant asks + + /// Which of the two servants this one belongs to. + public abstract ButlerFamily Family { get; } + + /// Can it work at all right now - fire lit, roof up? An inoperable station is skipped + /// in silence, which is a decision and not an oversight (sec. 7.7). + public abstract bool Operable { get; } + + /// How many more items it can take. Zero means full. + public abstract int FreeSlots { get; } + + public abstract bool Accepts(string prefabName); + + /// Puts one unit in. Called FreeSlots times at most, never more. + public abstract void Add(string prefabName); + + /// True while it has something to work on - so an empty furnace is never stoked. + public abstract bool HasWork { get; } + + public abstract string FuelPrefab { get; } + + /// Units of fuel it wants right now, already filtered by the configured threshold. + public abstract int FuelWanted { get; } + + public abstract void AddFuel(); + + /// Something finished and needs a hand to get out. Always false for the Smelter, which + /// throws its own output on the floor. + public abstract bool HasOutput { get; } + + /// Gets the finished goods onto the ground at , where the one + /// pickup routine will find them. + public abstract void PullOutput(Vector3 at); + + /// Seconds until something in here is ruined. float.MaxValue for the two families that + /// cannot spoil, which is what keeps the urgency comparison honest without special cases. + public virtual float SecondsToSpoil { get { return float.MaxValue; } } + + // ================================================================ the private doors + + /// + /// Every private member of the three station classes this feature touches, resolved once. + /// + /// Anything that fails to resolve stays null and its caller falls back to the safe answer - + /// "cannot tell, do not act" - so a future patch that renames one method costs that one + /// capability and a line in the log, not a servant that stands still or, worse, one that keeps + /// pouring ore into a station it can no longer read. + /// + private static class Vanilla + { + public static readonly MethodInfo SmelterQueueSize = AccessTools.Method(typeof(Smelter), "GetQueueSize"); + public static readonly MethodInfo SmelterAllowed = + AccessTools.Method(typeof(Smelter), "IsItemAllowed", new[] { typeof(string) }); + public static readonly MethodInfo SmelterFuel = AccessTools.Method(typeof(Smelter), "GetFuel"); + public static readonly FieldInfo SmelterHaveRoof = AccessTools.Field(typeof(Smelter), "m_haveRoof"); + + public static readonly MethodInfo CookGetSlot = AccessTools.Method(typeof(CookingStation), "GetSlot"); + public static readonly MethodInfo CookEmpty = AccessTools.Method(typeof(CookingStation), "IsEmpty"); + public static readonly MethodInfo CookHaveDone = AccessTools.Method(typeof(CookingStation), "HaveDoneItem"); + public static readonly MethodInfo CookAllowed = + AccessTools.Method(typeof(CookingStation), "IsItemAllowed", new[] { typeof(string) }); + public static readonly MethodInfo CookConversion = + AccessTools.Method(typeof(CookingStation), "GetItemConversion", new[] { typeof(string) }); + public static readonly MethodInfo CookFuel = AccessTools.Method(typeof(CookingStation), "GetFuel"); + public static readonly MethodInfo CookFireLit = AccessTools.Method(typeof(CookingStation), "IsFireLit"); + + public static readonly MethodInfo FermenterStatus = AccessTools.Method(typeof(Fermenter), "GetStatus"); + public static readonly MethodInfo FermenterAllowed = + AccessTools.Method(typeof(Fermenter), "IsItemAllowed", new[] { typeof(string) }); + + // CookingStation.Status and Fermenter.Status are private nested enums: they cannot be named + // in source, so they travel as ints. Values read from the assembly, not assumed. + public const int CookNotDone = 0; + public const int CookDone = 1; + public const int CookBurnt = 2; + + public const int FermentEmpty = 0; + public const int FermentExposed = 2; + public const int FermentReady = 3; + + public static bool Call(MethodInfo method, object target, bool fallback) + { + if (method == null) return fallback; + return (bool)method.Invoke(target, null); + } + + public static int CallInt(MethodInfo method, object target, int fallback) + { + if (method == null) return fallback; + return Convert.ToInt32(method.Invoke(target, null)); + } + + public static float CallFloat(MethodInfo method, object target, float fallback) + { + if (method == null) return fallback; + return Convert.ToSingle(method.Invoke(target, null)); + } + + public static bool Allowed(MethodInfo method, object target, string prefabName) + { + if (method == null || string.IsNullOrEmpty(prefabName)) return false; + return (bool)method.Invoke(target, new object[] { prefabName }); + } + } + + // ================================================================ Smelter + + private class SmelterStation : ButlerStation + { + public Smelter m_smelter; + + public override ButlerFamily Family { get { return ButlerFamily.Forge; } } + + public override bool Operable + { + get + { + if (!m_smelter.m_requiresRoof) return true; + if (Vanilla.SmelterHaveRoof == null) return true; // cannot tell: let it try + return (bool)Vanilla.SmelterHaveRoof.GetValue(m_smelter); + } + } + + private int Queued { get { return Vanilla.CallInt(Vanilla.SmelterQueueSize, m_smelter, int.MaxValue); } } + + public override int FreeSlots + { + get { return Mathf.Max(0, m_smelter.m_maxOre - Queued); } + } + + public override bool Accepts(string prefabName) + { + return Vanilla.Allowed(Vanilla.SmelterAllowed, m_smelter, prefabName); + } + + public override void Add(string prefabName) + { + Claim(); + Nview.InvokeRPC("RPC_AddOre", prefabName); + } + + public override bool HasWork { get { return Queued > 0; } } + + public override string FuelPrefab + { + get { return m_smelter.m_fuelItem != null ? m_smelter.m_fuelItem.gameObject.name : null; } + } + + public override int FuelWanted + { + get + { + if (m_smelter.m_fuelItem == null || m_smelter.m_maxFuel <= 0) return 0; + if (!HasWork) return 0; + + float fuel = Vanilla.CallFloat(Vanilla.SmelterFuel, m_smelter, float.MaxValue); + if (fuel >= m_smelter.m_maxFuel * ButlerConfig.FuelThreshold.Value) return 0; + + return Mathf.Max(0, Mathf.FloorToInt(m_smelter.m_maxFuel - fuel)); + } + } + + public override void AddFuel() + { + Claim(); + Nview.InvokeRPC("RPC_AddFuel"); + } + + // The whole point of this family: nothing to collect, it drops its own. + public override bool HasOutput { get { return false; } } + public override void PullOutput(Vector3 at) { } + } + + // ================================================================ CookingStation + + private class CookingStationStation : ButlerStation + { + public CookingStation m_cooking; + + public override ButlerFamily Family { get { return ButlerFamily.Kitchen; } } + + private int SlotCount + { + get { return m_cooking.m_slots != null ? m_cooking.m_slots.Length : 0; } + } + + /// GetSlot hands back three values through out parameters, one of which is a + /// private enum. Through reflection that means an args array and an int. + private bool ReadSlot(int index, out string name, out float cooked, out int status) + { + name = null; + cooked = 0f; + status = Vanilla.CookNotDone; + + if (Vanilla.CookGetSlot == null) return false; + + object[] args = new object[] { index, null, null, null }; + Vanilla.CookGetSlot.Invoke(m_cooking, args); + + name = args[1] as string; + cooked = Convert.ToSingle(args[2]); + status = Convert.ToInt32(args[3]); + return true; + } + + public override bool Operable + { + get { return !m_cooking.m_requireFire || Vanilla.Call(Vanilla.CookFireLit, m_cooking, false); } + } + + public override int FreeSlots + { + get + { + int free = 0; + for (int i = 0; i < SlotCount; i++) + { + string name; + float cooked; + int status; + if (!ReadSlot(i, out name, out cooked, out status)) return 0; + if (string.IsNullOrEmpty(name)) free++; + } + return free; + } + } + + public override bool Accepts(string prefabName) + { + return Vanilla.Allowed(Vanilla.CookAllowed, m_cooking, prefabName); + } + + public override void Add(string prefabName) + { + Claim(); + Nview.InvokeRPC("RPC_AddItem", prefabName); + } + + public override bool HasWork { get { return !Vanilla.Call(Vanilla.CookEmpty, m_cooking, true); } } + + public override string FuelPrefab + { + get + { + return m_cooking.m_useFuel && m_cooking.m_fuelItem != null + ? m_cooking.m_fuelItem.gameObject.name + : null; + } + } + + public override int FuelWanted + { + get + { + if (!m_cooking.m_useFuel || m_cooking.m_fuelItem == null || m_cooking.m_maxFuel <= 0) return 0; + if (!HasWork) return 0; + + float fuel = Vanilla.CallFloat(Vanilla.CookFuel, m_cooking, float.MaxValue); + if (fuel >= m_cooking.m_maxFuel * ButlerConfig.FuelThreshold.Value) return 0; + + return Mathf.Max(0, Mathf.FloorToInt(m_cooking.m_maxFuel - fuel)); + } + } + + public override void AddFuel() + { + Claim(); + Nview.InvokeRPC("RPC_AddFuel"); + } + + public override bool HasOutput { get { return Vanilla.Call(Vanilla.CookHaveDone, m_cooking, false); } } + + /// + /// ONE per done slot, and the 1 is not a stylistic choice. RPC_RemoveDoneItem spawns the + /// item amount times PER SLOT (verified in the IL: the inner loop runs to the + /// argument), so passing anything above 1 would not collect faster - it would print money. + /// + public override void PullOutput(Vector3 at) + { + Claim(); + Nview.InvokeRPC("RPC_RemoveDoneItem", at, 1); + } + + /// + /// The clock this whole feature exists for. Done at m_cookTime, Burnt at 2x - so what is + /// left is 2*cookTime - cookedTime, and a slot already Done is the urgent one because its + /// remaining half is all that stands between dinner and charcoal. + /// + /// GetItemConversion is asked with whatever name the slot currently holds, which is the raw + /// item before Done and the COOKED one after: CookingStation.GetItemConversion matches on + /// both m_from and m_to (verified), so the cook time is readable in either phase. + /// + public override float SecondsToSpoil + { + get + { + if (Vanilla.CookConversion == null) return float.MaxValue; + + float soonest = float.MaxValue; + + for (int i = 0; i < SlotCount; i++) + { + string name; + float cooked; + int status; + if (!ReadSlot(i, out name, out cooked, out status)) break; + + if (string.IsNullOrEmpty(name)) continue; + if (status == Vanilla.CookBurnt) continue; // already lost, no hurry + + CookingStation.ItemConversion conversion = + Vanilla.CookConversion.Invoke(m_cooking, new object[] { name }) + as CookingStation.ItemConversion; + if (conversion == null) continue; + + float left = conversion.m_cookTime * 2f - cooked; + if (left < soonest) soonest = left; + } + + return soonest; + } + } + } + + // ================================================================ Fermenter + + private class FermenterStation : ButlerStation + { + public Fermenter m_fermenter; + + /// Mead goes with the food. It has no deadline of its own, so it costs the cook + /// nothing beyond one more thing to fill and one more tap to open. + public override ButlerFamily Family { get { return ButlerFamily.Kitchen; } } + + private int Status + { + get { return Vanilla.CallInt(Vanilla.FermenterStatus, m_fermenter, Vanilla.FermentExposed); } + } + + public override bool Operable { get { return Status != Vanilla.FermentExposed; } } + + public override int FreeSlots { get { return Status == Vanilla.FermentEmpty ? 1 : 0; } } + + public override bool Accepts(string prefabName) + { + return Vanilla.Allowed(Vanilla.FermenterAllowed, m_fermenter, prefabName); + } + + public override void Add(string prefabName) + { + Claim(); + Nview.InvokeRPC("RPC_AddItem", prefabName); + } + + public override bool HasWork { get { return Status != Vanilla.FermentEmpty; } } + + public override string FuelPrefab { get { return null; } } + public override int FuelWanted { get { return 0; } } + public override void AddFuel() { } + + public override bool HasOutput { get { return Status == Vanilla.FermentReady; } } + + /// Opens the tap. The bottles are not out yet when this returns - DelayedTap waits + /// m_tapDelay for the animation - so the servant collects them on a later pass, which the + /// pickup sweep handles without knowing anything about fermenting. + public override void PullOutput(Vector3 at) + { + Claim(); + Nview.InvokeRPC("RPC_Tap"); + } + } + } +} diff --git a/JotunnModStub/Butler/ServantTableBehaviour.cs b/JotunnModStub/Butler/ServantTableBehaviour.cs new file mode 100644 index 0000000..4d70f81 --- /dev/null +++ b/JotunnModStub/Butler/ServantTableBehaviour.cs @@ -0,0 +1,170 @@ +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// A servant's table: an anchor, a summoning point and the feature's only window. One class serves + /// both trades - what changes between the smith's and the cook's is three fields set at + /// registration, not behaviour. + /// + /// It does no work of its own. Everything it knows it asks the servant, and everything the servant + /// says it says here - the hover text is the ONE feedback channel this feature has, by decision, so + /// a servant that has stopped must be able to explain itself from a line of text or it is + /// indistinguishable from a broken mod. + /// + /// E RAISES, and that is all E does. There is no pause switch and no automatic re-forming: a fallen + /// servant leaves the table empty until somebody notices. That was chosen over a sixty-second + /// respawn on the grounds that a death nobody notices is a death that might as well not happen. + /// + /// It registers itself with RaisedThrall's station list, which is what BoneServantAI's wither clock + /// asks when it wants to know whether its table is still standing. That list is the only part of + /// the thrall machinery this feature uses. + /// + public class ServantTableBehaviour : MonoBehaviour + { + public Switch m_switch; + + /// Set on the prefab at registration, so both travel to every instance. + public string m_title = "Servant's Table"; + public string m_servantPrefab = BoneServant.SmithName; + public ButlerFamily m_family = ButlerFamily.Forge; + + private const string KeyLastRaise = "RoV_butlerRaisedAt"; + + /// Where the servant stands up: in front of the table, clear of the mesh. + private const float RaiseOffset = 1.2f; + + private ZNetView m_nview; + + private void Awake() + { + RaisedThrall.RegisterStation(transform); + + m_nview = GetComponent(); + + if (m_switch != null) + { + m_switch.m_onUse = OnUse; + m_switch.m_onHover = Hover; + } + } + + private void OnDestroy() + { + RaisedThrall.UnregisterStation(transform); + } + + // ---------------------------------------------------------------- interaction + + private bool OnUse(Switch caller, Humanoid user, ItemDrop.ItemData item) + { + Player player = user as Player; + if (player == null) return false; + + if (item != null) + { + player.Message(MessageHud.MessageType.Center, "$msg_wontwork"); + return false; + } + + if (Servant() != null) + { + player.Message(MessageHud.MessageType.Center, "It is already at work."); + return false; + } + + float wait = Cooldown(); + if (wait > 0f) + { + player.Message(MessageHud.MessageType.Center, + $"The bones are not ready. {Mathf.CeilToInt(wait)}s."); + return false; + } + + return Raise(player); + } + + private bool Raise(Player player) + { + if (m_nview == null || !m_nview.IsValid()) return false; + if (ZNetScene.instance == null) return false; + + GameObject prefab = ZNetScene.instance.GetPrefab(m_servantPrefab); + if (prefab == null) + { + Jotunn.Logger.LogWarning($"[Butler] No '{m_servantPrefab}' in ZNetScene; nothing was raised."); + player.Message(MessageHud.MessageType.Center, "Nothing answers."); + return false; + } + + // Owner-only, so in multiplayer exactly one servant stands up rather than one per client. + m_nview.ClaimOwnership(); + + Vector3 at = transform.position + transform.forward * RaiseOffset; + GameObject spawned = Object.Instantiate(prefab, at, Quaternion.identity); + + BoneServantAI servant = spawned.GetComponent(); + if (servant != null) servant.Bind(transform.position); + + if (ZNet.instance != null) m_nview.GetZDO().Set(KeyLastRaise, ZNet.instance.GetTime().Ticks); + + player.Message(MessageHud.MessageType.Center, "The servant rises."); + return true; + } + + /// Seconds still to wait, or zero. Kept in world time so logging out does not pay it off + /// for free - and configured to zero for the test, where it is simply never in the way. + private float Cooldown() + { + if (m_nview == null || !m_nview.IsValid() || ZNet.instance == null) return 0f; + + float required = ButlerConfig.ResummonSeconds.Value; + if (required <= 0f) return 0f; + + long stamp = m_nview.GetZDO().GetLong(KeyLastRaise, 0L); + if (stamp == 0L) return 0f; + + double elapsed = (ZNet.instance.GetTime() - new System.DateTime(stamp)).TotalSeconds; + return Mathf.Max(0f, required - (float)elapsed); + } + + // ---------------------------------------------------------------- the hover + + private string Hover() + { + BoneServantAI servant = Servant(); + + if (servant == null) + { + return m_title + "\nNo servant stands here.\n" + + "[$KEY_Use] Raise one"; + } + + string status = servant.Status; + if (string.IsNullOrEmpty(status)) status = "Waiting."; + + return m_title + "\n" + status; + } + + /// + /// This table's servant, if it is alive and loaded. + /// + /// Matched by anchor rather than by a stored id, so a table rebuilt on the same spot adopts the + /// servant already standing there - and by TRADE as well, because a smith's table and a cook's + /// table are allowed to stand a metre apart and must not adopt each other's servant. + /// + private BoneServantAI Servant() + { + foreach (Character character in Character.GetAllCharacters()) + { + if (character == null || character.IsDead()) continue; + + BoneServantAI servant = character.GetComponent(); + if (servant == null || servant.m_family != m_family) continue; + if (servant.IsBoundTo(transform.position)) return servant; + } + + return null; + } + } +} diff --git a/JotunnModStub/Dvergar/DvergarBanco.cs b/JotunnModStub/Dvergar/DvergarBanco.cs index 2b519aa..d842803 100644 --- a/JotunnModStub/Dvergar/DvergarBanco.cs +++ b/JotunnModStub/Dvergar/DvergarBanco.cs @@ -295,6 +295,17 @@ namespace RacesOfValheim // Trol/TrolTotemStore.cs, which is generic and is deliberately NOT copied here. Trader trader = prefab.GetComponent() ?? prefab.AddComponent(); 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.m_useItems = new List(); trader.m_randomTalk = new List(); diff --git a/JotunnModStub/Factions/FactionMerchantPatches.cs b/JotunnModStub/Factions/FactionMerchantPatches.cs index c308da0..dbdecfa 100644 --- a/JotunnModStub/Factions/FactionMerchantPatches.cs +++ b/JotunnModStub/Factions/FactionMerchantPatches.cs @@ -11,19 +11,63 @@ namespace RacesOfValheim // notices the player - not what a "press E to talk" merchant should do. Skipping Update() // entirely leaves Interactable.Interact() (E opens StoreGui) and Hoverable.GetHoverText() // (the "E - Talk" prompt) untouched, since neither of those depends on Update() running. + // + // The same prefix also refuses to run Update() on a Trader that has no rig to drive, which is + // the general form of a bug that reached a tester: Trader.Start() resolves m_animator and + // m_lookAt with GetComponentInChildren, and Update() then dereferences BOTH with no null check - + // m_animator.SetBool("Stand", ...) and m_lookAt.ResetTarget() on the branch taken whenever no + // player is nearby, which is most frames. A building is not a creature and has neither, so a + // Trader bolted onto one threw a NullReferenceException every frame and filled the BepInEx + // console. The prefabs that do that (the Dvergar bank, the Trol totem, the Hive Market) now + // disable their Trader outright, which is the real fix; this check is the net under it, and it + // costs one cached field read per trader per frame. [HarmonyPatch(typeof(Trader), "Update")] public static class FactionMerchantSuppressAmbientPatch { + // Both fields are private in the assembly this project compiles against. Resolved once + // rather than through Traverse, because this runs on every trader on every frame. + private static readonly AccessTools.FieldRef AnimatorField = + AccessTools.FieldRefAccess("m_animator"); + private static readonly AccessTools.FieldRef LookAtField = + AccessTools.FieldRefAccess("m_lookAt"); + public static bool Prefix(Trader __instance) { if (((Component)__instance).GetComponent() != null) { return false; } + + if (AnimatorField(__instance) == null || LookAtField(__instance) == null) + { + return false; + } + return true; } } + // Trader.Start() ends with InvokeRepeating("RandomTalk", m_randomTalkInterval, + // m_randomTalkInterval), and a Trader added with AddComponent comes up with that interval at + // zero, because nobody authored it in the editor. On a faction merchant the repeat is pure + // waste for as long as the creature exists: RandomTalk's first act is to read the animator's + // "Stand" bool, and nothing ever sets it, because Update() - the only thing that would - is + // suppressed for these by the patch above. So it wakes up, asks one question, answers no, and + // is scheduled again. + // + // Cancelled in a postfix rather than by skipping Start with a prefix: Start also resolves + // m_animator and m_lookAt and snaps a SnapToGround rig to the terrain, and none of that is in + // the way. Only the timer is. + [HarmonyPatch(typeof(Trader), "Start")] + public static class FactionMerchantStopRandomTalkPatch + { + public static void Postfix(Trader __instance) + { + if (((Component)__instance).GetComponent() == null) return; + __instance.CancelInvoke("RandomTalk"); + } + } + // Player.FindHoverObject() always figures out m_hoveringCreature correctly (it only // needs a Character component on the hit collider, no Hoverable/Interactable // involved) but separately sets m_hovering - the field the "E - Talk" prompt and the diff --git a/JotunnModStub/RaceClaws.cs b/JotunnModStub/RaceClaws.cs index ba4fda8..2e11b50 100644 --- a/JotunnModStub/RaceClaws.cs +++ b/JotunnModStub/RaceClaws.cs @@ -8,7 +8,7 @@ namespace RacesOfValheim /// /// Claws that are part of the body, for the races that grow a pair. /// - /// This is SvermClawSlot generalised, not reinvented: the Sverm's Vilebone Maulclaws worked out + /// This is SvermClawSlot generalised, not reinvented: the Sverm's Chitin Claws worked out /// the whole shape of the problem, and the Aswid and the Fenrir are asking for the same object /// with a different face. So the machinery moved here and each race supplies only what is /// genuinely its own - the item name, the model to wear, and whether it is currently a wolf. @@ -178,6 +178,15 @@ namespace RacesOfValheim shared.m_weight = 0f; shared.m_maxQuality = 1; + // INDESTRUCTIBLE, and it has to be the flag rather than a big number. The claws are + // never crafted, so no workbench will ever repair them: left on normal durability + // they wear down to zero and Humanoid.EquipItem then refuses to put them back in + // hand, which strands the race bare-fisted for good. m_useDurability = false is the + // single switch every path reads - the attack drain, the broken-item check, the + // inventory bar and the tooltip line all skip the item entirely. + shared.m_useDurability = false; + shared.m_canBeReparied = false; + // No recipe and no station: this item is never crafted, only issued. } @@ -375,6 +384,11 @@ namespace RacesOfValheim Jotunn.Logger.LogInfo($"[{RaceId}] Issued the {DisplayName}."); } + // A pair issued before the claws stopped wearing out is still carrying whatever it had + // ground down to. Nothing reads that number any more, but it is saved with the item, so + // it is put back to full once rather than left as a stale figure in the save file. + if (claws.m_durability < claws.GetMaxDurability()) claws.m_durability = claws.GetMaxDurability(); + // Empty-handed means clawed. Anything else in the right hand wins until it is put away, // which is the whole compromise. ItemDrop.ItemData held = Traverse.Create((Humanoid)player).Field("m_rightItem").Value; diff --git a/JotunnModStub/RaceCompendium.cs b/JotunnModStub/RaceCompendium.cs index 1305920..7c9861e 100644 --- a/JotunnModStub/RaceCompendium.cs +++ b/JotunnModStub/RaceCompendium.cs @@ -135,7 +135,7 @@ namespace RacesOfValheim sb.AppendLine("[Base Passive] Insect Metabolism: You eat everything anyone else eats, and honey is worth double to you. Alchemical blood is the one thing you will not swallow.\n"); - sb.AppendLine($"[Base Passive] Vilebone Maulclaws: Your hands are the weapon. Bare-handed blows land at {rules.ClawDamagePercent * 100f:0}% of the claws' full weight, and they cannot be taken from you - draw a sword and they wait, sheathe it and they are back.\n"); + sb.AppendLine($"[Base Passive] Chitin Claws: Your hands are the weapon. Bare-handed blows land at {rules.ClawDamagePercent * 100f:0}% of the claws' full weight, and they cannot be taken from you - draw a sword and they wait, sheathe it and they are back.\n"); if (rules.MetabolicSurge) sb.AppendLine("[Eikthyr Unlock] Metabolic Surge: Running and jumping cost you less, and you jump higher.\n"); diff --git a/JotunnModStub/RacesOfValheim.cs b/JotunnModStub/RacesOfValheim.cs index 8c8648a..495b593 100644 --- a/JotunnModStub/RacesOfValheim.cs +++ b/JotunnModStub/RacesOfValheim.cs @@ -15,7 +15,7 @@ namespace RacesOfValheim { public const string PluginGUID = "com.nandor.racesofvalheim"; public const string PluginName = "Races Of Valheim"; - public const string PluginVersion = "1.4.2"; + public const string PluginVersion = "1.4.3"; private readonly Harmony harmony = new Harmony(PluginGUID); @@ -43,6 +43,9 @@ namespace RacesOfValheim // Not a race either: a tool any race can craft, so it sits beside the vulture rather // than inside the alphabetical run above. TrolsHammerConfig.Bind(Config); + // Not a race either: the two Bone Servants, shared by the Skeleton and Skadi, so they + // bind here rather than inside either race's run. + ButlerConfig.Bind(Config); harmony.PatchAll(); gameObject.AddComponent(); gameObject.AddComponent(); @@ -130,6 +133,7 @@ namespace RacesOfValheim SvermRace.Instance.CreateModAssets(); WarVultureItem.Register(); TrolsHammerItem.Register(); + BoneServant.Register(); } // --- RACE SELECTION UI --- public void ShowRaceSelectionMenu() diff --git a/JotunnModStub/Sverm/SvermClawSlot.cs b/JotunnModStub/Sverm/SvermClawSlot.cs index 11b911c..17b783c 100644 --- a/JotunnModStub/Sverm/SvermClawSlot.cs +++ b/JotunnModStub/Sverm/SvermClawSlot.cs @@ -6,7 +6,7 @@ using UnityEngine; namespace RacesOfValheim { /// - /// The Maulclaws as a REAL equipped weapon, sitting in the inventory in plain sight and + /// The Chitin Claws as a REAL equipped weapon, sitting in the inventory in plain sight and /// refusing to be moved. /// /// WHY THIS REPLACED THE COSMETIC VERSION. Bolting a model to the hand bones worked, but the @@ -36,8 +36,13 @@ namespace RacesOfValheim /// public static class SvermClawSlot { + /// + /// The prefab id, and it keeps the old spelling on purpose: it is what every save on disk + /// names the item by, and renaming it would leave a Sverm holding an item ObjectDB can no + /// longer resolve. The display name below is the only half a player ever reads. + /// public const string ItemName = "SvermMaulclaws"; - public const string ItemDisplayName = "Vilebone Maulclaws"; + public const string ItemDisplayName = "Chitin Claws"; /// Row in the reserved column the claws sit on. The other three await the carapace. private const int ClawRow = 0; @@ -84,6 +89,15 @@ namespace RacesOfValheim shared.m_weight = 0f; shared.m_maxQuality = 1; + // INDESTRUCTIBLE, and it has to be the flag rather than a big number. The claws are + // never crafted, so no workbench will ever repair them: left on normal durability + // they wear down to zero and Humanoid.EquipItem then refuses to put them back in + // hand, which strands the Sverm bare-fisted for good. m_useDurability = false is the + // single switch every path reads - the attack drain, the broken-item check, the + // inventory bar and the tooltip line all skip the item entirely. + shared.m_useDurability = false; + shared.m_canBeReparied = false; + // No recipe and no station: this item is never crafted, only issued. } @@ -153,9 +167,14 @@ namespace RacesOfValheim claws.m_gridPos = corner; } - Jotunn.Logger.LogInfo("[Sverm] Issued the Maulclaws."); + Jotunn.Logger.LogInfo("[Sverm] Issued the Chitin Claws."); } + // A pair issued before the claws stopped wearing out is still carrying whatever it had + // ground down to. Nothing reads that number any more, but it is saved with the item, so + // it is put back to full once rather than left as a stale figure in the save file. + if (claws.m_durability < claws.GetMaxDurability()) claws.m_durability = claws.GetMaxDurability(); + // Empty-handed means clawed. Anything else in the right hand wins until it is put // away, which is the whole compromise. ItemDrop.ItemData held = Traverse.Create((Humanoid)player).Field("m_rightItem").Value; diff --git a/JotunnModStub/Sverm/SvermClaws.cs b/JotunnModStub/Sverm/SvermClaws.cs index 5b01176..0e03b1a 100644 --- a/JotunnModStub/Sverm/SvermClaws.cs +++ b/JotunnModStub/Sverm/SvermClaws.cs @@ -3,7 +3,7 @@ using UnityEngine; namespace RacesOfValheim { /// - /// The Vilebone Maulclaws: attached to the hands for good, and never equipped. + /// The Chitin Claws: attached to the hands for good, and never equipped. /// /// WHY NOT A REAL WEAPON. Valheim has one weapon slot. A claw that is genuinely equipped locks /// the Sverm out of every sword, bow and staff in the game for the whole run, which is not @@ -52,7 +52,7 @@ namespace RacesOfValheim if (candidate != null) { resolved = candidate; - Jotunn.Logger.LogInfo($"[Sverm] Maulclaws resolved to '{name}'."); + Jotunn.Logger.LogInfo($"[Sverm] Chitin Claws resolved to '{name}'."); return resolved; } } @@ -70,7 +70,7 @@ namespace RacesOfValheim /// /// The vanilla weapon's damage at quality 4, read once. This is the ceiling the tier - /// percentages are a fraction of, and state 7 is 100% of it - the real Maulclaws. + /// percentages are a fraction of, and state 7 is 100% of it - the real Chitin Claws. /// /// Public because it is the shared yardstick: the Aswid's and the Fenrir's claws /// (RaceClawSet) are balanced against this same figure rather than against the models they @@ -108,7 +108,7 @@ namespace RacesOfValheim }; referenceRead = true; - Jotunn.Logger.LogInfo($"[Sverm] Maulclaws at quality {SvermConfig.ArmorReferenceQuality}: " + + Jotunn.Logger.LogInfo($"[Sverm] Chitin Claws at quality {SvermConfig.ArmorReferenceQuality}: " + $"slash {referenceDamage.m_slash:0.#}, pierce {referenceDamage.m_pierce:0.#}, " + $"blunt {referenceDamage.m_blunt:0.#}."); return referenceDamage; diff --git a/JotunnModStub/Sverm/SvermConfig.cs b/JotunnModStub/Sverm/SvermConfig.cs index e75684a..cda6818 100644 --- a/JotunnModStub/Sverm/SvermConfig.cs +++ b/JotunnModStub/Sverm/SvermConfig.cs @@ -88,7 +88,7 @@ namespace RacesOfValheim public const string CarapaceLegsVisual = "ArmorCarapaceLegs"; public const string CarapaceHelmetVisual = "HelmetCarapace"; - // ─── Vilebone Maulclaws ────────────────────────────────────────────── + // ─── Chitin Claws ──────────────────────────────────────────────────── // FOUR near-identical names exist in the manifest and only some carry a recipe, so the // prefab is resolved by trying them in order and logging which one answered. A wrong guess // here fails soft and silently - two empty hands - which is exactly the failure this @@ -106,7 +106,7 @@ namespace RacesOfValheim /// /// Fraction of the vanilla weapon's quality-4 damage the bare hands hit for, per state. - /// State 7 is the ceiling - the real Maulclaws - and state 8 adds fire on top rather than + /// State 7 is the ceiling - the real Chitin Claws - and state 8 adds fire on top rather than /// going past it. Index 0 unused, as above. /// public static readonly float[] ClawDamagePercentByState = diff --git a/JotunnModStub/Sverm/SvermProgression.cs b/JotunnModStub/Sverm/SvermProgression.cs index 1e311d9..ac1f09b 100644 --- a/JotunnModStub/Sverm/SvermProgression.cs +++ b/JotunnModStub/Sverm/SvermProgression.cs @@ -28,7 +28,7 @@ namespace RacesOfValheim /// public float FireWeakness; - /// Fraction of the Maulclaws' quality-4 damage a bare-handed blow lands for. + /// Fraction of the Chitin Claws' quality-4 damage a bare-handed blow lands for. public float ClawDamagePercent; public bool MetabolicSurge; // cheaper running and jumping, higher jump diff --git a/JotunnModStub/Sverm/SvermStingerForm.cs b/JotunnModStub/Sverm/SvermStingerForm.cs index 5c5a4f7..a3a789e 100644 --- a/JotunnModStub/Sverm/SvermStingerForm.cs +++ b/JotunnModStub/Sverm/SvermStingerForm.cs @@ -84,7 +84,7 @@ namespace RacesOfValheim // // The first version emptied the hands completely and the form could not attack: with // nothing equipped there is no weapon to swing, and Valheim's bare fist is not the - // thing this form is supposed to be throwing. Leaving the Maulclaws equipped makes the + // thing this form is supposed to be throwing. Leaving the Chitin Claws equipped makes the // sting an ordinary weapon attack - which works - and costs nothing visually, because // the whole body is hidden a line later. Fist weapons report Skills.SkillType.Unarmed, // so the damage patch still recognises the blow and swaps the deathsquito's figure in. @@ -254,7 +254,7 @@ namespace RacesOfValheim } Jotunn.Logger.LogWarning($"[Sverm] Could not read a weapon off '{SvermConfig.StingerCreature}'; " + - "the sting falls back to the Maulclaws."); + "the sting falls back to the Chitin Claws."); stingerDamageRead = true; return stingerDamage; // all zeroes: the damage patch then leaves the claw values alone } diff --git a/JotunnModStub/Sverm/SvermVisuals.cs b/JotunnModStub/Sverm/SvermVisuals.cs index 9e5b79c..07477b5 100644 --- a/JotunnModStub/Sverm/SvermVisuals.cs +++ b/JotunnModStub/Sverm/SvermVisuals.cs @@ -16,7 +16,7 @@ namespace RacesOfValheim /// matures on screen as it advances. /// /// What gets mounted, all of it borrowed from vanilla: - /// the claws - the Vilebone Maulclaws, on both hands, always; + /// the claws - the Chitin Claws, on both hands, always; /// the spines - UndeadBjornRibcage worn spine-up, a static crest, from tier 5; /// the eyes - two emissive spheres, the Aswid's geometry unchanged; /// the motes - a firefly swarm under the body, only while falling; diff --git a/JotunnModStub/Trol/TrolTotem.cs b/JotunnModStub/Trol/TrolTotem.cs index 945433f..0dea4fb 100644 --- a/JotunnModStub/Trol/TrolTotem.cs +++ b/JotunnModStub/Trol/TrolTotem.cs @@ -261,6 +261,17 @@ namespace RacesOfValheim // GameObject - walks straight into Say(m_randomStartTrade, ...) right after opening the store. Trader trader = prefab.GetComponent() ?? prefab.AddComponent(); 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 totem both of those are null, so the + // piece threw a NullReferenceException every frame from the moment it was raised. 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.m_useItems = new List(); trader.m_randomTalk = new List(); diff --git a/README.md b/README.md index dd323fc..80a5c3d 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,13 @@ A comprehensive Valheim mod allowing you to play as unique races, each providing --- -## New Patch v1.4.2: The Sverm +## New Patch v1.4.3 + +The War Vulture is craftable at last, Trol's Hammer builds everything 20% bigger, and two portal bugs are gone. See the [Changelog](#changelog). + +--- + +## The Sverm The tenth race is an insect. The Sverm never dresses: chest, legs and helm are carapace that never comes off and is always worth a full set of the biome ahead of you — best quality, weightless, no movement penalty. It fights with claws it cannot put down, poison cannot touch it, and no invertebrate in the game will attack it from tier zero. Blunt and fire hit it 40% harder, which is the price. @@ -87,7 +93,7 @@ Full details under [Sverm](#10-sverm) and [Sverm Progression](#race-progressions ### 10. Sverm - **Chitin Plating:** You never dress. Chest, legs and helm are carapace worth a full set of the biome ahead of you at every tier — best quality, weightless, no movement penalty. Only cloak and trinket may still be worn. -- **Vilebone Maulclaws:** Your hands are the weapon — see [Permanent Claws](#permanent-claws). +- **Chitin Claws:** Your hands are the weapon — see [Permanent Claws](#permanent-claws). - **Hive Pheromones:** No invertebrate attacks you — leeches, ticks, deathsquitos, seekers and bees all ignore you, from tier zero. - **Toxin Immunity:** Poison cannot touch you. Blunt and fire hit you 40% harder — until Fader, when the fire weakness burns out and comes back as a resistance. - **The Colony:** After the Elder, a Brood Mound, a Hive Market and a roster of insect troops bought with digested biomass. @@ -101,7 +107,7 @@ Three races grow a pair of their own. The terms are identical for all three: iss - **Aswid — Claws of the Beast:** burned almost black. Lands the whole of it as slash. - **Fenrir — Cursed Claws:** the flesh rippers worn as the game made them. Also pure slash. -- **Sverm — Vilebone Maulclaws:** splits the same weight three ways, and sets it alight at Fader. +- **Sverm — Chitin Claws:** splits the same weight three ways, and sets it alight at Fader. --- @@ -218,7 +224,7 @@ Right Mouse toggles flight. Glide towards aim, W = forward/climb, Shift+W = use
Sverm Progression -- **Base:** Chitin Plating (full next-biome set at every tier, weightless, no speed penalty; only cloak and trinket wearable). Toxin Immunity — poison cannot touch you, but +40% blunt and +40% fire damage taken. Hive Pheromones — no invertebrate attacks you. Insect Metabolism — eats everything, honey counts double, alchemical blood is the one refusal. Vilebone Maulclaws — unarmed blows land at a share of the claws' full weight, rising with every tier. +- **Base:** Chitin Plating (full next-biome set at every tier, weightless, no speed penalty; only cloak and trinket wearable). Toxin Immunity — poison cannot touch you, but +40% blunt and +40% fire damage taken. Hive Pheromones — no invertebrate attacks you. Insect Metabolism — eats everything, honey counts double, alchemical blood is the one refusal. Chitin Claws — unarmed blows land at a share of the claws' full weight, rising with every tier. - **Eikthyr:** Metabolic Surge – running and jumping cost less, and you jump higher. Ventral Pouches – +100 carry weight. - **Elder:** Grinding Mandibles – seeds are food (raw nourishment, no garden buffs). Sensory Antennae – feel what lives around you, through stone and soil. **The colony wakes:** Brood Mound unlocked. - **Bonemass:** Venom Glands – every blow carries bonus poison, growing per tier. Acid Hemolymph – melee attackers take poison back. @@ -385,17 +391,22 @@ The **Sverm** belongs to no faction. Its Hive Pheromones make every invertebrate ## Development & Feedback This is a stable release, but more races and refinements are planned! -Bug reports, feedback, ideas: [https://discord.gg/gbBEK2VTE](https://discord.gg/gbBEK2VTE) +Bug reports, feedback, ideas: [https://discord.gg/gbBEK2VTE](https://discord.gg/gbBEK2VTE) +Support the mod: [Patreon — NandorTheModder](https://www.patreon.com/c/NandorTheModder) --- ## Changelog +### v1.4.3 +- **NEW - Trol's Hammer:** a second builder's hammer (1 Core Wood, 2 Fine Wood, Workbench) that builds everything the ordinary one builds, 20% larger. Any race can craft it. +- **War Vulture:** now craftable — 10 Greydwarf Eyes, 2 Black Metal, 2 Raw Lox Meat at a Forge. The recipe only appears for the races that can ride. +- **Fix - Portals:** teleporting no longer leaves you in a world that has stopped loading, and the Skeleton's head flame no longer burns torches into the world for everyone to find. + ### v1.4.2 - **NEW - Sverm Race:** the tenth race. Wears carapace instead of armour (never removable, always worth the next biome's full set, weightless), fights with permanent claws, is immune to poison but takes 40% more from blunt and fire, and is ignored by every invertebrate in the game from tier zero. After the Elder it stops being one body and becomes a colony. - **NEW - The Colony (Sverm):** Brood Mound, digestion bank, brood eggs on a timer, an insect troop roster, a Hive Market, blister ticks that regrow free, and vanilla beehives taken over by the nest — twice the speed, three times the honey, royal jelly after Yagluth. -- **NEW - War Vulture (Flying Mount):** a vulture trophy on a stick that puts you on a real, network-visible flying bird. Unlimited cruise, a limited sprint reserve on the run key that refills in mid-air, and its own bar under your stamina. Furling and Dvergar by default, configurable. Crafted at a forge from 10 greydwarf eyes, 2 black metal ingots and 2 raw lox meat, and the recipe is hidden from every race that cannot ride. -- **NEW - Trol's Hammer:** a second builder's hammer (1 Core Wood, 2 Fine Wood, Workbench) that builds everything the ordinary one builds — same menu, same cost, same drop — 20% larger. The preview is already at full size, the size is saved with the piece and shared with other players, and both hammers keep working side by side in the same house. +- **NEW - War Vulture (Flying Mount):** a vulture trophy on a stick that puts you on a real, network-visible flying bird. Unlimited cruise, a limited sprint reserve on the run key that refills in mid-air, and its own bar under your stamina. Furling and Dvergar by default, configurable. No recipe yet while the flight is being proven — spawn it from the console. - **NEW - Claws for the Aswid and the Fenrir:** both races now grow a permanent pair, on the same terms the Sverm has always had. All three are measured against **one** yardstick rather than against the models they wear, so the same tier is worth the same damage whichever race you are, and no pair counts while you are wearing another body. - **NEW - Dvergar Contract Bank:** the hire bench is now a proper contract bank — five crew slots, 400 to 2000 coin, paid at your own trader discount, with the Queen's drop opening the Runic Crew and the Ash Guard. Hired crews keep their employer's truce with the mountain's dvergr, seekers at heel included, so a band walking into an outpost no longer means a dead shopkeeper. They carry no loot, heal themselves, and a dead crew is money spent. Race locked, one per square kilometre, and the only chain that needs no reagent — the Dvergar pay for everything, so 100 coin goes in the recipe instead. - **NEW - Dvergar Rune Barrel:** 20 doses of any vanilla brew, poured into everything you have raised within 30 m. It refuses nothing and promises nothing: a healing mead heals a dvergr, a stamina mead does nothing, because a creature has no stamina bar. diff --git a/manifest.json b/manifest.json index c9a811b..b78d9d0 100644 --- a/manifest.json +++ b/manifest.json @@ -1,7 +1,7 @@ { "name": "RacesOfValheim", "description": "A Valheim mod that adds ten custom playable races (Aswid, Draugh, Dvergar, Fenrir, Furling, Skadi, Skeleton, Sverm, Trenta, Trol) each with unique abilities, traits, race stations and a deep boss-driven progression system.", - "version_number": "1.4.2", + "version_number": "1.4.3", "website_url": "", "dependencies": [ "denikson-BepInExPack_Valheim-5.4.2333",