From b1f5da2249065e16af2884ed8c197a18d05b8413 Mon Sep 17 00:00:00 2001 From: Ferdinando Date: Fri, 7 Aug 2026 17:02:34 +0200 Subject: [PATCH 1/8] feat: shared foundations for stations and servants RaisedThrall is the common servant base (leash, wither timer, follow command, anchor), used by Draugh, Skeleton and Trol. ModelBorrow lends a vanilla prefab's look without its behaviour. PieceDensityLimit caps how many of a piece fit in an area. Co-Authored-By: Claude Opus 5 --- JotunnModStub/ModelBorrow.cs | 189 +++++++++++ JotunnModStub/PieceDensityLimit.cs | 147 +++++++++ JotunnModStub/RaisedThrall.cs | 491 +++++++++++++++++++++++++++++ 3 files changed, 827 insertions(+) create mode 100644 JotunnModStub/ModelBorrow.cs create mode 100644 JotunnModStub/PieceDensityLimit.cs create mode 100644 JotunnModStub/RaisedThrall.cs diff --git a/JotunnModStub/ModelBorrow.cs b/JotunnModStub/ModelBorrow.cs new file mode 100644 index 0000000..097f44d --- /dev/null +++ b/JotunnModStub/ModelBorrow.cs @@ -0,0 +1,189 @@ +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// Borrowing a vanilla prefab's LOOK without borrowing anything it does. + /// + /// This exists because of a bug that shipped: the Trol's war totem mounted trophy models by calling + /// Instantiate and then stripping the components off the copy. Instantiate runs Awake FIRST, so for + /// one frame the copy was a real, live object - and a trophy is an ItemDrop, which means a giant + /// Yagluth head fell out of the sky every time the totem's ghost was drawn. + /// + /// For a world prop (the Trenta grove borrows a Yggdrasil shoot this way) the stray frame does + /// nothing visible, which is why the technique looked fine the first two times it was used. For + /// anything carrying ItemDrop, ZNetView or a Rigidbody it is a live object with physics. + /// + /// The fix is one line and it is the reason this is a shared helper rather than a third copy of the + /// same loop: instantiate into a holder that is ALREADY INACTIVE. Unity does not run Awake on a + /// component that comes up disabled, so the strip happens before anything can wake. + /// + /// SECOND ROUND: the borrowed model is now sized in METRES instead of by a multiplier, because a + /// multiplier against an unknown mesh is a guess and guesses shipped a Yagluth head three times + /// taller than the post it stood on. The mesh is measured and scaled to fit, and it is grounded so + /// the holder's origin is the model's BOTTOM CENTRE rather than whatever the item's author happened + /// to use as a pivot - which is what makes "put the head on top of the totem" a subtraction instead + /// of another guess. This is rule 3.2 of the house guide applied to geometry: a number that was + /// measured is already balanced. + /// + public static class ModelBorrow + { + /// + /// Hangs the renderers of a vanilla prefab under and returns the holder, + /// which the caller can switch on and off. Null-safe: a missing source logs and returns an empty + /// holder rather than throwing, so a wrong name costs a warning and not a startup. + /// + /// is where the model's BOTTOM CENTRE goes. + /// is how big its largest dimension should end up, in metres, + /// measured AFTER has been applied. + /// + public static GameObject Attach(Transform parent, string holderName, string sourcePrefab, + Vector3 localPosition, Quaternion localRotation, float targetSize, + string label) + { + GameObject holder = new GameObject(holderName); + holder.transform.SetParent(parent, false); + holder.transform.localPosition = localPosition; + + // BEFORE the Instantiate below. This single line is the whole point of the class. + holder.SetActive(false); + + GameObject source = Jotunn.Managers.PrefabManager.Cache.GetPrefab(sourcePrefab); + if (source == null) + { + Jotunn.Logger.LogWarning($"[{label}] No '{sourcePrefab}' to borrow a model from; nothing was attached."); + holder.SetActive(true); + return holder; + } + + GameObject copy = Object.Instantiate(source, holder.transform); + copy.name = "model"; + copy.transform.localPosition = Vector3.zero; + copy.transform.localRotation = localRotation; + copy.transform.localScale = Vector3.one; + + // Everything that is not a Renderer or a Transform. Order matters for the same reason it did + // on the Aswid's lights: behaviours first, then the things they hold references to. + foreach (MonoBehaviour behaviour in copy.GetComponentsInChildren(true)) + { + if (behaviour != null) Object.DestroyImmediate(behaviour); + } + foreach (Collider collider in copy.GetComponentsInChildren(true)) + { + if (collider != null) Object.DestroyImmediate(collider); + } + foreach (Rigidbody body in copy.GetComponentsInChildren(true)) + { + if (body != null) Object.DestroyImmediate(body); + } + foreach (ZNetView nview in copy.GetComponentsInChildren(true)) + { + if (nview != null) Object.DestroyImmediate(nview); + } + + FitAndGround(copy.transform, holder.transform, targetSize, sourcePrefab, label); + + holder.SetActive(true); + return holder; + } + + /// + /// How tall the borrowed model actually turned out, in the holder's parent's space. Used to stack + /// one borrowed model on top of another without a magic offset. + /// + public static float HeightOf(GameObject holder) + { + if (holder == null) return 0f; + return TryMeasure(holder.transform, holder.transform, out Bounds bounds) ? bounds.size.y : 0f; + } + + // ---------------------------------------------------------------- measuring + + /// + /// Scales the copy so its largest dimension is metres, then slides it + /// so its bottom centre sits on the holder's origin. + /// + private static void FitAndGround(Transform copy, Transform holder, float targetSize, + string sourcePrefab, string label) + { + if (!TryMeasure(copy, holder, out Bounds raw)) + { + Jotunn.Logger.LogWarning($"[{label}] '{sourcePrefab}' has no readable mesh, so it could not be " + + "sized or grounded; it is attached at scale 1 and may sit wrong."); + return; + } + + float biggest = Mathf.Max(raw.size.x, Mathf.Max(raw.size.y, raw.size.z)); + if (biggest <= 0.0001f) + { + Jotunn.Logger.LogWarning($"[{label}] '{sourcePrefab}' measured as a point ({raw.size}); " + + "left at scale 1."); + return; + } + + float scale = targetSize / biggest; + copy.localScale = Vector3.one * scale; + + if (TryMeasure(copy, holder, out Bounds fitted)) + { + copy.localPosition = new Vector3(-fitted.center.x, -fitted.min.y, -fitted.center.z); + } + + Jotunn.Logger.LogInfo($"[{label}] Borrowed '{sourcePrefab}': measured {raw.size}, " + + $"scaled by {scale:0.###} to fit {targetSize} m, grounded on its own base."); + } + + /// + /// Bounds of every mesh under , expressed in 's local + /// coordinates. Read from sharedMesh rather than Renderer.bounds on purpose: the holder is INACTIVE + /// while this runs (that is the whole point of the class) and a renderer that has never been enabled + /// has no world bounds yet, so Renderer.bounds would quietly return zero. + /// + private static bool TryMeasure(Transform root, Transform space, out Bounds bounds) + { + bounds = new Bounds(); + bool any = false; + + Matrix4x4 toSpace = space.worldToLocalMatrix; + + foreach (Renderer renderer in root.GetComponentsInChildren(true)) + { + if (renderer == null) continue; + + Mesh mesh; + if (renderer is SkinnedMeshRenderer skinned) + { + mesh = skinned.sharedMesh; + } + else + { + MeshFilter filter = renderer.GetComponent(); + mesh = filter != null ? filter.sharedMesh : null; + } + if (mesh == null) continue; + + Encapsulate(ref bounds, ref any, toSpace * renderer.transform.localToWorldMatrix, mesh.bounds); + } + + return any; + } + + /// All eight corners, because a rotated box's bounds are not its centre plus its extents. + private static void Encapsulate(ref Bounds bounds, ref bool any, Matrix4x4 matrix, Bounds local) + { + Vector3 centre = local.center; + Vector3 extents = local.extents; + + for (int corner = 0; corner < 8; corner++) + { + Vector3 point = matrix.MultiplyPoint3x4(centre + new Vector3( + (corner & 1) == 0 ? -extents.x : extents.x, + (corner & 2) == 0 ? -extents.y : extents.y, + (corner & 4) == 0 ? -extents.z : extents.z)); + + if (!any) { bounds = new Bounds(point, Vector3.zero); any = true; } + else bounds.Encapsulate(point); + } + } + } +} diff --git a/JotunnModStub/PieceDensityLimit.cs b/JotunnModStub/PieceDensityLimit.cs new file mode 100644 index 0000000..024014f --- /dev/null +++ b/JotunnModStub/PieceDensityLimit.cs @@ -0,0 +1,147 @@ +using System.Collections.Generic; +using HarmonyLib; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// "How many of these may stand in one region." One place, one patch, one line per station. + /// + /// Every station in the per-race item-progression system that produces something continuously has + /// to be capped, or five copies are five times the effect - a field of groves is a carpet of bees, + /// five body piles are fifty draugr. Each chain used to be expected to write its own placement + /// check; this exists so the five races still to come add a limit with one call instead of + /// re-deriving ZDO counting, and so there is exactly one Player.PlacePiece prefix rather than one + /// per race. + /// + /// Counting is done over ZDOs and not over loaded GameObjects, and that distinction is the whole + /// point: Valheim keeps only a handful of zones alive around the player, a few hundred metres at + /// most, so counting objects would let anyone dodge the cap by walking away and building again. + /// + /// HONEST LIMIT: a client only holds the ZDOs the server has sent it. In singleplayer and on the + /// host the count is exact; on a remote client it can undercount, so a cap can be exceeded by + /// someone building far from every other copy. It still closes the case that matters - fifty of + /// them around one base - and no client-side hook can do better without a server-authoritative + /// check. + /// + public static class PieceDensityLimit + { + private class Limit + { + public float Radius; + public int Max; + public string Message; + } + + private static readonly Dictionary Limits = new Dictionary(); + + /// + /// The radius of a circle with the given area, so a limit can be written the way it is + /// actually discussed - "five per 1.6 square kilometres" - instead of as a magic distance. + /// + public static float RadiusForArea(float squareKilometres) + { + return Mathf.Sqrt(squareKilometres * 1000000f / Mathf.PI); + } + + /// + /// Caps a piece. Call once from the chain's Register(); calling twice just replaces the entry, + /// so a Register() that runs more than once cannot stack limits. + /// + public static void Register(string piecePrefabName, float radius, int max, string refusalMessage) + { + if (string.IsNullOrEmpty(piecePrefabName) || max < 1 || radius <= 0f) + { + Jotunn.Logger.LogWarning($"[Density] Refusing a nonsense limit for '{piecePrefabName}' " + + $"(radius {radius}, max {max}); it will not be capped."); + return; + } + + Limits[piecePrefabName] = new Limit { Radius = radius, Max = max, Message = refusalMessage }; + Jotunn.Logger.LogInfo($"[Density] {piecePrefabName}: at most {max} within {radius:0} m."); + } + + /// + /// How many of that piece already stand within the radius of a point, or -1 if the world + /// cannot be asked right now - in which case callers must let the placement through rather + /// than refuse on no information. + /// + public static int Count(string piecePrefabName, Vector3 position, float radius) + { + if (ZDOMan.instance == null) return -1; + + List zdos = new List(); + int index = 0; + // The iterative sweep hands back a chunk per call and reports true when it is done. The + // guard is so a pathological world cannot spin here forever. + for (int guard = 0; guard < 1000; guard++) + { + if (ZDOMan.instance.GetAllZDOsWithPrefabIterative(piecePrefabName, zdos, ref index)) break; + } + + float rangeSq = radius * radius; + int count = 0; + foreach (ZDO zdo in zdos) + { + if (zdo == null) continue; + if (Vector3.SqrMagnitude(zdo.GetPosition() - position) <= rangeSq) count++; + } + + return count; + } + + /// + /// True if one more may be placed there. Unknown pieces are always allowed - a station with no + /// registered limit is not this class's business. + /// + public static bool Allow(Player player, string piecePrefabName, Vector3 position) + { + if (!Limits.TryGetValue(piecePrefabName, out Limit limit)) return true; + + int nearby = Count(piecePrefabName, position, limit.Radius); + if (nearby < 0 || nearby < limit.Max) return true; + + if (player != null) + { + player.Message(MessageHud.MessageType.Center, string.Format(limit.Message, nearby, limit.Max)); + } + return false; + } + } + + /// + /// The single enforcement point, at the moment of building - which is the only moment a refusal is + /// both cheap and understandable. Refusing later, or building and then quietly deleting what it + /// produced, would spend the player's gate item before telling them no. + /// + /// + /// The single enforcement point. + /// + /// The signature is spelled out because it is NOT the one every Valheim modding example uses. The + /// familiar `bool PlacePiece(Piece)` does not exist in this build; the real one is + /// + /// void PlacePiece(Piece piece, Vector3 pos, Quaternion rot, bool doAttack) + /// + /// read off the HarmonyX error this patch produced on the first launch. Two things follow, and the + /// first one cost a whole startup: + /// - it returns VOID, so there is no __result to write. Asking for one throws "Cannot get result + /// from void method" at patch time, and that exception propagates out of Harmony.PatchAll() - + /// which means one bad signature here stops the rest of the mod's patches from being applied + /// at all. A prefix returning false is the whole mechanism: the original simply does not run, + /// nothing is placed, and no resources are spent. + /// - the placement position is an ARGUMENT, not the piece's transform. At prefix time the Piece + /// is the build ghost, so `pos` is the authority on where this thing is actually going. + /// Parameters are bound positionally (__0, __1) so a rename cannot break startup either. + /// + [HarmonyPatch(typeof(Player), "PlacePiece", + new[] { typeof(Piece), typeof(Vector3), typeof(Quaternion), typeof(bool) })] + public static class PieceDensityLimitPatch + { + public static bool Prefix(Player __instance, Piece __0, Vector3 __1) + { + if (__instance != Player.m_localPlayer || __0 == null) return true; + + return PieceDensityLimit.Allow(__instance, Utils.GetPrefabName(__0.gameObject), __1); + } + } +} diff --git a/JotunnModStub/RaisedThrall.cs b/JotunnModStub/RaisedThrall.cs new file mode 100644 index 0000000..c838ec8 --- /dev/null +++ b/JotunnModStub/RaisedThrall.cs @@ -0,0 +1,491 @@ +using System; +using System.Collections.Generic; +using HarmonyLib; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// One conjured servant, of any race. Keeps itself within its leash of the station that made it, + /// unless the right kind of player has told it to follow. + /// + /// This started life as DraughThrall and was generalised the moment the Skeleton needed the same + /// thing - which is the call ItemProgression_Guida.txt 8.3 says to make BEFORE writing the second + /// copy rather than after. Nothing in here is draugr-specific: a leash, a wither timer, a follow + /// command and an anchor are the same problem whoever raised the body. + /// + /// The leash is not custom pathing - it is vanilla's own patrol behaviour, pointed at the station. + /// BaseAI already has m_patrol and m_patrolPoint and already wanders around that point inside + /// m_randomMoveRange, which each prefab sets to its own leash. All this component does is keep the + /// point pinned, which is also what makes "stay" send one home rather than root it wherever it + /// happened to be standing. + /// + /// The anchor lives in the creature's own ZDO as a Vector3 and doubles as the mark of which + /// station owns it - so a station can count its own even when one is three biomes away following + /// its master. + /// + public class RaisedThrall : MonoBehaviour + { + // Deliberately still spelled "draugh". These keys are in players' save files already, on + // thralls raised before this class was generalised; renaming them would leave every existing + // thrall anchorless - no leash, no wither, no orders - for the sake of a tidier string. + public const string KeyAnchor = "RoV_draughAnchor"; + public const string KeyOrphanAt = "RoV_draughOrphanAt"; + + // ─── Set on the prefab at registration ─────────────────────────────── + + /// Groups thralls for follower caps and for a station's per-kind roster. + public string m_kind = ""; + + /// Only a player of this race may give orders. Empty means anyone may. + public string m_commandingRace = ""; + + /// How many of this KIND may follow one player at once. -1 for no limit. + public int m_maxFollowers = -1; + + public float m_witherSeconds = 60f; + public float m_homeCheckRange = 20f; + + /// Shown in the refusal when a station is not this player's to command. + public string m_refusalMessage = "It does not answer to you."; + + /// + /// How many thralls of OTHER kinds, from the same station, come along when this one is + /// commanded directly. 0 for a thrall that only speaks for itself. + /// + /// This is what makes a Rancid Remains a squad leader: clicking it takes it and five of the + /// rank and file, rather than the whole garrison the pile would send. Only applies to a direct + /// click - a station moving its whole line calls SetFollowing itself, so the two cannot nest. + /// + public int m_escortCount = 0; + + // SetPatrolPoint(Vector3) is private - only the parameterless overload, which uses the + // creature's current position, is public. Resolved once here rather than per call. + private static readonly System.Reflection.MethodInfo SetPatrolPointMethod = + AccessTools.Method(typeof(BaseAI), "SetPatrolPoint", new[] { typeof(Vector3) }); + + /// + /// Every station currently loaded that owns thralls. Registered by the station's own behaviour + /// so a thrall can ask "is my station still standing?" without sweeping ZDOs or raycasting on a + /// two-second timer, ten thralls at a time. + /// + /// TRANSFORMS, not positions, and that is the whole bug this once had: the first version cached + /// transform.position at Awake, which is not yet the object's final placement. Every lookup then + /// missed, every thrall decided it was an orphan, and with the Skeleton's zero-second wither the + /// whole garrison died about four seconds after it rose. Reading .position at query time is what + /// the Draugh's own list did before it was generalised, and why that one worked. + /// + private static readonly List LiveStations = new List(); + + public static void RegisterStation(Transform station) + { + if (station != null && !LiveStations.Contains(station)) LiveStations.Add(station); + } + + public static void UnregisterStation(Transform station) => LiveStations.Remove(station); + + /// True if a loaded station stands at that point. Only meaningful when the asker is + /// close enough that the station would be loaded if it existed - see m_homeCheckRange. + public static bool StationStandsAt(Vector3 position) + { + for (int i = LiveStations.Count - 1; i >= 0; i--) + { + Transform station = LiveStations[i]; + if (station == null) { LiveStations.RemoveAt(i); continue; } // destroyed without notice + + if (Vector3.SqrMagnitude(station.position - position) < 0.25f) return true; + } + return false; + } + + private Character m_character; + private BaseAI m_ai; + private MonsterAI m_monsterAI; + private ZNetView m_nview; + + private void Awake() + { + m_character = GetComponent(); + m_ai = GetComponent(); + m_monsterAI = GetComponent(); + m_nview = GetComponent(); + + InvokeRepeating("TickLeash", 2f, 2f); + } + + /// Where the station that made this one stands, or null if it was not made by one. + 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 string Kind => m_kind; + + public bool IsFollowing(Player player) + { + return m_monsterAI != null && player != null && m_monsterAI.GetFollowTarget() == player.gameObject; + } + + /// Called at spawn by the station. Tames it, marks it, and sends it home. + public void Bind(Vector3 anchor) + { + if (m_nview == null || !m_nview.IsValid()) return; + + m_nview.GetZDO().Set(KeyAnchor, anchor); + if (m_monsterAI != null) m_monsterAI.MakeTame(); + if (m_character != null) m_character.SetTamed(true); + + GoHome(); + } + + // ---------------------------------------------------------------- the leash + + private void TickLeash() + { + if (m_nview == null || !m_nview.IsValid() || !m_nview.IsOwner()) return; + if (m_character == null || m_character.IsDead()) return; + + // Checked before anything else, and NOT skipped while following: a thrall out with its + // master still has to wither if the station behind it has fallen. + if (TickWither()) return; + + // Following overrides the leash entirely; that is the whole point of the command. + if (m_monsterAI != null && m_monsterAI.GetFollowTarget() != null) return; + + GoHome(); + } + + /// Starts the clock when the station is gone, and stops the thrall when it runs out. + /// Returns true once it has killed this one, so the caller stops bothering with it. + 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) + { + // The station marks its own thralls when it falls, but it can only mark the ones that + // are loaded at that moment. This is the other half: a thrall that was away comes + // home, finds nothing there, and marks itself. + // + // Deliberately only asked near home. Further out the station's zone is almost + // certainly unloaded, so "nothing here" would be a lie - and acting on it would kill + // the escort of anyone who walked away from their base. + if (Vector3.SqrMagnitude(transform.position - anchor.Value) > + m_homeCheckRange * m_homeCheckRange) return false; + + if (StationStandsAt(anchor.Value)) return false; + + MarkOrphaned(); + return false; + } + + // Rebuilt in time, on the same spot: the clock is cleared and the thrall lives. Safe to + // ask unconditionally - StationStandsAt can only answer true where one is actually + // loaded, so being far from home simply never rescues anything. And it opens no exploit: + // a station on the same spot adopts these thralls by anchor anyway. + if (StationStandsAt(anchor.Value)) + { + m_nview.GetZDO().Set(KeyOrphanAt, 0L); + return false; + } + + double elapsed = (ZNet.instance.GetTime() - new DateTime(stamp)).TotalSeconds; + if (elapsed < m_witherSeconds) return false; + + Kill(); + return true; + } + + /// + /// Starts the wither clock, once. Called by the station as it is destroyed, and by the thrall + /// itself if it comes home to nothing. Idempotent so the two cannot restart each other's clock + /// and keep an orphan alive forever. + /// + public void MarkOrphaned() + { + if (m_nview == null || !m_nview.IsValid() || ZNet.instance == null) return; + if (m_nview.GetZDO().GetLong(KeyOrphanAt, 0L) != 0L) return; + + m_nview.ClaimOwnership(); + m_nview.GetZDO().Set(KeyOrphanAt, ZNet.instance.GetTime().Ticks); + } + + /// + /// Pins the patrol point back onto the station. Cheap enough to call on a timer, and calling it + /// repeatedly is what stops a thrall drifting after it has been pushed, knocked back or told to + /// stay somewhere far from home. + /// + private void GoHome() + { + Vector3? anchor = Anchor; + if (anchor == null || m_ai == null) return; + + if (SetPatrolPointMethod != null) + { + SetPatrolPointMethod.Invoke(m_ai, new object[] { anchor.Value }); + } + else + { + // Fall back to writing the two fields the private method writes. + Traverse traverse = Traverse.Create(m_ai); + traverse.Field("m_patrolPoint").SetValue(anchor.Value); + traverse.Field("m_patrol").SetValue(true); + } + } + + // ---------------------------------------------------------------- commands + + public bool MayBeCommandedBy(Player player) + { + if (player == null) return false; + if (string.IsNullOrEmpty(m_commandingRace)) return true; + + return player.m_customData != null && + player.m_customData.TryGetValue("Race", out string race) && + race == m_commandingRace; + } + + /// Sends it after the player, or home. Returns false if it refused. + public bool SetFollowing(Player player, bool follow, bool announce) + { + if (player == null || m_monsterAI == null || m_character == null) return false; + + if (!MayBeCommandedBy(player)) + { + if (announce) player.Message(MessageHud.MessageType.Center, m_refusalMessage); + return false; + } + + if (!follow) + { + m_monsterAI.SetFollowTarget(null); + GoHome(); + if (announce) player.Message(MessageHud.MessageType.Center, $"{m_character.m_name} returns."); + return true; + } + + // Counted fresh on every command so deaths and dismissals free slots up on their own, + // with no tally to drift out of step. + if (m_maxFollowers >= 0 && CountFollowers(player, m_kind) >= m_maxFollowers) + { + if (announce) + { + player.Message(MessageHud.MessageType.Center, $"Only {m_maxFollowers} may walk with you."); + } + return false; + } + + m_monsterAI.SetFollowTarget(player.gameObject); + if (announce) player.Message(MessageHud.MessageType.Center, $"{m_character.m_name} follows."); + return true; + } + + /// + /// Follow if it is not, come home if it is - the wolf's own single-key behaviour, plus an escort + /// if this thrall leads one. + /// + public void ToggleCommand(Player player) + { + bool follow = !IsFollowing(player); + if (!SetFollowing(player, follow, announce: m_escortCount <= 0)) return; + if (m_escortCount <= 0) return; + + // A squad, not the whole line. Anchor-bound, other kinds only - the rank and file, never + // another leader - and capped at m_escortCount. + Vector3? anchor = Anchor; + if (anchor == null) return; + + int taken = 0; + foreach (RaisedThrall other in BoundTo(anchor.Value)) + { + if (other == this || other.m_kind == m_kind) continue; + + // Going out: only pick up ones that are not already out. Coming home: only send back + // the ones that are actually with this player, so another squad is left alone. + if (follow ? other.IsFollowing(player) : !other.IsFollowing(player)) continue; + if (taken >= m_escortCount) break; + + if (other.SetFollowing(player, follow, announce: false)) taken++; + } + + player.Message(MessageHud.MessageType.Center, follow + ? $"{m_character.m_name} rises with {taken}." + : $"{m_character.m_name} stands down with {taken}."); + } + + private static int CountFollowers(Player player, string kind) + { + int count = 0; + foreach (Character character in Character.GetAllCharacters()) + { + if (character == null || character.IsDead()) continue; + + RaisedThrall thrall = character.GetComponent(); + if (thrall == null || thrall.m_kind != kind) continue; + if (thrall.IsFollowing(player)) count++; + } + return count; + } + + /// Every living thrall bound to the station at this position. + public static List BoundTo(Vector3 anchor) + { + List bound = new List(); + + foreach (Character character in Character.GetAllCharacters()) + { + if (character == null || character.IsDead()) continue; + + RaisedThrall thrall = character.GetComponent(); + if (thrall == null) continue; + + Vector3? own = thrall.Anchor; + // A generous epsilon: a station never moves, so this only has to survive float + // round-tripping through the ZDO. + if (own != null && Vector3.SqrMagnitude(own.Value - anchor) < 0.25f) bound.Add(thrall); + } + + return bound; + } + + // ---------------------------------------------------------------- the call + + /// Earshot. A shouted gesture reaches what is nearby, not the whole world. + public const float TauntRange = 30f; + + /// + /// The emote that calls thralls to their master. A SET rather than one string because the emote + /// names are not in the assembly at all - Valheim builds them from what the player types in + /// chat, so unlike every other name in this project this one could not be read off the game and + /// verified. The patch below logs whatever it actually receives, so a wrong guess here is one + /// line away from being right instead of a mystery. + /// + private static readonly HashSet TauntEmotes = new HashSet + { + "comehere", "come_here", "followme", + }; + + /// + /// Everything within earshot that answers to this player falls in behind them. + /// + /// Only ever a call, never a dismissal: "come here" means come here. Sending them home stays + /// with the station and with a click on the thrall itself. + /// + /// The per-race follower cap needs no special handling - SetFollowing enforces m_maxFollowers + /// itself, so the Skeleton's whole garrison answers (-1, no limit) and the Draugh's gets three + /// draugr and one officer, from exactly the same call. + /// + public static void CallToArms(Player player) + { + if (player == null) return; + + int came = 0; + int refused = 0; + + foreach (Character character in Character.GetAllCharacters()) + { + if (character == null || character.IsDead()) continue; + + RaisedThrall thrall = character.GetComponent(); + if (thrall == null || thrall.IsFollowing(player)) continue; + if (!thrall.MayBeCommandedBy(player)) continue; + if (Vector3.SqrMagnitude(character.transform.position - player.transform.position) > + TauntRange * TauntRange) continue; + + if (thrall.SetFollowing(player, true, announce: false)) came++; + else refused++; + } + + if (came > 0) + { + player.Message(MessageHud.MessageType.Center, $"{came} answer the call."); + } + else if (refused > 0) + { + // The only way SetFollowing refuses a thrall that may be commanded is the cap. + player.Message(MessageHud.MessageType.Center, "No more may walk with you."); + } + } + + public static bool IsTauntEmote(string emote) + { + return emote != null && TauntEmotes.Contains(emote.ToLowerInvariant()); + } + + public void Kill() + { + if (m_character == null || m_character.IsDead()) return; + + HitData hit = new HitData(); + hit.m_damage.m_damage = 1E+10f; + hit.m_hitType = HitData.HitType.Undefined; + m_character.ApplyDamage(hit, true, false); + } + } + + /// + /// Routes E on a thrall to , before vanilla resolves the + /// target itself. + /// + /// This is a prefix on Player.Interact rather than an Interactable on the thrall, and that is not + /// a style choice. AswidPatches' own Character.Awake postfix adds AswidThrall - also Interactable + /// - to essentially every mob carrying a MonsterAI, and it wins vanilla's + /// GetComponentInParent<Interactable>() race on whatever it touches. That is the exact bug + /// FactionMerchantInteractPatch exists to work around, where pressing E called AswidThrall.Interact + /// instead of Trader.Interact, silently and with no error. Handling our own thralls here sidesteps + /// component order entirely instead of depending on it. + /// + /// The feedback is a centre-screen message and not hover text for the same reason: Character is + /// itself Hoverable and sits ahead of everything added later, so hover is a race this cannot win + /// cleanly. The station's own hover text carries the roster and the rules. + /// + /// + /// The "come here" gesture calls every thrall in earshot to its master. + /// + /// A POSTFIX with positional binding and no __result, which is the safest shape available: postfixes + /// need no return value, so this cannot repeat the PlacePiece failure where asking for a __result on + /// a void method threw at patch time and stopped the rest of the mod being patched. + /// + /// The emote name is logged on every emote the local player performs, because the names are the one + /// class of string in this project that could not be verified against the game - they are built from + /// the player's own chat input, not stored in the assembly. Do the gesture once and the log names it. + /// + [HarmonyPatch(typeof(Player), "StartEmote")] + public static class RaisedThrallTauntPatch + { + public static void Postfix(Player __instance, string __0) + { + if (__instance != Player.m_localPlayer) return; + + Jotunn.Logger.LogInfo($"[Thrall] emote '{__0}'" + + (RaisedThrall.IsTauntEmote(__0) ? " - calling thralls." : ".")); + + if (RaisedThrall.IsTauntEmote(__0)) RaisedThrall.CallToArms(__instance); + } + } + + [HarmonyPatch(typeof(Player), "Interact")] + public static class RaisedThrallInteractPatch + { + public static bool Prefix(Player __instance, GameObject go, bool hold, bool alt) + { + if (go == null || hold) return true; + if (__instance != Player.m_localPlayer) return true; + + RaisedThrall thrall = go.GetComponentInParent(); + if (thrall == null) return true; // not ours - let vanilla's own resolution run + + thrall.ToggleCommand(__instance); + return false; + } + } +} -- 2.52.0 From fae82162beed7cd81e0a126729c4f17f156f42ab Mon Sep 17 00:00:00 2001 From: Ferdinando Date: Fri, 7 Aug 2026 17:02:34 +0200 Subject: [PATCH 2/8] feat(aswid): blood refinery and blood potions Co-Authored-By: Claude Opus 5 --- JotunnModStub/Aswid/AswidBloodPotions.cs | 298 +++++++++ JotunnModStub/Aswid/AswidBloodRefinery.cs | 573 ++++++++++++++++++ JotunnModStub/Aswid/AswidPatches.cs | 4 +- JotunnModStub/Aswid/AswidRace.cs | 18 +- JotunnModStub/Aswid/BloodRefineryBehaviour.cs | 299 +++++++++ 5 files changed, 1185 insertions(+), 7 deletions(-) create mode 100644 JotunnModStub/Aswid/AswidBloodPotions.cs create mode 100644 JotunnModStub/Aswid/AswidBloodRefinery.cs create mode 100644 JotunnModStub/Aswid/BloodRefineryBehaviour.cs diff --git a/JotunnModStub/Aswid/AswidBloodPotions.cs b/JotunnModStub/Aswid/AswidBloodPotions.cs new file mode 100644 index 0000000..5e7e10f --- /dev/null +++ b/JotunnModStub/Aswid/AswidBloodPotions.cs @@ -0,0 +1,298 @@ +using System.Collections; +using HarmonyLib; +using Jotunn.Configs; +using Jotunn.Entities; +using Jotunn.Managers; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// The second step of the refinement chain, brewed at the Mead Ketill: + /// + /// 5 Blood Essence -> 1 Superior Blood Essence + /// 3 Blood Essence + 5 Blueberries + /// + 5 Yellow Mushrooms -> Blood Potion mead base + /// 3 Superior Blood Essence + 5 Sap + /// + 5 Cloudberry -> Superior Blood Potion mead base + /// + /// Either base then goes into a Fermenter and comes out as five bottles. Drinking one force + /// feeds every food slot with the matching essence - full stomachs and all - and heals a + /// percentage of maximum health over eight seconds. + /// + public static class AswidBloodPotions + { + public const string BaseName = "MeadBaseBloodPotion"; + public const string PotionName = "MeadBloodPotion"; + public const string SuperiorBaseName = "MeadBaseSuperiorBloodPotion"; + public const string SuperiorPotionName = "MeadSuperiorBloodPotion"; + + private const string PotionDisplayName = "Blood Potion"; + private const string SuperiorPotionDisplayName = "Superior Blood Potion"; + + private const float HealDuration = 8f; + private const float HealFraction = 0.05f; + private const float SuperiorHealFraction = 0.10f; + + // Five bottles per barrel, as designed. + private const int BottlesPerBrew = 5; + + /// + /// Blood brews are done in a quarter of the normal time. The fermenter keeps a single + /// duration for every recipe, so instead of shortening it - which would speed up every + /// vanilla mead in the barrel - the elapsed time is multiplied while our base is inside. + /// + public const double FermentSpeedMultiplier = 4.0; + + private static readonly System.Reflection.MethodInfo GetContentMethod = + AccessTools.Method(typeof(Fermenter), "GetContent"); + + public static void Register() + { + SE_BloodPotion drink = CreateEffect("SE_BloodPotion", PotionDisplayName, HealFraction, + AswidBloodRefinery.EssenceName, "GemstoneRed"); + SE_BloodPotion superiorDrink = CreateEffect("SE_SuperiorBloodPotion", SuperiorPotionDisplayName, + SuperiorHealFraction, AswidBloodRefinery.SuperiorEssenceName, "MoltenCore"); + + GameObject meadBase = CloneItem(BaseName, "MeadBaseHealthMinor", "Blood Potion Mead Base", + "Blood, berries and crypt light, waiting on a barrel."); + GameObject potion = CloneItem(PotionName, "MeadHealthMinor", PotionDisplayName, + "Drink and the hunger stops mattering for a while. Fills every stomach with blood essence, " + + "full or not, and knits the flesh back together."); + GameObject superiorBase = CloneItem(SuperiorBaseName, "MeadBaseHealthMedium", "Superior Blood Potion Mead Base", + "The twice-rendered draught, still raw."); + GameObject superiorPotion = CloneItem(SuperiorPotionName, "MeadHealthMedium", SuperiorPotionDisplayName, + "The same mercy, twice as deep."); + + AttachEffect(potion, drink); + AttachEffect(superiorPotion, superiorDrink); + + AddRecipe(AswidBloodRefinery.SuperiorEssenceName, new[] + { + new RequirementConfig(AswidBloodRefinery.EssenceName, 5), + }); + + AddRecipe(BaseName, new[] + { + new RequirementConfig(AswidBloodRefinery.EssenceName, 3), + new RequirementConfig("Blueberries", 5), + // "Funghi luminosi": the Yellow Mushroom, the one that glows in the burial + // chambers. Same tier as the blueberries, unlike the Mistlands blue one. + new RequirementConfig("MushroomYellow", 5), + }); + + AddRecipe(SuperiorBaseName, new[] + { + new RequirementConfig(AswidBloodRefinery.SuperiorEssenceName, 3), + new RequirementConfig("Sap", 5), + new RequirementConfig("Cloudberry", 5), + }); + + AddFermenterConversion(meadBase, potion); + AddFermenterConversion(superiorBase, superiorPotion); + } + + // ---------------------------------------------------------------- items + + private static GameObject CloneItem(string prefabName, string source, string displayName, string description) + { + GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(prefabName, source); + if (prefab == null) + { + Jotunn.Logger.LogWarning($"[Aswid] Could not clone '{source}'; {displayName} not registered."); + return null; + } + + ItemDrop drop = prefab.GetComponent(); + if (drop == null) return null; + + ItemDrop.ItemData.SharedData shared = drop.m_itemData.m_shared; + shared.m_name = displayName; + shared.m_description = description; + // The clone arrives carrying the vanilla health mead's own effect; ours is attached + // afterwards, and the mead bases must carry none at all. + shared.m_consumeStatusEffect = null; + + ItemManager.Instance.AddItem(new CustomItem(prefab, fixReference: false)); + return prefab; + } + + private static void AttachEffect(GameObject potion, SE_BloodPotion effect) + { + ItemDrop drop = potion != null ? potion.GetComponent() : null; + if (drop == null || effect == null) return; + drop.m_itemData.m_shared.m_consumeStatusEffect = effect; + } + + private static void AddRecipe(string item, RequirementConfig[] requirements) + { + ItemManager.Instance.AddRecipe(new CustomRecipe(new RecipeConfig + { + Item = item, + Amount = 1, + CraftingStation = CraftingStations.MeadKetill, + Requirements = requirements, + })); + } + + /// + /// Teaches the vanilla fermenter one more brew. The vanilla prefab's conversion list is + /// appended to rather than replaced, so every stock mead still works. + /// + private static void AddFermenterConversion(GameObject from, GameObject to) + { + if (from == null || to == null) return; + + GameObject barrel = PrefabManager.Cache.GetPrefab("fermenter"); + Fermenter fermenter = barrel != null ? barrel.GetComponent() : null; + if (fermenter == null) + { + Jotunn.Logger.LogWarning("[Aswid] No fermenter prefab; blood potions cannot be brewed."); + return; + } + + ItemDrop fromDrop = from.GetComponent(); + ItemDrop toDrop = to.GetComponent(); + if (fromDrop == null || toDrop == null) return; + + foreach (Fermenter.ItemConversion existing in fermenter.m_conversion) + { + if (existing != null && existing.m_from == fromDrop) return; // already taught + } + + fermenter.m_conversion.Add(new Fermenter.ItemConversion + { + m_from = fromDrop, + m_to = toDrop, + m_producedItems = BottlesPerBrew, + }); + } + + // ---------------------------------------------------------------- status effect + + private static SE_BloodPotion CreateEffect(string name, string displayName, float fraction, + string essencePrefab, string iconSource) + { + SE_BloodPotion effect = ScriptableObject.CreateInstance(); + effect.name = name; + effect.m_name = displayName; + effect.m_tooltip = $"Stomachs filled with blood. Healing {Mathf.RoundToInt(fraction * 100f)}% over {HealDuration:0} seconds."; + effect.m_ttl = HealDuration; + effect.m_healFraction = fraction; + effect.m_essencePrefab = essencePrefab; + + // A flat m_healthOverTime cannot express "5% of maximum health", so the real number is + // computed per drinker in SE_BloodPotion.Setup. One tick a second over the eight. + effect.m_healthOverTimeDuration = HealDuration; + effect.m_healthOverTimeInterval = 1f; + + ItemDrop source = PrefabManager.Cache.GetPrefab(iconSource); + Sprite[] icons = source != null && source.m_itemData != null && source.m_itemData.m_shared != null + ? source.m_itemData.m_shared.m_icons + : null; + if (icons != null && icons.Length > 0) effect.m_icon = icons[0]; + + ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(effect, fixReference: false)); + return effect; + } + + /// + /// Force feeds every food slot with the given essence, ignoring whether the stomachs are + /// full - that refusal is the whole point of drinking the potion. The Aswid's fourth slot + /// is filled too once the progression has unlocked it. + /// + public static void FillStomachs(Player player, string essencePrefabName) + { + if (player == null || ObjectDB.instance == null) return; + + GameObject prefab = ObjectDB.instance.GetItemPrefab(essencePrefabName); + ItemDrop drop = prefab != null ? prefab.GetComponent() : null; + if (drop == null) return; + + Traverse traverse = Traverse.Create(player); + IList foods = traverse.Field("m_foods").GetValue(); + if (foods == null) return; + + foods.Clear(); + for (int slot = 0; slot < 3; slot++) + { + foods.Add(MakeFood(drop, prefab, essencePrefabName)); + } + + if (AswidRace.IsAswid() && BossProgressionManager.GetCurrentProgressionState() >= 8) + { + ItemDrop.ItemData item = drop.m_itemData.Clone(); + item.m_dropPrefab = prefab; + AswidFoodManager.SetExtraFood(player, item); + } + + traverse.Method("UpdateFood", 0f, true).GetValue(); + } + + /// True while one of our two mead bases is the thing fermenting in that barrel. + public static bool IsBloodBrew(Fermenter fermenter) + { + if (fermenter == null || GetContentMethod == null) return false; + + string content = GetContentMethod.Invoke(fermenter, null) as string; + return content == BaseName || content == SuperiorBaseName; + } + + private static Player.Food MakeFood(ItemDrop drop, GameObject prefab, string prefabName) + { + ItemDrop.ItemData item = drop.m_itemData.Clone(); + // Vanilla reads m_dropPrefab.name when it rebuilds a food entry, and a cloned + // ItemData off a raw prefab does not carry it. + item.m_dropPrefab = prefab; + + return new Player.Food + { + m_name = prefabName, + m_item = item, + m_time = item.m_shared.m_foodBurnTime, + m_health = item.m_shared.m_food, + m_stamina = item.m_shared.m_foodStamina, + m_eitr = item.m_shared.m_foodEitr, + }; + } + } + + /// + /// Blood ferments fast. GetFermentationTime is the single place the barrel measures progress + /// from - GetStatus is its only caller - so scaling the elapsed time here makes the brew ready + /// at a quarter of the duration and keeps the hover text agreeing with it, without touching + /// m_fermentationDuration and dragging every vanilla mead along. + /// + [HarmonyPatch(typeof(Fermenter), "GetFermentationTime")] + public static class AswidBloodPotionFermentPatch + { + public static void Postfix(Fermenter __instance, ref double __result) + { + if (__result <= 0.0) return; + if (!AswidBloodPotions.IsBloodBrew(__instance)) return; + + __result *= AswidBloodPotions.FermentSpeedMultiplier; + } + } + + /// + /// The effect both potions apply. Heals a fraction of maximum health rather than a flat + /// amount, which SE_Stats cannot express on its own, and refills the drinker's food slots. + /// + public class SE_BloodPotion : SE_Stats + { + public float m_healFraction = 0.05f; + public string m_essencePrefab = ""; + + public override void Setup(Character character) + { + // SEMan clones the effect before setting it up, so writing the resolved amount here + // touches this drinker's copy only. + if (character != null) m_healthOverTime = character.GetMaxHealth() * m_healFraction; + + base.Setup(character); + + AswidBloodPotions.FillStomachs(character as Player, m_essencePrefab); + } + } +} diff --git a/JotunnModStub/Aswid/AswidBloodRefinery.cs b/JotunnModStub/Aswid/AswidBloodRefinery.cs new file mode 100644 index 0000000..1990b1e --- /dev/null +++ b/JotunnModStub/Aswid/AswidBloodRefinery.cs @@ -0,0 +1,573 @@ +using System.Collections.Generic; +using HarmonyLib; +using Jotunn.Configs; +using Jotunn.Entities; +using Jotunn.Managers; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// The Aswid station: a half-size, blood-dark copy of the Eitr Refinery that eats raw flesh + /// and bone and produces Blood Essence, the base currency of the (future) Aswid potion tree. + /// + /// The whole chain is gated behind the Blood Core, an item sold by the Draugr faction + /// merchant, so the station cannot be reached without going through the Factions system. + /// + /// The vanilla refinery is a : a queue of "ore" names plus a single + /// fuel type, one product per queued item. That shape does not fit two numeric tanks fed by + /// many different items with different yields, so the Smelter component is stripped after its + /// scene references (switches, animators, output point, effect lists, state objects) are + /// handed over to . That is why the animation and the VFX + /// stay exactly the ones the vanilla refinery plays. + /// + public static class AswidBloodRefinery + { + public const string PieceName = "AswidBloodRefinery"; + public const string EssenceName = "BloodEssence"; + public const string SuperiorEssenceName = "SuperiorBloodEssence"; + public const string CoreName = "BloodCore"; + + // The Aswid food patches recognise a meal by its display name, so these strings are part + // of the contract with AswidPatches - see IsAswidMeal. + public const string EssenceDisplayName = "Blood Essence"; + public const string SuperiorEssenceDisplayName = "Superior Blood Essence"; + public const string CoreDisplayName = "Blood Core"; + public const string PieceDisplayName = "Blood Refinery"; + + // Regeneration is tied to the health value rather than set per tier, so 60 hp gives 5 and + // 80 hp gives 6.67 without a second number to keep in sync. + private const float RegenPerHealth = 12f; + + public static GameObject EssencePrefab { get; private set; } + public static GameObject SuperiorEssencePrefab { get; private set; } + + // Half size, as designed. Everything under the root scales with it. + private const float ModelScale = 0.5f; + + private static readonly Color BodyTint = new Color(0.13f, 0.07f, 0.07f, 1f); + private static readonly Color BodyEmission = new Color(0.20f, 0.01f, 0.01f, 1f); + private static readonly Color EssenceTint = new Color(0.62f, 0.03f, 0.04f, 1f); + private static readonly Color SuperiorEssenceTint = new Color(0.85f, 0.0f, 0.02f, 1f); + private static readonly Color EssenceEmission = new Color(0.16f, 0.0f, 0.0f, 1f); + + /// + /// Every bone in the game and what it is worth to the machine. Bones carry no food values + /// to derive a number from, unlike meat, so this table is explicit. Names verified against + /// the shipped asset manifest, not guessed; entries the running game does not have are + /// simply never matched. + /// + public static readonly Dictionary BoneValues = new Dictionary + { + { "BoneFragments", 1 }, // Swamp / skeletons, the common one + { "CharredBone", 2 }, // Ashlands + { "Charredskull", 3 }, // Ashlands + { "WitheredBone", 3 }, // Bonemass offering, still just a bone + { "AsksvinCarrionNeck", 2 }, // Ashlands asksvin carrion + { "AsksvinCarrionPelvic", 2 }, + { "AsksvinCarrionRibcage", 3 }, + { "AsksvinCarrionSkull", 3 }, + { "UndeadBjornRibcage", 3 }, // Deep North + }; + + // Vanilla grills. Anything they cook counts as raw flesh, which keeps modded meat working. + private static readonly string[] CookingStationPrefabs = + { + "piece_cookingstation", + "piece_cookingstation_iron", + }; + + private static Dictionary meatToCooked; + + public static void Register() + { + RegisterCore(); + RegisterEssence(); + RegisterPiece(); + AswidBloodPotions.Register(); + } + + /// + /// True for anything the Aswid is allowed to put in a food slot: the blood drained from a + /// mob, or refined Blood Essence. AswidPatches routes both through the same slot logic. + /// + public static bool IsAswidMeal(ItemDrop.ItemData item) + { + if (item == null || item.m_shared == null || item.m_shared.m_name == null) return false; + return item.m_shared.m_name.StartsWith("Aswid Food:") + || item.m_shared.m_name == EssenceDisplayName + || IsEssence(item); + } + + /// Either tier of refined blood - the things only an Aswid may swallow. + public static bool IsEssence(ItemDrop.ItemData item) + { + if (item == null || item.m_shared == null || item.m_shared.m_name == null) return false; + return item.m_shared.m_name == EssenceDisplayName || item.m_shared.m_name == SuperiorEssenceDisplayName; + } + + // ---------------------------------------------------------------- items + + private static void RegisterCore() + { + GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(CoreName, "Bloodbag"); + if (prefab == null) + { + Jotunn.Logger.LogWarning("[Aswid] Could not clone Bloodbag; Blood Core not registered."); + return; + } + + ItemDrop drop = prefab.GetComponent(); + if (drop == null) return; + + ItemDrop.ItemData.SharedData shared = drop.m_itemData.m_shared; + shared.m_name = CoreDisplayName; + shared.m_description = "A knot of clotted blood kept beating by something that is not a heart. " + + "The dead trade them; only the dead know how they are made."; + shared.m_itemType = ItemDrop.ItemData.ItemType.Material; + shared.m_food = 0f; + shared.m_foodStamina = 0f; + shared.m_foodEitr = 0f; + shared.m_weight = 0.5f; + shared.m_maxStackSize = 20; + + Sprite icon = BorrowIcon("MorgenHeart"); + if (icon != null) shared.m_icons = new[] { icon }; + + ItemManager.Instance.AddItem(new CustomItem(prefab, fixReference: false)); + } + + private static void RegisterEssence() + { + EssencePrefab = BuildEssence( + EssenceName, + EssenceDisplayName, + "Blood rendered down to what it actually is. The only real food an Aswid can " + + "still chew, and the base of every draught worth brewing.", + food: 60f, + tint: EssenceTint, + iconSource: "GemstoneRed"); + + SuperiorEssencePrefab = BuildEssence( + SuperiorEssenceName, + SuperiorEssenceDisplayName, + "The same blood, rendered twice. Darker, thicker, and worth five of the first pass.", + food: 80f, + tint: SuperiorEssenceTint, + iconSource: "MoltenCore"); + } + + /// + /// Both essences are the same object with a different weight of red behind them. Stamina + /// and burn time are deliberately shared: only the health and the regeneration that scales + /// off it change between the two tiers. + /// + private static GameObject BuildEssence(string prefabName, string displayName, string description, + float food, Color tint, string iconSource) + { + GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(prefabName, "Eitr"); + if (prefab == null) + { + Jotunn.Logger.LogWarning($"[Aswid] Could not clone Eitr; {displayName} not registered."); + return null; + } + + // Refined eitr carries a Radiator of its own plus a point light. The design calls for + // red spheres that emit no light and hurt nothing, so both go. + StripOffensive(prefab, prefabName); + StripGlow(prefab, prefabName); + Recolour(prefab, tint, EssenceEmission); + RedShiftEffects(prefab, tint); + + ItemDrop drop = prefab.GetComponent(); + if (drop == null) return null; + + ItemDrop.ItemData.SharedData shared = drop.m_itemData.m_shared; + shared.m_name = displayName; + shared.m_description = description; + shared.m_itemType = ItemDrop.ItemData.ItemType.Consumable; + shared.m_weight = 0.2f; + + // Top of the food ladder on purpose: it costs a station, a purchased Core, and a pile + // of corpses, and no other race can swallow it. + shared.m_food = food; + shared.m_foodStamina = 60f; + shared.m_foodEitr = 0f; + shared.m_foodBurnTime = 2400f; // 40 minutes + shared.m_foodRegen = food / RegenPerHealth; + shared.m_consumeStatusEffect = null; + + // Repainting the eitr sprite pixel by pixel produced an empty slot in the inventory + // (the icon atlas is not readable), so a vanilla red icon is borrowed instead. + Sprite icon = BorrowIcon(iconSource); + if (icon != null) shared.m_icons = new[] { icon }; + + ItemManager.Instance.AddItem(new CustomItem(prefab, fixReference: false)); + return prefab; + } + + // ---------------------------------------------------------------- piece + + private static void RegisterPiece() + { + GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(PieceName, "eitrrefinery"); + if (prefab == null) + { + Jotunn.Logger.LogWarning("[Aswid] Could not clone eitrrefinery; Blood Refinery not registered."); + return; + } + + Smelter smelter = prefab.GetComponentInChildren(true); + if (smelter == null) + { + Jotunn.Logger.LogWarning("[Aswid] eitrrefinery clone has no Smelter; Blood Refinery not registered."); + return; + } + + BloodRefineryBehaviour refinery = smelter.gameObject.AddComponent(); + refinery.m_addMeatSwitch = smelter.m_addOreSwitch; // the soft tissue slot + refinery.m_addBoneSwitch = smelter.m_addWoodSwitch; // the sap slot + refinery.m_outputPoint = smelter.m_outputPoint; + refinery.m_enabledObject = smelter.m_enabledObject; + refinery.m_disabledObject = smelter.m_disabledObject; + refinery.m_haveBoneObject = smelter.m_haveFuelObject; + refinery.m_haveMeatObject = smelter.m_haveOreObject; + refinery.m_noMeatObject = smelter.m_noOreObject; + refinery.m_animators = smelter.m_animators; + refinery.m_meatAddedEffects = smelter.m_oreAddedEffects; + refinery.m_boneAddedEffects = smelter.m_fuelAddedEffects; + refinery.m_produceEffects = smelter.m_produceEffects; + refinery.m_smokeSpawner = smelter.m_smokeSpawner; + + Object.DestroyImmediate(smelter); + + // Two Radiators under _enabled are what shot the tester: see IsOffensive. + StripOffensive(prefab, PieceName); + SanitiseEffects(refinery.m_meatAddedEffects, PieceName + ".oreAdded"); + SanitiseEffects(refinery.m_boneAddedEffects, PieceName + ".fuelAdded"); + SanitiseEffects(refinery.m_produceEffects, PieceName + ".produce"); + + prefab.transform.localScale = Vector3.one * ModelScale; + Recolour(prefab, BodyTint, BodyEmission); + RedShiftEffects(prefab); + + Piece piece = prefab.GetComponent(); + if (piece != null) + { + // Same call as RaceMenuWard: a piece whose crafting station is out of range is + // hidden from the hammer entirely, and this one has to be findable. + piece.m_craftingStation = null; + piece.m_resources = new Piece.Requirement[0]; + piece.m_name = PieceDisplayName; + } + + PieceConfig config = new PieceConfig + { + Name = PieceDisplayName, + Description = "Flesh goes in, bone goes in, and what is left of both comes out red.", + PieceTable = PieceTables.Hammer, + Category = PieceCategories.Crafting, + Requirements = new[] + { + new RequirementConfig(CoreName, 1, 0, true), + new RequirementConfig("Stone", 20, 0, true), + new RequirementConfig("Bronze", 10, 0, true), + } + }; + + PieceManager.Instance.AddPiece(new CustomPiece(prefab, fixReference: false, config)); + } + + /// + /// A piece only shows up in the hammer once it is in the player's known recipes, and the + /// vanilla learning pass misses pieces injected after the fact - the same trap + /// RaceMenuWard fell into. The Blood Core requirement is the real gate; this only makes + /// the entry visible (greyed out until you own one). + /// + public static void EnsureKnown(Player player) + { + if (player == null) return; + + GameObject prefab = PrefabManager.Instance.GetPrefab(PieceName); + Piece piece = prefab != null ? prefab.GetComponent() : null; + if (piece == null) return; + + Traverse traverse = Traverse.Create(player); + traverse.Method("AddKnownPiece", piece).GetValue(); + traverse.Method("UpdateAvailablePiecesList").GetValue(); + } + + // ---------------------------------------------------------------- input values + + /// Units of blood a single piece of this item is worth, 0 if it is not flesh. + public static int BloodValue(string prefabName) + { + EnsureMeatMap(); + if (string.IsNullOrEmpty(prefabName) || !meatToCooked.TryGetValue(prefabName, out string cookedName)) return 0; + + // The yield is what the COOKED version would have given the eater: health plus + // stamina, so a lox steak is worth more than a neck tail without a second table. + ItemDrop.ItemData.SharedData source = SharedOf(cookedName) ?? SharedOf(prefabName); + if (source == null) return 1; + + int units = Mathf.CeilToInt((source.m_food + source.m_foodStamina) / 20f); + return Mathf.Max(1, units); + } + + /// + /// The same question BloodValue answers - "how much soft tissue is this piece of flesh + /// worth" - under a name that does not say "blood", for callers outside the Aswid. The + /// Trenta's Composter rots the same meat this refinery renders, so it asks here rather + /// than keeping a second table that would drift out of step with this one. + /// + public static int FleshValue(string prefabName) => BloodValue(prefabName); + + /// Units of bone a single piece of this item is worth, 0 if it is not a bone. + public static int BoneValue(string prefabName) + { + if (string.IsNullOrEmpty(prefabName)) return 0; + return BoneValues.TryGetValue(prefabName, out int units) ? units : 0; + } + + private static void EnsureMeatMap() + { + if (meatToCooked != null) return; + + // The raw -> cooked table the Draugh already maintains is the source of truth. + meatToCooked = new Dictionary(DraughFoodPatches.rawToCookedMapping); + meatToCooked.Remove("GreydwarfEye"); // stew ingredient, not flesh + meatToCooked["AsksvinMeat"] = "CookedAsksvinMeat"; + meatToCooked["BoneMawSerpentMeat"] = "CookedBoneMawSerpentMeat"; + + foreach (string stationName in CookingStationPrefabs) + { + GameObject station = PrefabManager.Cache.GetPrefab(stationName); + CookingStation cooking = station != null ? station.GetComponent() : null; + if (cooking == null || cooking.m_conversion == null) continue; + + foreach (CookingStation.ItemConversion conversion in cooking.m_conversion) + { + if (conversion == null || conversion.m_from == null || conversion.m_to == null) continue; + string from = conversion.m_from.gameObject.name; + if (!meatToCooked.ContainsKey(from)) meatToCooked[from] = conversion.m_to.gameObject.name; + } + } + } + + private static ItemDrop.ItemData.SharedData SharedOf(string prefabName) + { + GameObject prefab = ObjectDB.instance != null ? ObjectDB.instance.GetItemPrefab(prefabName) : null; + ItemDrop drop = prefab != null ? prefab.GetComponent() : null; + return drop != null ? drop.m_itemData.m_shared : null; + } + + // ---------------------------------------------------------------- prefab surgery + + /// + /// Removes anything on the prefab that can hurt somebody. Kept type-based rather than + /// name-based so a game update that renames a child object cannot quietly bring the + /// damage back. + /// + internal static void StripOffensive(GameObject root, string label) + { + foreach (MonoBehaviour behaviour in root.GetComponentsInChildren(true)) + { + if (behaviour == null || !IsOffensive(behaviour)) continue; + + Jotunn.Logger.LogInfo($"[Aswid] {label}: stripped {behaviour.GetType().Name} from '{behaviour.gameObject.name}'."); + Object.DestroyImmediate(behaviour); + } + } + + private static bool IsOffensive(MonoBehaviour behaviour) + { + // Radiator is the one that shoots. It is a plain MonoBehaviour holding a projectile + // prefab in a field and firing it every 2-5 seconds while its object is enabled, which + // is why neither an interface check nor a hierarchy scan for projectiles found it. The + // refinery carries two under _enabled (so only while it is running) and refined eitr + // carries one of its own - hence the 60 damage plus poison out of nowhere. + if (behaviour is Radiator) return true; + if (behaviour is IProjectile || behaviour is Aoe || behaviour is Turret) return true; + + // An EffectArea is usually harmless bookkeeping - PlayerBase marks the thing as part of + // a home, and stripping that was a mistake in the first pass. Only the burning kinds go. + EffectArea area = behaviour as EffectArea; + if (area == null) return false; + return (area.m_type & (EffectArea.Type.Heat | EffectArea.Type.Fire | EffectArea.Type.Burning)) != 0; + } + + private static bool IsOffensivePrefab(GameObject prefab) + { + if (prefab == null) return false; + if (prefab.name.ToLowerInvariant().Contains("radiation")) return true; + + foreach (MonoBehaviour behaviour in prefab.GetComponentsInChildren(true)) + { + if (behaviour != null && IsOffensive(behaviour)) return true; + } + return false; + } + + /// + /// Drops any effect the refinery plays that carries something damaging with it. Only the + /// list on our own clone is rebuilt - the referenced prefabs are the vanilla ones and are + /// never touched, so the real eitr refinery keeps working. + /// + private static void SanitiseEffects(EffectList list, string label) + { + if (list == null || list.m_effectPrefabs == null) return; + + List kept = new List(); + foreach (EffectList.EffectData data in list.m_effectPrefabs) + { + if (data == null || data.m_prefab == null) continue; + + if (IsOffensivePrefab(data.m_prefab)) + { + Jotunn.Logger.LogInfo($"[Aswid] {label}: dropped effect '{data.m_prefab.name}' (carries damage)."); + continue; + } + + Jotunn.Logger.LogInfo($"[Aswid] {label}: kept effect '{data.m_prefab.name}'."); + kept.Add(data); + } + list.m_effectPrefabs = kept.ToArray(); + } + + private static void StripGlow(GameObject root, string label) + { + // LightFlicker and LightLod both grab the Light in Awake without a null check, so + // deleting the Light on its own threw on every sphere the machine produced. They go + // first, and the light after. + foreach (LightFlicker flicker in root.GetComponentsInChildren(true)) + { + if (flicker != null) Object.DestroyImmediate(flicker); + } + foreach (LightLod lod in root.GetComponentsInChildren(true)) + { + if (lod != null) Object.DestroyImmediate(lod); + } + foreach (Light light in root.GetComponentsInChildren(true)) + { + if (light != null) Object.DestroyImmediate(light); + } + + foreach (Transform child in root.GetComponentsInChildren(true)) + { + if (child == null || child == root.transform) continue; + string name = child.gameObject.name.ToLowerInvariant(); + if (name.Contains("radiation") || name.Contains("gamma") || name.Contains("halo") || name.Contains("glow")) + { + Jotunn.Logger.LogInfo($"[Aswid] {label}: removed glow child '{child.gameObject.name}'."); + Object.DestroyImmediate(child.gameObject); + } + } + } + + /// + /// Turns the borrowed eitr VFX from purple to blood: particle tint and every remaining + /// light. The refinery keeps its lights - a running one should glow red - while the + /// essence spheres had theirs removed outright by StripGlow. + /// + private static void RedShiftEffects(GameObject root) + { + RedShiftEffects(root, EssenceTint); + } + + private static void RedShiftEffects(GameObject root, Color tint) + { + foreach (ParticleSystem particles in root.GetComponentsInChildren(true)) + { + if (particles == null) continue; + + ParticleSystem.MainModule main = particles.main; + main.startColor = new ParticleSystem.MinMaxGradient(tint); + } + + foreach (Light light in root.GetComponentsInChildren(true)) + { + if (light != null) light.color = tint; + } + } + + 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; + if (icons != null && icons.Length > 0 && icons[0] != null) return icons[0]; + + Jotunn.Logger.LogWarning($"[Aswid] Could not borrow the icon from '{prefabName}'."); + return null; + } + + private static void Recolour(GameObject root, Color tint, Color emission) + { + foreach (Renderer renderer in root.GetComponentsInChildren(true)) + { + if (renderer == null) continue; + + // Particle renderers are handled by RedShiftEffects - painting flames and smoke + // with the dark body tint just turns the VFX into soot. + if (renderer is ParticleSystemRenderer) continue; + + // renderer.material instantiates a copy, so the vanilla refinery and the vanilla + // eitr keep their own look. + foreach (Material material in renderer.materials) + { + if (material == null) continue; + material.color = tint; + if (material.HasProperty("_Color")) material.SetColor("_Color", tint); + if (material.HasProperty("_EmissionColor")) material.SetColor("_EmissionColor", emission); + } + } + } + } + + /// + /// Teaches the piece on spawn, exactly like RaceMenuWard does, because a piece registered + /// after the vanilla learning pass never reaches the hammer on its own. + /// + [HarmonyPatch(typeof(Player), "OnSpawned")] + public static class AswidBloodRefineryKnownPatch + { + public static void Postfix(Player __instance) + { + if (__instance != Player.m_localPlayer) return; + AswidBloodRefinery.EnsureKnown(__instance); + } + } + + /// + /// Blood Essence is Aswid food. Anyone else who tries to swallow it gets nothing, the same + /// way the Draugh's human meat is refused to the living. + /// + [HarmonyPatch(typeof(Player), "CanConsumeItem")] + public static class AswidBloodEssenceGatePatch + { + public static void Postfix(Player __instance, ItemDrop.ItemData item, ref bool __result) + { + if (__instance != Player.m_localPlayer || item == null || item.m_shared == null) return; + if (!AswidBloodRefinery.IsEssence(item)) return; + if (AswidRace.IsAswid()) return; + + __result = false; + } + } + + [HarmonyPatch(typeof(Humanoid), "UseItem")] + public static class AswidBloodEssenceMessagePatch + { + public static bool Prefix(Humanoid __instance, ItemDrop.ItemData item) + { + Player player = __instance as Player; + if (player == null || player != Player.m_localPlayer || item == null || item.m_shared == null) return true; + if (!AswidBloodRefinery.IsEssence(item)) return true; + if (AswidRace.IsAswid()) return true; + + player.Message(MessageHud.MessageType.Center, "Living blood curdles in a living throat."); + return false; + } + } +} diff --git a/JotunnModStub/Aswid/AswidPatches.cs b/JotunnModStub/Aswid/AswidPatches.cs index e3f2724..c115515 100644 --- a/JotunnModStub/Aswid/AswidPatches.cs +++ b/JotunnModStub/Aswid/AswidPatches.cs @@ -285,7 +285,7 @@ namespace RacesOfValheim { public static void Postfix(Player __instance, ItemDrop.ItemData item, ref bool __result) { - if (__instance == Player.m_localPlayer && AswidRace.IsAswid() && item != null && item.m_shared != null && item.m_shared.m_name.StartsWith("Aswid Food:")) + if (__instance == Player.m_localPlayer && AswidRace.IsAswid() && AswidBloodRefinery.IsAswidMeal(item)) { var foods = HarmonyLib.Traverse.Create(__instance).Field("m_foods").GetValue(); if (foods != null) @@ -339,7 +339,7 @@ namespace RacesOfValheim public static bool Prefix(Player __instance, ItemDrop.ItemData item, ref bool __result) { hiddenFoods.Clear(); - if (__instance == Player.m_localPlayer && AswidRace.IsAswid() && item != null && item.m_shared != null && item.m_shared.m_name.StartsWith("Aswid Food:")) + if (__instance == Player.m_localPlayer && AswidRace.IsAswid() && AswidBloodRefinery.IsAswidMeal(item)) { var m_foods = HarmonyLib.Traverse.Create(__instance).Field("m_foods").GetValue(); if (m_foods != null) diff --git a/JotunnModStub/Aswid/AswidRace.cs b/JotunnModStub/Aswid/AswidRace.cs index a117fa9..93606cf 100644 --- a/JotunnModStub/Aswid/AswidRace.cs +++ b/JotunnModStub/Aswid/AswidRace.cs @@ -24,9 +24,13 @@ namespace RacesOfValheim { "Leech", "TrophyLeech" }, { "Hatchling", "TrophyHatchling" }, { "Lox", "TrophyLox" }, - { "Fuling", "TrophyGoblin" }, - { "FulingShaman", "TrophyGoblinShaman" }, - { "FulingBerserker", "TrophyGoblinBrute" }, + // The Fuling family is named Goblin* in code - "Fuling" is only ever the display name, + // and no prefab by that name exists. These three keys never matched anything, so the + // Aswid could not drain a Fuling of any kind. Verified against the asset manifest. + { "Goblin", "TrophyGoblin" }, + { "GoblinArcher", "TrophyGoblin" }, + { "GoblinShaman", "TrophyGoblinShaman" }, + { "GoblinBrute", "TrophyGoblinBrute" }, { "Deathsquito", "TrophyDeathsquito" }, { "Hare", "TrophyHare" }, { "Seeker", "TrophySeeker" }, @@ -35,7 +39,7 @@ namespace RacesOfValheim { "Gjall", "TrophyGjall" }, { "Tick", "TrophyTick" }, { "Ulv", "TrophyUlv" }, - { "Cultist", "TrophyCultist" }, + { "Fenring_Cultist", "TrophyCultist" }, // the prefab is Fenring_Cultist, not "Cultist" { "Asksvin", "TrophyAsksvin" }, { "Volture", "TrophyVolture" } }; @@ -84,6 +88,7 @@ namespace RacesOfValheim { AswidStatusEffects.RegisterStatusEffects(); CreateFoodItems(); + AswidBloodRefinery.Register(); GameObject geirrhafa = Jotunn.Managers.PrefabManager.Cache.GetPrefab("Fenring_Cultist_Hildir"); if (geirrhafa != null) @@ -137,7 +142,10 @@ namespace RacesOfValheim { float foodHp = Mathf.Min(c.m_health / 2f, 150f); float burnTime = c.m_health * 2f; - if (mobName == "Cultist" || mobName.StartsWith("Fenring") || mobName.StartsWith("Fuling")) + // StartsWith("Fenring") already covers Fenring_Cultist. "Fuling" was + // never a prefab prefix - the family is Goblin* - so that arm of the + // test matched nothing until now. + if (mobName.StartsWith("Fenring") || mobName.StartsWith("Goblin")) { burnTime = 1200f; // 20 minutes } diff --git a/JotunnModStub/Aswid/BloodRefineryBehaviour.cs b/JotunnModStub/Aswid/BloodRefineryBehaviour.cs new file mode 100644 index 0000000..f64e983 --- /dev/null +++ b/JotunnModStub/Aswid/BloodRefineryBehaviour.cs @@ -0,0 +1,299 @@ +using System; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// The Blood Refinery's logic. Modelled on - same one-second tick, same + /// owner-only accounting with everything in the ZDO so it keeps working in multiplayer and + /// keeps ticking while the zone is unloaded - but with two numeric tanks instead of an ore + /// queue and a single fuel item. + /// + /// Raw flesh is destroyed on the spot and becomes blood; bone is destroyed on the spot and + /// becomes bone dust. When both tanks can pay, the machine refines a Blood Essence and spits + /// it out of the vanilla output point. It never deals damage - see AswidBloodRefinery for the + /// strip pass that guarantees that. + /// + public class BloodRefineryBehaviour : MonoBehaviour + { + // Wired up from the vanilla Smelter before it is destroyed, which is what keeps the + // animation and the VFX identical to the eitr refinery's. + public Switch m_addMeatSwitch; + public Switch m_addBoneSwitch; + public Transform m_outputPoint; + public GameObject m_enabledObject; + public GameObject m_disabledObject; + public GameObject m_haveMeatObject; + public GameObject m_haveBoneObject; + public GameObject m_noMeatObject; + public Animator[] m_animators; + public EffectList m_meatAddedEffects; + public EffectList m_boneAddedEffects; + public EffectList m_produceEffects; + public SmokeSpawner m_smokeSpawner; + + // Balance. Ten units of blood is roughly one cooked lox steak's worth. + public float m_maxBlood = 50f; + public float m_maxBone = 20f; + public float m_bloodPerEssence = 5f; + public float m_bonePerEssence = 2f; + public float m_secPerEssence = 20f; + + private const string KeyBlood = "RoV_blood"; + private const string KeyBone = "RoV_bone"; + private const string KeyTimer = "RoV_refineTimer"; + private const string KeyAccumulator = "RoV_accTime"; + private const string KeyStartTime = "RoV_startTime"; + + private ZNetView m_nview; + private bool m_blockedSmoke; + + private void Awake() + { + m_nview = GetComponent(); + if (m_nview == null) m_nview = GetComponentInParent(); + if (m_nview == null || m_nview.GetZDO() == null) return; + + if (m_addMeatSwitch != null) + { + m_addMeatSwitch.m_onUse = OnAddMeat; + m_addMeatSwitch.m_onHover = HoverMeat; + } + if (m_addBoneSwitch != null) + { + m_addBoneSwitch.m_onUse = OnAddBone; + m_addBoneSwitch.m_onHover = HoverBone; + } + + m_nview.Register("RoV_AddMeat", RPC_AddMeat); + m_nview.Register("RoV_AddBone", RPC_AddBone); + + WearNTear wear = GetComponent(); + if (wear == null) wear = GetComponentInParent(); + if (wear != null) wear.m_onDestroyed = (Action)Delegate.Combine(wear.m_onDestroyed, new Action(OnDestroyed)); + + InvokeRepeating("UpdateRefinery", 1f, 1f); + } + + // ---------------------------------------------------------------- input + + private bool OnAddMeat(Switch caller, Humanoid user, ItemDrop.ItemData item) + { + return TryAdd(user, item, isMeat: true); + } + + private bool OnAddBone(Switch caller, Humanoid user, ItemDrop.ItemData item) + { + return TryAdd(user, item, isMeat: false); + } + + private bool TryAdd(Humanoid user, ItemDrop.ItemData item, bool isMeat) + { + if (user == null) return false; + Inventory inventory = user.GetInventory(); + if (inventory == null) return false; + + if (item == null) item = FindUsable(inventory, isMeat); + if (item == null) + { + user.Message(MessageHud.MessageType.Center, isMeat ? "No raw flesh to render." : "No bone to grind."); + return false; + } + + string prefabName = item.m_dropPrefab != null ? item.m_dropPrefab.name : null; + int value = isMeat ? AswidBloodRefinery.BloodValue(prefabName) : AswidBloodRefinery.BoneValue(prefabName); + if (value <= 0) + { + user.Message(MessageHud.MessageType.Center, "$msg_wontwork"); + return false; + } + + float stored = isMeat ? GetBlood() : GetBone(); + float capacity = isMeat ? m_maxBlood : m_maxBone; + if (stored >= capacity) + { + user.Message(MessageHud.MessageType.Center, "$msg_itsfull"); + return false; + } + + user.Message(MessageHud.MessageType.Center, "$msg_added " + item.m_shared.m_name); + inventory.RemoveItem(item, 1); + m_nview.InvokeRPC(isMeat ? "RoV_AddMeat" : "RoV_AddBone", prefabName); + return true; + } + + private ItemDrop.ItemData FindUsable(Inventory inventory, bool isMeat) + { + foreach (ItemDrop.ItemData candidate in inventory.GetAllItems()) + { + if (candidate == null || candidate.m_dropPrefab == null) continue; + string prefabName = candidate.m_dropPrefab.name; + int value = isMeat ? AswidBloodRefinery.BloodValue(prefabName) : AswidBloodRefinery.BoneValue(prefabName); + if (value > 0) return candidate; + } + return null; + } + + private void RPC_AddMeat(long sender, string prefabName) + { + if (!m_nview.IsOwner()) return; + + int value = AswidBloodRefinery.BloodValue(prefabName); + if (value <= 0) return; + + SetBlood(Mathf.Min(m_maxBlood, GetBlood() + value)); + if (m_meatAddedEffects != null) m_meatAddedEffects.Create(transform.position, transform.rotation); + } + + private void RPC_AddBone(long sender, string prefabName) + { + if (!m_nview.IsOwner()) return; + + int value = AswidBloodRefinery.BoneValue(prefabName); + if (value <= 0) return; + + SetBone(Mathf.Min(m_maxBone, GetBone() + value)); + if (m_boneAddedEffects != null) m_boneAddedEffects.Create(transform.position, transform.rotation, transform); + } + + // ---------------------------------------------------------------- the loop + + private void UpdateRefinery() + { + if (m_nview == null || !m_nview.IsValid()) return; + + m_blockedSmoke = m_smokeSpawner != null && m_smokeSpawner.IsBlocked(); + UpdateState(); + + if (!m_nview.IsOwner()) return; + + float accumulator = m_nview.GetZDO().GetFloat(KeyAccumulator) + (float)GetDeltaTime(); + if (accumulator > 3600f) accumulator = 3600f; // one hour of catch-up, as vanilla + + while (accumulator >= 1f) + { + accumulator -= 1f; + if (!IsActive()) continue; + + float timer = m_nview.GetZDO().GetFloat(KeyTimer) + 1f; + if (timer >= m_secPerEssence) + { + timer = 0f; + SetBlood(GetBlood() - m_bloodPerEssence); + SetBone(GetBone() - m_bonePerEssence); + Produce(); + } + m_nview.GetZDO().Set(KeyTimer, timer); + } + + m_nview.GetZDO().Set(KeyAccumulator, accumulator); + } + + private void Produce() + { + GameObject prefab = ObjectDB.instance != null + ? ObjectDB.instance.GetItemPrefab(AswidBloodRefinery.EssenceName) + : null; + if (prefab == null || m_outputPoint == null) return; + + if (m_produceEffects != null) m_produceEffects.Create(transform.position, transform.rotation); + + GameObject spawned = Instantiate(prefab, m_outputPoint.position, m_outputPoint.rotation); + ItemDrop drop = spawned.GetComponent(); + if (drop != null) + { + drop.m_itemData.m_stack = 1; + ItemDrop.OnCreateNew(drop); + } + } + + /// + /// Bones survive the machine, blood does not, so a demolished refinery gives the bone back + /// and keeps the blood. The hover text says so before anyone swings a hammer at it. + /// + private void OnDestroyed() + { + if (m_nview == null || !m_nview.IsOwner()) return; + + int bones = Mathf.FloorToInt(GetBone()); + SetBone(0f); + SetBlood(0f); + if (bones <= 0) return; + + GameObject prefab = ObjectDB.instance != null ? ObjectDB.instance.GetItemPrefab("BoneFragments") : null; + if (prefab == null) return; + + for (int i = 0; i < bones; i++) + { + Vector3 position = transform.position + Vector3.up * 0.5f + UnityEngine.Random.insideUnitSphere * 0.3f; + Quaternion rotation = Quaternion.Euler(0f, UnityEngine.Random.Range(0, 360), 0f); + ItemDrop.OnCreateNew(Instantiate(prefab, position, rotation)); + } + } + + // ---------------------------------------------------------------- state and display + + public bool IsActive() + { + if (m_blockedSmoke) return false; + return GetBlood() >= m_bloodPerEssence && GetBone() >= m_bonePerEssence; + } + + private void UpdateState() + { + bool active = IsActive(); + + if (m_enabledObject != null) m_enabledObject.SetActive(active); + if (m_disabledObject != null) m_disabledObject.SetActive(!active); + if (m_haveBoneObject != null) m_haveBoneObject.SetActive(GetBone() > 0f); + if (m_haveMeatObject != null) m_haveMeatObject.SetActive(GetBlood() > 0f); + if (m_noMeatObject != null) m_noMeatObject.SetActive(GetBlood() <= 0f); + + if (m_animators == null) return; + foreach (Animator animator in m_animators) + { + if (animator == null || !animator.gameObject.activeInHierarchy) continue; + animator.SetBool("active", active); + animator.SetFloat("activef", active ? 1f : 0f); + } + } + + private string HoverMeat() + { + return Localization.instance.Localize( + $"{AswidBloodRefinery.PieceDisplayName} (blood {Mathf.Floor(GetBlood())}/{m_maxBlood})\n" + + "[$KEY_Use] Render raw flesh"); + } + + private string HoverBone() + { + return Localization.instance.Localize( + $"{AswidBloodRefinery.PieceDisplayName} (bone {Mathf.Floor(GetBone())}/{m_maxBone})\n" + + "[$KEY_Use] Grind bone"); + } + + // ---------------------------------------------------------------- ZDO accessors + + private double GetDeltaTime() + { + DateTime now = ZNet.instance.GetTime(); + DateTime last = new DateTime(m_nview.GetZDO().GetLong(KeyStartTime, now.Ticks)); + m_nview.GetZDO().Set(KeyStartTime, now.Ticks); + return (now - last).TotalSeconds; + } + + private float GetBlood() => m_nview != null && m_nview.IsValid() ? m_nview.GetZDO().GetFloat(KeyBlood) : 0f; + + private float GetBone() => m_nview != null && m_nview.IsValid() ? m_nview.GetZDO().GetFloat(KeyBone) : 0f; + + private void SetBlood(float value) + { + if (m_nview != null && m_nview.IsValid()) m_nview.GetZDO().Set(KeyBlood, Mathf.Max(0f, value)); + } + + private void SetBone(float value) + { + if (m_nview != null && m_nview.IsValid()) m_nview.GetZDO().Set(KeyBone, Mathf.Max(0f, value)); + } + } +} -- 2.52.0 From 96bc7796f9319ef5e816917f08df544c0b5abe16 Mon Sep 17 00:00:00 2001 From: Ferdinando Date: Fri, 7 Aug 2026 17:02:34 +0200 Subject: [PATCH 3/8] feat(draugh): body pile spawner Co-Authored-By: Claude Opus 5 --- JotunnModStub/Draugh/DraughRace.cs | 5 + JotunnModStub/Draugh/DraughSpawner.cs | 335 ++++++++++++++++ .../Draugh/DraughSpawnerBehaviour.cs | 366 ++++++++++++++++++ 3 files changed, 706 insertions(+) create mode 100644 JotunnModStub/Draugh/DraughSpawner.cs create mode 100644 JotunnModStub/Draugh/DraughSpawnerBehaviour.cs diff --git a/JotunnModStub/Draugh/DraughRace.cs b/JotunnModStub/Draugh/DraughRace.cs index 0293ec8..0fa6662 100644 --- a/JotunnModStub/Draugh/DraughRace.cs +++ b/JotunnModStub/Draugh/DraughRace.cs @@ -18,6 +18,11 @@ namespace RacesOfValheim public void CreateModAssets() { + // The body pile and its thralls. Registered here because the faction merchant catalogue + // resolves its entries by prefab name, so the two cursed bones have to exist before a + // Draugr is ever set up as a bench. + DraughSpawner.Register(); + // Generate EdibleUncooked prefabs for Draugh raw food logic foreach (var mapping in DraughFoodPatches.rawToCookedMapping) { diff --git a/JotunnModStub/Draugh/DraughSpawner.cs b/JotunnModStub/Draugh/DraughSpawner.cs new file mode 100644 index 0000000..b921be7 --- /dev/null +++ b/JotunnModStub/Draugh/DraughSpawner.cs @@ -0,0 +1,335 @@ +using HarmonyLib; +using Jotunn.Configs; +using Jotunn.Entities; +using Jotunn.Managers; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// The Draugh station: a smaller, green body pile that eats raw flesh and answers with tamed + /// draugr. Third of the per-race station chains, after the Aswid's Blood Refinery and the + /// Trenta's Composter, and it takes its input rules straight from the second one - 100 units of + /// flesh valued by , one batch, one draugr. + /// + /// What makes it a Draugh thing rather than a piece of furniture anyone can use: the pile itself + /// works for whoever built it, but the draugr only take ORDERS from a Draugh. Anyone else gets a + /// grave that defends its own ten metres; a Draugh gets an escort. That asymmetry is the design, + /// not a limitation. + /// + /// Two special inputs, both of them draugr remains, because the pile is not fussy about where the + /// meat comes from: a Draugr trophy is worth a whole batch, and an Elite trophy is worth an elite + /// outright once the pile has been upgraded to hold any. + /// + public static class DraughSpawner + { + // ─── Names ─────────────────────────────────────────────────────────── + public const string PieceName = "DraughBodyPile"; + public const string PieceDisplayName = "Cursed Body Pile"; + + public const string BoneName = "CursedBone"; + public const string BoneDisplayName = "Cursed Bone"; + public const string GreaterBoneName = "GreaterCursedBone"; + public const string GreaterBoneDisplayName = "Greater Cursed Bone"; + + public const string ThrallName = "DraughThrall_Draugr"; + public const string ThrallEliteName = "DraughThrall_DraugrElite"; + public const string ThrallDisplayName = "Draugr Thrall"; + public const string ThrallEliteDisplayName = "Draugr Elite Thrall"; + + // RaisedThrall groups by kind for follower caps and for the roster, so these are the strings + // that decide "is this one an officer" - no longer a display-name comparison. + public const string KindNormal = "DraughDraugr"; + public const string KindElite = "DraughDraugrElite"; + + public const string RaceId = "Draugh"; + + // The two trophies the pile accepts in place of meat. + public const string TrophyDraugr = "TrophyDraugr"; + public const string TrophyDraugrElite = "TrophyDraugrElite"; + + // ─── Balance ───────────────────────────────────────────────────────── + // 100 units is one full Composter batch on the same FleshValue scale, which is deliberate: + // it makes a Draugr trophy (worth exactly one batch) the real currency and raw meat the + // fallback. A trophy drops from roughly one draugr in ten, so the pile is fed mostly by + // doing the thing it is thematically about. + public const float FleshPerThrall = 100f; + + public const int AliveCap = 5; + public const int AliveCapUpgraded = 7; // +2 normals, as designed + public const int EliteCap = 0; // none at all until upgraded + public const int EliteCapUpgraded = 3; + + public const int ReserveCap = 5; + public const int ReserveCapElite = 3; + + // Local seconds, and only while the zone is loaded - see DraughSpawnerBehaviour. + public const float RespawnSeconds = 60f; + + // How long a thrall outlives the pile that made it. The same minute as the respawn on + // purpose: the player learns one number and it reads as "this pile thinks in minutes". + // + // Not zero, which is what it used to be. Killing them on the spot closed the duplication + // exploit but read terribly - dismantle your own pile and ten bodies drop with no + // explanation - and it disarmed you mid-fight if a raid took the pile down while your + // escort was out with you. A minute is short enough that rebuilding elsewhere to keep the + // old thralls is not worth the walk, and the anchor check in RaisedThrall is what actually + // closes that door rather than the length of this timer. + // + // World time, not local: an orphan has to keep withering while its zone is unloaded, or + // walking away would be a way to keep a dead pile's army alive indefinitely. + public const float OrphanWitherSeconds = 60f; + + // A thrall only asks "is my pile still standing?" when it is this close to home, because the + // answer can only be trusted where the pile would be loaded if it existed. Further out - out + // following its master, most of the time - the question is unanswerable and gets skipped. + // The leash is 10 m; this leaves room for one that has been knocked about. + public const float HomeCheckRange = 20f; + + // How far a thrall strays from the pile when it is not following anybody. Written onto the + // clone's BaseAI.m_randomMoveRange, which is the radius vanilla's own patrol wandering uses. + public const float LeashRange = 10f; + + // An escort, not a doomstack. The pile can hold ten; it can lend you four. + public const int MaxFollowers = 3; + public const int MaxEliteFollowers = 1; + + // Upgrading is gated on the lord of the swamp dead rather than on money alone. + public const int UpgradeProgressionState = 4; // Bonemass + + // ─── Density ───────────────────────────────────────────────────────── + // Five piles per 1.6 square kilometres, enforced by PieceDensityLimit. For scale, a Valheim + // zone is 64 m square, so 1.6 km2 is a disc about 22 zones across - big enough that five + // piles is a regional army rather than base decoration. + public const int MaxPilesInRange = 5; + public const float DensityAreaKm2 = 1.6f; + + // ─── Looks ─────────────────────────────────────────────────────────── + // Bigger than the vanilla pile, not smaller. The first pass went to 0.8 on the assumption that + // a buildable wants to be unobtrusive; in game it read as a scrap heap rather than as something + // that raises the dead. 1.2 gives it the presence the feature deserves. + private const float ModelScale = 1.2f; + + // Green, and far enough from the vanilla pile's brown-grey to be told apart across a swamp. + private static readonly Color PileTint = new Color(0.22f, 0.52f, 0.24f, 1f); + private static readonly Color BoneTint = new Color(0.35f, 0.45f, 0.30f, 1f); + private static readonly Color GreaterBoneTint = new Color(0.20f, 0.55f, 0.25f, 1f); + + public static void Register() + { + RegisterBone(BoneName, BoneDisplayName, BoneTint, + "A bone that will not stay quiet. The dead sell them; the dead do not say why."); + RegisterBone(GreaterBoneName, GreaterBoneDisplayName, GreaterBoneTint, + "The same bone, older, and louder. A pile fed one of these starts keeping officers."); + + RegisterThrall(ThrallName, "Draugr", ThrallDisplayName, KindNormal, MaxFollowers); + RegisterThrall(ThrallEliteName, "Draugr_Elite", ThrallEliteDisplayName, KindElite, MaxEliteFollowers); + + RegisterPiece(); + + PieceDensityLimit.Register(PieceName, + PieceDensityLimit.RadiusForArea(DensityAreaKm2), MaxPilesInRange, + "The ground here already carries {0} of these. Find another country."); + } + + // ---------------------------------------------------------------- items + + private static void RegisterBone(string prefabName, string displayName, Color tint, string description) + { + GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(prefabName, "BoneFragments"); + if (prefab == null) + { + Jotunn.Logger.LogWarning($"[Draugh] Could not clone BoneFragments; {displayName} not registered."); + return; + } + + Recolour(prefab, tint); + + ItemDrop drop = prefab.GetComponent(); + if (drop == null) return; + + ItemDrop.ItemData.SharedData shared = drop.m_itemData.m_shared; + shared.m_name = displayName; + shared.m_description = description; + shared.m_itemType = ItemDrop.ItemData.ItemType.Material; + shared.m_weight = 1f; + shared.m_maxStackSize = 10; + + ItemManager.Instance.AddItem(new CustomItem(prefab, fixReference: false)); + } + + // ---------------------------------------------------------------- thralls + + /// + /// A draugr that is born tame and on a leash. + /// + /// Cloned rather than tamed in place so the leash range, the name and the loot table are the + /// prefab's own business and no vanilla draugr is touched. Its CharacterDrop is destroyed + /// outright: a conjured corpse leaves nothing behind. Without that, killing your own thralls + /// would farm the entrails and bone fragments this whole chain is built out of - and, at a one + /// in ten trophy rate, hand back a slice of the flesh that paid for it. + /// + private static void RegisterThrall(string prefabName, string source, string displayName, + string kind, int maxFollowers) + { + GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(prefabName, source); + if (prefab == null) + { + Jotunn.Logger.LogWarning($"[Draugh] Could not clone {source}; {displayName} not registered."); + return; + } + + Character character = prefab.GetComponent(); + if (character != null) character.m_name = displayName; + + BaseAI ai = prefab.GetComponent(); + if (ai != null) + { + // The radius vanilla's own patrol wandering keeps to around m_patrolPoint, which + // RaisedThrall pins to the pile. + ai.m_randomMoveRange = LeashRange; + } + + foreach (CharacterDrop drops in prefab.GetComponentsInChildren(true)) + { + if (drops != null) Object.DestroyImmediate(drops); + } + + RaisedThrall thrall = prefab.AddComponent(); + thrall.m_kind = kind; + thrall.m_commandingRace = RaceId; // only a Draugh may give these orders + thrall.m_maxFollowers = maxFollowers; + thrall.m_witherSeconds = OrphanWitherSeconds; + thrall.m_homeCheckRange = HomeCheckRange; + thrall.m_refusalMessage = "The dead do not take orders from the living."; + + PrefabManager.Instance.AddPrefab(prefab); + } + + // ---------------------------------------------------------------- piece + + private static void RegisterPiece() + { + // Spawner_DraugrPile is the visible, destructible body pile of the swamps - the only one + // of the seven Spawner_Draugr* prefabs with hit and destruction effects of its own, which + // is what says it has a model rather than being a world-generation spawn point. + GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(PieceName, "Spawner_DraugrPile"); + if (prefab == null) + { + Jotunn.Logger.LogWarning("[Draugh] Could not clone Spawner_DraugrPile; the body pile is not registered."); + return; + } + + // The vanilla pile's whole job is spawning hostile draugr on a timer at anyone who walks + // past. Every bit of that goes: what it produces, when, and for whom is ours now. + foreach (SpawnArea area in prefab.GetComponentsInChildren(true)) + { + if (area != null) Object.DestroyImmediate(area); + } + + // Same belt as the Composter: a bone pile carries nothing that shoots, but the eitr + // refinery taught this codebase not to assume. A silent log is the proof. + AswidBloodRefinery.StripOffensive(prefab, PieceName); + + DraughSpawnerBehaviour behaviour = prefab.AddComponent(); + + // One interaction point, as on the Composter: what is in your hand decides what the click + // means. Any Switch the prefab happened to carry goes first so it cannot win the hover + // from a child collider - the components only, never their colliders. + foreach (Switch existing in prefab.GetComponentsInChildren(true)) + { + if (existing != null) Object.DestroyImmediate(existing); + } + behaviour.m_switch = prefab.AddComponent(); + behaviour.m_switch.m_name = PieceDisplayName; + + prefab.transform.localScale = Vector3.one * ModelScale; + Recolour(prefab, PileTint); + + Piece piece = prefab.GetComponent() ?? prefab.AddComponent(); + piece.m_craftingStation = null; + piece.m_resources = new Piece.Requirement[0]; + piece.m_name = PieceDisplayName; + piece.m_canBeRemoved = true; + piece.m_groundPiece = true; + piece.m_groundOnly = true; + piece.m_icon = BorrowIcon(TrophyDraugr); + + // Learned on the Furling's bushes: a Piece added to world scenery is born with no icon + // and no place effect, and a null icon is a blank, unclickable square in the build menu. + 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 = PieceDisplayName, + Description = "Feed it and it answers. The dead here are yours, if you are dead enough to ask.", + PieceTable = PieceTables.Hammer, + Category = PieceCategories.Crafting, + Icon = BorrowIcon(TrophyDraugr), + Requirements = new[] + { + new RequirementConfig(BoneName, 1, 0, true), + new RequirementConfig("Entrails", 10, 0, true), + new RequirementConfig("BoneFragments", 20, 0, true), + } + })); + } + + /// + /// Same reason as the Composter's and the Furling's: a piece registered after the vanilla + /// learning pass never reaches the hammer on its own. The purchased Cursed Bone is the gate. + /// + public static void EnsureKnown(Player player) + { + if (player == null) return; + + GameObject prefab = PrefabManager.Instance.GetPrefab(PieceName); + Piece piece = prefab != null ? prefab.GetComponent() : null; + if (piece == null) return; + + Traverse traverse = Traverse.Create(player); + traverse.Method("AddKnownPiece", piece).GetValue(); + traverse.Method("UpdateAvailablePiecesList").GetValue(); + } + + // ---------------------------------------------------------------- helpers + + private static Sprite BorrowIcon(string prefabName) + { + ItemDrop drop = PrefabManager.Cache.GetPrefab(prefabName); + Sprite[] icons = drop != null && drop.m_itemData != null && drop.m_itemData.m_shared != null + ? drop.m_itemData.m_shared.m_icons + : null; + if (icons != null && icons.Length > 0 && icons[0] != null) return icons[0]; + + Jotunn.Logger.LogWarning($"[Draugh] Could not borrow the icon from '{prefabName}'."); + return null; + } + + private static void Recolour(GameObject root, Color tint) + { + foreach (Renderer renderer in root.GetComponentsInChildren(true)) + { + if (renderer == null || renderer is ParticleSystemRenderer) continue; + + foreach (Material material in renderer.materials) + { + if (material == null) continue; + material.color = tint; + if (material.HasProperty("_Color")) material.SetColor("_Color", tint); + } + } + } + } + + [HarmonyPatch(typeof(Player), "OnSpawned")] + public static class DraughSpawnerKnownPatch + { + public static void Postfix(Player __instance) + { + if (__instance != Player.m_localPlayer) return; + DraughSpawner.EnsureKnown(__instance); + } + } +} diff --git a/JotunnModStub/Draugh/DraughSpawnerBehaviour.cs b/JotunnModStub/Draugh/DraughSpawnerBehaviour.cs new file mode 100644 index 0000000..98c760d --- /dev/null +++ b/JotunnModStub/Draugh/DraughSpawnerBehaviour.cs @@ -0,0 +1,366 @@ +using System; +using System.Collections.Generic; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// The body pile's logic. Same skeleton as ComposterBehaviour - one Switch, one numeric tank fed + /// by many different meats, all state in the ZDO, owner-only accounting - with a roster on top. + /// + /// Two deliberate differences from the Composter's timing, both of them about not punishing the + /// player for walking away: + /// - the respawn timer runs on LOCAL time and only while the zone is loaded. The Composter's + /// seal time is world time, because rotting happens whether anyone watches; a grave refilling + /// itself while unloaded would instead let a wandering troll drain the whole reserve into a + /// field of corpses nobody was there to use. + /// - the roster is counted, never tallied. Alive thralls are found by asking the world which + /// creatures are bound to this pile, so a death, a despawn or a player killing his own thrall + /// all correct themselves with no bookkeeping to drift. + /// + public class DraughSpawnerBehaviour : MonoBehaviour + { + public Switch m_switch; + + private const string KeyFlesh = "RoV_draughFlesh"; + private const string KeyReserve = "RoV_draughReserve"; + private const string KeyReserveElite = "RoV_draughReserveElite"; + private const string KeyUpgraded = "RoV_draughUpgraded"; + + private ZNetView m_nview; + private float m_respawnTimer; + + private void OnDestroy() + { + RaisedThrall.UnregisterStation(transform); + } + + private void Awake() + { + // The shared registry RaisedThrall consults to answer "is my pile still standing?". + RaisedThrall.RegisterStation(transform); + + m_nview = GetComponent(); + if (m_nview == null || m_nview.GetZDO() == null) return; + + if (m_switch != null) + { + m_switch.m_onUse = OnUse; + m_switch.m_onHover = Hover; + } + + m_nview.Register("RoV_DraughFeed", RPC_Feed); + m_nview.Register("RoV_DraughUpgrade", RPC_Upgrade); + + WearNTear wear = GetComponent(); + if (wear != null) wear.m_onDestroyed = (Action)Delegate.Combine(wear.m_onDestroyed, new Action(OnDestroyed)); + + InvokeRepeating("UpdatePile", 2f, 2f); + } + + // ---------------------------------------------------------------- interaction + + /// + /// One interaction point, like the Composter's: what is in hand decides what the click means. + /// Raw flesh feeds it, a Draugr trophy is a whole batch, an Elite trophy is an officer, and a + /// Greater Cursed Bone upgrades it. Empty hands just report. + /// + private bool OnUse(Switch caller, Humanoid user, ItemDrop.ItemData item) + { + if (user == null) return false; + + Inventory inventory = user.GetInventory(); + if (inventory == null) return false; + + if (item == null) item = FindAnyInput(inventory); + if (item == null) + { + user.Message(MessageHud.MessageType.Center, "It wants flesh, or the head of one of its own."); + return false; + } + + string prefabName = item.m_dropPrefab != null ? item.m_dropPrefab.name : null; + if (prefabName == null) return false; + + if (prefabName == DraughSpawner.GreaterBoneName) return TryUpgrade(user, inventory, item); + + if (prefabName == DraughSpawner.TrophyDraugrElite && !IsUpgraded()) + { + user.Message(MessageHud.MessageType.Center, "This pile keeps no officers yet."); + return false; + } + + if (prefabName != DraughSpawner.TrophyDraugr && + prefabName != DraughSpawner.TrophyDraugrElite && + AswidBloodRefinery.FleshValue(prefabName) <= 0) + { + user.Message(MessageHud.MessageType.Center, "$msg_wontwork"); + return false; + } + + // Fullness depends on which shelf the input goes on. Asking the wrong one is not cosmetic: + // an Elite trophy accepted here and then dropped by RPC_Feed for want of an officer slot + // would be an item destroyed for nothing. + bool elite = prefabName == DraughSpawner.TrophyDraugrElite; + if (elite ? GetReserveElite() >= DraughSpawner.ReserveCapElite : IsFull()) + { + user.Message(MessageHud.MessageType.Center, "$msg_itsfull"); + return false; + } + + // An Elite trophy banks an officer each, and the shelf holds three - so a stack of ten + // would have had seven of them clamped away by RPC_Feed and destroyed. Found on the + // Skeleton's pile, which has the identical shape, and fixed here before it could bite. + // Flesh needs no equivalent because its remainder stays in the tank rather than vanishing. + if (elite) + { + int room = DraughSpawner.ReserveCapElite - GetReserveElite(); + int takenElite = Mathf.Min(Mathf.Max(1, item.m_stack), room); + + user.Message(MessageHud.MessageType.Center, $"$msg_added {item.m_shared.m_name} x{takenElite}"); + inventory.RemoveItem(item, takenElite); + m_nview.InvokeRPC("RoV_DraughFeed", prefabName, takenElite); + return true; + } + + // A whole stack per click. The Composter asks for a hundred units one item at a time and + // gets away with it because a batch is the end of the story; a full complement here is ten + // batches, and clicking that out one neck tail at a time is not a mechanic. + // + // The count goes over as an argument rather than as one RPC per item - a stack of fifty + // neck tails would otherwise be fifty round trips to say the same thing. + int stack = Mathf.Max(1, item.m_stack); + user.Message(MessageHud.MessageType.Center, $"$msg_added {item.m_shared.m_name} x{stack}"); + inventory.RemoveItem(item, stack); + + m_nview.InvokeRPC("RoV_DraughFeed", prefabName, stack); + return true; + } + + private ItemDrop.ItemData FindAnyInput(Inventory inventory) + { + foreach (ItemDrop.ItemData candidate in inventory.GetAllItems()) + { + if (candidate == null || candidate.m_dropPrefab == null) continue; + + string name = candidate.m_dropPrefab.name; + if (name == DraughSpawner.TrophyDraugr) return candidate; + if (name == DraughSpawner.TrophyDraugrElite && IsUpgraded()) return candidate; + if (AswidBloodRefinery.FleshValue(name) > 0) return candidate; + } + return null; + } + + private bool TryUpgrade(Humanoid user, Inventory inventory, ItemDrop.ItemData item) + { + if (IsUpgraded()) + { + user.Message(MessageHud.MessageType.Center, "It has already had one."); + return false; + } + + if (BossProgressionManager.GetCurrentProgressionState() < DraughSpawner.UpgradeProgressionState) + { + user.Message(MessageHud.MessageType.Center, "The bone will not wake. Something older has to fall first."); + return false; + } + + inventory.RemoveItem(item, 1); + m_nview.InvokeRPC("RoV_DraughUpgrade"); + user.Message(MessageHud.MessageType.Center, "The pile stirs. It will keep officers now."); + return true; + } + + // ---------------------------------------------------------------- accounting + + private void RPC_Feed(long sender, string prefabName, int count) + { + if (!m_nview.IsOwner()) return; + if (count < 1) count = 1; + + // An Elite trophy is not flesh - it banks an officer outright. + if (prefabName == DraughSpawner.TrophyDraugrElite) + { + if (!IsUpgraded()) return; + SetReserveElite(GetReserveElite() + count); // the setter clamps to the shelf + return; + } + + float value = prefabName == DraughSpawner.TrophyDraugr + ? DraughSpawner.FleshPerThrall // a head is worth a whole batch + : AswidBloodRefinery.FleshValue(prefabName); + if (value <= 0f) return; + + float flesh = GetFlesh() + value * count; + + // Every complete batch becomes a banked thrall. A loop rather than a single test so a + // trophy - or a stack of them - cannot overflow into flesh that never gets counted. + while (flesh >= DraughSpawner.FleshPerThrall && GetReserve() < DraughSpawner.ReserveCap) + { + flesh -= DraughSpawner.FleshPerThrall; + SetReserve(GetReserve() + 1); + } + + SetFlesh(flesh); + } + + private void RPC_Upgrade(long sender) + { + if (!m_nview.IsOwner()) return; + m_nview.GetZDO().Set(KeyUpgraded, true); + } + + private void UpdatePile() + { + if (m_nview == null || !m_nview.IsValid() || !m_nview.IsOwner()) return; + + List bound = RaisedThrall.BoundTo(transform.position); + int aliveNormal = 0; + int aliveElite = 0; + foreach (RaisedThrall thrall in bound) + { + if (thrall.Kind == DraughSpawner.KindElite) aliveElite++; else aliveNormal++; + } + + bool wantsNormal = aliveNormal < AliveCap() && GetReserve() > 0; + bool wantsElite = aliveElite < EliteCap() && GetReserveElite() > 0; + + if (!wantsNormal && !wantsElite) + { + m_respawnTimer = 0f; + return; + } + + m_respawnTimer += 2f; // the tick interval + if (m_respawnTimer < DraughSpawner.RespawnSeconds) return; + m_respawnTimer = 0f; + + // Officers first: they are the scarcer resource and the reason to upgrade at all. + if (wantsElite) + { + if (Spawn(DraughSpawner.ThrallEliteName)) SetReserveElite(GetReserveElite() - 1); + } + else if (wantsNormal) + { + if (Spawn(DraughSpawner.ThrallName)) SetReserve(GetReserve() - 1); + } + } + + private bool Spawn(string prefabName) + { + GameObject prefab = ZNetScene.instance != null ? ZNetScene.instance.GetPrefab(prefabName) : null; + if (prefab == null) + { + Jotunn.Logger.LogWarning($"[Draugh] No '{prefabName}' in ZNetScene; the pile cannot raise anything."); + return false; + } + + Vector3 offset = UnityEngine.Random.insideUnitSphere * 2f; + offset.y = 0f; + Vector3 position = transform.position + offset + Vector3.up * 0.5f; + + GameObject spawned = Instantiate(prefab, position, Quaternion.Euler(0f, UnityEngine.Random.Range(0, 360), 0f)); + RaisedThrall thrall = spawned.GetComponent(); + if (thrall != null) thrall.Bind(transform.position); + + return true; + } + + /// + /// The pile sustains them, so it takes them with it - but on a minute's delay rather than on + /// the spot. Without some form of this a pile is a duplication exploit: fill it, dismantle it, + /// rebuild it elsewhere, fill it again, and keep every thrall from every round. + /// + /// This marks the ones it can reach. It cannot reach thralls whose zone is unloaded right now, + /// which is why RaisedThrall also checks for itself once it is home again - between the two, + /// nothing outlives its pile. + /// + private void OnDestroyed() + { + if (m_nview == null || !m_nview.IsOwner()) return; + + List bound = RaisedThrall.BoundTo(transform.position); + foreach (RaisedThrall thrall in bound) thrall.MarkOrphaned(); + + // Said once, by the client that just knocked it down, because the hover text that would + // otherwise explain this is going away with the pile. + if (bound.Count > 0 && Player.m_localPlayer != null) + { + Player.m_localPlayer.Message(MessageHud.MessageType.Center, + $"The pile is broken. {bound.Count} will not outlast it by more than a minute."); + } + + SetFlesh(0f); + SetReserve(0); + SetReserveElite(0); + } + + // ---------------------------------------------------------------- state and display + + public bool IsUpgraded() => m_nview != null && m_nview.IsValid() && m_nview.GetZDO().GetBool(KeyUpgraded, false); + + private int AliveCap() => IsUpgraded() ? DraughSpawner.AliveCapUpgraded : DraughSpawner.AliveCap; + + private int EliteCap() => IsUpgraded() ? DraughSpawner.EliteCapUpgraded : DraughSpawner.EliteCap; + + /// Full when there is nowhere left to put a finished thrall. + private bool IsFull() => GetReserve() >= DraughSpawner.ReserveCap; + + /// + /// Everything a player needs to know without opening a log, which is the standard this project + /// arrived at the hard way: a mechanic that cannot say whether it is working looks exactly like + /// one that is broken. + /// + private string Hover() + { + List bound = RaisedThrall.BoundTo(transform.position); + int aliveNormal = 0; + int aliveElite = 0; + foreach (RaisedThrall thrall in bound) + { + if (thrall.Kind == DraughSpawner.KindElite) aliveElite++; else aliveNormal++; + } + + string body = $"flesh {Mathf.Floor(GetFlesh())}/{DraughSpawner.FleshPerThrall}, " + + $"risen {aliveNormal}/{AliveCap()}, waiting {GetReserve()}/{DraughSpawner.ReserveCap}"; + + if (IsUpgraded()) + { + body += $"\nofficers {aliveElite}/{EliteCap()}, waiting {GetReserveElite()}/{DraughSpawner.ReserveCapElite}"; + } + + if (m_respawnTimer > 0f) + { + int left = Mathf.Max(1, Mathf.CeilToInt(DraughSpawner.RespawnSeconds - m_respawnTimer)); + body += $"\nnext rises in {left}s"; + } + + body += "\n[$KEY_Use] Feed it flesh, or a draugr's head"; + + return Localization.instance.Localize($"{DraughSpawner.PieceDisplayName} ({body})"); + } + + // ---------------------------------------------------------------- ZDO accessors + + private float GetFlesh() => m_nview != null && m_nview.IsValid() ? m_nview.GetZDO().GetFloat(KeyFlesh) : 0f; + + private void SetFlesh(float value) + { + if (m_nview != null && m_nview.IsValid()) m_nview.GetZDO().Set(KeyFlesh, Mathf.Max(0f, value)); + } + + private int GetReserve() => m_nview != null && m_nview.IsValid() ? m_nview.GetZDO().GetInt(KeyReserve) : 0; + + private void SetReserve(int value) + { + if (m_nview != null && m_nview.IsValid()) m_nview.GetZDO().Set(KeyReserve, Mathf.Clamp(value, 0, DraughSpawner.ReserveCap)); + } + + private int GetReserveElite() => m_nview != null && m_nview.IsValid() ? m_nview.GetZDO().GetInt(KeyReserveElite) : 0; + + private void SetReserveElite(int value) + { + if (m_nview != null && m_nview.IsValid()) m_nview.GetZDO().Set(KeyReserveElite, Mathf.Clamp(value, 0, DraughSpawner.ReserveCapElite)); + } + } +} -- 2.52.0 From b67a324cb8ce9b94347a196ee7aca034772ae53f Mon Sep 17 00:00:00 2001 From: Ferdinando Date: Fri, 7 Aug 2026 17:02:35 +0200 Subject: [PATCH 4/8] feat(skeleton): bound bone pile and bound sentry Co-Authored-By: Claude Opus 5 --- JotunnModStub/Skeleton/SkeletonBonePile.cs | 383 +++++++++++++++++ .../Skeleton/SkeletonBonePileBehaviour.cs | 403 ++++++++++++++++++ JotunnModStub/Skeleton/SkeletonPatches.cs | 4 +- JotunnModStub/Skeleton/SkeletonRace.cs | 5 + JotunnModStub/Skeleton/SkeletonSentry.cs | 283 ++++++++++++ 5 files changed, 1077 insertions(+), 1 deletion(-) create mode 100644 JotunnModStub/Skeleton/SkeletonBonePile.cs create mode 100644 JotunnModStub/Skeleton/SkeletonBonePileBehaviour.cs create mode 100644 JotunnModStub/Skeleton/SkeletonSentry.cs diff --git a/JotunnModStub/Skeleton/SkeletonBonePile.cs b/JotunnModStub/Skeleton/SkeletonBonePile.cs new file mode 100644 index 0000000..19f22f7 --- /dev/null +++ b/JotunnModStub/Skeleton/SkeletonBonePile.cs @@ -0,0 +1,383 @@ +using HarmonyLib; +using Jotunn.Configs; +using Jotunn.Entities; +using Jotunn.Managers; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// The Skeleton station: a bone pile from the crypts that raises a standing garrison. + /// + /// Same family as the Draugh's body pile and it shares that feature's whole thrall layer + /// (), but the economy is the opposite way round on purpose. The Draugh + /// pays per draugr out of a reserve that empties; the Skeleton pays ONCE PER SLOT and that slot + /// then refills itself forever. Skeletons are fragile - a troll or a drake clears the whole line + /// in one swing - so an army you have to re-buy after every fight is an army nobody would take + /// out of the house. + /// + /// That permanent slot is also, by itself, the "skeletons leave exactly the materials that made + /// them" idea: the bones are not dropped and re-fed, they simply get up again. Nothing is + /// generated, nothing is consumed, and the same twenty fragments stand back up as many times as + /// they are knocked down. It needs no death hook and no drop table - which is why the thralls have + /// their CharacterDrop stripped like the Draugh's, rather than filled in. + /// + /// Two differences from the Draugh worth stating because they are deliberate, not oversights: + /// - a destroyed pile kills its garrison INSTANTLY, where a body pile gives its draugr a minute. + /// Free perpetual regeneration is the trade for a hard off switch. + /// - melee and ranged are the same vanilla creature with different hands. There is no ranged + /// skeleton prefab: Skeleton_NoArcher is vanilla's own guaranteed-melee variant, and the + /// archer is a plain Skeleton whose loadout is forced to the bow. + /// + public static class SkeletonBonePile + { + // ─── Names ─────────────────────────────────────────────────────────── + public const string PieceName = "SkeletonBonePile"; + public const string PieceDisplayName = "Bound Bone Pile"; + + // The Soul Stone: a green ruby, sold by the Skeleton bench, and the thing that binds a skull and + // ten fragments into a sentry that cannot walk. Cheap on purpose - 50 coins - because the real + // cost of a sentry is the skull, which has to be taken off a skeleton rather than bought. + public const string SoulStoneName = "SoulStone"; + public const string SoulStoneDisplayName = "Soul Stone"; + public const int SoulStonePrice = 50; + + private static readonly Color SoulStoneTint = new Color(0.15f, 0.85f, 0.35f, 1f); + + public const string SkullName = "CursedSkull"; + public const string SkullDisplayName = "Cursed Skull"; + public const string GreaterSkullName = "GreaterCursedSkull"; + public const string GreaterSkullDisplayName = "Greater Cursed Skull"; + + public const string ThrallMeleeName = "SkeletonThrall_Melee"; + public const string ThrallRangedName = "SkeletonThrall_Ranged"; + public const string ThrallRancidName = "SkeletonThrall_Rancid"; + + public const string ThrallMeleeDisplay = "Bound Skeleton"; + public const string ThrallRangedDisplay = "Bound Archer"; + public const string ThrallRancidDisplay = "Bound Rancid Remains"; + + public const string KindMelee = "SkeletonMelee"; + public const string KindRanged = "SkeletonRanged"; + public const string KindRancid = "SkeletonRancid"; + + public const string RaceId = "Skeleton"; + + /// The one material a slot is bought with. Fixed, not a fungible bone tank - see the + /// class comment on why "exactly the materials that made them" needs a recipe. + public const string BonePrefab = "BoneFragments"; + public const int BonesPerSlot = 20; + + /// Buys a Rancid slot outright, the way an Elite trophy buys the Draugh an officer. + public const string RancidTrophy = "TrophySkeletonPoison"; + + // ─── Balance ───────────────────────────────────────────────────────── + public const int MeleeSlots = 4; + public const int RangedSlots = 4; + public const int MeleeSlotsUpgraded = 5; + public const int RangedSlotsUpgraded = 5; + public const int RancidSlots = 0; // none at all until upgraded + public const int RancidSlotsUpgraded = 2; + + // Local seconds, and only while the zone is loaded - a garrison should not quietly rebuild + // itself in an unloaded zone. Faster once upgraded: the pile gets better at it. + public const float RespawnSeconds = 20f; + public const float RespawnSecondsUpgraded = 15f; + + // NOT the "instant" from the design conversation - that lives in the pile's OnDestroyed, which + // calls Kill() on the spot. This number only governs the FALLBACK: a skeleton that was in an + // unloaded zone when the pile fell and finds nothing at home when it loads again. + // + // It was 0, and zero has no tolerance for a hiccup: a pile whose zone unloads for a moment + // while a skeleton at the boundary stays loaded reads as "no pile" and wipes the garrison with + // no appeal. Five seconds costs nothing anyone can perceive - the deliberate destruction path + // is still immediate - and it means one bad frame is not a wipe. + public const float OrphanWitherSeconds = 5f; + public const float HomeCheckRange = 20f; + public const float LeashRange = 10f; + + // No cap: the whole point of the new command is that the garrison moves as one. + public const int MaxFollowers = -1; + + // A Rancid Remains clicked directly takes five of the rank and file with it, instead of the + // whole line the pile would send. Its own squad, and small enough that it stays a squad. + public const int RancidEscort = 5; + + public const int UpgradeProgressionState = 4; // Bonemass, same gate as the Draugh's officers + + public const int MaxPilesInRange = 5; + public const float DensityAreaKm2 = 1.6f; + + // ─── Looks ─────────────────────────────────────────────────────────── + private const float ModelScale = 1.2f; + + // Cold bone-white, so it never reads as the Draugh's green pile at a glance. + private static readonly Color PileTint = new Color(0.82f, 0.84f, 0.78f, 1f); + private static readonly Color SkullTint = new Color(0.78f, 0.80f, 0.74f, 1f); + private static readonly Color GreaterSkullTint = new Color(0.62f, 0.72f, 0.80f, 1f); + + public static void Register() + { + RegisterSkull(SkullName, SkullDisplayName, SkullTint, + "A skull that keeps counting. Set it down and the ground starts answering."); + RegisterSkull(GreaterSkullName, GreaterSkullDisplayName, GreaterSkullTint, + "Older, and it counts higher. A pile given one of these raises the rotten too."); + + RegisterSoulStone(); + + RegisterThrall(ThrallMeleeName, "Skeleton_NoArcher", ThrallMeleeDisplay, KindMelee, null); + RegisterThrall(ThrallRangedName, "Skeleton", ThrallRangedDisplay, KindRanged, "skeleton_bow"); + RegisterThrall(ThrallRancidName, "Skeleton_Poison", ThrallRancidDisplay, KindRancid, null, RancidEscort); + + RegisterPiece(); + + // The standing sentry. Registered after the archer it clones, so that prefab exists first. + SkeletonSentry.Register(); + + PieceDensityLimit.Register(PieceName, + PieceDensityLimit.RadiusForArea(DensityAreaKm2), MaxPilesInRange, + "There are already {0} of these listening nearby. Take it further out."); + } + + // ---------------------------------------------------------------- items + + private static void RegisterSkull(string prefabName, string displayName, Color tint, string description) + { + GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(prefabName, "TrophySkeleton"); + if (prefab == null) + { + Jotunn.Logger.LogWarning($"[Skeleton] Could not clone TrophySkeleton; {displayName} not registered."); + return; + } + + Recolour(prefab, tint); + + ItemDrop drop = prefab.GetComponent(); + if (drop == null) return; + + ItemDrop.ItemData.SharedData shared = drop.m_itemData.m_shared; + shared.m_name = displayName; + shared.m_description = description; + shared.m_itemType = ItemDrop.ItemData.ItemType.Material; + shared.m_weight = 1f; + shared.m_maxStackSize = 10; + + ItemManager.Instance.AddItem(new CustomItem(prefab, fixReference: false)); + } + + /// + /// A ruby, turned green. Cloned rather than tinted in place so real rubies keep being red, the + /// same discipline every other borrowed prefab in this project follows. + /// + /// One caveat that always applies and is worth repeating on a gemstone: the tint reaches the + /// world and held models but NOT the inventory icon, because icons are atlas sprites and + /// repainting one produces an empty slot. In the inventory this reads as a ruby; the name and + /// the tooltip are what tell it apart. If that matters, borrow the icon of a green vanilla item + /// instead - it is one line. + /// + private static void RegisterSoulStone() + { + GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(SoulStoneName, "Ruby"); + if (prefab == null) + { + Jotunn.Logger.LogWarning("[Skeleton] Could not clone Ruby; Soul Stone not registered."); + return; + } + + Recolour(prefab, SoulStoneTint); + + ItemDrop drop = prefab.GetComponent(); + if (drop == null) return; + + ItemDrop.ItemData.SharedData shared = drop.m_itemData.m_shared; + shared.m_name = SoulStoneDisplayName; + shared.m_description = "Something is still in there, and it is still angry. Bind it to a skull " + + "and it will stand watch as long as the bones hold."; + shared.m_itemType = ItemDrop.ItemData.ItemType.Material; + shared.m_weight = 0.5f; + shared.m_maxStackSize = 20; + + ItemManager.Instance.AddItem(new CustomItem(prefab, fixReference: false)); + } + + // ---------------------------------------------------------------- thralls + + /// + /// One kind of bound skeleton, born tame and leashed to its pile. + /// + /// The weapon argument is what separates melee from ranged, because the distinction does not + /// exist at the prefab level: Skeleton_NoArcher is vanilla's guaranteed-melee variant, and a + /// plain Skeleton rolls its own weapon. Forcing m_defaultItems and clearing the random lists is + /// what makes an archer an archer every time instead of four times in eight. + /// + /// CharacterDrop is destroyed for the same reason as the Draugh's, plus one of its own: a + /// garrison that regenerates for free and drops its bones on death would be a bone mill. + /// + private static void RegisterThrall(string prefabName, string source, string displayName, + string kind, string forcedWeapon, int escortCount = 0) + { + GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(prefabName, source); + if (prefab == null) + { + Jotunn.Logger.LogWarning($"[Skeleton] Could not clone {source}; {displayName} not registered."); + return; + } + + Character character = prefab.GetComponent(); + if (character != null) character.m_name = displayName; + + BaseAI ai = prefab.GetComponent(); + if (ai != null) ai.m_randomMoveRange = LeashRange; + + if (forcedWeapon != null) + { + Humanoid humanoid = prefab.GetComponent(); + GameObject weapon = PrefabManager.Cache.GetPrefab(forcedWeapon); + if (humanoid != null && weapon != null) + { + humanoid.m_defaultItems = new[] { weapon }; + humanoid.m_randomWeapon = new GameObject[0]; + humanoid.m_randomSets = new Humanoid.ItemSet[0]; + Jotunn.Logger.LogInfo($"[Skeleton] {prefabName}: loadout forced to '{forcedWeapon}'."); + } + else + { + Jotunn.Logger.LogWarning($"[Skeleton] {prefabName}: could not force '{forcedWeapon}'; " + + "it will roll a random weapon like a wild one."); + } + } + + foreach (CharacterDrop drops in prefab.GetComponentsInChildren(true)) + { + if (drops != null) Object.DestroyImmediate(drops); + } + + RaisedThrall thrall = prefab.AddComponent(); + thrall.m_kind = kind; + thrall.m_commandingRace = RaceId; + thrall.m_maxFollowers = MaxFollowers; + thrall.m_witherSeconds = OrphanWitherSeconds; + thrall.m_homeCheckRange = HomeCheckRange; + thrall.m_refusalMessage = "These bones answer only to their own kind."; + thrall.m_escortCount = escortCount; + + PrefabManager.Instance.AddPrefab(prefab); + } + + // ---------------------------------------------------------------- piece + + private static void RegisterPiece() + { + // BonePileSpawner is the skeleton's own crypt spawner - the right base rather than a + // repainted body pile, and it already has hit and destruction effects of its own. + GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(PieceName, "BonePileSpawner"); + if (prefab == null) + { + Jotunn.Logger.LogWarning("[Skeleton] Could not clone BonePileSpawner; the bone pile is not registered."); + return; + } + + // Its whole vanilla job is throwing hostile skeletons at whoever walks past. All of it goes. + foreach (SpawnArea area in prefab.GetComponentsInChildren(true)) + { + if (area != null) Object.DestroyImmediate(area); + } + + AswidBloodRefinery.StripOffensive(prefab, PieceName); + + SkeletonBonePileBehaviour behaviour = prefab.AddComponent(); + + foreach (Switch existing in prefab.GetComponentsInChildren(true)) + { + if (existing != null) Object.DestroyImmediate(existing); + } + behaviour.m_switch = prefab.AddComponent(); + behaviour.m_switch.m_name = PieceDisplayName; + + prefab.transform.localScale = Vector3.one * ModelScale; + Recolour(prefab, PileTint); + + Piece piece = prefab.GetComponent() ?? prefab.AddComponent(); + piece.m_craftingStation = null; + piece.m_resources = new Piece.Requirement[0]; + piece.m_name = PieceDisplayName; + piece.m_canBeRemoved = true; + piece.m_groundPiece = true; + piece.m_groundOnly = true; + piece.m_icon = BorrowIcon("TrophySkeleton"); + + // A Piece added to world scenery is born with no icon and no place effect - the Furling's + // bushes taught this the hard way, where the entry existed as a blank unclickable square. + 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 = PieceDisplayName, + Description = "Twenty fragments buy a place in the line. The one who fills it will keep standing up.", + PieceTable = PieceTables.Hammer, + Category = PieceCategories.Crafting, + Icon = BorrowIcon("TrophySkeleton"), + Requirements = new[] + { + new RequirementConfig(SkullName, 1, 0, true), + new RequirementConfig("BoneFragments", 30, 0, true), + new RequirementConfig("Ooze", 10, 0, true), + } + })); + } + + public static void EnsureKnown(Player player) + { + if (player == null) return; + + GameObject prefab = PrefabManager.Instance.GetPrefab(PieceName); + Piece piece = prefab != null ? prefab.GetComponent() : null; + if (piece == null) return; + + Traverse traverse = Traverse.Create(player); + traverse.Method("AddKnownPiece", piece).GetValue(); + traverse.Method("UpdateAvailablePiecesList").GetValue(); + } + + // ---------------------------------------------------------------- helpers + + private static Sprite BorrowIcon(string prefabName) + { + ItemDrop drop = PrefabManager.Cache.GetPrefab(prefabName); + Sprite[] icons = drop != null && drop.m_itemData != null && drop.m_itemData.m_shared != null + ? drop.m_itemData.m_shared.m_icons + : null; + if (icons != null && icons.Length > 0 && icons[0] != null) return icons[0]; + + Jotunn.Logger.LogWarning($"[Skeleton] Could not borrow the icon from '{prefabName}'."); + return null; + } + + private static void Recolour(GameObject root, Color tint) + { + foreach (Renderer renderer in root.GetComponentsInChildren(true)) + { + if (renderer == null || renderer is ParticleSystemRenderer) continue; + + foreach (Material material in renderer.materials) + { + if (material == null) continue; + material.color = tint; + if (material.HasProperty("_Color")) material.SetColor("_Color", tint); + } + } + } + } + + [HarmonyPatch(typeof(Player), "OnSpawned")] + public static class SkeletonBonePileKnownPatch + { + public static void Postfix(Player __instance) + { + if (__instance != Player.m_localPlayer) return; + SkeletonBonePile.EnsureKnown(__instance); + SkeletonSentry.EnsureKnown(__instance); + } + } +} diff --git a/JotunnModStub/Skeleton/SkeletonBonePileBehaviour.cs b/JotunnModStub/Skeleton/SkeletonBonePileBehaviour.cs new file mode 100644 index 0000000..83c6046 --- /dev/null +++ b/JotunnModStub/Skeleton/SkeletonBonePileBehaviour.cs @@ -0,0 +1,403 @@ +using System; +using System.Collections.Generic; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// The bone pile's logic. Simpler than the body pile's, because there is no reserve to keep books + /// on: the ZDO holds how many SLOTS have been paid for per kind, and a slot with nobody standing + /// in it refills itself on a timer, forever. + /// + /// That is the whole "skeletons are immortal" mechanic, and it is why nothing here drops or + /// consumes bones on death. Twenty fragments buy a place in the line once; whoever is standing in + /// that place gets back up as often as they are knocked down. No death hook, no drop table, no + /// resource created or destroyed. + /// + /// The roster is counted from the world rather than tallied, exactly like the body pile's, so a + /// death, a despawn or a player killing his own skeleton all correct themselves. + /// + public class SkeletonBonePileBehaviour : MonoBehaviour + { + public Switch m_switch; + + private const string KeyBones = "RoV_skelBones"; + private const string KeySlotsMelee = "RoV_skelSlotsMelee"; + private const string KeySlotsRanged = "RoV_skelSlotsRanged"; + private const string KeySlotsRancid = "RoV_skelSlotsRancid"; + private const string KeyUpgraded = "RoV_skelUpgraded"; + + private ZNetView m_nview; + private float m_respawnTimer; + + private void Awake() + { + // The registry RaisedThrall consults to answer "is my pile still standing?". + RaisedThrall.RegisterStation(transform); + + m_nview = GetComponent(); + if (m_nview == null || m_nview.GetZDO() == null) return; + + if (m_switch != null) + { + m_switch.m_onUse = OnUse; + m_switch.m_onHover = Hover; + } + + m_nview.Register("RoV_SkelFeed", RPC_Feed); + m_nview.Register("RoV_SkelUpgrade", RPC_Upgrade); + + WearNTear wear = GetComponent(); + if (wear != null) wear.m_onDestroyed = (Action)Delegate.Combine(wear.m_onDestroyed, new Action(OnDestroyed)); + + InvokeRepeating("UpdatePile", 2f, 2f); + } + + private void OnDestroy() + { + RaisedThrall.UnregisterStation(transform); + } + + // ---------------------------------------------------------------- interaction + + /// + /// Bones in hand feed it, a Greater Cursed Skull upgrades it, a Rancid trophy buys an officer - + /// and EMPTY HANDS move the whole garrison. That last one is the mechanic the Draugh does not + /// have: a body pile is commanded draugr by draugr, a bone pile is commanded as a line. + /// + /// Empty hands were free to use for this because the pile's own hover already carries the + /// status the Draugh needs an empty-handed click to report. + /// + private bool OnUse(Switch caller, Humanoid user, ItemDrop.ItemData item) + { + Player player = user as Player; + if (player == null) return false; + + Inventory inventory = player.GetInventory(); + if (inventory == null) return false; + + // EMPTY HANDS MEAN THE COMMAND, always, and nothing else is consulted. + // + // This used to scan the pack for something to feed first, copied from the body pile where + // empty hands mean nothing else. Two bugs came out of it: a Rancid trophy in the pack was + // skipped in SILENCE when the pile was not upgraded yet - the refusal that explains why was + // only reachable by holding the item - and, worse, anyone carrying bone fragments (which is + // everyone) would feed the pile when they meant to move the line. The hover has always said + // "bone in hand to buy a place, empty hands to move the line"; now the code agrees with it. + if (item == null) return ToggleGarrison(player); + + string prefabName = item.m_dropPrefab != null ? item.m_dropPrefab.name : null; + if (prefabName == null) return false; + + if (prefabName == SkeletonBonePile.GreaterSkullName) return TryUpgrade(player, inventory, item); + + // How many of this the pile can still take. Not "is there room for one" - that was the bug: + // the old check only asked whether a single trophy would fit and then handed over the WHOLE + // stack, so ten Rancid trophies went in, RPC_Feed clamped the slots to two, and eight were + // destroyed for nothing. Anything taken from the player has to be something the pile will + // actually keep. + int room; + if (prefabName == SkeletonBonePile.RancidTrophy) + { + if (!IsUpgraded()) + { + player.Message(MessageHud.MessageType.Center, "This pile cannot hold the rotten yet."); + return false; + } + room = RancidCap() - GetSlots(SkeletonBonePile.KindRancid); + } + else if (prefabName == SkeletonBonePile.BonePrefab) + { + // Bone is measured in fragments, not places: what is left to buy, minus what is already + // part-paid towards the next place. + room = (TotalCap() - PaidSlots()) * SkeletonBonePile.BonesPerSlot + - m_nview.GetZDO().GetInt(KeyBones); + } + else + { + player.Message(MessageHud.MessageType.Center, "$msg_wontwork"); + return false; + } + + if (room <= 0) + { + player.Message(MessageHud.MessageType.Center, "$msg_itsfull"); + return false; + } + + int taken = Mathf.Min(Mathf.Max(1, item.m_stack), room); + player.Message(MessageHud.MessageType.Center, $"$msg_added {item.m_shared.m_name} x{taken}"); + inventory.RemoveItem(item, taken); + + m_nview.InvokeRPC("RoV_SkelFeed", prefabName, taken); + return true; + } + + /// + /// The new command: every skeleton of this pile follows, or every one of them comes home. One + /// click for the line, decided by whether any of them is already out. + /// + private bool ToggleGarrison(Player player) + { + List bound = RaisedThrall.BoundTo(transform.position); + if (bound.Count == 0) + { + player.Message(MessageHud.MessageType.Center, "Nothing is standing yet. It wants bone."); + return false; + } + + bool anyFollowing = false; + foreach (RaisedThrall thrall in bound) + { + if (thrall.IsFollowing(player)) { anyFollowing = true; break; } + } + + int moved = 0; + foreach (RaisedThrall thrall in bound) + { + // announce: false - one message for the line, not one per skeleton. + if (thrall.SetFollowing(player, !anyFollowing, announce: false)) moved++; + } + + if (moved == 0) + { + // Every one of them refused, which for these means the player is not a Skeleton. + player.Message(MessageHud.MessageType.Center, "These bones answer only to their own kind."); + return false; + } + + player.Message(MessageHud.MessageType.Center, anyFollowing + ? $"{moved} return to the pile." + : $"{moved} rise and follow."); + return true; + } + + private bool TryUpgrade(Player player, Inventory inventory, ItemDrop.ItemData item) + { + if (IsUpgraded()) + { + player.Message(MessageHud.MessageType.Center, "It has already had one."); + return false; + } + + if (BossProgressionManager.GetCurrentProgressionState() < SkeletonBonePile.UpgradeProgressionState) + { + player.Message(MessageHud.MessageType.Center, "The skull will not wake. Something older has to fall first."); + return false; + } + + inventory.RemoveItem(item, 1); + m_nview.InvokeRPC("RoV_SkelUpgrade"); + player.Message(MessageHud.MessageType.Center, "The pile deepens. The rotten will stand here too."); + return true; + } + + // ---------------------------------------------------------------- accounting + + private void RPC_Feed(long sender, string prefabName, int count) + { + if (!m_nview.IsOwner()) return; + if (count < 1) count = 1; + + if (prefabName == SkeletonBonePile.RancidTrophy) + { + if (!IsUpgraded()) return; + SetSlots(SkeletonBonePile.KindRancid, + Mathf.Min(RancidCap(), GetSlots(SkeletonBonePile.KindRancid) + count)); + return; + } + + if (prefabName != SkeletonBonePile.BonePrefab) return; + + int bones = m_nview.GetZDO().GetInt(KeyBones) + count; + + // Melee places fill first, then the archers'. A loop rather than a single test so a whole + // stack cannot overflow into bones that are never counted. + while (bones >= SkeletonBonePile.BonesPerSlot && PaidSlots() < TotalCap()) + { + bones -= SkeletonBonePile.BonesPerSlot; + + if (GetSlots(SkeletonBonePile.KindMelee) < MeleeCap()) + { + SetSlots(SkeletonBonePile.KindMelee, GetSlots(SkeletonBonePile.KindMelee) + 1); + } + else + { + SetSlots(SkeletonBonePile.KindRanged, GetSlots(SkeletonBonePile.KindRanged) + 1); + } + } + + m_nview.GetZDO().Set(KeyBones, bones); + } + + private void RPC_Upgrade(long sender) + { + if (!m_nview.IsOwner()) return; + m_nview.GetZDO().Set(KeyUpgraded, true); + } + + private void UpdatePile() + { + if (m_nview == null || !m_nview.IsValid() || !m_nview.IsOwner()) return; + + string empty = FirstEmptyKind(); + if (empty == null) + { + m_respawnTimer = 0f; + return; + } + + m_respawnTimer += 2f; // the tick interval + if (m_respawnTimer < RespawnSeconds()) return; + m_respawnTimer = 0f; + + Spawn(empty); + } + + /// A kind that has a paid slot with nobody standing in it, or null. Rotten first - + /// they are the scarcest and the reason to upgrade. + private string FirstEmptyKind() + { + Dictionary alive = CountAlive(); + + if (alive[SkeletonBonePile.KindRancid] < GetSlots(SkeletonBonePile.KindRancid)) return SkeletonBonePile.KindRancid; + if (alive[SkeletonBonePile.KindMelee] < GetSlots(SkeletonBonePile.KindMelee)) return SkeletonBonePile.KindMelee; + if (alive[SkeletonBonePile.KindRanged] < GetSlots(SkeletonBonePile.KindRanged)) return SkeletonBonePile.KindRanged; + return null; + } + + private Dictionary CountAlive() + { + Dictionary alive = new Dictionary + { + { SkeletonBonePile.KindMelee, 0 }, + { SkeletonBonePile.KindRanged, 0 }, + { SkeletonBonePile.KindRancid, 0 }, + }; + + foreach (RaisedThrall thrall in RaisedThrall.BoundTo(transform.position)) + { + if (thrall.Kind != null && alive.ContainsKey(thrall.Kind)) alive[thrall.Kind]++; + } + return alive; + } + + private void Spawn(string kind) + { + string prefabName = + kind == SkeletonBonePile.KindRancid ? SkeletonBonePile.ThrallRancidName : + kind == SkeletonBonePile.KindRanged ? SkeletonBonePile.ThrallRangedName : + SkeletonBonePile.ThrallMeleeName; + + GameObject prefab = ZNetScene.instance != null ? ZNetScene.instance.GetPrefab(prefabName) : null; + if (prefab == null) + { + Jotunn.Logger.LogWarning($"[Skeleton] No '{prefabName}' in ZNetScene; the pile cannot raise anything."); + return; + } + + Vector3 offset = UnityEngine.Random.insideUnitSphere * 2f; + offset.y = 0f; + Vector3 position = transform.position + offset + Vector3.up * 0.5f; + + GameObject spawned = Instantiate(prefab, position, Quaternion.Euler(0f, UnityEngine.Random.Range(0, 360), 0f)); + RaisedThrall thrall = spawned.GetComponent(); + if (thrall != null) thrall.Bind(transform.position); + } + + /// + /// Instantly, unlike the body pile's minute. The garrison rebuilds itself for free forever, so + /// the pile being broken has to be an immediate off switch or there is no counterweight at all. + /// MarkOrphaned still covers any that were unloaded when it fell - with a wither of zero they + /// die on their first tick home rather than lingering. + /// + private void OnDestroyed() + { + if (m_nview == null || !m_nview.IsOwner()) return; + + List bound = RaisedThrall.BoundTo(transform.position); + foreach (RaisedThrall thrall in bound) + { + thrall.MarkOrphaned(); + thrall.Kill(); + } + + if (bound.Count > 0 && Player.m_localPlayer != null) + { + Player.m_localPlayer.Message(MessageHud.MessageType.Center, + $"The pile is broken. {bound.Count} fall where they stand."); + } + } + + // ---------------------------------------------------------------- state and display + + public bool IsUpgraded() => m_nview != null && m_nview.IsValid() && m_nview.GetZDO().GetBool(KeyUpgraded, false); + + private int MeleeCap() => IsUpgraded() ? SkeletonBonePile.MeleeSlotsUpgraded : SkeletonBonePile.MeleeSlots; + + private int RangedCap() => IsUpgraded() ? SkeletonBonePile.RangedSlotsUpgraded : SkeletonBonePile.RangedSlots; + + private int RancidCap() => IsUpgraded() ? SkeletonBonePile.RancidSlotsUpgraded : SkeletonBonePile.RancidSlots; + + private float RespawnSeconds() => + IsUpgraded() ? SkeletonBonePile.RespawnSecondsUpgraded : SkeletonBonePile.RespawnSeconds; + + /// Paid melee and archer places. Rotten ones are bought with trophies, not bone, so + /// they are counted separately and do not compete for the same twenty fragments. + private int PaidSlots() => GetSlots(SkeletonBonePile.KindMelee) + GetSlots(SkeletonBonePile.KindRanged); + + private int TotalCap() => MeleeCap() + RangedCap(); + + private string Hover() + { + Dictionary alive = CountAlive(); + + // A line per kind, each reading "standing / places bought / places possible", because the + // first version told the player none of that: the rotten line was hidden until the pile was + // upgraded, so there was no way to know the cap was two until ten trophies had gone in. + // Every shelf is now visible whether or not it can be used yet, and says why when it cannot. + string body = + $"\nmelee {alive[SkeletonBonePile.KindMelee]}/{GetSlots(SkeletonBonePile.KindMelee)} of {MeleeCap()}" + + $"\narchers {alive[SkeletonBonePile.KindRanged]}/{GetSlots(SkeletonBonePile.KindRanged)} of {RangedCap()}" + + $"\nrotten {alive[SkeletonBonePile.KindRancid]}/{GetSlots(SkeletonBonePile.KindRancid)} of {RancidCap()}"; + + if (!IsUpgraded()) body += " (needs a Greater Cursed Skull)"; + + int bonesToward = m_nview.GetZDO().GetInt(KeyBones); + int placesLeft = TotalCap() - PaidSlots(); + body += placesLeft > 0 + ? $"\nbone {bonesToward}/{SkeletonBonePile.BonesPerSlot} toward the next of {placesLeft} places" + : "\nevery place is bought"; + + if (m_respawnTimer > 0f) + { + int left = Mathf.Max(1, Mathf.CeilToInt(RespawnSeconds() - m_respawnTimer)); + body += $"\nnext rises in {left}s"; + } + + body += "\n[$KEY_Use] Bone in hand to buy a place, empty hands to move the line"; + + return Localization.instance.Localize($"{SkeletonBonePile.PieceDisplayName} ({body})"); + } + + // ---------------------------------------------------------------- ZDO accessors + + private int GetSlots(string kind) + { + if (m_nview == null || !m_nview.IsValid()) return 0; + return m_nview.GetZDO().GetInt(KeyFor(kind)); + } + + private void SetSlots(string kind, int value) + { + if (m_nview != null && m_nview.IsValid()) m_nview.GetZDO().Set(KeyFor(kind), Mathf.Max(0, value)); + } + + private static string KeyFor(string kind) + { + if (kind == SkeletonBonePile.KindRanged) return KeySlotsRanged; + if (kind == SkeletonBonePile.KindRancid) return KeySlotsRancid; + return KeySlotsMelee; + } + } +} diff --git a/JotunnModStub/Skeleton/SkeletonPatches.cs b/JotunnModStub/Skeleton/SkeletonPatches.cs index 1fee96c..10a6ce5 100644 --- a/JotunnModStub/Skeleton/SkeletonPatches.cs +++ b/JotunnModStub/Skeleton/SkeletonPatches.cs @@ -84,7 +84,9 @@ namespace RacesOfValheim __result = false; return false; } - else if (AswidRace.IsAswid() && !AswidRace.BypassAswidFoodCheck && item.m_shared.m_itemType == ItemDrop.ItemData.ItemType.Consumable && (item.m_shared.m_food > 0 || item.m_shared.m_foodStamina > 0 || item.m_shared.m_foodEitr > 0)) + // Blood Essence is the one real food an Aswid can still chew, so it has to + // survive this blanket refusal - everything else mortal still bounces. + else if (AswidRace.IsAswid() && !AswidRace.BypassAswidFoodCheck && !AswidBloodRefinery.IsAswidMeal(item) && item.m_shared.m_itemType == ItemDrop.ItemData.ItemType.Consumable && (item.m_shared.m_food > 0 || item.m_shared.m_foodStamina > 0 || item.m_shared.m_foodEitr > 0)) { __instance.Message(MessageHud.MessageType.Center, "Mortal food disgusts you."); __result = false; diff --git a/JotunnModStub/Skeleton/SkeletonRace.cs b/JotunnModStub/Skeleton/SkeletonRace.cs index fa1b74f..b894318 100644 --- a/JotunnModStub/Skeleton/SkeletonRace.cs +++ b/JotunnModStub/Skeleton/SkeletonRace.cs @@ -17,6 +17,11 @@ namespace RacesOfValheim public void CreateModAssets() { + // The bone pile and its garrison. Registered here because the faction merchant catalogue + // resolves its entries by prefab name, so the two cursed skulls have to exist before a + // Skeleton is ever set up as a bench. + SkeletonBonePile.Register(); + var se = ScriptableObject.CreateInstance(); se.name = "SE_SkeletonStats"; se.m_name = "Undead Fortitude"; diff --git a/JotunnModStub/Skeleton/SkeletonSentry.cs b/JotunnModStub/Skeleton/SkeletonSentry.cs new file mode 100644 index 0000000..ef37404 --- /dev/null +++ b/JotunnModStub/Skeleton/SkeletonSentry.cs @@ -0,0 +1,283 @@ +using HarmonyLib; +using Jotunn.Configs; +using Jotunn.Entities; +using Jotunn.Managers; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// A bound archer that cannot walk: built with the hammer, stands where it is put, shoots what comes + /// near, knits itself back together when left alone, and hands its parts back when it falls. + /// + /// TWO PREFABS, and that is forced rather than chosen. The design settled on cloning the tamed + /// archer, so the sentry is a CHARACTER - and a Character cannot sit in the hammer's piece table, + /// because the hammer builds Piece. So a small seed piece goes in the table, spawns the sentry the + /// moment it is placed, and removes itself. The alternative was cloning the Ballista, which would + /// have brought WearNTear's health, repair and component refund for free; cloning the archer instead + /// means those are written here, which is the trade that was made deliberately. + /// + /// The refund is a CharacterDrop at full chance - which makes the sentry the one skeleton in this mod + /// that drops anything. Every other thrall has its drop table stripped precisely so a garrison that + /// regenerates for free cannot be farmed; this one is not free and does not regenerate its slot, so + /// giving the parts back is safe and is what was asked for. + /// + public static class SkeletonSentry + { + public const string SentryName = "SkeletonSentry"; + public const string SeedPieceName = "SkeletonSentrySeed"; + public const string DisplayName = "Bound Sentry"; + + /// Seconds without being hit before it starts closing its wounds. + public const float RegenDelay = 10f; + + /// Fraction of maximum health per second once it starts. + public const float RegenPerSecond = 0.02f; + + // What it costs, and therefore exactly what it gives back. + public const int BoneCost = 10; + + public static void Register() + { + GameObject sentry = BuildSentry(); + if (sentry != null) BuildSeedPiece(); + } + + // ---------------------------------------------------------------- the sentry + + private static GameObject BuildSentry() + { + // The archer we already register for the bone pile, so its forced bow loadout comes along. + GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(SentryName, SkeletonBonePile.ThrallRangedName); + if (prefab == null) + { + Jotunn.Logger.LogWarning($"[Skeleton] Could not clone {SkeletonBonePile.ThrallRangedName}; the sentry is not registered."); + return null; + } + + Character character = prefab.GetComponent(); + if (character != null) + { + character.m_name = DisplayName; + + // Rooted. Every way it could move, set to nothing - and m_randomMoveRange so it does not + // even try to wander. If the AI still shuffles or stops shooting because it wants to + // close distance and cannot, the fallback is to pin it from the AI side instead, with + // the patrol trick the thralls and the grove already use. + character.m_speed = 0f; + character.m_walkSpeed = 0f; + character.m_runSpeed = 0f; + character.m_acceleration = 0f; + character.m_jumpForce = 0f; + } + + BaseAI ai = prefab.GetComponent(); + if (ai != null) ai.m_randomMoveRange = 0f; + + // Its parts back, all of them, every time. Replaces the stripped table the archer clone + // inherits rather than adding to it. + foreach (CharacterDrop existing in prefab.GetComponentsInChildren(true)) + { + if (existing != null) Object.DestroyImmediate(existing); + } + + CharacterDrop drops = prefab.AddComponent(); + drops.m_drops = new System.Collections.Generic.List(); + AddDrop(drops, SkeletonBonePile.SoulStoneName, 1); + AddDrop(drops, "TrophySkeleton", 1); + AddDrop(drops, SkeletonBonePile.BonePrefab, BoneCost); + + prefab.AddComponent(); + + PrefabManager.Instance.AddPrefab(prefab); + return prefab; + } + + private static void AddDrop(CharacterDrop drops, string prefabName, int amount) + { + GameObject prefab = PrefabManager.Cache.GetPrefab(prefabName); + if (prefab == null) + { + Jotunn.Logger.LogWarning($"[Skeleton] Sentry: no '{prefabName}' to give back; that part is lost on death."); + return; + } + + drops.m_drops.Add(new CharacterDrop.Drop + { + m_prefab = prefab, + m_amountMin = amount, + m_amountMax = amount, + m_chance = 1f, + m_levelMultiplier = false, + m_dontScale = true, // the refund is the cost, not a loot roll + m_onePerPlayer = false, + }); + } + + // ---------------------------------------------------------------- the seed + + /// + /// The hammer entry. Exists only to be placed and immediately replaced by the sentry, which is + /// how a creature gets into a piece table at all. + /// + private static void BuildSeedPiece() + { + // An armour stand, because the seed's real job is its BUILD GHOST: the sentry itself only + // exists a frame later, so what the player aims at while placing is this prefab's silhouette. + // A workbench read as furniture; a standing human frame reads as "someone will be here", which + // is what is about to happen. ArmorStand is the buildable one, so it arrives with the Piece, + // ZNetView and WearNTear the strip below keeps. + GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(SeedPieceName, "ArmorStand"); + if (prefab == null) + { + Jotunn.Logger.LogWarning("[Skeleton] Could not clone ArmorStand; the sentry cannot be built."); + return; + } + + // Everything the stand actually DOES goes - its armour slots included. All that is wanted is a + // placeable shell with the right outline, alive for one frame. + 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.AddComponent(); + + 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 = BorrowIcon("TrophySkeleton"); + + PieceManager.Instance.AddPiece(new CustomPiece(prefab, fixReference: false, new PieceConfig + { + Name = DisplayName, + Description = "A skull on a soul stone. It will not walk, and it will not stop watching.", + PieceTable = PieceTables.Hammer, + Category = PieceCategories.Crafting, + Icon = BorrowIcon("TrophySkeleton"), + Requirements = new[] + { + new RequirementConfig(SkeletonBonePile.SoulStoneName, 1, 0, true), + new RequirementConfig("TrophySkeleton", 1, 0, true), + new RequirementConfig(SkeletonBonePile.BonePrefab, BoneCost, 0, true), + } + })); + } + + public static void EnsureKnown(Player player) + { + if (player == null) return; + + GameObject prefab = PrefabManager.Instance.GetPrefab(SeedPieceName); + Piece piece = prefab != null ? prefab.GetComponent() : null; + if (piece == null) return; + + Traverse traverse = Traverse.Create(player); + traverse.Method("AddKnownPiece", piece).GetValue(); + traverse.Method("UpdateAvailablePiecesList").GetValue(); + } + + private static Sprite BorrowIcon(string prefabName) + { + ItemDrop drop = PrefabManager.Cache.GetPrefab(prefabName); + Sprite[] icons = drop != null && drop.m_itemData != null && drop.m_itemData.m_shared != null + ? drop.m_itemData.m_shared.m_icons + : null; + if (icons != null && icons.Length > 0 && icons[0] != null) return icons[0]; + return null; + } + } + + /// + /// Lives for one frame: swaps itself for the sentry and goes. Owner only, so in multiplayer exactly + /// one archer stands up rather than one per client. + /// + public class SkeletonSentrySeed : MonoBehaviour + { + private void Start() + { + ZNetView nview = GetComponent(); + if (nview == null || !nview.IsValid() || !nview.IsOwner()) return; + + GameObject prefab = ZNetScene.instance != null + ? ZNetScene.instance.GetPrefab(SkeletonSentry.SentryName) + : null; + + if (prefab == null) + { + Jotunn.Logger.LogWarning($"[Skeleton] No '{SkeletonSentry.SentryName}' in ZNetScene; nothing was raised."); + return; + } + + GameObject spawned = Instantiate(prefab, transform.position, transform.rotation); + + // Tamed, so it never turns on the person who built it. The bone pile's thralls get this from + // RaisedThrall.Bind; a sentry has no pile to be bound to, so it is done here. + MonsterAI ai = spawned.GetComponent(); + if (ai != null) ai.MakeTame(); + Character character = spawned.GetComponent(); + if (character != null) character.SetTamed(true); + + ZNetScene.instance.Destroy(gameObject); + } + } + + /// + /// The regeneration: untouched for ten seconds, then two percent of maximum health a second until + /// whole. The clock is local rather than world time on purpose - a sentry nobody is near is a sentry + /// in an unloaded zone, and healing through that would mean coming home to a full-health guard that + /// was left at death's door. + /// + public class SkeletonSentryBehaviour : MonoBehaviour + { + private Character m_character; + private ZNetView m_nview; + private float m_sinceDamage; + + private void Awake() + { + m_character = GetComponent(); + m_nview = GetComponent(); + InvokeRepeating("TickRegen", 1f, 1f); + } + + /// Called from the Character.Damage postfix below. + public void NoteDamage() => m_sinceDamage = 0f; + + private void TickRegen() + { + if (m_character == null || m_character.IsDead()) return; + if (m_nview == null || !m_nview.IsValid() || !m_nview.IsOwner()) return; + + m_sinceDamage += 1f; + if (m_sinceDamage < SkeletonSentry.RegenDelay) return; + + float max = m_character.GetMaxHealth(); + if (m_character.GetHealth() >= max) return; + + m_character.Heal(max * SkeletonSentry.RegenPerSecond, false); + } + } + + /// + /// Resets a sentry's regeneration clock whenever it is hit. A postfix on the same method the Trenta's + /// Thorns already patches, so the shape is known to work. + /// + [HarmonyPatch(typeof(Character), "Damage")] + public static class SkeletonSentryDamagePatch + { + public static void Postfix(Character __instance) + { + if (__instance == null) return; + + SkeletonSentryBehaviour sentry = __instance.GetComponent(); + if (sentry != null) sentry.NoteDamage(); + } + } +} -- 2.52.0 From 1a741978bfea915e35c9767b14a6e576e69c19fa Mon Sep 17 00:00:00 2001 From: Ferdinando Date: Fri, 7 Aug 2026 17:02:47 +0200 Subject: [PATCH 5/8] feat(trenta): composter and heartwood grove Co-Authored-By: Claude Opus 5 --- JotunnModStub/Trenta/ComposterBehaviour.cs | 279 +++++++++++ JotunnModStub/Trenta/GroveBehaviour.cs | 373 ++++++++++++++ JotunnModStub/Trenta/TrentaComposter.cs | 488 +++++++++++++++++++ JotunnModStub/Trenta/TrentaConfig.cs | 157 +++++- JotunnModStub/Trenta/TrentaHeartwoodGrove.cs | 237 +++++++++ JotunnModStub/Trenta/TrentaHornetsNest.cs | 137 +++++- JotunnModStub/Trenta/TrentaRace.cs | 7 + 7 files changed, 1659 insertions(+), 19 deletions(-) create mode 100644 JotunnModStub/Trenta/ComposterBehaviour.cs create mode 100644 JotunnModStub/Trenta/GroveBehaviour.cs create mode 100644 JotunnModStub/Trenta/TrentaComposter.cs create mode 100644 JotunnModStub/Trenta/TrentaHeartwoodGrove.cs diff --git a/JotunnModStub/Trenta/ComposterBehaviour.cs b/JotunnModStub/Trenta/ComposterBehaviour.cs new file mode 100644 index 0000000..f59dbe8 --- /dev/null +++ b/JotunnModStub/Trenta/ComposterBehaviour.cs @@ -0,0 +1,279 @@ +using System; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// The Composter's logic. Modelled on - same one-second tick, same + /// owner-only accounting with all state in the ZDO - but with a numeric tank filled by many + /// different meats in place of the barrel's single stored item. + /// + /// Three states, and the barrel already has a visual for each of them: filling, composting, + /// ready. Raw flesh is destroyed on the spot and becomes mass; at capacity the lid closes and + /// the clock starts; when it runs out the tap gives a batch of Fertilizer and the cycle resets. + /// + /// One simplification over worth pointing out: the refinery + /// has to carry a time accumulator because it produces continuously and must catch up on every + /// second it spent unloaded. This works in batches, so the whole timer is one stored timestamp + /// compared against ZNet's world clock - which gets "keeps composting while the zone is + /// unloaded and the game is shut" for free rather than by bookkeeping. + /// + public class ComposterBehaviour : MonoBehaviour + { + // Handed over from the vanilla Fermenter before it is destroyed, which is what keeps the + // three visual states, the sounds and the tap effects identical to the real barrel's. The + // Switch is ours - see the comment in TrentaComposter.RegisterPiece for why. + public Switch m_switch; + public GameObject m_topObject; + public GameObject m_fermentingObject; + public GameObject m_readyObject; + public Transform m_outputPoint; + public EffectList m_addedEffects; + public EffectList m_tapEffects; + public EffectList m_spawnEffects; + + public float m_capacity = 100f; + public float m_compostSeconds = 2400f; + public int m_yield = 20; + + private const string KeyFlesh = "RoV_compostFlesh"; + private const string KeySealed = "RoV_compostSealed"; + + private ZNetView m_nview; + + public enum State + { + Filling, + Composting, + Ready, + } + + private void Awake() + { + m_nview = GetComponent(); + if (m_nview == null) m_nview = GetComponentInParent(); + if (m_nview == null || m_nview.GetZDO() == null) return; + + if (m_switch != null) + { + m_switch.m_onUse = OnUse; + m_switch.m_onHover = Hover; + } + + m_nview.Register("RoV_CompostAdd", RPC_Add); + m_nview.Register("RoV_CompostTap", RPC_Tap); + + WearNTear wear = GetComponent(); + if (wear == null) wear = GetComponentInParent(); + if (wear != null) wear.m_onDestroyed = (Action)Delegate.Combine(wear.m_onDestroyed, new Action(OnDestroyed)); + + InvokeRepeating("UpdateComposter", 1f, 1f); + } + + // ---------------------------------------------------------------- interaction + + /// + /// One interaction point, exactly like the vanilla barrel: the item in hand decides what the + /// click means. Holding flesh feeds it; empty hands tap it when it is ready and otherwise + /// just report what it is doing. + /// + private bool OnUse(Switch caller, Humanoid user, ItemDrop.ItemData item) + { + if (user == null) return false; + + State state = GetState(); + + if (state == State.Ready) + { + m_nview.InvokeRPC("RoV_CompostTap"); + return true; + } + + if (state == State.Composting) + { + user.Message(MessageHud.MessageType.Center, $"Still rotting. {MinutesLeft()} minutes."); + return false; + } + + Inventory inventory = user.GetInventory(); + if (inventory == null) return false; + + if (item == null) item = FindFlesh(inventory); + if (item == null) + { + user.Message(MessageHud.MessageType.Center, "No raw flesh to rot."); + return false; + } + + string prefabName = item.m_dropPrefab != null ? item.m_dropPrefab.name : null; + if (AswidBloodRefinery.FleshValue(prefabName) <= 0) + { + user.Message(MessageHud.MessageType.Center, "$msg_wontwork"); + return false; + } + + user.Message(MessageHud.MessageType.Center, "$msg_added " + item.m_shared.m_name); + inventory.RemoveItem(item, 1); + m_nview.InvokeRPC("RoV_CompostAdd", prefabName); + return true; + } + + private ItemDrop.ItemData FindFlesh(Inventory inventory) + { + foreach (ItemDrop.ItemData candidate in inventory.GetAllItems()) + { + if (candidate == null || candidate.m_dropPrefab == null) continue; + if (AswidBloodRefinery.FleshValue(candidate.m_dropPrefab.name) > 0) return candidate; + } + return null; + } + + private void RPC_Add(long sender, string prefabName) + { + if (!m_nview.IsOwner()) return; + if (GetState() != State.Filling) return; + + int value = AswidBloodRefinery.FleshValue(prefabName); + if (value <= 0) return; + + float flesh = Mathf.Min(m_capacity, GetFlesh() + value); + SetFlesh(flesh); + + // Reaching capacity is what starts the clock. Stamped once, here, so a barrel that fills + // up while nobody is watching still seals at the right moment. + if (flesh >= m_capacity) m_nview.GetZDO().Set(KeySealed, ZNet.instance.GetTime().Ticks); + + if (m_addedEffects != null) m_addedEffects.Create(transform.position, transform.rotation); + } + + private void RPC_Tap(long sender) + { + if (!m_nview.IsOwner()) return; + if (GetState() != State.Ready) return; + + SetFlesh(0f); + m_nview.GetZDO().Set(KeySealed, 0L); + Produce(); + } + + private void Produce() + { + GameObject prefab = ObjectDB.instance != null + ? ObjectDB.instance.GetItemPrefab(TrentaConfig.FertilizerName) + : null; + if (prefab == null || m_outputPoint == null) return; + + if (m_tapEffects != null) m_tapEffects.Create(transform.position, transform.rotation); + if (m_spawnEffects != null) m_spawnEffects.Create(m_outputPoint.position, m_outputPoint.rotation); + + // One stack rather than twenty objects on the ground: Fertilizer stacks to 50, so the + // whole batch fits, the same way Smelter.m_spawnStack gathers its output. + GameObject spawned = Instantiate(prefab, m_outputPoint.position, m_outputPoint.rotation); + ItemDrop drop = spawned.GetComponent(); + if (drop != null) + { + drop.m_itemData.m_stack = m_yield; + ItemDrop.OnCreateNew(drop); + } + } + + /// + /// A finished batch is given back; flesh that has already rotted is not. Same rule the Blood + /// Refinery follows for blood, and for the same reason - what the machine has absorbed is + /// gone by design, and the hover text says so before anyone swings a hammer at it. + /// + private void OnDestroyed() + { + if (m_nview == null || !m_nview.IsOwner()) return; + + bool ready = GetState() == State.Ready; + SetFlesh(0f); + m_nview.GetZDO().Set(KeySealed, 0L); + if (!ready) return; + + GameObject prefab = ObjectDB.instance != null + ? ObjectDB.instance.GetItemPrefab(TrentaConfig.FertilizerName) + : null; + if (prefab == null) return; + + Vector3 position = transform.position + Vector3.up * 0.5f; + GameObject spawned = Instantiate(prefab, position, Quaternion.Euler(0f, UnityEngine.Random.Range(0, 360), 0f)); + ItemDrop drop = spawned.GetComponent(); + if (drop != null) + { + drop.m_itemData.m_stack = m_yield; + ItemDrop.OnCreateNew(drop); + } + } + + // ---------------------------------------------------------------- state and display + + public State GetState() + { + if (GetFlesh() < m_capacity) return State.Filling; + return SecondsSealed() >= m_compostSeconds ? State.Ready : State.Composting; + } + + private void UpdateComposter() + { + if (m_nview == null || !m_nview.IsValid()) return; + + State state = GetState(); + if (m_topObject != null) m_topObject.SetActive(state == State.Filling); + if (m_fermentingObject != null) m_fermentingObject.SetActive(state == State.Composting); + if (m_readyObject != null) m_readyObject.SetActive(state == State.Ready); + } + + private int MinutesLeft() + { + double left = m_compostSeconds - SecondsSealed(); + return Mathf.Max(1, Mathf.CeilToInt((float)left / 60f)); + } + + private string Hover() + { + string body; + switch (GetState()) + { + case State.Ready: + body = $"ready: {m_yield} {TrentaConfig.FertilizerDisplayName}\n" + + "[$KEY_Use] Empty it"; + break; + + case State.Composting: + body = $"rotting, {MinutesLeft()} minutes left"; + break; + + default: + body = $"flesh {Mathf.Floor(GetFlesh())}/{m_capacity}\n" + + "[$KEY_Use] Feed it raw flesh"; + break; + } + + return Localization.instance.Localize($"{TrentaConfig.ComposterDisplayName} ({body})"); + } + + // ---------------------------------------------------------------- ZDO accessors + + /// + /// Seconds since the barrel sealed itself, on ZNet's world clock rather than on frames - so + /// it keeps counting while the zone is unloaded and across a restart. 0 while still filling. + /// + private double SecondsSealed() + { + if (m_nview == null || !m_nview.IsValid() || ZNet.instance == null) return 0.0; + + long ticks = m_nview.GetZDO().GetLong(KeySealed, 0L); + if (ticks == 0L) return 0.0; + + return (ZNet.instance.GetTime() - new DateTime(ticks)).TotalSeconds; + } + + private float GetFlesh() => m_nview != null && m_nview.IsValid() ? m_nview.GetZDO().GetFloat(KeyFlesh) : 0f; + + private void SetFlesh(float value) + { + if (m_nview != null && m_nview.IsValid()) m_nview.GetZDO().Set(KeyFlesh, Mathf.Max(0f, value)); + } + } +} diff --git a/JotunnModStub/Trenta/GroveBehaviour.cs b/JotunnModStub/Trenta/GroveBehaviour.cs new file mode 100644 index 0000000..39388e4 --- /dev/null +++ b/JotunnModStub/Trenta/GroveBehaviour.cs @@ -0,0 +1,373 @@ +using System; +using Jotunn.Managers; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// The Heartwood Grove's logic: three independent jobs on one timer. + /// + /// GROWING UP one timestamp on ZNet's world clock, exactly like the Composter's seal time, so + /// a planted grove keeps ageing with the zone unloaded and the game shut. The only + /// visible effect is which of the two models is showing. + /// FERTILISING once grown, one plant per minute inside the radius, one Fertilizer each, drawn + /// from a tank the player fills through the Switch on the trunk. Deliberately one + /// plant per tick and not the whole radius: a full tank is then twenty minutes of + /// autonomy instead of one tick's worth. + /// HONEY accrues into the Container on the root at the vanilla Beehive's own rate, read + /// off that prefab rather than invented. + /// + /// A tank that is empty stops the fertilising and nothing else. The bees do not care, and neither + /// does the honey - they are three jobs, not three stages. + /// + /// Everything that changes state runs on the ZNetView owner only, which is also why the swarm is + /// spawned there: bees on every client would mean every client's copy landing its own sting. + /// + public class GroveBehaviour : MonoBehaviour + { + public Switch m_switch; + public Container m_container; + public GameObject m_youngModel; + public GameObject m_grownModel; + + private const string KeyPlanted = "RoV_grovePlanted"; + private const string KeyFertilizer = "RoV_groveFert"; + private const string KeyHoneyTime = "RoV_groveHoneyTime"; + + // Container.Save is private, so it is reached the same way AswidBloodPotions reaches + // Fermenter.GetContent. Honey added by us has to be written to the ZDO explicitly: a player + // dropping items in goes through the inventory's own change callback, and nothing guarantees + // that callback covers a write made from outside the container's own UI. + private static readonly System.Reflection.MethodInfo ContainerSaveMethod = + HarmonyLib.AccessTools.Method(typeof(Container), "Save"); + + private ZNetView m_nview; + private GameObject m_bees; + + // Read off the vanilla Beehive at Awake, so the grove uses the game's own honey rate. Only + // the capacity is scaled - a tree of bees has to last while the player is away. + private float m_secPerHoney = 1200f; + private int m_honeyCapacity = 20; + private GameObject m_honeyPrefab; + + // The fertilise tick is local time, not world time, and that is correct rather than lazy: an + // unloaded grove cannot grow plants in a zone that is not there, so banking the time it spent + // unloaded would hand back growth that never could have happened. Honey banks; growth does not. + private float m_fertilizeTimer; + + private void Awake() + { + m_nview = GetComponent(); + if (m_nview == null || m_nview.GetZDO() == null) return; + + if (m_switch != null) + { + m_switch.m_onUse = OnUse; + m_switch.m_onHover = Hover; + } + + m_nview.Register("RoV_GroveFeed", RPC_Feed); + + ReadHoneyRates(); + + if (m_nview.IsOwner()) + { + // Stamped once, on the first client to own it, which is the moment it was planted. + if (m_nview.GetZDO().GetLong(KeyPlanted, 0L) == 0L) + { + m_nview.GetZDO().Set(KeyPlanted, ZNet.instance.GetTime().Ticks); + } + if (m_nview.GetZDO().GetLong(KeyHoneyTime, 0L) == 0L) + { + m_nview.GetZDO().Set(KeyHoneyTime, ZNet.instance.GetTime().Ticks); + } + } + + InvokeRepeating("UpdateGrove", 1f, 1f); + } + + private void OnDestroy() + { + if (m_bees != null) Destroy(m_bees); + } + + /// + /// Borrows m_secPerUnit, m_maxHoney and the honey item off the vanilla Beehive. The rate is + /// not a design decision this mod gets to make - a hive's is already tuned - so only the + /// capacity is multiplied. + /// + private void ReadHoneyRates() + { + Beehive hive = TrentaConfig.FindVanillaBeehive(); + + if (hive != null) + { + if (hive.m_secPerUnit > 0f) m_secPerHoney = hive.m_secPerUnit; + if (hive.m_maxHoney > 0) m_honeyCapacity = hive.m_maxHoney * TrentaConfig.GroveHoneyCapacityFactor; + if (hive.m_honeyItem != null) m_honeyPrefab = hive.m_honeyItem.gameObject; + } + else + { + Jotunn.Logger.LogWarning("[Trenta] Heartwood Grove: no vanilla beehive; falling back to default honey rates."); + } + + if (m_honeyPrefab == null && ObjectDB.instance != null) + { + m_honeyPrefab = ObjectDB.instance.GetItemPrefab("Honey"); + } + + // Without this the honey half fails silently, which is exactly how the night-gate bug + // managed to hide: nothing appeared and nothing said why. The log line also settles a + // question the design doc left open - whether the tuned Beehive component lives on + // "Beehive" or on "piece_beehive" - by printing what was actually read. + if (m_honeyPrefab == null) + { + Jotunn.Logger.LogWarning("[Trenta] Heartwood Grove: no honey prefab found; this grove will never produce honey."); + return; + } + + Jotunn.Logger.LogInfo($"[Trenta] Heartwood Grove: honey every {m_secPerHoney:0}s, capacity {m_honeyCapacity} " + + $"(rates {(hive != null ? "read from the vanilla beehive" : "defaulted")})."); + } + + // ---------------------------------------------------------------- the loop + + private void UpdateGrove() + { + if (m_nview == null || !m_nview.IsValid()) return; + + bool grown = IsGrown(); + if (m_youngModel != null) m_youngModel.SetActive(!grown); + if (m_grownModel != null) m_grownModel.SetActive(grown); + + if (!m_nview.IsOwner()) return; + + if (!grown) return; + + EnsureBees(); + TickHoney(); + + m_fertilizeTimer += 1f; + if (m_fertilizeTimer >= TrentaConfig.GroveFertilizeInterval) + { + m_fertilizeTimer = 0f; + TickFertilize(); + } + } + + private void EnsureBees() + { + if (m_bees != null) return; + m_bees = TrentaHornetSwarm.SpawnAtAnchor(transform, TrentaConfig.GroveStingRadius); + } + + /// + /// Grows exactly one thing per tick, through the very same method a player's Fertilizer click + /// goes through. That sharing is the point: two tiers growing plants by two slightly + /// different sets of rules is the failure this is written to prevent. + /// + private void TickFertilize() + { + if (GetFertilizer() <= 0) return; + + foreach (Collider collider in Physics.OverlapSphere(transform.position, TrentaConfig.GroveRadius)) + { + if (collider == null) continue; + + if (TrentaComposter.TryGrow(collider.gameObject) != TrentaComposter.GrowOutcome.Grown) continue; + + SetFertilizer(GetFertilizer() - 1); + return; // One per tick, by design + } + } + + private void TickHoney() + { + if (m_honeyPrefab == null || m_container == null) return; + + long stamp = m_nview.GetZDO().GetLong(KeyHoneyTime, 0L); + if (stamp == 0L) return; + + DateTime now = ZNet.instance.GetTime(); + + // No night gate. There used to be one, and it was what stopped the honey ever appearing - + // see the long note in TrentaConfig where GroveHoneyAtNight used to live. + double elapsed = (now - new DateTime(stamp)).TotalSeconds; + if (elapsed < m_secPerHoney) return; + + Inventory inventory = m_container.GetInventory(); + if (inventory == null) return; + + int produced = 0; + bool blocked = false; + while (elapsed >= m_secPerHoney) + { + if (CountHoney(inventory) >= m_honeyCapacity || !inventory.AddItem(m_honeyPrefab, 1)) + { + blocked = true; + break; + } + + elapsed -= m_secPerHoney; + produced++; + } + + if (blocked) + { + // Full chest: the clock is reset to now and the surplus is thrown away, so an + // untouched grove cannot bank an unbounded debt that dumps all at once the moment + // the player finally empties it. This is also what a vanilla hive does when it caps. + m_nview.GetZDO().Set(KeyHoneyTime, now.Ticks); + } + else + { + // Only the time actually spent on the honey produced is consumed. Resetting to now + // here instead would silently throw away the remainder on every single unit and + // leave the grove producing slower than the hive whose rate it borrowed. + m_nview.GetZDO().Set(KeyHoneyTime, now.AddSeconds(-elapsed).Ticks); + } + + if (produced > 0 && ContainerSaveMethod != null) ContainerSaveMethod.Invoke(m_container, null); + } + + private int CountHoney(Inventory inventory) + { + if (m_honeyPrefab == null) return 0; + + ItemDrop drop = m_honeyPrefab.GetComponent(); + string name = drop != null && drop.m_itemData != null && drop.m_itemData.m_shared != null + ? drop.m_itemData.m_shared.m_name + : null; + if (name == null) return 0; + + // Counted by hand rather than through Inventory.CountItems so no overload's quality and + // world-level arguments have to be guessed at. + int total = 0; + foreach (ItemDrop.ItemData item in inventory.GetAllItems()) + { + if (item != null && item.m_shared != null && item.m_shared.m_name == name) total += item.m_stack; + } + return total; + } + + // ---------------------------------------------------------------- interaction + + /// + /// E on the tree. Holding Fertilizer fills the tank; empty-handed it reports what the grove is + /// doing. Loading a tank before the tree has grown is allowed on purpose - there is no reason + /// to make the player come back twice. + /// + private bool OnUse(Switch caller, Humanoid user, ItemDrop.ItemData item) + { + if (user == null) return false; + + Inventory inventory = user.GetInventory(); + if (inventory == null) return false; + + if (item == null) item = FindFertilizer(inventory); + if (item == null) + { + user.Message(MessageHud.MessageType.Center, IsGrown() + ? "Nothing to feed it. It wants Fertilizer." + : $"Still growing. {MinutesLeft()} minutes."); + return false; + } + + if (!TrentaComposter.IsFertilizer(item)) + { + user.Message(MessageHud.MessageType.Center, "$msg_wontwork"); + return false; + } + + if (GetFertilizer() >= TrentaConfig.GroveFertilizerCapacity) + { + user.Message(MessageHud.MessageType.Center, "$msg_itsfull"); + return false; + } + + user.Message(MessageHud.MessageType.Center, "$msg_added " + item.m_shared.m_name); + inventory.RemoveItem(item, 1); + m_nview.InvokeRPC("RoV_GroveFeed"); + return true; + } + + private ItemDrop.ItemData FindFertilizer(Inventory inventory) + { + foreach (ItemDrop.ItemData candidate in inventory.GetAllItems()) + { + if (TrentaComposter.IsFertilizer(candidate)) return candidate; + } + return null; + } + + private void RPC_Feed(long sender) + { + if (!m_nview.IsOwner()) return; + + int stored = GetFertilizer(); + if (stored >= TrentaConfig.GroveFertilizerCapacity) return; + SetFertilizer(stored + 1); + } + + private string Hover() + { + if (!IsGrown()) + { + return Localization.instance.Localize( + $"{TrentaConfig.GroveDisplayName} (growing, {MinutesLeft()} minutes left)"); + } + + // The honey line is here because it was missing, and its absence is why a grove that + // was quietly producing nothing looked exactly like one that was working. + return Localization.instance.Localize( + $"{TrentaConfig.GroveDisplayName} ({TrentaConfig.FertilizerDisplayName} " + + $"{GetFertilizer()}/{TrentaConfig.GroveFertilizerCapacity}, honey {HoneyStatus()})\n" + + "[$KEY_Use] Feed it Fertilizer"); + } + + /// How much honey is in the crate and how long until the next drop of it. + private string HoneyStatus() + { + if (m_honeyPrefab == null) return "none (no honey item found)"; + + Inventory inventory = m_container != null ? m_container.GetInventory() : null; + int stored = inventory != null ? CountHoney(inventory) : 0; + + string status = $"{stored}/{m_honeyCapacity}"; + if (stored >= m_honeyCapacity) return status + ", full"; + + long stamp = m_nview.GetZDO().GetLong(KeyHoneyTime, 0L); + if (stamp == 0L || ZNet.instance == null) return status; + + double left = m_secPerHoney - (ZNet.instance.GetTime() - new DateTime(stamp)).TotalSeconds; + return status + $", next in {Mathf.Max(1, Mathf.CeilToInt((float)left / 60f))} min"; + } + + // ---------------------------------------------------------------- state + + public bool IsGrown() => SecondsSincePlanted() >= TrentaConfig.GroveGrowSeconds; + + private double SecondsSincePlanted() + { + if (m_nview == null || !m_nview.IsValid() || ZNet.instance == null) return 0.0; + + long ticks = m_nview.GetZDO().GetLong(KeyPlanted, 0L); + if (ticks == 0L) return 0.0; + + return (ZNet.instance.GetTime() - new DateTime(ticks)).TotalSeconds; + } + + private int MinutesLeft() + { + double left = TrentaConfig.GroveGrowSeconds - SecondsSincePlanted(); + return Mathf.Max(1, Mathf.CeilToInt((float)left / 60f)); + } + + private int GetFertilizer() => m_nview != null && m_nview.IsValid() ? m_nview.GetZDO().GetInt(KeyFertilizer) : 0; + + private void SetFertilizer(int value) + { + if (m_nview != null && m_nview.IsValid()) m_nview.GetZDO().Set(KeyFertilizer, Mathf.Max(0, value)); + } + } +} diff --git a/JotunnModStub/Trenta/TrentaComposter.cs b/JotunnModStub/Trenta/TrentaComposter.cs new file mode 100644 index 0000000..b245c2e --- /dev/null +++ b/JotunnModStub/Trenta/TrentaComposter.cs @@ -0,0 +1,488 @@ +using System.Collections.Generic; +using HarmonyLib; +using Jotunn.Configs; +using Jotunn.Entities; +using Jotunn.Managers; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// The Trenta station: a slightly smaller fermenter wearing the Draugr's flies and green gas, + /// which rots raw flesh into Fertilizer. A Fertilizer used on any plant grows it on the spot. + /// + /// Second half of the per-race "item progression" system the Aswid's Blood Refinery started, + /// and deliberately the same shape: an item bought from a faction merchant gates a buildable + /// station, and the station produces the race's own material. Design doc: Trenta_Composter.txt. + /// + /// Where it differs from the refinery is worth stating, because it drove the code: the refinery + /// produces FOOD for its race and runs continuously off two tanks, while this produces a TOOL + /// that acts on the world and runs in batches, because that is what a fermenter does. And the + /// vanilla is one item in, N items out, which is no more usable here + /// than 's ore queue was there - so the component is stripped after its + /// scene references are handed to , which is what keeps the + /// barrel's three visual states and its sounds identical to the vanilla one's. + /// + public static class TrentaComposter + { + /// What a single use of Fertilizer managed to do, so callers can pick the message. + public enum GrowOutcome + { + NoTarget, + NotGrowable, + AlreadyRipe, + Unhealthy, + Grown, + } + + /// + /// Every Pickable the Fertilizer is allowed to bring back, as a CLOSED list - the same + /// standard the Aswid's bone table is held to, and for a sharper reason here. + /// + /// The "wild plant" branch works by un-picking a Pickable, and Pickable is also what a tin + /// deposit, a flint pile, a tar pit, a meteorite and every crypt remains pile are. Deducing + /// "is this a plant?" from the component would hand the player a fertilizer that regenerates + /// ore, which is an exploit made entirely of code nobody wrote. Names verified against the + /// shipped asset manifest; entries the running game does not have are simply never matched. + /// + public static readonly HashSet GrowablePickables = new HashSet + { + // Cultivated crops, in their grown-and-harvestable form + "Pickable_Carrot", "Pickable_Turnip", "Pickable_Onion", + "Pickable_Barley", "Pickable_Flax", + "Pickable_SeedCarrot", "Pickable_SeedOnion", "Pickable_SeedTurnip", + + // Wild versions of the same + "Pickable_Barley_Wild", "Pickable_Flax_Wild", + + // Wild plants and mushrooms + "Pickable_Mushroom", "Pickable_Mushroom_yellow", "Pickable_Mushroom_blue", + "Pickable_Mushroom_Magecap", "Pickable_Mushroom_JotunPuffs", "Pickable_SmokePuff", + "Pickable_Thistle", "Pickable_Dandelion", "Pickable_Fiddlehead", + + // Berry bushes - not Pickable_-prefixed, the Pickable sits on the bush itself + "RaspberryBush", "BlueberryBush", "CloudberryBush", + + // Grown vines (the sapling stages are Plants and go through the other branch) + "VineGreen", "VineAsh", + }; + + public static void Register() + { + RegisterRotSeed(); + RegisterFertilizer(); + RegisterPiece(); + } + + /// True for the Fertilizer, by prefab first and display name only as a fallback. + public static bool IsFertilizer(ItemDrop.ItemData item) + { + if (item == null || item.m_shared == null) return false; + if (item.m_dropPrefab != null) return item.m_dropPrefab.name == TrentaConfig.FertilizerName; + return item.m_shared.m_name == TrentaConfig.FertilizerDisplayName; + } + + // ---------------------------------------------------------------- items + + private static void RegisterRotSeed() + { + GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(TrentaConfig.RotSeedName, "AncientSeed"); + if (prefab == null) + { + Jotunn.Logger.LogWarning("[Trenta] Could not clone AncientSeed; Rot Seed not registered."); + return; + } + + Recolour(prefab, TrentaConfig.RotSeedTint); + + ItemDrop drop = prefab.GetComponent(); + if (drop == null) return; + + ItemDrop.ItemData.SharedData shared = drop.m_itemData.m_shared; + shared.m_name = TrentaConfig.RotSeedDisplayName; + shared.m_description = "A seed that died before it could sprout, and did not stop. " + + "The forest folk sell them; only the forest knows what grows from one."; + shared.m_itemType = ItemDrop.ItemData.ItemType.Material; + shared.m_weight = 0.5f; + shared.m_maxStackSize = 20; + + ItemManager.Instance.AddItem(new CustomItem(prefab, fixReference: false)); + } + + private static void RegisterFertilizer() + { + GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(TrentaConfig.FertilizerName, "Entrails"); + if (prefab == null) + { + Jotunn.Logger.LogWarning("[Trenta] Could not clone Entrails; Fertilizer not registered."); + return; + } + + Recolour(prefab, TrentaConfig.FertilizerTint); + + ItemDrop drop = prefab.GetComponent(); + if (drop == null) return; + + ItemDrop.ItemData.SharedData shared = drop.m_itemData.m_shared; + shared.m_name = TrentaConfig.FertilizerDisplayName; + shared.m_description = "Everything that was meat, a month later. Press it into the soil and " + + "whatever is rooted there stops waiting."; + + // Consumable, not Material, and this is the only reason: a Material never reaches + // Humanoid.UseItem - vanilla refuses it before that - while a Consumable does, which is + // where TrentaFertilizerUsePatch takes it over. With every food value at zero it also + // stays invisible to the two prefixes that would otherwise fight over it: the vegan + // check in TrentaFoodPatches, and the "Mortal food disgusts you" block on + // Player.ConsumeItem in Skeleton/SkeletonPatches.cs. + shared.m_itemType = ItemDrop.ItemData.ItemType.Consumable; + shared.m_food = 0f; + shared.m_foodStamina = 0f; + shared.m_foodEitr = 0f; + shared.m_foodBurnTime = 0f; + shared.m_foodRegen = 0f; + shared.m_consumeStatusEffect = null; + + shared.m_weight = 0.5f; + shared.m_maxStackSize = 50; + + // The tint above only reaches the world and held models. Icons are atlas sprites and + // cannot be repainted - repainting one produced an empty inventory slot when the Aswid + // tried it - so a vanilla dark icon is borrowed instead. + Sprite icon = BorrowIcon(TrentaConfig.FertilizerIconSource); + if (icon != null) shared.m_icons = new[] { icon }; + + ItemManager.Instance.AddItem(new CustomItem(prefab, fixReference: false)); + } + + // ---------------------------------------------------------------- piece + + private static void RegisterPiece() + { + // "fermenter", not "piece_fermenter" - the same name AswidBloodPotions already reads. + GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(TrentaConfig.ComposterPieceName, "fermenter"); + if (prefab == null) + { + Jotunn.Logger.LogWarning("[Trenta] Could not clone fermenter; Composter not registered."); + return; + } + + Fermenter fermenter = prefab.GetComponentInChildren(true); + if (fermenter == null) + { + Jotunn.Logger.LogWarning("[Trenta] fermenter clone has no Fermenter; Composter not registered."); + return; + } + + ComposterBehaviour composter = fermenter.gameObject.AddComponent(); + composter.m_topObject = fermenter.m_topObject; + composter.m_fermentingObject = fermenter.m_fermentingObject; + composter.m_readyObject = fermenter.m_readyObject; + composter.m_outputPoint = fermenter.m_outputPoint; + composter.m_addedEffects = fermenter.m_addedEffects; + composter.m_tapEffects = fermenter.m_tapEffects; + composter.m_spawnEffects = fermenter.m_spawnEffects; + composter.m_capacity = TrentaConfig.ComposterCapacity; + composter.m_compostSeconds = TrentaConfig.ComposterCompostSeconds; + composter.m_yield = TrentaConfig.ComposterYield; + + // The vanilla barrel is its own Hoverable and Interactable: one interaction point on the + // root, unlike the eitr refinery, whose two assigned Switches the Blood Refinery could + // simply inherit. So the interaction is rebuilt with a Switch of our own on the same + // object, which is a component this repo already drives (see BloodRefineryBehaviour) and + // costs no interface implementation. Any Switch the prefab happened to carry is dropped + // first so it cannot win the hover from a child collider - the components only, never + // their colliders, which the barrel still needs. + foreach (Switch existing in prefab.GetComponentsInChildren(true)) + { + if (existing != null) Object.DestroyImmediate(existing); + } + + Object.DestroyImmediate(fermenter); + + composter.m_switch = composter.gameObject.AddComponent(); + composter.m_switch.m_name = TrentaConfig.ComposterDisplayName; + + // A barrel carries nothing that shoots, unlike the eitr refinery and its two Radiators. + // Called anyway as a belt: it logs whatever it finds, and a silent log is the proof. + AswidBloodRefinery.StripOffensive(prefab, TrentaConfig.ComposterPieceName); + + prefab.transform.localScale = Vector3.one * TrentaConfig.ComposterScale; + BuildRotVfx(prefab.transform); + + Piece piece = prefab.GetComponent(); + if (piece != null) + { + // Same call as RaceMenuWard and the Blood Refinery: a piece with a crafting station + // set vanishes from the hammer whenever that station is out of range, and this one + // has to stay findable. + piece.m_craftingStation = null; + piece.m_resources = new Piece.Requirement[0]; + piece.m_name = TrentaConfig.ComposterDisplayName; + } + + PieceConfig config = new PieceConfig + { + Name = TrentaConfig.ComposterDisplayName, + Description = "What rots is not lost. It feeds.", + PieceTable = PieceTables.Hammer, + Category = PieceCategories.Crafting, + Requirements = new[] + { + new RequirementConfig(TrentaConfig.RotSeedName, 1, 0, true), + new RequirementConfig("Wood", 20, 0, true), + new RequirementConfig("Resin", 10, 0, true), + new RequirementConfig("Bronze", 5, 0, true), + } + }; + + PieceManager.Instance.AddPiece(new CustomPiece(prefab, fixReference: false, config)); + } + + /// + /// Hangs the Draugr's flies and green gas over the lid. + /// + /// The same particles, off the same prefab, with the same loop filter DraughVisuals.BuildAura + /// uses - looping is what separates a creature's ambient rot from its one-shot hit and death + /// effects. Copied rather than shared: DraughVisuals takes a Player, is driven by both + /// DraughRace and ZdoVisualSync, and generalising it to oblige a compost barrel would put a + /// working multiplayer aura at risk to save twenty lines. + /// + /// The holder is parented to the ROOT, never to the three state objects, which + /// ComposterBehaviour switches on and off - the VFX would blink out with them. + /// + private static void BuildRotVfx(Transform root) + { + GameObject source = PrefabManager.Cache.GetPrefab(TrentaConfig.ComposterVfxSourcePrefab); + if (source == null) + { + Jotunn.Logger.LogWarning($"[Trenta] Composter: could not find VFX source prefab '{TrentaConfig.ComposterVfxSourcePrefab}'."); + return; + } + + GameObject holder = new GameObject("ComposterVFX"); + holder.transform.SetParent(root, false); + holder.transform.localPosition = TrentaConfig.ComposterVfxLocalPosition; + + foreach (ParticleSystem particles in source.GetComponentsInChildren(true)) + { + if (particles == null || !particles.main.loop) continue; + + string name = particles.gameObject.name.ToLowerInvariant(); + + // Dripping water reads as rain coming off the barrel. DraughVisuals rejects the + // same three for the same reason. + if (name.Contains("drip") || name.Contains("drop") || name.Contains("rain") || name.Contains("splash")) continue; + + GameObject copy = Object.Instantiate(particles.gameObject, holder.transform); + copy.name = particles.gameObject.name; + copy.SetActive(true); + copy.transform.localPosition = Vector3.zero; + copy.transform.localRotation = particles.transform.localRotation; + } + } + + /// + /// A piece only reaches the hammer once it is in the player's known recipes, and the vanilla + /// learning pass misses pieces injected after the fact - the trap RaceMenuWard and the Blood + /// Refinery both fell into. The Rot Seed requirement is the real gate; this only makes the + /// entry visible, greyed out until one is owned. + /// + public static void EnsureKnown(Player player) + { + if (player == null) return; + + GameObject prefab = PrefabManager.Instance.GetPrefab(TrentaConfig.ComposterPieceName); + Piece piece = prefab != null ? prefab.GetComponent() : null; + if (piece == null) return; + + Traverse traverse = Traverse.Create(player); + traverse.Method("AddKnownPiece", piece).GetValue(); + traverse.Method("UpdateAvailablePiecesList").GetValue(); + } + + // ---------------------------------------------------------------- growing things + + /// + /// Grows one thing, now. The single place that knows how, called both by a player clicking a + /// Fertilizer and by a Heartwood Grove's own tick - the two tiers must not grow plants by + /// two slightly different rules, which is exactly what would happen if this were written + /// twice. + /// + /// Three families, and the order matters: a planted carrot is a Plant (sapling_carrot) and + /// only becomes a Pickable (Pickable_Carrot) once grown, so asking Pickable first would try + /// to "un-pick" a seedling, do nothing visible, and eat the item. + /// + public static GrowOutcome TryGrow(GameObject candidate) + { + if (candidate == null) return GrowOutcome.NoTarget; + + // a. Cultivated crops and tree saplings. Plant.Grow is the very method Plant.SUpdate + // calls once the natural timer runs out, so calling it by hand means literally "the + // time has passed" - no state is faked and nothing is short-circuited. + Plant plant = candidate.GetComponentInParent(); + if (plant != null) + { + // Growing regardless of conditions would beat sun, space, biome and cultivated + // ground all at once and make half of vanilla farming pointless. GetStatus is + // public, so this costs one comparison. + if (plant.GetStatus() != Plant.Status.Healthy) return GrowOutcome.Unhealthy; + + ZNetView nview = plant.GetComponent(); + if (nview == null || !nview.IsValid()) return GrowOutcome.NotGrowable; + + // Grow() instantiates the grown prefab and destroys this one through ZNetScene: + // both are the owner's work. + nview.ClaimOwnership(); + plant.Grow(); + return GrowOutcome.Grown; + } + + // b. Wild plants that are already grown. A berry bush does not grow, it ripens: for + // those, "grow instantly" means "be ripe again now". + Pickable pickable = candidate.GetComponentInParent(); + if (pickable != null) + { + if (!IsGrowablePickable(pickable)) return GrowOutcome.NotGrowable; + if (!pickable.GetPicked()) return GrowOutcome.AlreadyRipe; + + ZNetView nview = pickable.GetComponent(); + if (nview == null || !nview.IsValid()) return GrowOutcome.NotGrowable; + + nview.ClaimOwnership(); + pickable.SetPicked(false); + return GrowOutcome.Grown; + } + + // c. Everything else, a full-grown tree included: TreeBase.Grow is the growth animation + // a fresh trunk plays for itself, not a stage to advance. + return GrowOutcome.NotGrowable; + } + + private static bool IsGrowablePickable(Pickable pickable) + { + if (GrowablePickables.Contains(Utils.GetPrefabName(pickable.gameObject))) return true; + + // Safety net for modded plants the closed list above cannot know about: allow one if + // what it produces is something the Trenta itself calls food. Deliberately NOT a plain + // "does it drop something edible" test - that would let a meat pile through. + ItemDrop drop = pickable.m_itemPrefab != null ? pickable.m_itemPrefab.GetComponent() : null; + if (drop == null) return false; + + return TrentaConfig.VeganFoodPrefabNames.Contains(Utils.GetPrefabName(pickable.m_itemPrefab)); + } + + /// + /// A Fertilizer used from the hotbar. The plant is whatever the player is looking at: + /// Player.GetHoverObject already enforces the vanilla interact distance on its own, so + /// there is no raycast and no radius here. + /// + /// One unit per plant grown, and only when something actually grew - every refusal leaves + /// the inventory alone. + /// + public static void UseFertilizer(Player player, Inventory inventory, ItemDrop.ItemData item) + { + if (player == null || item == null) return; + if (inventory == null) inventory = player.GetInventory(); + + GrowOutcome outcome = TryGrow(player.GetHoverObject()); + switch (outcome) + { + case GrowOutcome.Grown: + if (inventory != null) inventory.RemoveItem(item, 1); + player.Message(MessageHud.MessageType.Center, "It grows."); + break; + + case GrowOutcome.AlreadyRipe: + player.Message(MessageHud.MessageType.Center, "It is ripe already."); + break; + + case GrowOutcome.Unhealthy: + player.Message(MessageHud.MessageType.Center, "This one is not well. Nothing will hurry it."); + break; + + case GrowOutcome.NoTarget: + player.Message(MessageHud.MessageType.Center, "Nothing there to feed."); + break; + + default: + player.Message(MessageHud.MessageType.Center, "$msg_wontwork"); + break; + } + } + + // ---------------------------------------------------------------- prefab surgery + + /// + /// Darkens every material on the clone. renderer.materials instantiates a copy, so the real + /// Entrails and the real Ancient seed keep their own look - which is the whole reason this + /// is the technique the Aswid settled on too. + /// + private static void Recolour(GameObject root, Color tint) + { + foreach (Renderer renderer in root.GetComponentsInChildren(true)) + { + if (renderer == null) continue; + if (renderer is ParticleSystemRenderer) continue; + + foreach (Material material in renderer.materials) + { + if (material == null) continue; + material.color = tint; + if (material.HasProperty("_Color")) material.SetColor("_Color", tint); + if (material.HasProperty("_EmissionColor")) material.SetColor("_EmissionColor", Color.black); + } + } + } + + 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; + if (icons != null && icons.Length > 0 && icons[0] != null) return icons[0]; + + Jotunn.Logger.LogWarning($"[Trenta] Could not borrow the icon from '{prefabName}'."); + return null; + } + } + + /// + /// Teaches every piece this mod registers after the vanilla learning pass, exactly like + /// RaceMenuWard does - none of them reach their table on their own. It lives in the Trenta's file + /// for historical reasons and now also covers the Furling's cultivator entries; one OnSpawned + /// postfix teaching all of them beats three postfixes doing the same thing. + /// + [HarmonyPatch(typeof(Player), "OnSpawned")] + public static class TrentaComposterKnownPatch + { + public static void Postfix(Player __instance) + { + if (__instance != Player.m_localPlayer) return; + TrentaComposter.EnsureKnown(__instance); + TrentaHeartwoodGrove.EnsureKnown(__instance); + FurlingCrops.EnsureKnown(__instance); + } + } + + /// + /// Turns using a Fertilizer into growing whatever the player is looking at. + /// + /// A prefix on the same method - and with the same signature - as + /// TrentaFoodPatches.Trenta_Humanoid_UseItem_Patch. The two never collide: that one returns + /// early for anything without food values, and the Fertilizer has none. + /// + [HarmonyPatch(typeof(Humanoid), "UseItem")] + public static class TrentaFertilizerUsePatch + { + public static bool Prefix(Humanoid __instance, Inventory inventory, ItemDrop.ItemData item) + { + Player player = __instance as Player; + if (player == null || player != Player.m_localPlayer) return true; + if (!TrentaComposter.IsFertilizer(item)) return true; + + TrentaComposter.UseFertilizer(player, inventory, item); + return false; // Never let vanilla try to eat it + } + } +} diff --git a/JotunnModStub/Trenta/TrentaConfig.cs b/JotunnModStub/Trenta/TrentaConfig.cs index 3db2fec..429c3d3 100644 --- a/JotunnModStub/Trenta/TrentaConfig.cs +++ b/JotunnModStub/Trenta/TrentaConfig.cs @@ -200,7 +200,6 @@ namespace RacesOfValheim // Source of the buzz: the ambient bee-swarm effect a placed Beehive plays, read for its // AudioClip only - never instantiated, so nothing about how it looks ever enters this // ability, matching "la sua unica componente visiva sarà le mosche" literally. - public const string HornetsNestBeehivePrefab = "Beehive"; // ─── Muspell (Fader) ───────────────────────────────────────────────── // A toggled transformation, the same shape as FenrirRace's own G/H/J forms: press J to @@ -387,7 +386,163 @@ namespace RacesOfValheim return lookup; } + // ─── Composter (item progression, tier 1) ──────────────────────────── + // The Trenta's half of the per-race station system the Aswid's Blood Refinery started. + // Full design in Trenta_Composter.txt; every number it settles on lives here. + // + // The chain: a Rot Seed bought from the Greydwarf faction bench gates the Composter, the + // Composter rots raw flesh into Fertilizer, and Fertilizer grows any plant on the spot. + public const string ComposterPieceName = "TrentaComposter"; + public const string ComposterDisplayName = "Composter"; + + public const string FertilizerName = "Fertilizer"; + public const string FertilizerDisplayName = "Fertilizer"; + + public const string RotSeedName = "RotSeed"; + public const string RotSeedDisplayName = "Rot Seed"; + + // Same band as the Aswid's Blood Core, which does the same job for the same reason. + public const int RotSeedPrice = 500; + + // "Slightly smaller than a fermenter" - the vanilla barrel is already human-sized, so this + // is a shave rather than the halving the (enormous) eitr refinery needed. + public const float ComposterScale = 0.85f; + + // One batch: 100 units of flesh in, 20 Fertilizer out after the compost time, so 5 units + // of flesh per Fertilizer. Flesh is valued by AswidBloodRefinery.FleshValue. + public const float ComposterCapacity = 100f; + public const float ComposterCompostSeconds = 2400f; // as a normal fermenter + public const int ComposterYield = 20; + + // Where the Draugr's flies and green gas hang over the lid. The scaled barrel is roughly a + // metre tall; this is an eyeball figure and is meant to be adjusted in game. + public static readonly Vector3 ComposterVfxLocalPosition = new Vector3(0f, 1f, 0f); + + // Same prefab TrentaHornetsNest and DraughVisuals already read their particles off. The + // Composter keeps the same subset DraughVisuals keeps - flies plus the green smoke - which + // is why the swarm on a Heartwood Grove and the haze over a Composter match by default. + public const string ComposterVfxSourcePrefab = "Draugr"; + + // Entrails, darkened to loam. Only the world/held model takes the tint - the inventory + // icon is an atlas sprite and cannot be repainted (proven the hard way on the Aswid's + // Blood Essence), so the icon is borrowed from Guck instead: green-black reads as + // "compost" without reading as "intestine". + public static readonly Color FertilizerTint = new Color(0.18f, 0.13f, 0.09f, 1f); + public const string FertilizerIconSource = "Guck"; + + public static readonly Color RotSeedTint = new Color(0.16f, 0.12f, 0.08f, 1f); + + // ─── Heartwood Grove (item progression, tier 2) ────────────────────── + // Plant a seed, wait, and the tree that comes up fertilises what surrounds it, stings what + // approaches it, and fills a chest with honey. Three independent functions on one piece. + public const string GroveSeedName = "HeartwoodSeed"; + public const string GroveSeedDisplayName = "Heartwood Seed"; + public const string GroveSaplingPieceName = "TrentaHeartwoodSapling"; + public const string GroveSaplingDisplayName = "Heartwood Sapling"; + public const string GrovePieceName = "TrentaHeartwoodGrove"; + public const string GroveDisplayName = "Heartwood Grove"; + + // A grove costs exactly one full Composter batch. That is the whole balance argument. + public const int GroveSeedFertilizerCost = ComposterYield; + + // World time, not session time: Plant.TimeSincePlanted reads ZNet's clock, so a sapling + // keeps growing with the zone unloaded and the game shut, same as the Composter's timer. + public const float GroveGrowSeconds = 7200f; + + // One radius for both halves on purpose - the grove defends exactly the ground it farms, + // and the player only has to learn one number. Matches PurpleRainRadius. + public const float GroveRadius = 8f; + + // One plant per tick, not the whole radius: 20 Fertilizer is then 20 minutes of autonomy. + // Growing everything at once would empty the trough in a single tick. + public const float GroveFertilizeInterval = 60f; + public const int GroveFertilizerCapacity = ComposterYield; + + // The honey rate is not invented: m_secPerUnit and m_maxHoney are read off the vanilla + // Beehive at registration. Only the capacity is scaled - a whole tree of bees has to last + // while the player is away, where a hive only has to last until they walk past it. + public const int GroveHoneyCapacityFactor = 5; + + // Honey accrues day and night, exactly as a vanilla hive's does. + // + // This used to be a GroveHoneyAtNight knob defaulting to false, on the reading that + // Beehive.m_effectOnlyInDaylight meant "bees only work in daylight". It does not: by its + // name and by the only method that touches it (Beehive.UpdateBees), it gates m_beeEffect - + // the buzz and the particles - not production. Vanilla hives make honey overnight. + // + // Getting that wrong did not merely slow the grove down, it starved it. The night was + // discarded by resetting the accrual stamp, which meant a whole m_secPerUnit had to fit + // inside one unbroken stretch of daylight - and m_secPerUnit is of the same order as a + // Valheim day is long (a full cycle is EnvMan.m_dayLengthSec, 1800s by default, of which + // roughly 1260s is not night). So honey was somewhere between rare and arithmetically + // impossible depending on the hive's real rate and what time it was when the tree matured. + // + // If the "bees sleep at night" flavour is ever wanted, it belongs where vanilla puts it: + // on the swarm's buzz, not on the honey. + + // Only the model is taken off this prefab, never its TreeBase or its log drop - the same + // discipline the VFX borrowing follows. A Yggdrasil shoot reads as "grown from a root of + // the world" rather than as any old beech, and matches YggdrasilWood being in the recipe. + public const string GroveModelPrefab = "YggaShoot_small1"; + public const float GroveModelScale = 1f; + + // Cloned for the sapling stage; must be a prefab that carries a Plant component. + public const string GroveSaplingSourcePrefab = "Beech_Sapling"; + + // The grove's swarm is the Hornet's Nest swarm with a different anchor - deliberately not + // a second copy of that code, so a change to the sting is a change to both. It therefore + // reads HornetsNestDamagePerTick / HornetsNestTickInterval and has no damage of its own. + // + // A grove is a piece, not a Character, so BaseAI.IsEnemy cannot be asked directly the way + // the player-anchored swarm asks it. The fallback rule lives in TrentaHornetSwarm. + public const float GroveStingRadius = GroveRadius; + + // Density cap, enforced by PieceDensityLimit. Without one, a field of groves is a carpet of + // bees that kills anything that comes near, and this was a known open point for two rounds. + // + // More permissive than the Draugh body pile's five, on the reading that a grove is a farm + // rather than an army and costs a Composter batch rather than a 500-coin bone. Unlike almost + // every other number in this file it has no vanilla equivalent to be read off, so it IS a + // guess - change it freely, it is one line and nothing else depends on it. + public const int GroveMaxInRange = 10; + public const float GroveDensityAreaKm2 = 1.6f; // the same frame the body pile uses + + // ─── The vanilla beehive ───────────────────────────────────────────── + // Two features read this prefab: the grove borrows its honey rate and capacity, and the + // Hornet's Nest borrows the AudioClip off its bee effect. + // + // Both used to look up "Beehive" and both silently got nothing - confirmed from the BepInEx + // log, which is the whole reason those lookups now warn instead of returning quietly. There is + // a Beehive.prefab in the asset manifest, but it is not what PrefabManager resolves under that + // name; the buildable hive is "piece_beehive", and that is the one carrying the tuned Beehive + // component. Both names are tried in order so a game update that moves it cannot silence this + // again without saying so. + public static readonly string[] BeehiveSourcePrefabs = { "piece_beehive", "Beehive" }; + // ─── Helpers ───────────────────────────────────────────────────────── + + /// + /// The vanilla Beehive component, or null. Shared by the grove and the Hornet's Nest so the + /// two cannot disagree about where it lives. + /// + public static Beehive FindVanillaBeehive() + { + foreach (string name in BeehiveSourcePrefabs) + { + GameObject prefab = Jotunn.Managers.PrefabManager.Cache.GetPrefab(name); + Beehive hive = prefab != null ? prefab.GetComponent() : null; + if (hive != null) + { + Jotunn.Logger.LogInfo($"[Trenta] Vanilla beehive resolved from '{name}'."); + return hive; + } + } + + Jotunn.Logger.LogWarning("[Trenta] No vanilla beehive found under any of: " + + string.Join(", ", BeehiveSourcePrefabs)); + return null; + } + /// Clamped table lookup, so a state outside 1..8 can never index out of range. public static float Lookup(float[] table, int state) { diff --git a/JotunnModStub/Trenta/TrentaHeartwoodGrove.cs b/JotunnModStub/Trenta/TrentaHeartwoodGrove.cs new file mode 100644 index 0000000..aeb43c1 --- /dev/null +++ b/JotunnModStub/Trenta/TrentaHeartwoodGrove.cs @@ -0,0 +1,237 @@ +using HarmonyLib; +using Jotunn.Configs; +using Jotunn.Entities; +using Jotunn.Managers; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// Tier 2 of the Trenta's item chain: plant it, wait, and the tree that comes up fertilises what + /// surrounds it, stings what approaches it, and fills a chest with honey. Three functions that do + /// not depend on each other, on one piece. Design doc: Trenta_Composter.txt section 11. + /// + /// ONE piece, not two. The doc called for a sapling carrying a vanilla Plant whose m_grownPrefabs + /// pointed at a separate grown prefab; this grows in place instead - same crate, same ZNetView, + /// with the young model swapped for the grown one when the clock runs out. Three risks went away + /// with that decision and nothing was lost: + /// - no second prefab to register outside a piece table, and no question about whether Jotunn + /// has put it in ZNetScene by the time a Plant tries to instantiate it; + /// - no dependency on Beech_Sapling actually carrying a Plant, which was the one link in the + /// tier-1 design nobody had opened yet; + /// - the honey chest and the Fertilizer trough survive the transition, because there is no + /// transition - nothing is destroyed and re-spawned, so nothing has to be carried over. + /// The growth timer is the same shape as the Composter's: one timestamp on ZNet's world clock, so + /// it advances with the zone unloaded and across a restart. + /// + /// The layout is forced by a single fact worth stating plainly: there is one ZNetView per + /// instantiated prefab, and Container keeps its inventory in the ZDO. So there can be exactly one + /// real chest, and it is the honey one. The Fertilizer goes in through a Switch on the plant + /// itself - E on the crate opens the honey, E on the tree feeds it - which is the same division + /// of labour the vanilla fermenter uses between its root component and its child switches. + /// + public static class TrentaHeartwoodGrove + { + public static void Register() + { + RegisterSeed(); + RegisterPiece(); + + PieceDensityLimit.Register(TrentaConfig.GrovePieceName, + PieceDensityLimit.RadiusForArea(TrentaConfig.GroveDensityAreaKm2), TrentaConfig.GroveMaxInRange, + "This country already answers to {0} of these. Plant it somewhere else."); + } + + // ---------------------------------------------------------------- the seed + + private static void RegisterSeed() + { + GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(TrentaConfig.GroveSeedName, "AncientSeed"); + if (prefab == null) + { + Jotunn.Logger.LogWarning("[Trenta] Could not clone AncientSeed; Heartwood Seed not registered."); + return; + } + + ItemDrop drop = prefab.GetComponent(); + if (drop == null) return; + + ItemDrop.ItemData.SharedData shared = drop.m_itemData.m_shared; + shared.m_name = TrentaConfig.GroveSeedDisplayName; + shared.m_description = "A seed fed on a whole barrel of rot. Plant it and go away for a while."; + shared.m_itemType = ItemDrop.ItemData.ItemType.Material; + shared.m_weight = 1f; + shared.m_maxStackSize = 10; + + ItemManager.Instance.AddItem(new CustomItem(prefab, fixReference: false)); + + // One grove costs exactly one full Composter batch - 100 units of flesh and forty + // minutes. That is the whole balance argument, and it is why the cost is expressed in + // Fertilizer rather than in some second currency. + ItemManager.Instance.AddRecipe(new CustomRecipe(new RecipeConfig + { + Item = TrentaConfig.GroveSeedName, + Amount = 1, + CraftingStation = "piece_preptable", + Requirements = new[] + { + new RequirementConfig(TrentaConfig.FertilizerName, TrentaConfig.GroveSeedFertilizerCost), + new RequirementConfig(TrentaConfig.RotSeedName, 1), + new RequirementConfig("YggdrasilWood", 10), + } + })); + } + + // ---------------------------------------------------------------- the piece + + private static void RegisterPiece() + { + // A wooden chest is the base because it arrives with everything a honey store needs + // already wired: ZNetView, Piece, WearNTear, colliders, and a Container whose lid + // objects and effect lists are assigned. Building one from scratch would mean assigning + // all of that by hand and finding out in game which field Container.Awake dereferences + // without checking. + GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(TrentaConfig.GrovePieceName, "piece_chest_wood"); + if (prefab == null) + { + Jotunn.Logger.LogWarning("[Trenta] Could not clone piece_chest_wood; Heartwood Grove not registered."); + return; + } + + Container container = prefab.GetComponent(); + if (container == null) + { + Jotunn.Logger.LogWarning("[Trenta] piece_chest_wood clone has no Container; Heartwood Grove not registered."); + return; + } + + container.m_name = TrentaConfig.GroveDisplayName; + + GroveBehaviour grove = prefab.AddComponent(); + grove.m_container = container; + grove.m_youngModel = BuildModel(prefab.transform, "GroveYoung", TrentaConfig.GroveSaplingSourcePrefab, TrentaConfig.GroveModelScale); + grove.m_grownModel = BuildModel(prefab.transform, "GroveGrown", TrentaConfig.GroveModelPrefab, TrentaConfig.GroveModelScale); + + // The plant is the second interaction point. It carries its own collider so the hover + // raycast resolves to the Switch on it rather than walking up to the Container on the + // root - which is how the crate keeps meaning "open the honey" while the tree means + // "feed me". Sized generously: it has to be clickable at both growth stages. + grove.m_switch = BuildTroughSwitch(grove.m_grownModel, grove.m_youngModel); + + Piece piece = prefab.GetComponent(); + if (piece != null) + { + piece.m_craftingStation = null; + piece.m_resources = new Piece.Requirement[0]; + piece.m_name = TrentaConfig.GroveDisplayName; + } + + PieceConfig config = new PieceConfig + { + Name = TrentaConfig.GroveDisplayName, + Description = "A crate of rot with something growing out of it. Give it time.", + PieceTable = PieceTables.Hammer, + Category = PieceCategories.Misc, + Requirements = new[] + { + new RequirementConfig(TrentaConfig.GroveSeedName, 1, 0, true), + } + }; + + PieceManager.Instance.AddPiece(new CustomPiece(prefab, fixReference: false, config)); + } + + /// + /// Borrows the visible half of a world prefab and nothing else. + /// + /// The same discipline the VFX borrowing follows, and here it matters more: the Yggdrasil + /// shoot is a TreeBase, so taken whole it would bring a choppable trunk, a log drop and a + /// tree collider along with the mesh - a grove that can be felled for wood instead of being + /// destroyed as a piece. Only Renderers and their transforms survive; every component that + /// is not a Renderer, and every collider, is stripped. + /// + private static GameObject BuildModel(Transform root, string name, string sourcePrefabName, float scale) + { + GameObject holder = new GameObject(name); + holder.transform.SetParent(root, false); + holder.transform.localPosition = Vector3.zero; + + GameObject source = PrefabManager.Cache.GetPrefab(sourcePrefabName); + if (source == null) + { + Jotunn.Logger.LogWarning($"[Trenta] Heartwood Grove: could not find model prefab '{sourcePrefabName}'."); + return holder; + } + + GameObject copy = Object.Instantiate(source, holder.transform); + copy.name = "model"; + copy.transform.localPosition = Vector3.zero; + copy.transform.localScale = Vector3.one * scale; + + foreach (MonoBehaviour behaviour in copy.GetComponentsInChildren(true)) + { + if (behaviour != null) Object.DestroyImmediate(behaviour); + } + foreach (Collider collider in copy.GetComponentsInChildren(true)) + { + if (collider != null) Object.DestroyImmediate(collider); + } + foreach (ZNetView nview in copy.GetComponentsInChildren(true)) + { + if (nview != null) Object.DestroyImmediate(nview); + } + + return holder; + } + + /// + /// The Fertilizer input: a Switch with a collider of its own, hung off the grown model but + /// parented so it stays live at both stages (the models get toggled, this does not). + /// + private static Switch BuildTroughSwitch(GameObject grownModel, GameObject youngModel) + { + // Parented to the models' shared parent - the piece root - precisely so GroveBehaviour + // can switch the two models on and off without taking the interaction point with them. + Transform parent = grownModel != null ? grownModel.transform.parent : youngModel.transform.parent; + + GameObject holder = new GameObject("GroveTrough"); + holder.transform.SetParent(parent, false); + holder.transform.localPosition = new Vector3(0f, 1.2f, 0f); + + // Two decisions here that both come down to "will the hover raycast find this at all", + // which is the one thing about this piece that cannot be settled by reading code: + // - the layer is copied from the piece root rather than left on Default, because + // Player.FindHoverObject raycasts against a mask and a brand new GameObject starts + // on whatever layer 0 happens to be; + // - it is NOT a trigger. Physics.queriesHitTriggers is a global whose value here is + // not ours, so a trigger collider might simply be invisible to that raycast. Solid + // also happens to be right: it is a tree trunk, and walking through it would be odd. + holder.layer = parent.gameObject.layer; + + BoxCollider collider = holder.AddComponent(); + collider.size = new Vector3(1.2f, 2.4f, 1.2f); + collider.isTrigger = false; + + Switch trough = holder.AddComponent(); + trough.m_name = TrentaConfig.GroveDisplayName; + return trough; + } + + /// + /// Same reason as the Composter's: a piece registered after the vanilla learning pass never + /// reaches the hammer on its own. The Heartwood Seed requirement is the real gate. + /// + public static void EnsureKnown(Player player) + { + if (player == null) return; + + GameObject prefab = PrefabManager.Instance.GetPrefab(TrentaConfig.GrovePieceName); + Piece piece = prefab != null ? prefab.GetComponent() : null; + if (piece == null) return; + + Traverse traverse = Traverse.Create(player); + traverse.Method("AddKnownPiece", piece).GetValue(); + traverse.Method("UpdateAvailablePiecesList").GetValue(); + } + } +} diff --git a/JotunnModStub/Trenta/TrentaHornetsNest.cs b/JotunnModStub/Trenta/TrentaHornetsNest.cs index ced6a53..dff625a 100644 --- a/JotunnModStub/Trenta/TrentaHornetsNest.cs +++ b/JotunnModStub/Trenta/TrentaHornetsNest.cs @@ -7,13 +7,22 @@ namespace RacesOfValheim /// /// The swarm itself. Not a Character - it has no health, no hitbox anything else can target, /// so "indistruttibile" falls out of what it simply isn't rather than needing invulnerability - /// code of its own. Idles in a slow orbit around the Trenta; the instant an enemy comes within - /// range it breaks off, hovers over that enemy instead, and sting-ticks it on a timer until it - /// dies or leaves range, then returns to orbiting. + /// code of its own. Idles in a slow orbit around whatever it is tied to; the instant an enemy + /// comes within range it breaks off, hovers over that enemy instead, and sting-ticks it on a + /// timer until it dies or leaves range, then returns to orbiting. + /// + /// Two things it can be tied to, and the difference is only in what counts as an enemy: + /// - a Trenta player (the Hornet's Nest perk), which can be asked BaseAI.IsEnemy directly; + /// - a Heartwood Grove's trunk (the tier-2 station), which cannot, because a piece is not a + /// Character. See IsHostile. + /// Deliberately one class rather than two copies: the sting is combat logic, and a second copy + /// means the next tweak to the venom gets made in one place and forgotten in the other. /// public class TrentaHornetSwarm : MonoBehaviour { - private Player owner; + private Player owner; // null for a grove swarm + private Transform anchor; // what it orbits; the owner's own transform for a player swarm + private float engageRadius; private Character target; private float tickTimer; private float orbitAngle; @@ -21,11 +30,38 @@ namespace RacesOfValheim public static GameObject Spawn(Player player) { - GameObject go = new GameObject("TrentaHornetsNest"); - go.transform.position = player.transform.position + Vector3.up; + GameObject go = Build("TrentaHornetsNest", player.transform.position + Vector3.up); + + TrentaHornetSwarm swarm = go.GetComponent(); + swarm.owner = player; + swarm.anchor = player.transform; + swarm.engageRadius = TrentaConfig.HornetsNestEngageRadius; + + return go; + } + + /// + /// The grove's swarm: same bees, tied to a fixed point instead of to a player. The radius is + /// its own number because 6 metres is tuned for something that walks - a tree that cannot + /// chase has to reach further, and it matches the ground the grove fertilises. + /// + public static GameObject SpawnAtAnchor(Transform anchorPoint, float radius) + { + GameObject go = Build("TrentaGroveBees", anchorPoint.position + Vector3.up); + + TrentaHornetSwarm swarm = go.GetComponent(); + swarm.anchor = anchorPoint; + swarm.engageRadius = radius; + + return go; + } + + private static GameObject Build(string name, Vector3 position) + { + GameObject go = new GameObject(name); + go.transform.position = position; TrentaHornetSwarm swarm = go.AddComponent(); - swarm.owner = player; BuildFliesVfx(go.transform); swarm.buzz = BuildBuzzAudio(go.transform); @@ -33,15 +69,20 @@ namespace RacesOfValheim return go; } + private Vector3 AnchorPosition => anchor != null ? anchor.position : transform.position; + private void Update() { - if (owner == null || owner.IsDead()) + // A player swarm dies with its player; a grove swarm dies with its tree. Either way the + // check is "is there still something to orbit", which is also what makes the swarm clean + // itself up when the grove is destroyed without the grove having to say so. + if (anchor == null || (owner != null && owner.IsDead())) { Destroy(gameObject); return; } - if (target != null && (target.IsDead() || Vector3.Distance(target.transform.position, owner.transform.position) > TrentaConfig.HornetsNestEngageRadius * 1.5f)) + if (target != null && (target.IsDead() || Vector3.Distance(target.transform.position, AnchorPosition) > engageRadius * 1.5f)) { target = null; } @@ -74,7 +115,7 @@ namespace RacesOfValheim // them - reads as "trying to stay on him" without looking glued in place. orbitAngle += Time.deltaTime * 60f; Vector3 orbitOffset = new Vector3(Mathf.Cos(orbitAngle * Mathf.Deg2Rad), 0.3f, Mathf.Sin(orbitAngle * Mathf.Deg2Rad)) * TrentaConfig.HornetsNestOrbitRadius; - Vector3 restPoint = owner.transform.position + Vector3.up + orbitOffset; + Vector3 restPoint = AnchorPosition + Vector3.up + orbitOffset; transform.position = Vector3.MoveTowards(transform.position, restPoint, TrentaConfig.HornetsNestFollowSpeed * Time.deltaTime); } } @@ -83,16 +124,17 @@ namespace RacesOfValheim { Character nearest = null; float nearestDist = float.MaxValue; + Vector3 centre = AnchorPosition; - foreach (Collider collider in Physics.OverlapSphere(owner.transform.position, TrentaConfig.HornetsNestEngageRadius)) + foreach (Collider collider in Physics.OverlapSphere(centre, engageRadius)) { if (collider == null) continue; Character character = collider.GetComponentInParent(); - if (character == null || character == owner || character.IsDead()) continue; - if (!BaseAI.IsEnemy(owner, character)) continue; + if (character == null || character == owner) continue; + if (!IsHostile(character)) continue; - float dist = Vector3.Distance(character.transform.position, owner.transform.position); + float dist = Vector3.Distance(character.transform.position, centre); if (dist < nearestDist) { nearestDist = dist; @@ -103,6 +145,59 @@ namespace RacesOfValheim return nearest; } + /// + /// Who gets stung. + /// + /// For a player swarm this is one line - BaseAI.IsEnemy - and it is the most valuable line in + /// the file: RaceHostilityManager is a postfix on that very method, so the Trenta's own + /// alliances (greyling, greydwarf, fuling, troll, leech, deathsquito) are honoured for free. + /// + /// A grove has no Character to ask on its own behalf, so the rule is rebuilt from parts: + /// never players, never tamed, and only things carrying a MonsterAI - which is the cut that + /// spares wild deer and boar, since vanilla gives passive animals AnimalAI instead. And if + /// there is a Trenta standing inside the radius, IsEnemy is consulted against them too, so + /// the alliances come back the moment someone is there to carry them. + /// + private bool IsHostile(Character character) + { + if (character == null || character.IsDead()) return false; + if (character.IsPlayer()) return false; + if (character.IsTamed()) return false; + + if (owner != null) return BaseAI.IsEnemy(owner, character); + + if (character.GetComponent() == null) return false; + + Player trenta = NearestTrenta(); + return trenta == null || BaseAI.IsEnemy(trenta, character); + } + + /// + /// The nearest Trenta inside the swarm's own radius, or null. Used both to borrow their + /// alliances and to attribute the sting - a hit with no attacker at all is what the old eitr + /// refinery's mystery damage looked like, and worth avoiding whenever there is a real one. + /// + private Player NearestTrenta() + { + Player nearest = null; + float nearestDist = float.MaxValue; + Vector3 centre = AnchorPosition; + + foreach (Player player in Player.GetAllPlayers()) + { + if (player == null || player.IsDead() || !TrentaVisuals.IsTrentaPlayer(player)) continue; + + float dist = Vector3.Distance(player.transform.position, centre); + if (dist <= engageRadius && dist < nearestDist) + { + nearestDist = dist; + nearest = player; + } + } + + return nearest; + } + /// /// Two hits, matching "come se il giocatore fosse costantemente avvelenato dalle api, più /// lo stesso danno ma perforante da sopra" literally: one Poison hit at the wild Bee @@ -111,16 +206,20 @@ namespace RacesOfValheim /// private void Sting(Character victim) { + // A grove's bees are still somebody's bees when a Trenta is standing under the tree; + // when nobody is, the sting lands with no attacker rather than picking one at random. + Character attacker = owner != null ? owner : NearestTrenta(); + HitData poison = new HitData(); poison.m_damage.m_poison = TrentaConfig.HornetsNestDamagePerTick; - poison.SetAttacker(owner); + if (attacker != null) poison.SetAttacker(attacker); poison.m_point = victim.GetCenterPoint(); poison.m_dir = Vector3.zero; victim.Damage(poison); HitData pierce = new HitData(); pierce.m_damage.m_pierce = TrentaConfig.HornetsNestDamagePerTick; - pierce.SetAttacker(owner); + if (attacker != null) pierce.SetAttacker(attacker); pierce.m_point = victim.GetCenterPoint(); pierce.m_dir = Vector3.down; victim.Damage(pierce); @@ -165,8 +264,10 @@ namespace RacesOfValheim source.spatialBlend = 1f; // 3D - it should sound like it is coming from the swarm source.volume = 0.6f; - GameObject beehivePrefab = PrefabManager.Cache.GetPrefab(TrentaConfig.HornetsNestBeehivePrefab); - Beehive beehive = beehivePrefab != null ? beehivePrefab.GetComponent() : null; + // Resolved through TrentaConfig, which tries "piece_beehive" before "Beehive". This used + // to look up "Beehive" alone and got nothing, every time, which is why the swarm has been + // silent since it was written - found in the BepInEx log, not by listening. + Beehive beehive = TrentaConfig.FindVanillaBeehive(); GameObject beeEffect = beehive != null ? Traverse.Create(beehive).Field("m_beeEffect").Value : null; AudioSource sourceClipHolder = beeEffect != null ? beeEffect.GetComponentInChildren(true) : null; diff --git a/JotunnModStub/Trenta/TrentaRace.cs b/JotunnModStub/Trenta/TrentaRace.cs index 7ce994d..eac4cca 100644 --- a/JotunnModStub/Trenta/TrentaRace.cs +++ b/JotunnModStub/Trenta/TrentaRace.cs @@ -27,6 +27,13 @@ namespace RacesOfValheim { TrentaStatusEffects.RegisterStatusEffects(); CreateAwakenedSeedFoods(); + + // The item-progression chain: the Composter and its Fertilizer, then the Heartwood Grove + // that runs on that Fertilizer. Registered here rather than lazily because the faction + // merchant catalogue resolves the Rot Seed by prefab name, so the item has to exist + // before that catalogue is read. + TrentaComposter.Register(); + TrentaHeartwoodGrove.Register(); } /// -- 2.52.0 From df7ce7c893cf77f0ba640a62512f885ec6a7c7cc Mon Sep 17 00:00:00 2001 From: Ferdinando Date: Fri, 7 Aug 2026 17:02:48 +0200 Subject: [PATCH 6/8] feat(trol): war totem and its mercenary store Co-Authored-By: Claude Opus 5 --- JotunnModStub/Trol/TrolRace.cs | 4 + JotunnModStub/Trol/TrolTotem.cs | 368 +++++++++++++++++++++++ JotunnModStub/Trol/TrolTotemBehaviour.cs | 288 ++++++++++++++++++ JotunnModStub/Trol/TrolTotemStore.cs | 257 ++++++++++++++++ 4 files changed, 917 insertions(+) create mode 100644 JotunnModStub/Trol/TrolTotem.cs create mode 100644 JotunnModStub/Trol/TrolTotemBehaviour.cs create mode 100644 JotunnModStub/Trol/TrolTotemStore.cs diff --git a/JotunnModStub/Trol/TrolRace.cs b/JotunnModStub/Trol/TrolRace.cs index 5b7eb15..9867b73 100644 --- a/JotunnModStub/Trol/TrolRace.cs +++ b/JotunnModStub/Trol/TrolRace.cs @@ -38,6 +38,10 @@ namespace RacesOfValheim Jotunn.Logger.LogInfo("Initializing Trol Race..."); TrolStatusEffects.RegisterStatusEffects(); + // The war totem and every creature it can hire. Race-locked at placement, unlike every + // other station in the mod. + TrolTotem.Register(); + // No custom projectile needed anymore string[] logNames = new string[] { diff --git a/JotunnModStub/Trol/TrolTotem.cs b/JotunnModStub/Trol/TrolTotem.cs new file mode 100644 index 0000000..945433f --- /dev/null +++ b/JotunnModStub/Trol/TrolTotem.cs @@ -0,0 +1,368 @@ +using System.Collections.Generic; +using HarmonyLib; +using Jotunn.Configs; +using Jotunn.Entities; +using Jotunn.Managers; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// The Trol's totem: a troll's head on a core-wood post that hires warbands for coin. + /// + /// The first station in the mod that is RACE LOCKED. Every other chain can be built by anyone and + /// only its output is restricted; this one refuses the hammer outright to anyone who is not a Trol, + /// because a warband of trolls and greydwarves for money is the Trol's whole identity rather than a + /// tool it happens to own. + /// + /// The troops are the real creatures, unaltered - a Troll is a Troll - with three differences: + /// - they answer to the follow command, because they carry RaisedThrall like every other servant + /// in this mod, so the taunt and the click already work on them with no new code; + /// - they knit their wounds back up when left alone, the sentry's regeneration reused whole; + /// - they drop NOTHING and never come back. A dead warband is money spent. That is the balance + /// against troops that cost coin instead of materials, and it is why they are worth what they + /// are worth. + /// + public static class TrolTotem + { + public const string PieceName = "TrolWarTotem"; + public const string PieceDisplayName = "War Totem"; + public const string RaceId = "Trol"; + + /// Core wood. The item is RoundLog - another display name that does not predict the id. + public const string CoreWood = "RoundLog"; + public const string TrollHead = "TrophyForestTroll"; + + /// Yagluth's secondary drop, already mapped to state 6 in BossProgressionManager. + /// Distinct from TrophyGoblinKing, which is the head that replaces the troll's on upgrade. + public const string UpgradeItem = "YagluthDrop"; + public const string YagluthHead = "TrophyGoblinKing"; + + public const int UpgradeProgressionState = 6; // Yagluth + public const int MaxTroops = 5; + + // ---------------------------------------------------------------- the look, in metres + // These used to be bare multipliers (3f for the totem, 1.5f for the head) guessed against meshes + // nobody had measured, and the head came out with a circumference three times the height of the + // post under it. ModelBorrow now measures the mesh and scales it to fit, so a number here is a + // SIZE and not a factor: 2.2 m is a totem you can stand next to, 0.55 m is a head on top of it. + private const float TotemHeight = 2.2f; + private const float HeadSize = 0.9f; + + /// + /// How far the head sinks into the totem's crown, as a fraction of its own size. Mounting it exactly + /// ON the measured top left it hovering with daylight under it - a trophy sitting on a post shares + /// some of the post, so the two models are made to overlap instead of merely touching. + /// + private const float HeadSink = 0.35f; + + /// + /// A trophy is authored lying down, and the first correction (Euler(90,0,0)) stood it up but left it + /// upside down and facing away - seen in game, not reasoned about. Another half turn on each of the + /// two axes that were wrong puts it the right way up and looking out. + /// If it is still off, this is the ONE line to touch: the two 180s are what was added. + /// + private static readonly Quaternion HeadTilt = Quaternion.Euler(90f + 180f, 180f, 0f); + + /// Written into each hired creature's ZDO so the totem can tell its warbands apart - + /// five slots means counting groups, not bodies. + public const string KeyGroup = "RoV_trolGroup"; + + public const float LeashRange = 12f; + public const float WitherSeconds = 60f; + public const float HomeCheckRange = 25f; + + /// No cap: a hired warband follows as a warband. + public const int MaxFollowers = -1; + + public class Troop + { + public string Id; + public string Display; + public int Price; + public bool NeedsUpgrade; + /// Trophy of the strongest thing in the band - the face it wears in the rack. + public string Icon; + /// Vanilla creature prefab -> how many of it. + public KeyValuePair[] Members; + } + + // Anchored at 2000 for the strongest, as specified, and laddered by what each band can actually + // do rather than by head count. + public static readonly Troop[] Troops = + { + new Troop + { + Id = "greydwarf_patrol", Display = "Greydwarf Patrol", Price = 400, NeedsUpgrade = false, Icon = "TrophyGreydwarfBrute", + Members = new[] + { + new KeyValuePair("Greydwarf", 4), + new KeyValuePair("Greydwarf_Shaman", 1), + new KeyValuePair("Greydwarf_Elite", 1), + } + }, + new Troop + { + Id = "troll", Display = "Troll", Price = 700, NeedsUpgrade = false, Icon = "TrophyForestTroll", + Members = new[] { new KeyValuePair("Troll", 1) } + }, + new Troop + { + Id = "troll_summoned", Display = "Staff Troll", Price = 900, NeedsUpgrade = false, Icon = "TrophyForestTroll", + Members = new[] { new KeyValuePair("Troll_Summoned", 1) } + }, + new Troop + { + Id = "goblin_patrol", Display = "Fuling Patrol", Price = 1400, NeedsUpgrade = true, Icon = "TrophyGoblinBrute", + Members = new[] + { + new KeyValuePair("Goblin", 4), + new KeyValuePair("GoblinShaman", 1), + new KeyValuePair("GoblinBrute", 1), + } + }, + new Troop + { + Id = "goblin_band", Display = "Fuling War Band", Price = 2000, NeedsUpgrade = true, Icon = "TrophyGoblin", + Members = new[] + { + new KeyValuePair("Goblin", 4), + new KeyValuePair("GoblinArcher", 4), + } + }, + }; + + public static Troop Find(string id) + { + foreach (Troop troop in Troops) if (troop.Id == id) return troop; + return null; + } + + /// Every distinct creature the totem can hire, so their clones exist before anyone buys. + private static readonly Dictionary HiredPrefabs = new Dictionary(); + + public static string HiredNameFor(string vanillaPrefab) => + HiredPrefabs.TryGetValue(vanillaPrefab, out string name) ? name : null; + + public static void Register() + { + HashSet sources = new HashSet(); + foreach (Troop troop in Troops) + { + foreach (KeyValuePair member in troop.Members) sources.Add(member.Key); + } + foreach (string source in sources) RegisterHired(source); + + RegisterPiece(); + } + + // ---------------------------------------------------------------- the hired + + /// + /// One hired creature: the vanilla thing, tamed, leashed, healing, and worth nothing dead. + /// + /// CharacterDrop is destroyed for the reason it always is here - a mercenary that dropped a troll + /// hide would make the totem a farm - and this time it is also what "leaves nothing when it dies" + /// literally means. + /// + private static void RegisterHired(string source) + { + string prefabName = "TrolHired_" + source; + + GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(prefabName, source); + if (prefab == null) + { + Jotunn.Logger.LogWarning($"[Trol] Could not clone {source}; that troop cannot be hired."); + return; + } + + BaseAI ai = prefab.GetComponent(); + if (ai != null) ai.m_randomMoveRange = LeashRange; + + foreach (CharacterDrop drops in prefab.GetComponentsInChildren(true)) + { + if (drops != null) Object.DestroyImmediate(drops); + } + + RaisedThrall thrall = prefab.AddComponent(); + thrall.m_kind = prefabName; + thrall.m_commandingRace = RaceId; + thrall.m_maxFollowers = MaxFollowers; + thrall.m_witherSeconds = WitherSeconds; + thrall.m_homeCheckRange = HomeCheckRange; + thrall.m_refusalMessage = "They were not paid by you."; + + // The sentry's regeneration, reused whole: untouched for ten seconds, then two percent a + // second. "Rigenerarsi come i nostri scheletri" is the healing, not a respawn - a dead + // mercenary stays dead and has to be hired again. + prefab.AddComponent(); + + PrefabManager.Instance.AddPrefab(prefab); + HiredPrefabs[source] = prefabName; + } + + // ---------------------------------------------------------------- the totem + + private static void RegisterPiece() + { + // A REAL PIECE as the base, and this is the whole bug fix. The first version cloned + // "GoblinTotem", which lives in Assets/GameElements/Items/misc - it is the ITEM offered at + // Yagluth's altar, not a building. An ItemDrop wearing a Piece destroyed itself the moment it + // was placed and left the item lying on the ground. Verified in this very project when the + // merchant catalogue's "FulingTotem" was corrected to "GoblinTotem" as an ITEM, and then + // contradicted here. + // + // piece_workbench is a genuine piece and is already the stripped base of the Skeleton + // sentry's seed, so the pattern is proven. goblin_totempole was the other candidate and is + // not a piece either - it is dungeon scenery under Assets/world. + GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(PieceName, "piece_workbench"); + if (prefab == null) + { + Jotunn.Logger.LogWarning("[Trol] Could not clone piece_workbench; the war totem is not registered."); + return; + } + + // Strip the workbench down to a placeable shell: no station, no crafting, no furniture. The + // look comes from the borrowed totem below. + 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); + } + foreach (Renderer renderer in prefab.GetComponentsInChildren(true)) + { + if (renderer != null) renderer.enabled = false; // the bench's own mesh, hidden + } + + AswidBloodRefinery.StripOffensive(prefab, PieceName); + + // The look the player asked for: the totem itself, not a log with a head on it. Grounded on + // its own base, so Vector3.zero really is "standing on the spot the hammer picked". + GameObject totemModel = ModelBorrow.Attach(prefab.transform, "TotemModel", "GoblinTotem", + Vector3.zero, Quaternion.identity, TotemHeight, "Trol"); + + TrolTotemBehaviour totem = prefab.AddComponent(); + + foreach (Switch existing in prefab.GetComponentsInChildren(true)) + { + if (existing != null) Object.DestroyImmediate(existing); + } + totem.m_switch = prefab.AddComponent(); + totem.m_switch.m_name = PieceDisplayName; + + // A Trader with an empty catalogue: StoreGui needs one to open at all, and an empty list is + // exactly "sells troops, buys nothing". An empty catalogue is also what used to kill the whole + // window - see StoreGuiEmptyCatalogueGuardPatch in TrolTotemStore.cs, which is the fix. + // + // Every list is filled in even though this trader never talks: a Trader added with + // AddComponent comes up with all of them null, and Trader.Interact - which fires if the + // player's E happens to reach the Trader instead of our Switch, both being on this same + // GameObject - walks straight into Say(m_randomStartTrade, ...) right after opening the store. + Trader trader = prefab.GetComponent() ?? prefab.AddComponent(); + trader.m_name = PieceDisplayName; + trader.m_items = new List(); + trader.m_useItems = new List(); + trader.m_randomTalk = new List(); + trader.m_randomGreets = new List(); + trader.m_randomGoodbye = new List(); + trader.m_randomStartTrade = new List(); + trader.m_randomBuy = new List(); + trader.m_randomSell = new List(); + trader.m_randomGiveItemNo = new List(); + trader.m_randomUseItemAlreadyRecieved = new List(); + trader.m_randomTalkConditionals = new List(); + + // Only ONE head now, and only for the upgraded tier. At tier one the totem is just a totem, + // which is what was asked for - the troll head on a post was the thing being replaced, and + // mounting trophies is also what dropped a giant Yagluth head out of the sky. Borrowed + // safely this time, and mounted on the MEASURED top of the totem rather than at a guessed + // 2.2 m up an unmeasured post - sunk into the crown so it sits on it instead of over it. + float crown = ModelBorrow.HeightOf(totemModel); + Jotunn.Logger.LogInfo($"[Trol] Totem crown measured at {crown:0.##} m; the king's head is " + + $"{HeadSize} m across and sunk {HeadSize * HeadSink:0.##} m into it."); + + totem.m_yagluthHead = ModelBorrow.Attach(prefab.transform, "TotemHeadYagluth", YagluthHead, + new Vector3(0f, crown - HeadSize * HeadSink, 0f), + HeadTilt, HeadSize, "Trol"); + totem.m_yagluthHead.SetActive(false); + + Piece piece = prefab.GetComponent() ?? prefab.AddComponent(); + piece.m_craftingStation = null; + piece.m_resources = new Piece.Requirement[0]; + piece.m_name = PieceDisplayName; + piece.m_canBeRemoved = true; + piece.m_groundPiece = true; + piece.m_groundOnly = true; + piece.m_icon = BorrowIcon(TrollHead); + + 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 = PieceDisplayName, + Description = "A head that still remembers how to shout. Coin goes in, a warband walks out.", + PieceTable = PieceTables.Hammer, + Category = PieceCategories.Crafting, + Icon = BorrowIcon(TrollHead), + Requirements = new[] + { + new RequirementConfig(CoreWood, 1, 0, true), + new RequirementConfig(TrollHead, 1, 0, true), + } + })); + } + + public static void EnsureKnown(Player player) + { + if (player == null) return; + + GameObject prefab = PrefabManager.Instance.GetPrefab(PieceName); + Piece piece = prefab != null ? prefab.GetComponent() : null; + if (piece == null) return; + + Traverse traverse = Traverse.Create(player); + traverse.Method("AddKnownPiece", piece).GetValue(); + traverse.Method("UpdateAvailablePiecesList").GetValue(); + } + + private static Sprite BorrowIcon(string prefabName) + { + ItemDrop drop = PrefabManager.Cache.GetPrefab(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 TrolTotemKnownPatch + { + public static void Postfix(Player __instance) + { + if (__instance != Player.m_localPlayer) return; + TrolTotem.EnsureKnown(__instance); + } + } + + /// + /// The race lock. Every other station in this mod is buildable by anyone; this one is not, so the + /// refusal is caught at placement - before the core wood and the head are spent. + /// + [HarmonyPatch(typeof(Player), "PlacePiece", + new[] { typeof(Piece), typeof(Vector3), typeof(Quaternion), typeof(bool) })] + public static class TrolTotemRaceLockPatch + { + public static bool Prefix(Player __instance, Piece __0) + { + if (__instance != Player.m_localPlayer || __0 == null) return true; + if (Utils.GetPrefabName(__0.gameObject) != TrolTotem.PieceName) return true; + if (TrolRace.IsTrol()) return true; + + __instance.Message(MessageHud.MessageType.Center, "The head will not shout for you."); + return false; + } + } +} diff --git a/JotunnModStub/Trol/TrolTotemBehaviour.cs b/JotunnModStub/Trol/TrolTotemBehaviour.cs new file mode 100644 index 0000000..c3ab254 --- /dev/null +++ b/JotunnModStub/Trol/TrolTotemBehaviour.cs @@ -0,0 +1,288 @@ +using System; +using System.Collections.Generic; +using HarmonyLib; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// The totem's logic: five warband slots, bought with coin, disbanded on demand. + /// + /// Slots count GROUPS, not bodies - a six-greydwarf patrol is one slot, and it stays one slot as its + /// members die. Each hired creature carries the group's id in its own ZDO, so the count survives a + /// reload and corrects itself when a whole band is wiped, with nothing tallied anywhere. + /// + /// E opens the vanilla store with a warband column in it, built in TrolTotemStore. It replaced a + /// hold-to-cycle gesture on the Switch that fired faster than anyone could read it. + /// Factions/FactionMerchantSellPanel.cs is the blueprint that made it possible without guessing at a + /// single UI field name. + /// + /// There is no disband button and no rack of slots: a warband that dies is dead, and a butcher knife + /// already dismisses one that has outlived its use. The count is the only bookkeeping there is. + /// + public class TrolTotemBehaviour : MonoBehaviour + { + public Switch m_switch; + public GameObject m_yagluthHead; + + private const string KeyUpgraded = "RoV_trolTotemUpgraded"; + private const string KeyNextGroup = "RoV_trolTotemNextGroup"; + + private ZNetView m_nview; + + private void Awake() + { + RaisedThrall.RegisterStation(transform); + + m_nview = GetComponent(); + if (m_nview == null || m_nview.GetZDO() == null) return; + + if (m_switch != null) + { + m_switch.m_onUse = OnUse; + m_switch.m_onHover = Hover; + } + + m_nview.Register("RoV_TrolHire", RPC_Hire); + m_nview.Register("RoV_TrolUpgrade", RPC_Upgrade); + + InvokeRepeating("UpdateHeads", 0.5f, 2f); + } + + private void OnDestroy() + { + RaisedThrall.UnregisterStation(transform); + } + + /// Both heads are mounted; the tier decides which one is looking at you. + private void UpdateHeads() + { + // Tier one is a plain totem; the king's head only appears once it has been earned. + if (m_yagluthHead != null) m_yagluthHead.SetActive(IsUpgraded()); + } + + // ---------------------------------------------------------------- interaction + + private bool OnUse(Switch caller, Humanoid user, ItemDrop.ItemData item) + { + Player player = user as Player; + if (player == null) return false; + + if (!TrolRace.IsTrol()) + { + player.Message(MessageHud.MessageType.Center, "The head will not shout for you."); + return false; + } + + // Yagluth's drop in hand upgrades it: a new head, and two more warbands on the list. + if (item != null && item.m_dropPrefab != null && item.m_dropPrefab.name == TrolTotem.UpgradeItem) + { + return TryUpgrade(player, item); + } + + if (item != null) + { + player.Message(MessageHud.MessageType.Center, "$msg_wontwork"); + return false; + } + + return OpenStore(player); + } + + private bool TryUpgrade(Player player, ItemDrop.ItemData item) + { + if (IsUpgraded()) + { + player.Message(MessageHud.MessageType.Center, "It has already had one."); + return false; + } + + if (BossProgressionManager.GetCurrentProgressionState() < TrolTotem.UpgradeProgressionState) + { + player.Message(MessageHud.MessageType.Center, "Not until the one it belonged to has fallen."); + return false; + } + + player.GetInventory().RemoveItem(item, 1); + m_nview.InvokeRPC("RoV_TrolUpgrade"); + player.Message(MessageHud.MessageType.Center, "The totem wears a king now."); + return true; + } + + /// + /// Opens the vanilla store window, with the warband column hung off it by + /// TrolTotemStore. A Trader has to be present for StoreGui.Show to have anything to show; the + /// totem's own sells nothing, which is how "does not buy from the player" is expressed. + /// + private bool OpenStore(Player player) + { + Trader trader = GetComponent(); + if (trader == null || StoreGui.instance == null) + { + player.Message(MessageHud.MessageType.Center, "The head has nothing to say."); + return false; + } + + // Nothing is handed to the panel here on purpose: TrolTotemStore reads the totem back out of + // StoreGui's own m_trader when it repaints, so the window cannot end up drawing one totem's + // warbands while showing another's - and there is no static left over to go stale. + StoreGui.instance.Show(trader); + return true; + } + + // ---------------------------------------------------------------- what the store calls + + /// Hire by id, from a row the player clicked. Every check TryHire makes still applies. + public void HireFromStore(string troopId) + { + Player player = Player.m_localPlayer; + if (player == null) return; + + TrolTotem.Troop troop = TrolTotem.Find(troopId); + if (troop == null) return; + if (troop.NeedsUpgrade && !IsUpgraded()) return; + + if (CountGroups() >= TrolTotem.MaxTroops) + { + player.Message(MessageHud.MessageType.Center, "Five warbands is all it can shout for."); + return; + } + + Inventory inventory = player.GetInventory(); + if (inventory == null) return; + + if (CountCoins(inventory) < troop.Price) + { + player.Message(MessageHud.MessageType.Center, "$msg_notenoughmoney"); + return; + } + + TakeCoins(inventory, troop.Price); + m_nview.InvokeRPC("RoV_TrolHire", troop.Id); + player.Message(MessageHud.MessageType.Center, $"{troop.Display} answers."); + } + + private const string CoinsPrefab = "Coins"; + + private static int CountCoins(Inventory inventory) + { + int total = 0; + foreach (ItemDrop.ItemData item in inventory.GetAllItems()) + { + if (item != null && item.m_dropPrefab != null && item.m_dropPrefab.name == CoinsPrefab) + { + total += item.m_stack; + } + } + return total; + } + + private static void TakeCoins(Inventory inventory, int amount) + { + foreach (ItemDrop.ItemData item in new List(inventory.GetAllItems())) + { + if (amount <= 0) return; + if (item == null || item.m_dropPrefab == null || item.m_dropPrefab.name != CoinsPrefab) continue; + + int take = Mathf.Min(amount, item.m_stack); + inventory.RemoveItem(item, take); + amount -= take; + } + } + + // ---------------------------------------------------------------- hiring + + private void RPC_Hire(long sender, string troopId) + { + if (!m_nview.IsOwner()) return; + + TrolTotem.Troop troop = TrolTotem.Find(troopId); + if (troop == null || CountGroups() >= TrolTotem.MaxTroops) return; + if (troop.NeedsUpgrade && !IsUpgraded()) return; + + int next = m_nview.GetZDO().GetInt(KeyNextGroup) + 1; + m_nview.GetZDO().Set(KeyNextGroup, next); + string group = troopId + "#" + next; + + foreach (KeyValuePair member in troop.Members) + { + string hired = TrolTotem.HiredNameFor(member.Key); + if (hired == null) continue; + + GameObject prefab = ZNetScene.instance != null ? ZNetScene.instance.GetPrefab(hired) : null; + if (prefab == null) + { + Jotunn.Logger.LogWarning($"[Trol] No '{hired}' in ZNetScene; part of {troop.Display} did not arrive."); + continue; + } + + for (int i = 0; i < member.Value; i++) SpawnOne(prefab, group); + } + } + + private void SpawnOne(GameObject prefab, string group) + { + Vector3 offset = UnityEngine.Random.insideUnitSphere * 3f; + offset.y = 0f; + Vector3 position = transform.position + offset + Vector3.up * 0.5f; + + GameObject spawned = Instantiate(prefab, position, Quaternion.Euler(0f, UnityEngine.Random.Range(0, 360), 0f)); + + ZNetView nview = spawned.GetComponent(); + if (nview != null && nview.IsValid()) nview.GetZDO().Set(TrolTotem.KeyGroup, group); + + RaisedThrall thrall = spawned.GetComponent(); + if (thrall != null) thrall.Bind(transform.position); + } + + private void RPC_Upgrade(long sender) + { + if (!m_nview.IsOwner()) return; + m_nview.GetZDO().Set(KeyUpgraded, true); + } + + // ---------------------------------------------------------------- state + + public bool IsUpgraded() => m_nview != null && m_nview.IsValid() && m_nview.GetZDO().GetBool(KeyUpgraded, false); + + private static string GroupOf(RaisedThrall thrall) + { + ZNetView nview = thrall != null ? thrall.GetComponent() : null; + if (nview == null || !nview.IsValid()) return null; + + string group = nview.GetZDO().GetString(TrolTotem.KeyGroup, ""); + return string.IsNullOrEmpty(group) ? null : group; + } + + /// + /// Live warbands, counted as distinct groups rather than as bodies. This is the whole of the + /// five-slot mechanic now that the rack is gone: nothing is stored, the count is the truth, and it + /// corrects itself the moment a band is wiped out. + /// + public int CountGroups() + { + HashSet groups = new HashSet(); + foreach (RaisedThrall thrall in RaisedThrall.BoundTo(transform.position)) + { + string group = GroupOf(thrall); + if (group != null) groups.Add(group); + } + return groups.Count; + } + + private string Hover() + { + string body = $"warbands {CountGroups()}/{TrolTotem.MaxTroops}"; + + if (!IsUpgraded()) body += "\n(a Yagluth drop in hand buys a king's head, and two more bands)"; + + // The roster lives in the window now, not in the hover - so this only has to get the player + // to open it. The hold gesture it used to advertise was unreadable: it cycled faster than + // anyone could see what was selected. + body += "\n[$KEY_Use] Call the warbands"; + + return Localization.instance.Localize($"{TrolTotem.PieceDisplayName} ({body})"); + } + } + +} diff --git a/JotunnModStub/Trol/TrolTotemStore.cs b/JotunnModStub/Trol/TrolTotemStore.cs new file mode 100644 index 0000000..2bb61f1 --- /dev/null +++ b/JotunnModStub/Trol/TrolTotemStore.cs @@ -0,0 +1,257 @@ +using System.Collections.Generic; +using System.Text; +using HarmonyLib; +using TMPro; +using UnityEngine; +using UnityEngine.UI; + +namespace RacesOfValheim +{ + /// + /// The war totem's window: the merchant's own store, with a column of hireable warbands in it. + /// + /// Built by cloning the vanilla store's list the way Factions/FactionMerchantSellPanel.cs already + /// does - same three patch points (Awake to build, FillList to repaint, Hide to clear), same trick of + /// instantiating StoreGui.m_listElement for rows. That file is the reason this one could be written + /// without guessing at a single UI field name. + /// + /// It replaces a hold-to-cycle gesture on the Switch, which was unreadable: the hold fired faster + /// than anyone could see what was selected. + /// + /// NO SLOT RACK. There was one, with five squares wearing the trophies of the bands standing in them + /// and a yes/no box to disband one. It is gone at the player's call: a warband that dies is simply + /// dead, and a butcher knife already dismisses one that has outlived its use - tested in game. The + /// five-band CEILING stays, counted in TrolTotemBehaviour and reported by the totem's hover text; it + /// was only ever the rack that was UI, not the limit. + /// + /// WHY THIS FILE ONCE DREW NOTHING AT ALL - see StoreGuiEmptyCatalogueGuardPatch at the bottom. It + /// was not this panel failing; it was vanilla FillList throwing on its last instruction, and a + /// Postfix never runs when the original throws. + /// + public static class TrolTotemStore + { + private static RectTransform _troopList; + private static readonly List _rows = new List(); + + /// + /// The totem the open window belongs to, read back out of StoreGui's own m_trader instead of being + /// pushed in by the totem before Show(). + /// + /// It used to be a static the totem set on its way in, which meant the panel's correctness depended + /// on the order Show/Hide/FillList happen to run in. Reading it back makes the question local: this + /// window belongs to whatever trader vanilla says it belongs to, and if that trader has a + /// TrolTotemBehaviour on it, it is a totem. Same field the factions sell panel reads. + /// + public static TrolTotemBehaviour ActiveTotem(StoreGui gui) + { + Trader trader = FactionMerchantRuntime.GetActiveTrader(gui); + return trader != null ? trader.GetComponent() : null; + } + + // ---------------------------------------------------------------- build + + public static void Create(StoreGui gui) + { + if (gui == null || gui.m_listRoot == null) + { + Jotunn.Logger.LogWarning("[Trol] StoreGui has no m_listRoot; the war totem's window cannot be built."); + return; + } + if (_troopList != null) return; + + GameObject clone = Object.Instantiate(gui.m_listRoot.gameObject, gui.m_listRoot.parent); + clone.name = "TrolTroopList"; + _troopList = clone.GetComponent(); + _troopList.anchoredPosition = gui.m_listRoot.anchoredPosition; + + // The clone carries whatever rows the vanilla list held at Awake. Usually none, but a leftover + // would sit under ours forever, so it starts empty by construction. + foreach (Transform child in _troopList) Object.Destroy(child.gameObject); + + _troopList.gameObject.SetActive(false); + } + + public static void Clear() + { + foreach (GameObject row in _rows) if (row != null) Object.Destroy(row); + _rows.Clear(); + + if (_troopList != null) _troopList.gameObject.SetActive(false); + } + + // ---------------------------------------------------------------- fill + + public static void Refresh(StoreGui gui) + { + Clear(); + + TrolTotemBehaviour totem = ActiveTotem(gui); + if (totem == null) return; // an ordinary merchant. Not ours, and not worth a line in the log. + + if (_troopList == null) + { + Jotunn.Logger.LogWarning("[Trol] The war totem's column was never built (did the patch on " + + "StoreGui.Awake fail?), so nothing can be drawn into it."); + return; + } + + _troopList.gameObject.SetActive(true); + + int row = 0; + int hidden = 0; + foreach (TrolTotem.Troop troop in TrolTotem.Troops) + { + if (troop.NeedsUpgrade && !totem.IsUpgraded()) { hidden++; continue; } + BuildRow(gui, totem, troop, row++); + } + + float baseSize = Traverse.Create(gui).Field("m_itemlistBaseSize").GetValue(); + _troopList.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, + Mathf.Max(baseSize, row * gui.m_itemSpacing)); + + Jotunn.Logger.LogInfo($"[Trol] War totem window: {row} warbands on offer, {hidden} still behind " + + $"the king's head, {totem.CountGroups()}/{TrolTotem.MaxTroops} bands alive."); + } + + private static void BuildRow(StoreGui gui, TrolTotemBehaviour totem, TrolTotem.Troop troop, int rowIndex) + { + GameObject element = Object.Instantiate(gui.m_listElement, _troopList); + element.SetActive(true); + + RectTransform rt = (RectTransform)element.transform; + float offset = (_troopList.rect.width - rt.rect.width) / 2f; + rt.anchoredPosition = new Vector2(offset, rowIndex * -gui.m_itemSpacing - offset); + + Sprite icon = TrophyIcon(troop.Icon); + Image iconImage = element.transform.Find("icon").GetComponent(); + if (icon != null) iconImage.sprite = icon; + else Jotunn.Logger.LogWarning($"[Trol] No icon on '{troop.Icon}' for {troop.Display}; the row keeps " + + "whatever the cloned element was showing."); + + element.transform.Find("name").GetComponent().text = troop.Display; + + TMP_Text price = FindDescendant(element.transform, "price"); + if (price != null) price.text = troop.Price.ToString(); + + UITooltip tooltip = element.GetComponent(); + if (tooltip != null) tooltip.Set(troop.Display, Composition(troop), gui.m_tooltipAnchor, default(Vector2)); + + string id = troop.Id; + element.GetComponent