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(); } ///