From 1d66b003745db66cc60205cff5e80eafdf080d29 Mon Sep 17 00:00:00 2001 From: Ferdinando Date: Tue, 11 Aug 2026 16:30:20 +0200 Subject: [PATCH] warvulture --- JotunnModStub/ModelBorrow.cs | 31 +- JotunnModStub/RaceCompendium.cs | 156 +++- JotunnModStub/RaceHostilityManager.cs | 32 + JotunnModStub/RaceScale.cs | 7 +- JotunnModStub/RacesOfValheim.cs | 56 ++ JotunnModStub/Sverm/SvermAntennae.cs | 170 ++++ JotunnModStub/Sverm/SvermBeehive.cs | 197 +++++ JotunnModStub/Sverm/SvermBiomass.cs | 243 ++++++ JotunnModStub/Sverm/SvermBlisterTick.cs | 289 +++++++ JotunnModStub/Sverm/SvermBrood.cs | 293 +++++++ JotunnModStub/Sverm/SvermCarapace.cs | 133 ++++ JotunnModStub/Sverm/SvermClawSlot.cs | 283 +++++++ JotunnModStub/Sverm/SvermClaws.cs | 154 ++++ JotunnModStub/Sverm/SvermConfig.cs | 535 +++++++++++++ JotunnModStub/Sverm/SvermConfigManagement.cs | 271 +++++++ JotunnModStub/Sverm/SvermFood.cs | 273 +++++++ JotunnModStub/Sverm/SvermHive.cs | 621 +++++++++++++++ JotunnModStub/Sverm/SvermHiveGoods.cs | 499 ++++++++++++ JotunnModStub/Sverm/SvermHiveStage.cs | 106 +++ JotunnModStub/Sverm/SvermHiveStore.cs | 518 ++++++++++++ JotunnModStub/Sverm/SvermHiveVfx.cs | 150 ++++ JotunnModStub/Sverm/SvermMedicine.cs | 114 +++ JotunnModStub/Sverm/SvermPatches.cs | 337 ++++++++ JotunnModStub/Sverm/SvermProgression.cs | 116 +++ JotunnModStub/Sverm/SvermRace.cs | 102 +++ JotunnModStub/Sverm/SvermStatusEffects.cs | 161 ++++ JotunnModStub/Sverm/SvermStingerForm.cs | 375 +++++++++ JotunnModStub/Sverm/SvermVisuals.cs | 780 +++++++++++++++++++ JotunnModStub/Sverm/SvermWorker.cs | 238 ++++++ 29 files changed, 7236 insertions(+), 4 deletions(-) create mode 100644 JotunnModStub/Sverm/SvermAntennae.cs create mode 100644 JotunnModStub/Sverm/SvermBeehive.cs create mode 100644 JotunnModStub/Sverm/SvermBiomass.cs create mode 100644 JotunnModStub/Sverm/SvermBlisterTick.cs create mode 100644 JotunnModStub/Sverm/SvermBrood.cs create mode 100644 JotunnModStub/Sverm/SvermCarapace.cs create mode 100644 JotunnModStub/Sverm/SvermClawSlot.cs create mode 100644 JotunnModStub/Sverm/SvermClaws.cs create mode 100644 JotunnModStub/Sverm/SvermConfig.cs create mode 100644 JotunnModStub/Sverm/SvermConfigManagement.cs create mode 100644 JotunnModStub/Sverm/SvermFood.cs create mode 100644 JotunnModStub/Sverm/SvermHive.cs create mode 100644 JotunnModStub/Sverm/SvermHiveGoods.cs create mode 100644 JotunnModStub/Sverm/SvermHiveStage.cs create mode 100644 JotunnModStub/Sverm/SvermHiveStore.cs create mode 100644 JotunnModStub/Sverm/SvermHiveVfx.cs create mode 100644 JotunnModStub/Sverm/SvermMedicine.cs create mode 100644 JotunnModStub/Sverm/SvermPatches.cs create mode 100644 JotunnModStub/Sverm/SvermProgression.cs create mode 100644 JotunnModStub/Sverm/SvermRace.cs create mode 100644 JotunnModStub/Sverm/SvermStatusEffects.cs create mode 100644 JotunnModStub/Sverm/SvermStingerForm.cs create mode 100644 JotunnModStub/Sverm/SvermVisuals.cs create mode 100644 JotunnModStub/Sverm/SvermWorker.cs diff --git a/JotunnModStub/ModelBorrow.cs b/JotunnModStub/ModelBorrow.cs index 097f44d..b064361 100644 --- a/JotunnModStub/ModelBorrow.cs +++ b/JotunnModStub/ModelBorrow.cs @@ -40,6 +40,33 @@ namespace RacesOfValheim public static GameObject Attach(Transform parent, string holderName, string sourcePrefab, Vector3 localPosition, Quaternion localRotation, float targetSize, string label) + { + 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."); + + GameObject empty = new GameObject(holderName); + empty.transform.SetParent(parent, false); + empty.transform.localPosition = localPosition; + return empty; + } + + return Attach(parent, holderName, source, localPosition, localRotation, targetSize, label); + } + + /// + /// The same, for a source that has already been found by hand. + /// + /// Not every borrowable model is a top-level prefab. The Seeker's wing, for one, is a + /// child of the creature's death effect rather than a prefab of its own, so no name lookup + /// can reach it and the caller has to walk to it first. Everything past the lookup - the + /// inactive holder, the component strip, the measure-and-ground - is identical, which is + /// exactly why this is an overload and not a second copy. + /// + public static GameObject Attach(Transform parent, string holderName, GameObject source, + Vector3 localPosition, Quaternion localRotation, float targetSize, + string label) { GameObject holder = new GameObject(holderName); holder.transform.SetParent(parent, false); @@ -48,14 +75,14 @@ namespace RacesOfValheim // 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."); + Jotunn.Logger.LogWarning($"[{label}] No source model handed to '{holderName}'; nothing was attached."); holder.SetActive(true); return holder; } + string sourcePrefab = source.name; GameObject copy = Object.Instantiate(source, holder.transform); copy.name = "model"; copy.transform.localPosition = Vector3.zero; diff --git a/JotunnModStub/RaceCompendium.cs b/JotunnModStub/RaceCompendium.cs index 0ddbc5f..1004049 100644 --- a/JotunnModStub/RaceCompendium.cs +++ b/JotunnModStub/RaceCompendium.cs @@ -16,7 +16,8 @@ namespace RacesOfValheim "Furling Secrets", "Trol Secrets", "Draugh Secrets", - "Dvergar Secrets" + "Dvergar Secrets", + "Sverm Secrets" }; public static void UpdateCompendiumText(Player player) @@ -72,6 +73,142 @@ namespace RacesOfValheim { GenerateDvergarText(knownTexts, state); } + else if (currentRace == SvermConfig.RaceId) + { + GenerateSvermText(knownTexts, state); + } + + // The War Vulture is not a racial power and does not belong inside any one race's + // generator: it is an item whose access list is a config entry. Appended here, once, + // to whichever page was just written - so adding a race to that list in Configuration + // Manager puts the paragraph on that race's page without a line of code changing. + AppendWarVulture(knownTexts, currentRace); + } + + /// + /// The War Vulture's half-page, added to any race allowed to call the bird. + /// + /// Asks WarVultureConfig instead of naming Furling and Dvergar, because the allowed list is + /// a config entry and a hard-coded pair would be wrong the moment anyone edits it. The + /// speeds are read the same way, so the page cannot promise a number the bird does not fly. + /// + private static void AppendWarVulture(Dictionary knownTexts, string race) + { + // Before Bind runs there are no numbers to print. RaceAllowed already survives a null + // config; the speeds below would not. + if (WarVultureConfig.CruiseSpeed == null) return; + if (!WarVultureConfig.RaceAllowed(race)) return; + + string key = race + " Secrets"; + if (!knownTexts.TryGetValue(key, out string page)) return; + + StringBuilder sb = new StringBuilder(page); + sb.AppendLine("\n-- THE WAR VULTURE --\n"); + + sb.AppendLine("A vulture's head kept on a stick, and the bird answers to it. Raise it and the vulture comes back under you. Raise it again and it carries you down, deaf to you until the ground arrives - and a third time lets go of it where you are.\n"); + + sb.AppendLine($"It goes where you look, and it goes as long as you care to stay up: {WarVultureConfig.CruiseSpeed.Value:0.#} meters a second costs it nothing at all. Hold your run key and it gives you {WarVultureConfig.SprintSpeed.Value:0.#} for {WarVultureConfig.SprintSeconds.Value:0} seconds and not a moment longer - there is only so much haste in a bird. Let go and the wind comes back into it in {WarVultureConfig.RechargeSeconds.Value:0} seconds, in the air. You never have to land for it.\n"); + + if (WarVultureConfig.ShowStaminaBar.Value) + sb.AppendLine("What the bird has left is the bar under your own.\n"); + + knownTexts[key] = sb.ToString(); + } + + /// + /// The Sverm's entry, in two halves because the race is two halves: a body that grows on its + /// own, and a colony that has to be built. Figures are read from the live rules and from the + /// colony's own tables rather than restated, so the page cannot drift from the code. + /// + private static void GenerateSvermText(Dictionary knownTexts, int state) + { + SvermProgression.SvermRules rules = SvermProgression.GetRules(state); + + StringBuilder sb = new StringBuilder(); + sb.AppendLine("The Sverm's Colony\n"); + + sb.AppendLine("[Base Passive] Chitin Plating: You do not dress. Chest, legs and helm are carapace and never come off, and at every tier they are worth the full set of the biome ahead of you - at its best quality, weightless, and without the slowness that armour costs anyone else. Cloak and trinket are the only things you may still wear.\n"); + + sb.AppendLine($"[Base Passive] Toxin Immunity: Poison cannot touch you. What can is the club and the torch: you take {rules.BluntWeakness * 100f:0}% more from blunt blows{(rules.FireWeakness > 0f ? $" and {rules.FireWeakness * 100f:0}% more from fire" : ", and fire has stopped being a weakness")}.\n"); + + sb.AppendLine("[Base Passive] Hive Pheromones: No invertebrate will attack you - not leeches, not ticks, not deathsquitos, not seekers, not the bees. Bonemass is not an insect and does not care.\n"); + + sb.AppendLine("[Base Passive] Insect Metabolism: You eat everything anyone else eats, and honey is worth double to you. Alchemical blood is the one thing you will not swallow.\n"); + + sb.AppendLine($"[Base Passive] Vilebone Maulclaws: Your hands are the weapon. Bare-handed blows land at {rules.ClawDamagePercent * 100f:0}% of the claws' full weight, and they cannot be taken from you - draw a sword and they wait, sheathe it and they are back.\n"); + + if (rules.MetabolicSurge) + sb.AppendLine("[Eikthyr Unlock] Metabolic Surge: Running and jumping cost you less, and you jump higher.\n"); + + if (rules.CarryWeightBonus > 0f) + sb.AppendLine($"[Eikthyr Unlock] Ventral Pouches: You carry {rules.CarryWeightBonus:0} more.\n"); + + if (rules.SeedsEdible) + sb.AppendLine("[Elder Unlock] Grinding Mandibles: Seeds are food. Raw nourishment and nothing more - the garden's blessings belong to somebody else.\n"); + + if (rules.SensoryAntennae) + sb.AppendLine("[Elder Unlock] Sensory Antennae: You feel what lives around you, through stone and through soil.\n"); + + if (rules.VenomOnHit > 0f) + sb.AppendLine($"[Bonemass Unlock] Venom Glands: Every blow you land carries +{rules.VenomOnHit:0.#} poison.\n"); + + if (rules.AcidHemolymph > 0f) + sb.AppendLine($"[Bonemass Unlock] Acid Hemolymph: Whoever strikes you in melee takes {rules.AcidHemolymph:0.#} poison back for the trouble.\n"); + + if (rules.FallDamageModifier <= 0f) + sb.AppendLine("[Moder Unlock] Vestigial Wings: Small wings, and no ground hard enough to hurt you.\n"); + + if (rules.StingerMorph) + sb.AppendLine($"[Yagluth Unlock] Stinger Morph ('{SvermConfigManagement.StingerKey.Value}' Key): Become a deathsquito. Real flight and the creature's own sting - and a body made of paper. It is how you kill, not how you travel.\n"); + + if (rules.BodyScale > 1f) + sb.AppendLine("[Queen Unlock] Surrenal Glands: You stand a tenth larger, and the carapace takes its greatest leap.\n"); + + if (rules.CarapaceRegenPerSecond > 0f) + sb.AppendLine($"[Fader Unlock] Carapace Regeneration: You knit yourself back together, {rules.CarapaceRegenPerSecond:0.##} health a second, always.\n"); + + if (rules.Emberform) + sb.AppendLine("[Fader Unlock] Annealed Chitin and Emberform: Eight tiers of burning have turned the flaw into armour - fire no longer hurts you, and the chitin goes black with a red heat under it.\n"); + + // ── The colony + sb.AppendLine("\n-- THE COLONY --\n"); + + if (state < SvermConfig.HiveUnlockState) + { + sb.AppendLine("The colony will not wake until the Elder falls. Until then you are a body, and the body is enough.\n"); + } + else + { + sb.AppendLine($"Brood Mound (Hammer): Your nest, and no more than two of them may stand within {SvermConfig.HiveDensityRadius:0} meters of each other. Press it, or the hive at its foot, to feed it a whole stack out of your pack: any food, any wood, any resin. Honey and royal jelly are medicine now and it will not take them.\n"); + + sb.AppendLine($"Digestion: what you feed it is not yours to spend yet. It seeps into the nest's bank at {SvermConfigManagement.DigestRate:0.#} a second, and only what has arrived can be spent.\n"); + + sb.AppendLine($"Brood Eggs: the nest lays one every {SvermConfig.EggInterval:0} seconds and holds {SvermConfig.EggCapBase + 1} of them at its first stage, one more at each stage after. Every troop costs an egg as well as biomass - the egg grows back, the biomass does not.\n"); + + sb.AppendLine("Hive Market (Hammer): a counter raised within ten meters of a nest. Everything the colony buys is bought here, out of that nest's bank.\n"); + + sb.AppendLine($"Growth: {SvermHiveStage.NameOf(2)} {SvermHiveStage.PriceToLeave(1):0}, {SvermHiveStage.NameOf(3)} {SvermHiveStage.PriceToLeave(2):0}, {SvermHiveStage.NameOf(4)} {SvermHiveStage.PriceToLeave(3):0}. Each one costs that stage's whole tankful and opens the next rung of the roster.\n"); + + StringBuilder roster = new StringBuilder(); + foreach (SvermBrood.Kind kind in SvermBrood.Roster) + { + roster.Append($"{kind.Display} {kind.Price:0} (from {SvermHiveStage.NameOf(kind.Stage)}, at most {kind.Cap}). "); + } + sb.AppendLine($"Troops: {roster}They follow when you ask, walk home when you let them go, and mend themselves.\n"); + + string haulers = state >= SvermConfig.HaulerUnlockState + ? $", and up to {SvermConfigManagement.Haulers} haulers come out of the nest to carry food back into it" + : ", and the haulers who carry food back into it will not hatch until Bonemass falls"; + sb.AppendLine($"Seeker Workers: free, and always free - no biomass, no egg, and a new one when an old one dies. Two trades that never share hands: up to {SvermConfigManagement.Farmers} farmers come out of the infected beehives to work the ground{haulers}. They are half a Seeker in size, in health and in reach, they take no orders and they never follow - they stay where they were born and defend what stands there.\n"); + + sb.AppendLine($"Blister Tick {SvermConfig.TickPrice:0}: buys a slot forever. It runs at what you are fighting and bursts, and the nest grows another one {SvermConfig.TickRespawnSeconds:0} seconds later, free.\n"); + + sb.AppendLine("Surrenal Glands 800 and Hyperplasia 1600: everything hatched after them is born with one star, then two.\n"); + + sb.AppendLine($"The beehives: raise vanilla hives inside the nest's ten meters and the colony takes them over after a minute - twice the speed, three times the honey, and royal jelly instead once Yagluth is down. Press honey or royal jelly on one of your own insects to heal it: {SvermConfig.HoneyHealing:0} and {SvermConfig.RoyalJellyHealing:0}.\n"); + } + + knownTexts["Sverm Secrets"] = sb.ToString(); } /// @@ -296,6 +433,23 @@ namespace RacesOfValheim sb.AppendLine("The bones of a dragon rise at your call, wreathed in frost. It rends with bite and claw, sweeps all around it with a spinning tail (Right Mouse), and its breath carries thrice the fury of Moder's.\n"); } + // ── The station. Figures come from SkadiGolem's own constants, which are also what + // MayRaise enforces, so the page and the refusal message can never disagree. + sb.AppendLine("\n-- THE CRYSTAL GOLEM --\n"); + + if (state < SkadiGolem.ModerProgressionState) + { + sb.AppendLine("The tear is cold. Nothing wakes in the stone until the mountain's queen has fallen.\n"); + } + else + { + sb.AppendLine($"Cut one at a stonecutter for a stone golem's trophy, {SkadiGolem.CrystalCost} crystal and a dragon tear. The stone answers to no one who is not Skadi, so what you raise is yours and stays yours.\n"); + + sb.AppendLine($"It is bound to the stonecutter that shaped it and may never leave the {SkadiGolem.LeashRange:0} meters around it - the same circle the station itself builds in. It cannot be named, cannot be ordered and will not follow you. It guards the stone that cut it, and that is the whole of what it does.\n"); + + sb.AppendLine($"One stonecutter holds {SkadiGolem.MaxPerStation} of them, and no more than {SkadiGolem.MaxInArea} may stand within a day's walk of each other. Break the stonecutter and what it cut goes still {SkadiGolem.WitherSeconds:0} seconds later.\n"); + } + knownTexts["Skadi Secrets"] = sb.ToString(); } diff --git a/JotunnModStub/RaceHostilityManager.cs b/JotunnModStub/RaceHostilityManager.cs index 2bd09b4..a60aa07 100644 --- a/JotunnModStub/RaceHostilityManager.cs +++ b/JotunnModStub/RaceHostilityManager.cs @@ -93,6 +93,38 @@ namespace RacesOfValheim __result = false; } } + + // Sverm Race Logic - Hive Pheromones. No progression gate at all, unlike + // Aswid's escalating list: an invertebrate is kin from the first minute. + // + // That absence of a gate is doing real work rather than saving a few lines. + // Every invertebrate in the game lives from the Swamp onward, so a gated + // version would have handed the race nothing until Bonemass; ungated, a + // newborn Sverm walks through leeches and deathsquitoes, which is the whole + // of its early game. + // + // Bonemass is deliberately NOT here. It is a mass of ooze and it would + // qualify, but a boss that ignores the player is not a boss. + if (p.m_customData.ContainsKey("Race") && p.m_customData["Race"] == SvermConfig.RaceId) + { + string prefabName = monster.gameObject.name.ToLower(); + + // "blob" covers Blob, BlobElite, BlobTar and the Ashlands lava blob + // whatever it turns out to be called - which is why the one prefab name + // still unconfirmed in the design doc costs nothing here. + // "seeker" covers Seeker, SeekerBrood, SeekerBrute and SeekerQueen. + bool isKin = prefabName.Contains("blob") + || prefabName.Contains("leech") + || prefabName.Contains("tick") + || prefabName.Contains("deathsquito") + || prefabName.Contains("gjall") + || prefabName.Contains("seeker"); + + if (isKin && !prefabName.Contains("bonemass")) + { + __result = false; + } + } } } } diff --git a/JotunnModStub/RaceScale.cs b/JotunnModStub/RaceScale.cs index f471666..bdbdde7 100644 --- a/JotunnModStub/RaceScale.cs +++ b/JotunnModStub/RaceScale.cs @@ -20,7 +20,12 @@ namespace RacesOfValheim "Trol", "Furling", DvergarConfig.RaceId, - TrentaConfig.RaceId + TrentaConfig.RaceId, + // Sverm sizes itself only from the Queen on (Surrenal Glands, +10%). It is listed here + // for every tier all the same: below that tier its own ApplyScale asks for 1, which is + // the same answer another race's reset would give, and being on the list is what stops + // those resets from fighting it once the +10% does arrive. + SvermConfig.RaceId }; public static bool ManagesOwnScale(string race) diff --git a/JotunnModStub/RacesOfValheim.cs b/JotunnModStub/RacesOfValheim.cs index c04e8d5..70dc814 100644 --- a/JotunnModStub/RacesOfValheim.cs +++ b/JotunnModStub/RacesOfValheim.cs @@ -34,6 +34,7 @@ namespace RacesOfValheim FurlingConfig.Bind(Config); SkadiConfig.Bind(Config); SkeletonConfig.Bind(Config); + SvermConfigManagement.Bind(Config); TrentaConfigManagement.Bind(Config); TrolConfig.Bind(Config); // Not a race: a summoned mount two races share, so it binds after the races rather @@ -49,6 +50,7 @@ namespace RacesOfValheim gameObject.AddComponent(); gameObject.AddComponent(); gameObject.AddComponent(); + gameObject.AddComponent(); // Not a race: a perk two races share (Skadi and Trol build inside troll caves), so it // gets its own component rather than living inside either one's Update. gameObject.AddComponent(); @@ -122,6 +124,7 @@ namespace RacesOfValheim DraughRace.Instance.CreateModAssets(); DvergarRace.Instance.CreateModAssets(); TrentaRace.Instance.CreateModAssets(); + SvermRace.Instance.CreateModAssets(); WarVultureItem.Register(); } // --- RACE SELECTION UI --- @@ -266,6 +269,7 @@ namespace RacesOfValheim // Row 3 (y = -140) CreateRaceButtonWithConfirm("Dvergar", new Vector2(-450, -140), GetDvergarIcon(), "Small, stubborn smiths of the deep. Frail of frame, but masters of metal, mine and market.", SelectDvergar); CreateRaceButtonWithConfirm("Trenta", new Vector2(-150, -140), GetTrentaIcon(), "Tree-born folk, kin to root and leaf. Patient and hard to fell.", SelectTrenta); + CreateRaceButtonWithConfirm("Sverm", new Vector2(150, -140), GetSvermIcon(), "Chitin-born swarm kin. Armoured from birth and never slowed, venomous, at peace with every crawling thing - but blunt trauma and fire find the seams.", SelectSverm); GUIManager.BlockInput(true); } @@ -632,6 +636,58 @@ namespace RacesOfValheim } } + private void SelectSverm() + { + if (Player.m_localPlayer != null) + { + Player.m_localPlayer.m_customData["Race"] = SvermConfig.RaceId; + ZNetView nview = Player.m_localPlayer.GetComponent(); + if (nview != null && nview.IsValid()) nview.GetZDO().Set("RacesOfValheim_Race", SvermConfig.RaceId); + + Player.m_localPlayer.GetSEMan().AddStatusEffect(SvermConfig.StatsSE.GetStableHashCode(), true); + + // The carapace seals chest, legs and helmet, so whatever the player was wearing in + // those slots has to come off before the visual rebuild - otherwise the old chest + // stays on screen underneath a carapace that the equip patch will refuse to remove + // later, because the refusal is on EQUIPPING, not on unequipping. + Humanoid humanoid = Player.m_localPlayer; + foreach (ItemDrop.ItemData.ItemType slot in SvermConfig.SealedSlots) + { + ItemDrop.ItemData worn = null; + foreach (ItemDrop.ItemData item in humanoid.GetInventory().GetEquippedItems()) + { + if (item != null && item.m_shared != null && item.m_shared.m_itemType == slot) { worn = item; break; } + } + if (worn != null) humanoid.UnequipItem(worn, false); + } + + VisEquipment visEq = Player.m_localPlayer.GetComponent(); + if (visEq != null) + { + visEq.GetType().GetMethod("UpdateVisuals", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Public)?.Invoke(visEq, null); + } + + Player.m_localPlayer.Message(MessageHud.MessageType.Center, "You chose the path of the Sverm."); + CloseRaceSelectionMenu(); + } + } + + private Sprite GetSvermIcon() + { + GameObject prefab = PrefabManager.Cache.GetPrefab("TrophySeekerBrute")?.gameObject; + if (prefab == null) prefab = PrefabManager.Cache.GetPrefab("TrophySeeker")?.gameObject; + if (prefab == null) prefab = PrefabManager.Cache.GetPrefab("Chitin")?.gameObject; + if (prefab != null) + { + ItemDrop drop = prefab.GetComponent(); + if (drop != null && drop.m_itemData.m_shared.m_icons.Length > 0) + { + return drop.m_itemData.m_shared.m_icons[0]; + } + } + return null; + } + private Sprite GetDvergarIcon() { GameObject prefab = PrefabManager.Cache.GetPrefab("HelmetDverger")?.gameObject; diff --git a/JotunnModStub/Sverm/SvermAntennae.cs b/JotunnModStub/Sverm/SvermAntennae.cs new file mode 100644 index 0000000..f256670 --- /dev/null +++ b/JotunnModStub/Sverm/SvermAntennae.cs @@ -0,0 +1,170 @@ +using System.Collections.Generic; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// Sensory Antennae: from The Elder on, a Sverm feels every living thing around it and reads + /// what each one is by colour. + /// + /// This is the Aswid's Auspex (AswidRace, the sensesCheckTimer loop) with one thing added: the + /// Aswid marks everything green because it only wants to know that something is THERE. An + /// insect's antennae are a chemical sense, and a chemical sense tells kin from prey from + /// threat - so the light is the same trick and the colour carries the information. + /// + /// red - hostile + /// yellow - invertebrate: kin, and by Hive Pheromones already harmless to you + /// azure - yours: tamed, and in due course the colony's own brood + /// green - alive and indifferent + /// + /// NOTHING HERE IS REPLICATED. A Light created on this client and parented to a creature costs + /// other players nothing and never touches the ZDO - the same reason the Aswid and the Dvergar + /// both mark with lights rather than with anything the server would have to carry. + /// + /// The cost that IS real is local: this is a passive with no cooldown, so in a busy forest it + /// can hold a dozen or more point lights at once, and Valheim renders few per pixel. If it + /// ever misbehaves the lever is the radius, not the mechanism. + /// + public static class SvermAntennae + { + private const string LightName = "SvermAntennaeLight"; + + private static readonly Dictionary lights = new Dictionary(); + private static readonly List stale = new List(); + + private static float nextSweep; + + public static void Tick(Player player) + { + bool active = player != null + && player == Player.m_localPlayer + && SvermVisuals.IsSvermPlayer(player) + && !player.IsDead() + && SvermProgression.Current.SensoryAntennae; + + if (!active) + { + ClearAll(); + return; + } + + if (Time.time < nextSweep) return; + nextSweep = Time.time + SvermConfig.AntennaeInterval; + + Sweep(player); + } + + private static void Sweep(Player player) + { + Vector3 centre = player.transform.position; + float radius = SvermConfig.AntennaeRadius; + + HashSet inRange = new HashSet(); + + foreach (Character c in Character.GetAllCharacters()) + { + if (c == null || c == player || c.IsDead()) continue; + if (Vector3.Distance(c.transform.position, centre) > radius) continue; + + inRange.Add(c); + + Color colour = ColourFor(player, c); + + if (lights.TryGetValue(c, out GameObject existing) && existing != null) + { + // Already lit. Only the colour can have changed - a boar that turns hostile, + // a creature that gets tamed - and re-colouring is cheaper than rebuilding. + Light live = existing.GetComponent(); + if (live != null && live.color != colour) live.color = colour; + continue; + } + + lights[c] = BuildLight(c, colour); + } + + // Anything no longer in range, or dead, or gone. Collected first and removed after: + // deleting from a dictionary while enumerating it throws. + stale.Clear(); + foreach (KeyValuePair pair in lights) + { + if (pair.Key == null || !inRange.Contains(pair.Key)) stale.Add(pair.Key); + } + + foreach (Character gone in stale) + { + if (lights.TryGetValue(gone, out GameObject go) && go != null) Object.Destroy(go); + lights.Remove(gone); + } + } + + /// + /// Order matters more than the colours do. + /// + /// Tamed is checked FIRST because a tamed wolf is still an enemy of nothing and a friend of + /// yours, and asking IsEnemy first would paint your own animals as threats. Invertebrates + /// come next because Hive Pheromones has already made them harmless, so calling them + /// hostile would contradict the rest of the race. Only then does the hostile test run, and + /// everything left over is simply alive. + /// + private static Color ColourFor(Player player, Character c) + { + if (c.IsTamed()) return SvermConfig.AntennaeKinColor; + + if (IsInvertebrate(c)) return SvermConfig.AntennaeInvertebrateColor; + + if (BaseAI.IsEnemy(player, c)) return SvermConfig.AntennaeHostileColor; + + return SvermConfig.AntennaePassiveColor; + } + + /// + /// The same substring test RaceHostilityManager uses for Hive Pheromones, and deliberately + /// so: whatever counts as kin for the truce has to count as kin for the antennae, or the + /// player is told one thing and shown another. + /// + private static bool IsInvertebrate(Character c) + { + string prefabName = c.gameObject.name.ToLowerInvariant(); + + if (prefabName.Contains("bonemass")) return false; + + return prefabName.Contains("blob") + || prefabName.Contains("leech") + || prefabName.Contains("tick") + || prefabName.Contains("deathsquito") + || prefabName.Contains("gjall") + || prefabName.Contains("seeker"); + } + + private static GameObject BuildLight(Character c, Color colour) + { + GameObject go = new GameObject(LightName); + go.transform.SetParent(c.transform); + go.transform.position = c.GetCenterPoint(); + + Light light = go.AddComponent(); + light.type = LightType.Point; + light.color = colour; + light.range = SvermConfig.AntennaeLightRange; + light.intensity = SvermConfig.AntennaeLightIntensity; + + // No shadows, ever. A dozen shadow-casting point lights in a forest is a slideshow, + // and none of these lights is meant to light the world - only to say "here". + light.shadows = LightShadows.None; + + return go; + } + + /// Puts out every light. Called when the perk stops applying, and on death. + public static void ClearAll() + { + if (lights.Count == 0) return; + + foreach (KeyValuePair pair in lights) + { + if (pair.Value != null) Object.Destroy(pair.Value); + } + lights.Clear(); + } + } +} diff --git a/JotunnModStub/Sverm/SvermBeehive.cs b/JotunnModStub/Sverm/SvermBeehive.cs new file mode 100644 index 0000000..bd0ad1e --- /dev/null +++ b/JotunnModStub/Sverm/SvermBeehive.cs @@ -0,0 +1,197 @@ +using System.Collections.Generic; +using Jotunn.Managers; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// The takeover of the ordinary beehives standing inside a nest's aura. + /// + /// A minute inside the aura and a hive stops being the player's and becomes the colony's: an + /// egg pushes out through the roof, and from then on it fills twice as fast and holds three + /// times as much. After Yagluth what comes out is royal jelly instead of honey. + /// + /// NOTHING IS CLONED AND NOTHING IS REPLACED. The vanilla Beehive component is retuned in + /// place on that one instance, and the state lives on that instance's ZDO - so an infected + /// hive stays infected across a reload, other players see the same thing, and a hive outside + /// any aura is never touched. The egg is a borrowed model parented to the hive, exactly the + /// way the crest is worn on a bone. + /// + /// Retuning a COMPONENT is safe where retuning m_shared would not be: m_secPerUnit lives on + /// the instance, not on shared item data, so one hive changing does not change every hive in + /// the world. + /// + public static class SvermBeehive + { + /// Written on the hive's own ZDO, so the takeover survives a reload. + private const string InfectedKey = "RacesOfValheim_SvermInfected"; + + /// When this hive first came under an aura, so the minute can be counted. + private const string ClaimedAtKey = "RacesOfValheim_SvermClaimedAt"; + + private const string EggName = "SvermHiveEgg"; + + /// Values captured before we touched them, so a hive can be handed back intact. + private static readonly Dictionary originalSecPerUnit = new Dictionary(); + + // ─── The sweep ─────────────────────────────────────────────────────── + + /// + /// Called by the nest, on a timer. Claims what is in range and ripens what has waited. + /// + public static void SweepAura(Vector3 nest) + { + foreach (Beehive hive in Find(nest)) + { + ZNetView nview = hive.GetComponent(); + if (nview == null || !nview.IsValid()) continue; + + if (nview.GetZDO().GetBool(InfectedKey, false)) + { + Apply(hive, nview); + continue; + } + + // First sighting starts the clock. Stored as world time rather than counted in a + // field, because a nest that unloads and comes back must not restart the minute. + double claimedAt = nview.GetZDO().GetFloat(ClaimedAtKey, 0f); + if (claimedAt <= 0.0) + { + nview.GetZDO().Set(ClaimedAtKey, (float)ZNet.instance.GetTimeSeconds()); + continue; + } + + if (ZNet.instance.GetTimeSeconds() - claimedAt < SvermConfig.BeehiveInfectionSeconds) continue; + + nview.GetZDO().Set(InfectedKey, true); + Apply(hive, nview); + + Jotunn.Logger.LogInfo("[Sverm] A beehive has been taken over by the colony."); + } + } + + /// + /// Retunes one infected hive and makes sure it is wearing its egg. + /// + /// Re-applied on every sweep rather than once at infection: Valheim rebuilds these + /// components when the zone reloads, and a hive that came back at vanilla speed would + /// quietly undo the whole feature with nothing in the log to say so. + /// + private static void Apply(Beehive hive, ZNetView nview) + { + if (!originalSecPerUnit.ContainsKey(hive)) originalSecPerUnit[hive] = hive.m_secPerUnit; + + float wanted = originalSecPerUnit[hive] / SvermConfig.BeehiveSpeedMultiplier; + if (!Mathf.Approximately(hive.m_secPerUnit, wanted)) hive.m_secPerUnit = wanted; + + int wantedMax = Mathf.RoundToInt(SvermConfig.BeehiveBaseMaxHoney * SvermConfig.BeehiveCapacityMultiplier); + if (hive.m_maxHoney != wantedMax) hive.m_maxHoney = wantedMax; + + // After Yagluth the colony stops making honey and starts making royal jelly. Read from + // ObjectDB rather than held as a reference, because the item has to exist first. + string wantedItem = BossProgressionManager.GetCurrentProgressionState() >= SvermConfig.RoyalJellyHiveState + ? SvermConfig.RoyalJellyPrefab + : "Honey"; + + if (hive.m_honeyItem == null || hive.m_honeyItem.gameObject.name != wantedItem) + { + ItemDrop replacement = PrefabManager.Cache.GetPrefab(wantedItem); + if (replacement != null) hive.m_honeyItem = replacement; + } + + EnsureEgg(hive.transform); + } + + /// + /// The egg on the roof: a permanent mark, and the only way to tell an infected hive from an + /// ordinary one at a glance. + /// + /// Borrowed through ModelBorrow, so it arrives stripped of its ItemDrop and its networking + /// and cannot be picked up, walked into, or dropped on the floor. + /// + private static void EnsureEgg(Transform hive) + { + if (hive.Find(EggName) != null) return; + + ModelBorrow.Attach( + hive, + EggName, + SvermConfig.HiveEggPrefab, + Vector3.up * SvermConfigManagement.EggHeight, + Quaternion.identity, + SvermConfigManagement.EggSize, + "Sverm"); + } + + // ─── Lookups ───────────────────────────────────────────────────────── + + /// Every beehive standing inside a nest's aura. + public static List Find(Vector3 nest) + { + List found = new List(); + + foreach (Collider collider in Physics.OverlapSphere(nest, SvermConfig.HiveAuraRadius)) + { + if (collider == null) continue; + + Beehive hive = collider.GetComponentInParent(); + if (hive != null && !found.Contains(hive)) found.Add(hive); + } + + return found; + } + + public static int CountInAura(Vector3 nest) => Find(nest).Count; + + public static int CountInfectedInAura(Vector3 nest) + { + int count = 0; + foreach (Beehive hive in Find(nest)) + { + if (IsInfected(hive)) count++; + } + return count; + } + + /// + /// Puts the colony's marks on every taken hive in range: flies always, green gas only when + /// the hive is FULL and has nothing left to do but wait for someone to empty it. + /// + /// Called by the nest on every client, not from the owner's sweep - particles are local, and + /// a hive that only smoked on the host's screen would be half a feature. + /// + public static void DressInfected(Vector3 nest) + { + float scale = SvermConfigManagement.BeehiveVfxScale; + + foreach (Beehive hive in Find(nest)) + { + if (!IsInfected(hive)) continue; + + SvermHiveVfx.EnsureFlies(hive.transform, scale); + SvermHiveVfx.SetGas(hive.transform, IsFull(hive), scale); + } + } + + /// + /// Whether the hive has no room left for honey. + /// + /// GetHoneyLevel is private in the assembly this project compiles against - like + /// Container.Save and Inventory.FindEmptySlot - so it is read through Traverse rather than + /// called, and rather than second-guessed by reading the ZDO key by hand. + /// + private static bool IsFull(Beehive hive) + { + if (hive == null) return false; + + int level = HarmonyLib.Traverse.Create(hive).Method("GetHoneyLevel").GetValue(); + return level >= hive.m_maxHoney; + } + + public static bool IsInfected(Beehive hive) + { + ZNetView nview = hive != null ? hive.GetComponent() : null; + return nview != null && nview.IsValid() && nview.GetZDO().GetBool(InfectedKey, false); + } + } +} diff --git a/JotunnModStub/Sverm/SvermBiomass.cs b/JotunnModStub/Sverm/SvermBiomass.cs new file mode 100644 index 0000000..e951543 --- /dev/null +++ b/JotunnModStub/Sverm/SvermBiomass.cs @@ -0,0 +1,243 @@ +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// The nest's tank, and the rule for what may go into it. + /// + /// The number lives on the nest's own ZDO rather than in a field, so it survives a reload, a + /// zone unload, and a different player walking up to the same nest. + /// + /// WHAT COUNTS AS FUEL is the part worth reading. Anything the Sverm could eat, at half its + /// nutritional sum, plus a flat rate for wood and resin - EXCEPT honey and royal jelly, which + /// stopped being fuel the moment they became medicine. Feeding the colony its own healing + /// supply would be the worst kind of bug: quiet, expensive, and entirely the mod's fault. + /// + public static class SvermBiomass + { + // ─── What burns ────────────────────────────────────────────────────── + + public static bool IsFuel(ItemDrop.ItemData item) + { + if (item == null || item.m_shared == null) return false; + + string prefabName = item.m_dropPrefab != null ? item.m_dropPrefab.name : ""; + + // The medicine. Explicitly first, so no later rule can accidentally readmit it. + if (prefabName == "Honey" || prefabName == SvermConfig.RoyalJellyPrefab) return false; + + if (IsWood(prefabName)) return true; + + return item.m_shared.m_food + item.m_shared.m_foodStamina + item.m_shared.m_foodEitr > 0f; + } + + /// + /// Wood and resin, at a flat rate regardless of biome. Ashwood is out. + /// + /// Flat because a per-biome table for firewood is a lot of bookkeeping for a resource whose + /// whole job is to be the bulk filler while food is the concentrate. + /// + private static bool IsWood(string prefabName) + { + if (string.IsNullOrEmpty(prefabName)) return false; + if (prefabName.ToLowerInvariant().Contains("ash")) return false; // ashwood excluded + + return prefabName == "Wood" + || prefabName == "RoundLog" + || prefabName == "FineWood" + || prefabName == "ElderBark" + || prefabName == "YggdrasilWood" + || prefabName == "Resin"; + } + + /// What one of this item is worth in the tank. + public static float ValueOf(ItemDrop.ItemData item) + { + if (!IsFuel(item)) return 0f; + + string prefabName = item.m_dropPrefab != null ? item.m_dropPrefab.name : ""; + if (IsWood(prefabName)) return SvermConfig.WoodBiomassValue; + + return (item.m_shared.m_food + item.m_shared.m_foodStamina + item.m_shared.m_foodEitr) * 0.5f; + } + + // ─── The tank ──────────────────────────────────────────────────────── + // + // THREE NUMBERS, NOT ONE, and the middle one is the whole point of the shop. What the hive + // has just been handed is not what the hive can spend: everything it eats lands in + // DIGESTION and seeps into the BANK at a fixed rate, and only the bank ever pays for + // anything. CAPACITY is the stage's ceiling and it covers both together, because a stomach + // that is full is full whether or not the last meal has gone down yet. + + // The bank keeps the key the tank has always had, so a hive standing in somebody's world + // reads back with its biomass intact rather than at zero. + private const string BankKey = "RacesOfValheim_SvermBiomass"; // spendable + private const string DigestKey = "RacesOfValheim_SvermDigesting"; // eaten, not yet spendable + private const string ClockKey = "RacesOfValheim_SvermDigestedAt"; // world second of the last digest + + /// What the hive can actually spend. + public static float Bank(Transform nest) + { + ZDO zdo = Zdo(nest); + return zdo != null ? zdo.GetFloat(BankKey, 0f) : 0f; + } + + /// Eaten but not yet spendable. + public static float Digesting(Transform nest) + { + ZDO zdo = Zdo(nest); + return zdo != null ? zdo.GetFloat(DigestKey, 0f) : 0f; + } + + public static float Capacity(Transform nest) + { + return SvermHiveStage.Capacity(SvermHiveStage.Of(nest)); + } + + /// How much more the hive can hold, digested or not. + public static float Space(Transform nest) + { + return Mathf.Max(0f, Capacity(nest) - Bank(nest) - Digesting(nest)); + } + + /// Adds one item's worth. Returns what actually fitted. + public static float Deposit(Transform nest, ItemDrop.ItemData item) + { + return Swallow(nest, ValueOf(item)); + } + + /// + /// Puts raw biomass into digestion, clamped to what is left of the tank. Returns what fitted. + /// + /// EVERYTHING the hive eats comes through here - the shop's one button and the haulers' + /// chest round alike. A meal that arrived by way of a chest is still a meal, and giving the + /// haulers a shortcut straight into the bank would make the wait the shop imposes + /// avoidable by anyone who owns a box. + /// + public static float Swallow(Transform nest, float amount) + { + if (amount <= 0f) return 0f; + + ZNetView nview = Claim(nest); + if (nview == null) return 0f; + + float accepted = Mathf.Min(amount, Space(nest)); + if (accepted <= 0f) return 0f; + + ZDO zdo = nview.GetZDO(); + + // The clock is started by the first mouthful and not before: an untouched hive has no + // "last digested" second, and reading a missing key as zero would hand it every second + // since the world began the moment it was finally fed. + // + // WHOLE SECONDS IN A LONG FIELD, deliberately and everywhere. ZDO.Set takes a long as + // readily as a float, and a clock written through one overload and read through the + // other is a key that always answers with its default - which here means an elapsed + // time of zero, forever, and a hive that digests nothing at all. + if (zdo.GetFloat(DigestKey, 0f) <= 0f) zdo.Set(ClockKey, WorldSecond()); + + zdo.Set(DigestKey, zdo.GetFloat(DigestKey, 0f) + accepted); + return accepted; + } + + /// + /// Moves what time has earned from digestion into the bank. + /// + /// Measured against the WORLD clock rather than frames, so a hive nobody is standing next + /// to still digests: come back to it in the morning and the meal has gone down. The owner + /// calls this on a timer - see SvermHiveBehaviour. + /// + public static void Digest(Transform nest) + { + ZNetView nview = nest != null ? nest.GetComponent() : null; + if (nview == null || !nview.IsValid() || !nview.IsOwner()) return; + + ZDO zdo = nview.GetZDO(); + float digesting = zdo.GetFloat(DigestKey, 0f); + if (digesting <= 0f) return; + + long now = WorldSecond(); + long last = zdo.GetLong(ClockKey, now); + long elapsed = now - last; + + // Whole seconds only, and the clock only moves by what was actually consumed, so the + // fraction left over is not quietly lost on every tick. + if (elapsed <= 0L) return; + + float moved = Mathf.Min(digesting, SvermConfigManagement.DigestRate * elapsed); + zdo.Set(ClockKey, now); + if (moved <= 0f) return; + + zdo.Set(DigestKey, digesting - moved); + zdo.Set(BankKey, zdo.GetFloat(BankKey, 0f) + moved); + } + + /// + /// Puts spent biomass straight back in the bank, past the digestion. + /// + /// Only ever for a purchase that was paid for and then could not be delivered. It skips the + /// digestion on purpose: the hive already digested this once, and making the player wait + /// again for a thing they did not get would be a second punishment for our own race. + /// + public static void Refund(Transform nest, float amount) + { + if (amount <= 0f) return; + + ZNetView nview = Claim(nest); + if (nview == null) return; + + ZDO zdo = nview.GetZDO(); + zdo.Set(BankKey, Mathf.Min(zdo.GetFloat(BankKey, 0f) + amount, Capacity(nest))); + } + + /// Takes from the bank if there is enough. All or nothing. + public static bool Spend(Transform nest, float amount) + { + ZNetView nview = Claim(nest); + if (nview == null) return false; + + ZDO zdo = nview.GetZDO(); + float bank = zdo.GetFloat(BankKey, 0f); + if (bank < amount) return false; + + zdo.Set(BankKey, bank - amount); + return true; + } + + // ─── Plumbing ──────────────────────────────────────────────────────── + + private static ZDO Zdo(Transform nest) + { + ZNetView nview = nest != null ? nest.GetComponent() : null; + return nview != null && nview.IsValid() ? nview.GetZDO() : null; + } + + /// + /// The nest's view, owned by us before we write to it. + /// + /// A write to a ZDO somebody else owns survives until their copy comes back over the wire + /// and overwrites it - which reads, to the player who just sold half their larder, as the + /// hive having eaten it and forgotten. + /// + private static ZNetView Claim(Transform nest) + { + ZNetView nview = nest != null ? nest.GetComponent() : null; + if (nview == null || !nview.IsValid()) return null; + if (!nview.IsOwner()) nview.ClaimOwnership(); + return nview; + } + + /// + /// The world clock in whole seconds. + /// + /// The world's own time and not Time.time, so the answer means the same thing to a hive + /// that has just loaded as to one that has been standing there all evening. Zero when there + /// is no net yet, which only happens before a world is up - and Digest reads a missing + /// clock as "now", so nothing is ever handed a windfall. + /// + private static long WorldSecond() + { + return ZNet.instance != null ? (long)ZNet.instance.GetTimeSeconds() : 0L; + } + } +} diff --git a/JotunnModStub/Sverm/SvermBlisterTick.cs b/JotunnModStub/Sverm/SvermBlisterTick.cs new file mode 100644 index 0000000..f8c0869 --- /dev/null +++ b/JotunnModStub/Sverm/SvermBlisterTick.cs @@ -0,0 +1,289 @@ +using Jotunn.Managers; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// The Blister Tick: fifty biomass buys a SLOT, and the slot is forever. + /// + /// SECTION 12, and it is the one troop that does not behave like the others. It runs at what the + /// colony is fighting and bursts. It leaves nothing behind, it heals nothing, and it does not + /// need to: thirty seconds after it dies the nest grows another one, free - no egg, no biomass. + /// The slot that was paid for is permanent, exactly like the Skeleton's chains, and ten of them + /// coming back every half minute is a continuous stream of explosions rather than a squad. That + /// is the whole point of the unit and the reason its damage is borrowed from two bombs the game + /// already balanced instead of from a number somebody invented. + /// + /// THE DAMAGE IS READ, NOT COPIED: the poison blob's own projectile prefab is asked what it + /// hits for, once, at registration. Ooze up to the second stage of the nest, the elite blob + /// after that - section 12's "BombOoze then BombBile" expressed in the two projectiles this + /// build actually ships. + /// + public static class SvermBlisterTick + { + public const string PrefabName = "SvermBlisterTick"; + public const string DisplayName = "Blister Tick"; + private const string SourcePrefab = "Tick"; + + /// How many slots this nest has bought. Permanent, and the respawn reads it. + private const string SlotKey = "RacesOfValheim_SvermTickSlots"; + + /// The blast, in rising order of nastiness. Both are verified manifest names. + private const string EarlyBlast = "BombBlob_Poison_projectile"; + private const string LateBlast = "BombBlob_PoisonElite_projectile"; + private const string BlastEffect = "BombBlob_explode_poison"; + + private static HitData.DamageTypes earlyDamage; + private static HitData.DamageTypes lateDamage; + private static float blastRadius = 4f; + + // ─── Registration ──────────────────────────────────────────────────── + + public static void Register() + { + GameObject source = PrefabManager.Cache.GetPrefab(SourcePrefab); + if (source == null) + { + Jotunn.Logger.LogWarning($"[Sverm] No '{SourcePrefab}' to build the Blister Tick from; no ticks."); + return; + } + + GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(PrefabName, source); + if (prefab == null) return; + + Character character = prefab.GetComponent(); + if (character != null) character.m_name = DisplayName; + + BaseAI ai = prefab.GetComponent(); + if (ai != null) ai.m_randomMoveRange = SvermConfig.TroopLeashRange; + + // Nothing to farm off something that respawns for free forever. This one matters more + // than on the other troops for exactly that reason. + foreach (CharacterDrop drops in prefab.GetComponentsInChildren(true)) + { + if (drops != null) Object.DestroyImmediate(drops); + } + + RaisedThrall thrall = prefab.AddComponent(); + thrall.m_kind = PrefabName; + thrall.m_commandingRace = SvermConfig.RaceId; + thrall.m_maxFollowers = -1; + thrall.m_witherSeconds = SvermConfig.TroopWitherSeconds; + thrall.m_homeCheckRange = SvermConfig.TroopHomeCheckRange; + thrall.m_refusalMessage = "It does not smell your colony on you."; + + // No SkeletonSentryBehaviour. A tick that healed itself would be a tick that never gets + // round to exploding, which is its entire job. + prefab.AddComponent(); + + ReadBlastDamage(); + + PrefabManager.Instance.AddPrefab(prefab); + Jotunn.Logger.LogInfo($"[Sverm] Registered '{PrefabName}' from '{SourcePrefab}'."); + } + + /// + /// Asks the two blob projectiles what they hit for, once. A missing one leaves its stage on + /// the fallback rather than on zero - a tick that exploded for nothing would look like it + /// was working. + /// + private static void ReadBlastDamage() + { + earlyDamage = DamageOf(EarlyBlast, SvermConfig.TickFallbackDamage); + lateDamage = DamageOf(LateBlast, SvermConfig.TickFallbackDamage * 2f); + } + + private static HitData.DamageTypes DamageOf(string projectileName, float fallbackPoison) + { + GameObject prefab = PrefabManager.Cache.GetPrefab(projectileName); + Projectile projectile = prefab != null ? prefab.GetComponent() : null; + + if (projectile == null) + { + Jotunn.Logger.LogWarning($"[Sverm] No '{projectileName}' to price the Blister Tick's blast; " + + $"it falls back to {fallbackPoison:0} poison."); + return new HitData.DamageTypes { m_poison = fallbackPoison }; + } + + if (projectile.m_aoe > 0f) blastRadius = projectile.m_aoe; + return projectile.m_damage; + } + + /// What one blast does, at this nest's stage. Section 12's two tiers. + public static HitData.DamageTypes BlastFor(int stage) + { + return stage >= SvermConfig.TickLateBlastStage ? lateDamage : earlyDamage; + } + + public static float BlastRadius => blastRadius; + + public static GameObject BlastVfx() + { + return PrefabManager.Cache.GetPrefab(BlastEffect); + } + + // ─── The slots ─────────────────────────────────────────────────────── + + public static int SlotsOf(Transform nest) + { + ZNetView nview = nest != null ? nest.GetComponent() : null; + if (nview == null || !nview.IsValid()) return 0; + + return Mathf.Clamp(nview.GetZDO().GetInt(SlotKey, 0), 0, SvermConfigManagement.BlisterTick); + } + + public static void BuySlot(Transform nest) + { + ZNetView nview = nest != null ? nest.GetComponent() : null; + if (nview == null || !nview.IsValid()) return; + + if (!nview.IsOwner()) nview.ClaimOwnership(); + nview.GetZDO().Set(SlotKey, SlotsOf(nest) + 1); + } + + /// How many are alive right now, counted off the nest the way the roster is. + public static int CountAlive(SvermHiveBehaviour hive) + { + if (hive == null) return 0; + + int count = 0; + foreach (RaisedThrall thrall in RaisedThrall.BoundTo(hive.transform.position)) + { + if (thrall != null && thrall.Kind == PrefabName) count++; + } + return count; + } + + /// + /// Fills the empty slots, free. Called by the nest on its own timer, owner only. + /// + /// One per call rather than all at once: ten ticks arriving in the same frame after a fight + /// would be a wall of bodies, and a slot every half minute is what the design asks for. + /// + public static void Replace(SvermHiveBehaviour hive) + { + if (hive == null) return; + + int slots = SlotsOf(hive.transform); + if (slots <= 0 || CountAlive(hive) >= slots) return; + + Hatch(hive); + } + + public static bool Hatch(SvermHiveBehaviour hive) + { + GameObject prefab = ZNetScene.instance != null ? ZNetScene.instance.GetPrefab(PrefabName) : null; + if (prefab == null) return false; + + Vector3 offset = Random.insideUnitSphere * 2f; + offset.y = 0f; + GameObject spawned = Object.Instantiate(prefab, hive.transform.position + offset + Vector3.up * 0.5f, + Quaternion.Euler(0f, Random.Range(0, 360), 0f)); + if (spawned == null) return false; + + Character character = spawned.GetComponent(); + if (character != null) + { + int stars = SvermBroodStars.Of(hive.transform); + if (stars > 0) character.SetLevel(1 + stars); + } + + RaisedThrall thrall = spawned.GetComponent(); + if (thrall != null) thrall.Bind(hive.transform.position); + + return true; + } + } + + /// + /// One tick's short life: get close to something the colony is fighting, and burst. + /// + /// It goes off on ITS OWN TARGET and not on anything that happens to be near. A tick that + /// exploded because a boar walked past would clear its own base of livestock, and one that went + /// off next to the player it was following would be a trap rather than a weapon - so the blast + /// spares everything tame, the player included. + /// + public class SvermBlisterTickBehaviour : MonoBehaviour + { + private Character m_character; + private MonsterAI m_ai; + private ZNetView m_nview; + private bool m_bursting; + + private void Awake() + { + m_character = GetComponent(); + m_ai = GetComponent(); + m_nview = GetComponent(); + + InvokeRepeating("TickCheck", 1f, 0.5f); + } + + private void TickCheck() + { + if (m_bursting) return; + if (m_character == null || m_character.IsDead()) return; + if (m_nview == null || !m_nview.IsValid() || !m_nview.IsOwner()) return; + if (m_ai == null) return; + + Character target = m_ai.GetTargetCreature(); + if (target == null || target.IsDead()) return; + + if (Vector3.Distance(transform.position, target.transform.position) > SvermConfig.TickBurstRange) return; + + Burst(); + } + + private void Burst() + { + m_bursting = true; + + Vector3 where = transform.position + Vector3.up * 0.3f; + + GameObject vfx = SvermBlisterTick.BlastVfx(); + if (vfx != null) Object.Instantiate(vfx, where, Quaternion.identity); + + // The stage of whichever nest it belongs to. A tick whose nest has been torn down still + // bursts - at the early damage, which is the honest answer when there is nobody left to + // ask. + int stage = SvermHiveStage.First; + RaisedThrall thrall = GetComponent(); + Vector3? anchor = thrall != null ? thrall.Anchor : null; + if (anchor != null) + { + SvermHiveBehaviour nest = SvermHive.NearestNest(anchor.Value, 2f); + if (nest != null) stage = SvermHiveStage.Of(nest.transform); + } + + HitData.DamageTypes damage = SvermBlisterTick.BlastFor(stage); + + foreach (Collider collider in Physics.OverlapSphere(where, SvermBlisterTick.BlastRadius)) + { + if (collider == null) continue; + + Character victim = collider.GetComponentInParent(); + if (victim == null || victim == m_character || victim.IsDead()) continue; + + // Everything of ours walks away from this: the player, their tames, and every other + // thing the colony has hatched. + if (victim.IsPlayer() || victim.IsTamed()) continue; + + HitData hit = new HitData(); + hit.m_damage = damage; + hit.m_point = victim.GetCenterPoint(); + hit.m_dir = (victim.transform.position - where).normalized; + hit.SetAttacker(m_character); + victim.Damage(hit); + } + + // Its own death is the cost of the attack, and it is what the free respawn is measured + // from: the nest sees an empty slot and grows another. + // + // Killed through RaisedThrall.Kill rather than by writing health to zero, because that + // is the one path in this mod already proven to take a summoned creature all the way + // through the game's own death sequence. + if (thrall != null) thrall.Kill(); + else m_character.SetHealth(0f); + } + } +} diff --git a/JotunnModStub/Sverm/SvermBrood.cs b/JotunnModStub/Sverm/SvermBrood.cs new file mode 100644 index 0000000..1d52a0e --- /dev/null +++ b/JotunnModStub/Sverm/SvermBrood.cs @@ -0,0 +1,293 @@ +using System.Collections.Generic; +using Jotunn.Managers; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// The army: four creatures, hatched at the market, bound to the nest that paid for them. + /// + /// TWO RESOURCES IN PARALLEL, which is section 10.2 and the whole shape of the colony. The EGG + /// is the slot and it grows back on its own; the BIOMASS is the price and it does not. A troop + /// needs both, so a hive with a full tank and no eggs waits, and a hive full of eggs and no + /// biomass waits differently. + /// + /// Nothing here is new machinery. A troop is a RaisedThrall - the same component the Draugh's + /// spawner, the Dvergar's bank and the Fenrir's trough hang their rosters on - so the follow and + /// stay orders, the leash, the walk home and the withering when the station falls all come for + /// free and behave exactly like every other summoned thing in the mod. The self-healing is + /// SkeletonSentryBehaviour, reused whole, which is section 11.2 word for word. + /// + public static class SvermBrood + { + /// + /// What every troop prefab's name starts with. One place, because two things ask the + /// question "is this creature one of ours" - the roster and the medicine. + /// + public const string PrefabPrefix = "SvermTroop_"; + + /// One rung of the ladder, from section 11's table. + public class Kind + { + public string Id; + public string Display; + public string Source; // the vanilla creature it is cloned from + public string Icon; + public float Price; + public int Stage; // the nest stage it becomes available at + public float Cooldown; // seconds between two of these + + public string PrefabName => PrefabPrefix + Source; + public int Cap => CapOf(Id); + } + + /// + /// Section 11's table, prices and caps and stage gates unchanged. + /// + /// The cooldowns are section 20.4's: ten minutes for a Gjall and "the others scaled + /// accordingly", which is read here as scaled BY PRICE - a Brood is a tenth of a Gjall in + /// biomass, so it is a tenth of a Gjall in patience too. + /// + public static readonly List Roster = new List + { + new Kind { Id = "brood", Display = "Brood", Source = "SeekerBrood", Icon = "TrophySeeker", Price = 100f, Stage = 1, Cooldown = 60f }, + new Kind { Id = "seeker", Display = "Seeker", Source = "Seeker", Icon = "TrophySeeker", Price = 250f, Stage = 2, Cooldown = 150f }, + new Kind { Id = "soldier", Display = "Soldier", Source = "SeekerBrute", Icon = "TrophySeekerBrute", Price = 500f, Stage = 3, Cooldown = 300f }, + new Kind { Id = "gjall", Display = "Gjall", Source = "Gjall", Icon = "TrophyGjall", Price = 1000f, Stage = 4, Cooldown = 600f }, + }; + + private static int CapOf(string id) + { + switch (id) + { + case "brood": return SvermConfigManagement.Brood; + case "seeker": return SvermConfigManagement.Seeker; + case "soldier": return SvermConfigManagement.Soldier; + case "gjall": return SvermConfigManagement.Gjall; + default: return 0; + } + } + + // ─── Registration ──────────────────────────────────────────────────── + + public static void Register() + { + foreach (Kind kind in Roster) RegisterOne(kind); + } + + /// + /// One troop prefab: the vanilla creature, tamed at spawn, leashed, healing, worth nothing dead. + /// + /// The drop table goes for the reason it always goes here - a troop that dropped seeker parts + /// would turn the colony into a trophy farm, and the biomass would be paying for itself. + /// + private static void RegisterOne(Kind kind) + { + GameObject source = PrefabManager.Cache.GetPrefab(kind.Source); + if (source == null) + { + Jotunn.Logger.LogWarning($"[Sverm] No '{kind.Source}' to build the {kind.Display} from; " + + "that rung of the roster is missing."); + return; + } + + GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(kind.PrefabName, source); + if (prefab == null) return; + + BaseAI ai = prefab.GetComponent(); + if (ai != null) ai.m_randomMoveRange = SvermConfig.TroopLeashRange; + + foreach (CharacterDrop drops in prefab.GetComponentsInChildren(true)) + { + if (drops != null) Object.DestroyImmediate(drops); + } + + RaisedThrall thrall = prefab.AddComponent(); + thrall.m_kind = kind.PrefabName; + thrall.m_commandingRace = SvermConfig.RaceId; + thrall.m_maxFollowers = -1; // the cap is the colony's, counted at the nest, not per player + thrall.m_witherSeconds = SvermConfig.TroopWitherSeconds; + thrall.m_homeCheckRange = SvermConfig.TroopHomeCheckRange; + thrall.m_refusalMessage = "It does not smell your colony on you."; + + // Section 11.2, reused whole: ten seconds untouched, then two percent a second. Healing + // and not respawning - a dead troop is dead, and the egg it cost is already back. + prefab.AddComponent(); + + PrefabManager.Instance.AddPrefab(prefab); + Jotunn.Logger.LogInfo($"[Sverm] Registered '{kind.PrefabName}' for the {kind.Display}."); + } + + // ─── Counting and hatching ─────────────────────────────────────────── + + /// + /// How many of this kind this nest has alive. + /// + /// Counted off the thralls bound to the nest, which is the same answer every other station in + /// the mod gives - and carries the same honest limit: it can only see creatures that are + /// loaded. A troop in an unloaded zone is not counted, so a cap can be briefly exceeded by + /// hatching a replacement for something that is still alive far away. + /// + public static int CountAlive(SvermHiveBehaviour hive, Kind kind) + { + if (hive == null || kind == null) return 0; + + int count = 0; + foreach (RaisedThrall thrall in RaisedThrall.BoundTo(hive.transform.position)) + { + if (thrall != null && thrall.Kind == kind.PrefabName) count++; + } + return count; + } + + /// + /// Puts one on the ground beside the nest, bound to it and born at whatever star the colony + /// has bought. + /// + public static bool Hatch(SvermHiveBehaviour hive, Kind kind) + { + if (hive == null || kind == null) return false; + + GameObject prefab = ZNetScene.instance != null ? ZNetScene.instance.GetPrefab(kind.PrefabName) : null; + if (prefab == null) + { + Jotunn.Logger.LogWarning($"[Sverm] No '{kind.PrefabName}' in ZNetScene; the {kind.Display} " + + "could not be hatched."); + return false; + } + + Vector3 offset = Random.insideUnitSphere * 2f; + offset.y = 0f; + Vector3 where = hive.transform.position + offset + Vector3.up * 0.5f; + + GameObject spawned = Object.Instantiate(prefab, where, Quaternion.Euler(0f, Random.Range(0, 360), 0f)); + if (spawned == null) return false; + + // The stars, and this is the ONLY thing the two star upgrades do: they are read here, at + // birth, so everything bought before them stays as it was born. Section 14's "valgono su + // tutto quello che nasce DOPO l'acquisto", enforced by the fact that nothing goes back + // and re-levels anyone. + Character character = spawned.GetComponent(); + if (character != null) + { + int stars = SvermBroodStars.Of(hive.transform); + if (stars > 0) character.SetLevel(1 + stars); + } + + RaisedThrall thrall = spawned.GetComponent(); + if (thrall != null) thrall.Bind(hive.transform.position); + + return true; + } + } + + /// + /// The brood eggs: the slot half of the price, section 10.2. + /// + /// One every twenty seconds up to five plus the stage, and it is worked out from the WORLD CLOCK + /// rather than ticked - the same trick the digestion uses. A nest nobody is standing next to + /// still fills its clutch, and there is no timer to lose when a zone unloads. + /// + public static class SvermBroodEggs + { + private const string EggKey = "RacesOfValheim_SvermEggs"; + private const string ClockKey = "RacesOfValheim_SvermEggAt"; + + public static int Cap(Transform nest) + { + return SvermConfig.EggCapBase + SvermHiveStage.Of(nest); + } + + /// What the clutch holds right now, without writing anything. + public static int Count(Transform nest) + { + ZNetView nview = View(nest); + if (nview == null) return 0; + + ZDO zdo = nview.GetZDO(); + int stored = zdo.GetInt(EggKey, 0); + long clock = zdo.GetLong(ClockKey, 0L); + + // A clutch that has never been settled has no elapsed time to claim. Reading a missing + // clock as zero would hand a brand new nest every egg since the world began. + if (clock <= 0L) return Mathf.Clamp(stored, 0, Cap(nest)); + + long elapsed = WorldSecond() - clock; + int laid = elapsed > 0L ? (int)(elapsed / SvermConfig.EggInterval) : 0; + + return Mathf.Clamp(stored + laid, 0, Cap(nest)); + } + + /// + /// Writes down what time has laid and restarts the clock. The owner calls this on a timer so + /// the number the other clients read is never far behind. + /// + public static void Settle(Transform nest) + { + ZNetView nview = View(nest); + if (nview == null || !nview.IsOwner()) return; + + ZDO zdo = nview.GetZDO(); + int now = Count(nest); + + zdo.Set(EggKey, now); + zdo.Set(ClockKey, WorldSecond()); + } + + /// Takes eggs out of the clutch. All or nothing. + public static bool Take(Transform nest, int howMany) + { + ZNetView nview = View(nest); + if (nview == null) return false; + + int have = Count(nest); + if (have < howMany) return false; + + if (!nview.IsOwner()) nview.ClaimOwnership(); + nview.GetZDO().Set(EggKey, have - howMany); + nview.GetZDO().Set(ClockKey, WorldSecond()); + return true; + } + + private static ZNetView View(Transform nest) + { + ZNetView nview = nest != null ? nest.GetComponent() : null; + return nview != null && nview.IsValid() ? nview : null; + } + + private static long WorldSecond() + { + return ZNet.instance != null ? (long)ZNet.instance.GetTimeSeconds() : 0L; + } + } + + /// + /// Surrenal Glands and Hyperplasia: what star the colony's troops are born at. + /// + /// One number on the nest, 0 to 2, and it is read at the moment a troop is hatched and never + /// again. Everything already walking around keeps the stars it was born with, which is the + /// document's own rule and also the only version that does not need to find and re-level a + /// garrison spread over half the map. + /// + public static class SvermBroodStars + { + private const string StarKey = "RacesOfValheim_SvermStars"; + + public static int Of(Transform nest) + { + ZNetView nview = nest != null ? nest.GetComponent() : null; + if (nview == null || !nview.IsValid()) return 0; + + return Mathf.Clamp(nview.GetZDO().GetInt(StarKey, 0), 0, 2); + } + + public static void Set(Transform nest, int stars) + { + ZNetView nview = nest != null ? nest.GetComponent() : null; + if (nview == null || !nview.IsValid()) return; + + if (!nview.IsOwner()) nview.ClaimOwnership(); + nview.GetZDO().Set(StarKey, Mathf.Clamp(stars, 0, 2)); + } + } +} diff --git a/JotunnModStub/Sverm/SvermCarapace.cs b/JotunnModStub/Sverm/SvermCarapace.cs new file mode 100644 index 0000000..03b74d7 --- /dev/null +++ b/JotunnModStub/Sverm/SvermCarapace.cs @@ -0,0 +1,133 @@ +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// The carapace: chest, legs and helmet, permanently, at every tier. + /// + /// WHAT IT IS WORTH IS NOT WRITTEN DOWN. Each tier names a vanilla set in SvermConfig, and the + /// armour value is that set's three pieces read off ObjectDB and priced at quality 4. The race + /// therefore tracks vanilla's own balance forever: if a game patch buffs iron, the Sverm's + /// third tier is buffed with it, and nobody has to remember this file exists. + /// + /// The lookup is cached per state and not per frame on purpose - GetBodyArmor runs from the + /// HUD and from every damage calculation, and ObjectDB.GetItemPrefab is a dictionary hit plus + /// a GetComponent on each of three prefabs. + /// + /// Resolution is deferred rather than done at startup: ObjectDB is not populated when the + /// plugin wakes, so the first caller inside a world is what fills the cache. A missing prefab + /// contributes zero and logs once, so a renamed vanilla item costs a warning and a soft tier + /// rather than a null-reference in the damage path. + /// + public static class SvermCarapace + { + private static readonly float[] armorCache = new float[BossProgressionManager.MaxState + 1]; + private static readonly bool[] armorCached = new bool[BossProgressionManager.MaxState + 1]; + + private static float eitrRegenReference = -1f; + + /// + /// Total armour the carapace is worth at this tier: the three reference pieces at quality + /// 4, plus the hand-picked Fader bonus, which is the one number in the race that is chosen + /// rather than derived - there is no biome after the Ashlands to read a set from. + /// + public static float GetArmor(int state) + { + state = Mathf.Clamp(state, BossProgressionManager.MinState, BossProgressionManager.MaxState); + if (armorCached[state]) return armorCache[state]; + + if (ObjectDB.instance == null) return 0f; // too early; do not poison the cache + + float total = 0f; + string[] set = SvermConfig.ArmorReferenceSets[state]; + if (set != null) + { + foreach (string prefabName in set) + { + total += ArmorOf(prefabName); + } + } + + if (state >= SvermConfig.AnnealedChitinState) total += SvermConfig.FaderArmorBonus; + + armorCache[state] = total; + armorCached[state] = true; + + Jotunn.Logger.LogInfo($"[Sverm] Carapace tier {state} priced at {total:0.#} armour " + + $"from {(set == null ? "nothing" : string.Join(" + ", set))} at quality " + + $"{SvermConfig.ArmorReferenceQuality}."); + return total; + } + + /// Armour of one vanilla piece at the reference quality, or 0 with a warning. + private static float ArmorOf(string prefabName) + { + GameObject prefab = ObjectDB.instance.GetItemPrefab(prefabName); + if (prefab == null) + { + Jotunn.Logger.LogWarning($"[Sverm] No item '{prefabName}' to price the carapace from; " + + "it contributes nothing to this tier."); + return 0f; + } + + ItemDrop drop = prefab.GetComponent(); + if (drop == null || drop.m_itemData == null || drop.m_itemData.m_shared == null) return 0f; + + // Valheim's own formula: armour + (quality - 1) * armourPerLevel. + return drop.m_itemData.m_shared.m_armor + + (SvermConfig.ArmorReferenceQuality - 1) * drop.m_itemData.m_shared.m_armorPerLevel; + } + + /// + /// Eitr regeneration the carapace hands back, from Eitr Sacs on. + /// + /// The eitr-weave set gives REGENERATION, not maximum eitr - the maximum comes from food, + /// which the Sverm eats like anyone else. So sealing the armour slots never blocked magic; + /// it only slowed the recovery, and this gives back a fraction of it. Deliberately a + /// fraction: eitr-weave is light armour and pays for its regeneration in defence, and a + /// Sverm carrying a biome set at quality 4 AND the full regeneration would simply be a + /// better mage than a mage. + /// + public static float GetEitrRegenBonus(int state) + { + if (state < SvermConfig.EitrSacsState) return 0f; + if (ObjectDB.instance == null) return 0f; + + if (eitrRegenReference < 0f) + { + float total = 0f; + foreach (string prefabName in SvermConfig.EitrReferenceSet) + { + GameObject prefab = ObjectDB.instance.GetItemPrefab(prefabName); + ItemDrop drop = prefab != null ? prefab.GetComponent() : null; + if (drop != null && drop.m_itemData != null && drop.m_itemData.m_shared != null) + { + total += drop.m_itemData.m_shared.m_eitrRegenModifier; + } + } + eitrRegenReference = total; + Jotunn.Logger.LogInfo($"[Sverm] Eitr Sacs reference: eitr-weave set regenerates {total:0.##}, " + + $"carapace returns {SvermConfig.EitrRegenFraction:P0} of it."); + } + + return eitrRegenReference * SvermConfig.EitrRegenFraction; + } + + /// True when this slot is taken by the carapace and cannot hold anything else. + public static bool IsSealedSlot(ItemDrop.ItemData.ItemType type) + { + foreach (ItemDrop.ItemData.ItemType sealedType in SvermConfig.SealedSlots) + { + if (sealedType == type) return true; + } + return false; + } + + /// The tint the carapace, the helmet and the claws all share at this tier. + public static Color GetTint(int state) + { + state = Mathf.Clamp(state, BossProgressionManager.MinState, BossProgressionManager.MaxState); + return SvermConfig.CarapaceTintByState[state]; + } + } +} diff --git a/JotunnModStub/Sverm/SvermClawSlot.cs b/JotunnModStub/Sverm/SvermClawSlot.cs new file mode 100644 index 0000000..11b911c --- /dev/null +++ b/JotunnModStub/Sverm/SvermClawSlot.cs @@ -0,0 +1,283 @@ +using System.Collections.Generic; +using HarmonyLib; +using Jotunn.Managers; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// The Maulclaws as a REAL equipped weapon, sitting in the inventory in plain sight and + /// refusing to be moved. + /// + /// WHY THIS REPLACED THE COSMETIC VERSION. Bolting a model to the hand bones worked, but the + /// carapace beside it did not: the game rebuilds equipment visuals from what is ACTUALLY in + /// the slots, so every unequip wiped the lot and something had to put it back, one frame late + /// and visibly. A real item in a real slot removes the whole class of problem - there is + /// nothing to put back, because nothing was ever faked. + /// + /// The trade, accepted deliberately: a real weapon occupies the right hand, so drawing a sword + /// puts the claws away. Three rules make that read as intended rather than as a bug: + /// + /// 1. sheathe anything else and the claws come straight back (UnequipItem postfix); + /// 2. the holster key cannot put the claws away - a Sverm is never empty-handed + /// (HideHandItems prefix); + /// 3. the claws cannot be dragged, moved or dropped (SetupDragItem prefix, quest-item flag). + /// + /// VISIBLE, NOT HIDDEN, and that is the second design this file has had. The first reserved + /// the rightmost column and switched its slots off in the inventory window - which meant + /// patching InventoryGrid.UpdateGui, a method that runs for every chest and every grid in the + /// game, to hide something in exactly one of them. It also cost the player four slots. + /// Showing the claws and refusing to let them move is less code, touches no UI, and tells the + /// player something true: they are carrying them, and they always will be. + /// + /// The last resort behind all three rules is that Maintain re-issues the claws whenever they + /// are missing. However they get lost - a tombstone, a mod, a bug in this file - they are back + /// within half a second. + /// + public static class SvermClawSlot + { + public const string ItemName = "SvermMaulclaws"; + public const string ItemDisplayName = "Vilebone Maulclaws"; + + /// Row in the reserved column the claws sit on. The other three await the carapace. + private const int ClawRow = 0; + + private static bool registered; + + // ─── Registration ──────────────────────────────────────────────────── + + /// + /// Clones whichever of the four candidate prefabs this build actually has. Deferred until + /// ObjectDB is up, so it is driven from the first player spawn rather than from Awake. + /// + public static void EnsureRegistered() + { + if (registered) return; + + if (ObjectDB.instance != null && ObjectDB.instance.GetItemPrefab(ItemName) != null) + { + registered = true; + return; + } + + GameObject source = SvermClaws.GetPrefab(); + if (source == null) return; // already logged once by the resolver + + GameObject clone = PrefabManager.Instance.CreateClonedPrefab(ItemName, source); + if (clone == null) + { + Jotunn.Logger.LogWarning($"[Sverm] Could not clone '{source.name}'; the claws stay unregistered."); + return; + } + + ItemDrop drop = clone.GetComponent(); + if (drop != null && drop.m_itemData != null && drop.m_itemData.m_shared != null) + { + ItemDrop.ItemData.SharedData shared = drop.m_itemData.m_shared; + shared.m_name = ItemDisplayName; + shared.m_description = "Grown, not forged. They do not come off."; + + // Quest item: Valheim refuses to drop, trade or stack these. It is the cheapest + // honest way to say "this is part of your body" without a patch per verb. + shared.m_questItem = true; + shared.m_teleportable = true; + shared.m_weight = 0f; + shared.m_maxQuality = 1; + + // No recipe and no station: this item is never crafted, only issued. + } + + ItemManager.Instance.AddItem(new Jotunn.Entities.CustomItem(clone, fixReference: false)); + registered = true; + Jotunn.Logger.LogInfo($"[Sverm] Registered '{ItemName}' from '{source.name}'."); + } + + // ─── Issue and re-equip ────────────────────────────────────────────── + + /// + /// Makes sure the player owns exactly one pair and is holding them whenever both hands are + /// free. Safe to call on a timer: every step checks first. + /// + /// + /// Guards against re-entry, and it is not belt-and-braces - it is the fix for a crash. + /// + /// Maintain equips the claws. Humanoid.EquipItem unequips the right hand first, which + /// fires the UnequipItem postfix, which calls Maintain, which equips the claws... Mono + /// answers an unbounded recursion by killing the process outright, with no exception and a + /// log file that ends mid-word. Switching race was enough to trigger it every time. + /// + /// The null check in the postfix closes the specific door; this closes the corridor. + /// + private static bool maintaining; + + public static void Maintain(Player player) + { + if (maintaining) return; + if (player == null || player != Player.m_localPlayer) return; + if (!SvermVisuals.IsSvermPlayer(player)) return; + + maintaining = true; + try { MaintainInner(player); } + finally { maintaining = false; } + } + + private static void MaintainInner(Player player) + { + EnsureRegistered(); + + Inventory inventory = player.GetInventory(); + if (inventory == null) return; + + ItemDrop.ItemData claws = Find(inventory); + + if (claws == null) + { + GameObject prefab = ObjectDB.instance != null ? ObjectDB.instance.GetItemPrefab(ItemName) : null; + if (prefab == null) return; + + // The GameObject overload, deliberately: it is the one that is public in the + // shipped assembly. The overloads that take a grid position are private there, and + // the project compiles against the shipped assembly rather than the publicized + // copy - so anything else would build on this machine and not on a clean one. + if (!inventory.AddItem(prefab, 1)) return; + + claws = Find(inventory); + if (claws == null) return; + + // Tidied into the bottom-right corner IF that corner is free, and left wherever + // the inventory put them otherwise. Nothing of the player's is ever displaced to + // make room: an item that cannot be moved has no business shoving one that can. + Vector2i corner = new Vector2i(inventory.GetWidth() - 1, inventory.GetHeight() - 1); + if (corner.x >= 0 && ItemAt(inventory, corner.x, corner.y) == null) + { + claws.m_gridPos = corner; + } + + Jotunn.Logger.LogInfo("[Sverm] Issued the Maulclaws."); + } + + // Empty-handed means clawed. Anything else in the right hand wins until it is put + // away, which is the whole compromise. + ItemDrop.ItemData held = Traverse.Create((Humanoid)player).Field("m_rightItem").Value; + if (held == null && !player.InAttack() && !player.IsDead()) + { + player.EquipItem(claws, false); + } + } + + /// + /// What is sitting at this grid position, read from the items themselves. + /// + /// Inventory.GetItemAt is private in the shipped assembly, and every item already carries + /// its own m_gridPos, so a scan over GetAllItems answers the same question with nothing + /// but public members. An inventory holds a few dozen items; this is not a hot path. + /// + private static ItemDrop.ItemData ItemAt(Inventory inventory, int x, int y) + { + foreach (ItemDrop.ItemData item in inventory.GetAllItems()) + { + if (item != null && item.m_gridPos.x == x && item.m_gridPos.y == y) return item; + } + return null; + } + + public static ItemDrop.ItemData Find(Inventory inventory) + { + if (inventory == null) return null; + + foreach (ItemDrop.ItemData item in inventory.GetAllItems()) + { + if (item != null && item.m_dropPrefab != null && item.m_dropPrefab.name == ItemName) return item; + if (item != null && item.m_shared != null && item.m_shared.m_name == ItemDisplayName) return item; + } + return null; + } + + public static bool IsClaws(ItemDrop.ItemData item) + { + if (item == null || item.m_shared == null) return false; + if (item.m_dropPrefab != null && item.m_dropPrefab.name == ItemName) return true; + return item.m_shared.m_name == ItemDisplayName; + } + } + + // ─── Patches ───────────────────────────────────────────────────────────── + + /// + /// Put anything else away and the claws come straight back. + /// + /// A postfix rather than doing it inside UnequipItem's own flow: the game is mid-way through + /// tearing down the old item's visuals when the prefix would run, and equipping there leaves + /// the new item without a model. + /// + [HarmonyPatch(typeof(Humanoid), nameof(Humanoid.UnequipItem))] + public static class Sverm_UnequipItem_Patch + { + public static void Postfix(Humanoid __instance, ItemDrop.ItemData item) + { + // NULL IS THE IMPORTANT CASE. Humanoid.EquipItem calls UnequipItem(m_rightItem) before + // putting a weapon in the hand, and an empty hand means that argument is null. Without + // this line the postfix treats "nothing was unequipped" as "something was unequipped", + // calls Maintain, which equips the claws, which unequips null again - and Mono kills + // the process on the recursion, instantly and silently. + if (item == null) return; + + Player player = __instance as Player; + if (player == null || player != Player.m_localPlayer) return; + if (!SvermVisuals.IsSvermPlayer(player)) return; + if (SvermClawSlot.IsClaws(item)) return; // do not re-equip what was just taken off + + SvermClawSlot.Maintain(player); + } + } + + /// + /// The holster key cannot put the claws away. + /// + /// HideHandItems is what R calls. Refused only while the claws ARE the thing in hand: holding + /// a sword, R sheathes the sword normally, and the unequip postfix above hands the claws back + /// on the same action. So the key keeps working and simply never leaves a Sverm empty-handed. + /// + [HarmonyPatch(typeof(Humanoid), nameof(Humanoid.HideHandItems))] + public static class Sverm_HideHandItems_Patch + { + public static bool Prefix(Humanoid __instance) + { + Player player = __instance as Player; + if (player == null || player != Player.m_localPlayer) return true; + if (!SvermVisuals.IsSvermPlayer(player)) return true; + + ItemDrop.ItemData held = Traverse.Create(__instance).Field("m_rightItem").Value; + return !SvermClawSlot.IsClaws(held); + } + } + + /// + /// The claws cannot be picked up with the mouse. + /// + /// SetupDragItem is the single door every manual move goes through - within the inventory, out + /// to a chest, onto the ground, into a crafting slot. Refusing here closes all of them with + /// one prefix, instead of one patch per destination, and leaves every OTHER item's handling + /// completely untouched. + /// + /// It replaces an earlier design that hid the rightmost column outright. That one had to patch + /// InventoryGrid.UpdateGui - a method that runs for every chest and every grid in the game - + /// in order to change exactly one of them, and it cost the player four slots. The claws are + /// visible now, which is also more honest: they are part of the character, and the character + /// can see them. + /// + [HarmonyPatch(typeof(InventoryGui), "SetupDragItem")] + public static class Sverm_SetupDragItem_Patch + { + public static bool Prefix(ItemDrop.ItemData item) + { + if (!SvermClawSlot.IsClaws(item)) return true; + + if (Player.m_localPlayer != null) + { + Player.m_localPlayer.Message(MessageHud.MessageType.Center, "They are part of your hands."); + } + return false; + } + } +} diff --git a/JotunnModStub/Sverm/SvermClaws.cs b/JotunnModStub/Sverm/SvermClaws.cs new file mode 100644 index 0000000..88acd56 --- /dev/null +++ b/JotunnModStub/Sverm/SvermClaws.cs @@ -0,0 +1,154 @@ +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// The Vilebone Maulclaws: attached to the hands for good, and never equipped. + /// + /// WHY NOT A REAL WEAPON. Valheim has one weapon slot. A claw that is genuinely equipped locks + /// the Sverm out of every sword, bow and staff in the game for the whole run, which is not + /// what "permanent claws" is supposed to mean. So the feature is split: + /// + /// the MODEL is cosmetic - two copies bolted to the hand bones, visible always, including + /// while holding a two-hander (SvermVisuals does the mounting); + /// the DAMAGE is unarmed - a bare-handed Sverm punches for the claws of its tier. Pick up a + /// sword and you swing the sword; the claws are still on your hands. + /// + /// So the race is never disarmed and never restricted, and the two halves can be tuned apart. + /// + /// THE PREFAB NAME IS NOT TRUSTED. The install's manifest carries four near-identical names - + /// FistBjornUndeadClaw, FistBjornClawUndead, FistUnbjornClaw, FistBjornClaw - and only some of + /// them have a recipe, which means the item and the mesh may not share a name. Guessing wrong + /// costs two empty hands and no error at all, so the resolve walks the list and logs the + /// winner. A warning beats a silent nothing. + /// + public static class SvermClaws + { + private static GameObject resolved; + private static bool resolveAttempted; + + private static HitData.DamageTypes referenceDamage; + private static bool referenceRead; + + /// + /// The claw prefab, or null. Resolution happens once, inside a world, because ObjectDB is + /// empty when the plugin wakes. + /// + public static GameObject GetPrefab() + { + if (resolved != null) return resolved; + + foreach (string name in SvermConfig.ClawPrefabFallbacks) + { + // PrefabManager's cache first, ObjectDB second, and that order is what lets this + // run at OnVanillaPrefabsAvailable - which is the only moment Jotunn will accept a + // new item. ObjectDB is still empty then. + GameObject candidate = Jotunn.Managers.PrefabManager.Cache.GetPrefab(name); + if (candidate == null && ObjectDB.instance != null) + { + candidate = ObjectDB.instance.GetItemPrefab(name); + } + + if (candidate != null) + { + resolved = candidate; + Jotunn.Logger.LogInfo($"[Sverm] Maulclaws resolved to '{name}'."); + return resolved; + } + } + + // Warned once, but NOT latched: a later call may run when more of the game is loaded, + // and a race with no hands is worth retrying for. + if (!resolveAttempted) + { + resolveAttempted = true; + Jotunn.Logger.LogWarning("[Sverm] None of " + string.Join(", ", SvermConfig.ClawPrefabFallbacks) + + " resolved yet; retrying as the game loads."); + } + return null; + } + + /// + /// The vanilla weapon's damage at quality 4, read once. This is the ceiling the tier + /// percentages are a fraction of, and state 7 is 100% of it - the real Maulclaws. + /// + private static HitData.DamageTypes GetReferenceDamage() + { + if (referenceRead) return referenceDamage; + + GameObject prefab = GetPrefab(); + ItemDrop drop = prefab != null ? prefab.GetComponent() : null; + if (drop == null || drop.m_itemData == null || drop.m_itemData.m_shared == null) + { + return referenceDamage; // all zeroes; referenceRead stays false so a later world can retry + } + + ItemDrop.ItemData.SharedData shared = drop.m_itemData.m_shared; + + HitData.DamageTypes at1 = shared.m_damages; + HitData.DamageTypes perLevel = shared.m_damagesPerLevel; + int steps = SvermConfig.ArmorReferenceQuality - 1; + + referenceDamage = new HitData.DamageTypes + { + m_blunt = at1.m_blunt + perLevel.m_blunt * steps, + m_slash = at1.m_slash + perLevel.m_slash * steps, + m_pierce = at1.m_pierce + perLevel.m_pierce * steps, + m_chop = at1.m_chop + perLevel.m_chop * steps, + m_pickaxe = at1.m_pickaxe + perLevel.m_pickaxe * steps, + m_fire = at1.m_fire + perLevel.m_fire * steps, + m_frost = at1.m_frost + perLevel.m_frost * steps, + m_lightning = at1.m_lightning + perLevel.m_lightning * steps, + m_poison = at1.m_poison + perLevel.m_poison * steps, + m_spirit = at1.m_spirit + perLevel.m_spirit * steps, + }; + + referenceRead = true; + Jotunn.Logger.LogInfo($"[Sverm] Maulclaws at quality {SvermConfig.ArmorReferenceQuality}: " + + $"slash {referenceDamage.m_slash:0.#}, pierce {referenceDamage.m_pierce:0.#}, " + + $"blunt {referenceDamage.m_blunt:0.#}."); + return referenceDamage; + } + + /// Fraction of the reference damage the bare hands hit for at this tier. + public static float GetDamagePercent(int state) + { + state = Mathf.Clamp(state, BossProgressionManager.MinState, BossProgressionManager.MaxState); + return SvermConfig.ClawDamagePercentByState[state]; + } + + /// + /// Rewrites a bare-handed blow into a claw blow. Called from the Character.Damage prefix, + /// and only when the attacker really is punching: an unarmed hit in Valheim carries a tiny + /// blunt figure, which is REPLACED here rather than added to, so the tier percentage means + /// what it says. + /// + public static void ApplyToUnarmedHit(HitData hit, int state) + { + if (hit == null) return; + + HitData.DamageTypes reference = GetReferenceDamage(); + float percent = GetDamagePercent(state); + if (percent <= 0f) return; + + float slash = reference.m_slash * percent; + float pierce = reference.m_pierce * percent; + float blunt = reference.m_blunt * percent; + + // Nothing to give: the reference item did not resolve. Leave vanilla's fist alone + // rather than zeroing the player's only attack. + if (slash + pierce + blunt <= 0f) return; + + hit.m_damage.m_slash = slash; + hit.m_damage.m_pierce = pierce; + hit.m_damage.m_blunt = blunt; + + // Annealed Chitin lights the claws too. A fraction of the physical total rather than a + // flat number, so it scales with whatever the reference weapon turns out to be worth. + if (state >= SvermConfig.AnnealedChitinState) + { + hit.m_damage.m_fire += (slash + pierce + blunt) * SvermConfig.ClawFireFraction; + } + } + } +} diff --git a/JotunnModStub/Sverm/SvermConfig.cs b/JotunnModStub/Sverm/SvermConfig.cs new file mode 100644 index 0000000..e75684a --- /dev/null +++ b/JotunnModStub/Sverm/SvermConfig.cs @@ -0,0 +1,535 @@ +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// Every tunable number the Sverm uses, in one place. + /// + /// Same contract as DvergarConfig: nothing here is baked into the logic. SvermProgression reads + /// these to build its per-tier rules and the patches read the rules, never a literal. Retuning + /// the race means editing this file only. + /// + /// Two of these numbers are NOT numbers but prefab names, and that is deliberate. The carapace + /// is worth "whatever the vanilla set of that biome is worth", and the claws hit for "whatever + /// the vanilla weapon hits for" - both read off ObjectDB at runtime rather than transcribed + /// here. A game patch that rebalances iron armour rebalances the Sverm with it, and nobody has + /// to remember that this file existed. + /// + public static class SvermConfig + { + // ─── Identity ──────────────────────────────────────────────────────── + // Stored in m_customData["Race"] and on the ZDO, so renaming it after players have chosen + // the race would orphan their characters. See DvergarRace.MigrateLegacyRaceId for what + // that costs to undo. + public const string RaceId = "Sverm"; + + public const string StatsSE = "SE_SvermStats"; + public const string StingerSE = "SE_SvermStingerForm"; + public const string StingerCdSE = "SE_SvermStingerCooldown"; + + // Mirrors the ZDO key layout the other races use, so remote clients can work out the tier + // without having the local player's progression state. + public const string StateZdoKey = "RacesOfValheim_SvermState"; + + // ─── Damage taken ──────────────────────────────────────────────────── + // Chitin burns and chitin cracks. Expressed as a plain multiplier rather than + // HitData.DamageModifier.Weak because that enum is discrete - Weak is a flat +50% and + // there is no rung at +40%. Applied in a Character.Damage prefix, the way Aswid, Draugh + // and Dvergar already scale damage. + public static readonly float BluntWeakness = 0.40f; + public static readonly float FireWeakness = 0.40f; + + // Annealed Chitin: at Fader the weakness inverts. 0.40 means fire lands at 60% of its + // value, i.e. roughly one rung of DamageModifier.Resistant, arrived at by the same knob + // that hurt for eight tiers. + public const int AnnealedChitinState = 8; + public static readonly float FireResistanceAtFader = 0.40f; + + // ─── Chitin Plating: the carapace ──────────────────────────────────── + // Reference sets, one per progression state. The carapace is worth the SUM of these three + // pieces AT QUALITY 4, read from ObjectDB. Every name here was verified against the + // install's own SoftRef manifest, so a null means the game changed, not that we guessed. + // + // Index 0 is unused: progression states run 1..8 and indexing by state is worth one wasted + // slot to avoid an off-by-one in every caller. + public static readonly string[][] ArmorReferenceSets = + { + null, // unused + new[] { "ArmorLeatherChest", "ArmorLeatherLegs", "HelmetLeather" }, // 1 + new[] { "ArmorBronzeChest", "ArmorBronzeLegs", "HelmetBronze" }, // 2 Eikthyr + new[] { "ArmorIronChest", "ArmorIronLegs", "HelmetIron" }, // 3 Elder + new[] { "ArmorWolfChest", "ArmorWolfLegs", "HelmetDrake" }, // 4 Bonemass + new[] { "ArmorPaddedCuirass", "ArmorPaddedGreaves", "HelmetPadded" }, // 5 Moder + new[] { "ArmorCarapaceChest", "ArmorCarapaceLegs", "HelmetCarapace" }, // 6 Yagluth + new[] { "ArmorFlametalChest", "ArmorFlametalLegs", "HelmetFlametal" }, // 7 Queen + new[] { "ArmorFlametalChest", "ArmorFlametalLegs", "HelmetFlametal" }, // 8 Fader + }; + + /// Quality the reference set is priced at. Valheim: armor + (q-1) * armorPerLevel. + public const int ArmorReferenceQuality = 4; + + /// + /// Added on top at Fader only. There is no biome after the Ashlands to read a set from, so + /// state 8 is the one tier whose number is chosen rather than derived - and it is a flat + /// bonus rather than a multiplier precisely so it reads as "chosen" in the log. + /// + public static readonly float FaderArmorBonus = 10f; + + /// Slots the carapace occupies and therefore forbids. + public static readonly ItemDrop.ItemData.ItemType[] SealedSlots = + { + ItemDrop.ItemData.ItemType.Chest, + ItemDrop.ItemData.ItemType.Legs, + ItemDrop.ItemData.ItemType.Helmet, + }; + + /// What the carapace LOOKS like, at every tier. The value changes, the shape does not. + public const string CarapaceChestVisual = "ArmorCarapaceChest"; + public const string CarapaceLegsVisual = "ArmorCarapaceLegs"; + public const string CarapaceHelmetVisual = "HelmetCarapace"; + + // ─── Vilebone Maulclaws ────────────────────────────────────────────── + // FOUR near-identical names exist in the manifest and only some carry a recipe, so the + // prefab is resolved by trying them in order and logging which one answered. A wrong guess + // here fails soft and silently - two empty hands - which is exactly the failure this + // chain exists to make loud. + public static readonly string[] ClawPrefabFallbacks = + { + "FistBjornUndeadClaw", + "FistBjornClawUndead", + "FistUnbjornClaw", + "FistBjornClaw", + }; + + /// Length in METRES from the back of the hand to the tip. ModelBorrow sizes in metres. + public static readonly float ClawLength = 0.22f; + + /// + /// Fraction of the vanilla weapon's quality-4 damage the bare hands hit for, per state. + /// State 7 is the ceiling - the real Maulclaws - and state 8 adds fire on top rather than + /// going past it. Index 0 unused, as above. + /// + public static readonly float[] ClawDamagePercentByState = + { + 0f, 0.35f, 0.45f, 0.55f, 0.70f, 0.85f, 0.95f, 1.00f, 1.00f + }; + + /// Fire added at Fader, as a fraction of the claws' physical total. + public static readonly float ClawFireFraction = 0.30f; + + // ─── Insect Metabolism ─────────────────────────────────────────────── + /// Raw meat is worth this much of its cooked counterpart. + public static readonly float RawMeatFraction = 0.70f; + + /// Honey and royal jelly: bonus and duration both multiplied by this. + public static readonly float HoneyMultiplier = 2f; + + /// Seeds become food from this state on (The Elder). + public const int SeedsEdibleState = 3; + + // Royal jelly, made edible from scratch. These are the FINAL values, already doubled - + // they are not multiplied again by HoneyMultiplier. + public const string RoyalJellyPrefab = "RoyalJelly"; + public static readonly float RoyalJellyHealth = 90f; + public static readonly float RoyalJellyStamina = 90f; + public static readonly float RoyalJellyEitr = 90f; + public static readonly float RoyalJellyDuration = 2400f; + public static readonly float RoyalJellyRegen = 5f; + + // ─── Perk unlock states ────────────────────────────────────────────── + public const int MetabolicSurgeState = 2; + public const int VentralPouchesState = 2; + public const int GrindingMandiblesState = 3; + public const int SensoryAntennaeState = 3; + public const int VenomGlandsState = 4; + public const int AcidHemolymphState = 4; + public const int VestigialWingsState = 5; + public const int StingerMorphState = 6; + public const int EitrSacsState = 6; + public const int MajesticCarapaceState = 7; + public const int SurrenalGlandsState = 7; + public const int FullWingspanState = 7; + public const int CarapaceRegenState = 8; + + // ─── Metabolic Surge (state 2) ─────────────────────────────────────── + public static readonly float RunStaminaDiscount = 0.20f; // -20% on running + public static readonly float JumpStaminaDiscount = 0.20f; + public static readonly float JumpBonus = 0.15f; // +15% jump force + + // ─── Ventral Pouches (state 2) ─────────────────────────────────────── + public static readonly float CarryWeightBonus = 100f; + + // ─── Sensory Antennae (state 3) ────────────────────────────────────── + // Passive and always on, so the radius is the only real brake on how many point lights can + // be alive at once. Raise it with that in mind. + public static readonly float AntennaeRadius = 30f; + public static readonly float AntennaeInterval = 2f; + public static readonly float AntennaeLightRange = 4f; + public static readonly float AntennaeLightIntensity = 1.4f; + + // What each colour means, and the meaning is the whole feature: the Aswid's Auspex marks + // everything the same because it only asks "is something there". A chemical sense answers + // "what is it". + public static readonly Color AntennaeHostileColor = new Color(1f, 0.15f, 0.10f, 1f); // red + public static readonly Color AntennaePassiveColor = new Color(0.25f, 1f, 0.30f, 1f); // green + public static readonly Color AntennaeInvertebrateColor = new Color(1f, 0.90f, 0.20f, 1f); // yellow + public static readonly Color AntennaeKinColor = new Color(0.35f, 0.75f, 1f, 1f); // azure + + // ─── Venom Glands (state 4) ────────────────────────────────────────── + /// Poison added to every blow, per state above the unlock. + public static readonly float VenomPerState = 6f; + + // ─── Acid Hemolymph (state 4) ──────────────────────────────────────── + /// Poison dealt back to whoever lands a melee blow, per state above the unlock. + public static readonly float HemolymphPerState = 5f; + public static readonly float HemolymphRange = 4f; + + // ─── Dorsal Spines (state 5) / Full Crest (state 7) ────────────────── + // Wings were the first design and they lost on cost. Wing_gib turned out not to be a + // prefab at all - it is a child inside a death effect, reachable only by walking somebody + // else's hierarchy and hoping the parent list is right - and animated wings on a static + // mount never look like anything but a prop. A ribcage worn spine-up is STATIC by nature, + // it is a real prefab that resolves by name, and it reads as xenomorph spines rather than + // as a bird. + public const string SpinesPrefab = "UndeadBjornRibcage"; + public static readonly float SpineSizeSmall = 0.45f; // metres, state 5-6 + public static readonly float SpineSizeFull = 0.80f; // metres, state 7+ + /// + /// Which bone they ride. Spine3 and ONLY Spine3 - no fallback chain. + /// + /// The earlier version tried Spine2, then Spine1, then Spine, on the theory that a missing + /// bone should degrade rather than disappear. On this rig all three exist, so the fallback + /// never fired for the right reason and only ever meant "somewhere on the back, roughly" - + /// which is not good enough for a crest that was positioned by eye. One bone, or nothing. + /// + public const string SpineBoneName = "Spine3"; + + // Found in game with the crest on screen. A ribcage is authored lying around a body, so + // standing it up out of a back is a quarter turn on two axes - not something anybody was + // going to derive on paper. + public static readonly float SpineRotationX = 0f; + public static readonly float SpineRotationY = -90f; + public static readonly float SpineRotationZ = 90f; + + /// + /// What holds a falling Sverm up: the Mistlands' own fireflies, swarming under the body. + /// + /// Note the capital F in the middle. "Fireflies" resolves to nothing and fails silently, + /// which is the whole reason every prefab name in this race is checked against the game's + /// manifest before it is written down. + /// + public const string GlideMotesPrefab = "FireFlies"; + + // ─── Eitr Sacs (state 6) ───────────────────────────────────────────── + /// Fraction of the eitr-weave set's regeneration the carapace gives back. + public static readonly float EitrRegenFraction = 0.50f; + public static readonly string[] EitrReferenceSet = { "ArmorMageChest", "ArmorMageLegs", "HelmetMage" }; + + // ─── Surrenal Glands (state 7) ─────────────────────────────────────── + public static readonly float BodyScaleAtQueen = 1.10f; + + // ─── Carapace Regeneration (state 8) ───────────────────────────────── + public static readonly float CarapaceRegenPerSecond = 0.5f; + + // ─── Stinger Morph (state 6) ───────────────────────────────────────── + public const string StingerCreature = "Deathsquito"; + public static readonly float StingerDurationSeconds = 120f; + public static readonly float StingerCooldownSeconds = 480f; + + /// + /// Multiplier on every point of damage taken while in form. 2.5 means a blow that the + /// carapace would shrug off very nearly ends you. + /// + /// This is the entire cost of the ability and it has to be steep: in form you deal the + /// hardest single hit in the Plains and you can leave any fight by going straight up. The + /// balance is not the cooldown, it is that a single arrow answers you. + /// + public static readonly float StingerFragility = 2.5f; + + // ─── The escort ────────────────────────────────────────────────────── + /// + /// Two deathsquitoes called up with the form, and they OUTLIVE it on purpose. + /// + /// Three minutes against the form's two. The extra minute is the whole idea: the form ends + /// wherever it ends, usually in the air, and the Sverm comes back to being a slow armoured + /// thing halfway through a fall. The escort is what covers that minute. Then it dies too. + /// + public const int EscortCount = 2; + public static readonly float EscortLifetimeSeconds = 180f; + public static readonly float EscortSpawnSpread = 2.5f; + + // ─── Transformation effects ────────────────────────────────────────── + // The Seeker's own spawn and death bursts, verified in the manifest. vfx_boar_death is the + // fallback because it is what the Aswid uses and is certain to exist. + public static readonly string[] MorphInEffects = { "fx_seeker_spawn", "vfx_boar_death" }; + public static readonly string[] MorphOutEffects = { "fx_seeker_death", "vfx_boar_death" }; + + // ─── Palette ───────────────────────────────────────────────────────── + // Read off a Seeker Soldier. The exposed skin is almost black and matte: what makes the + // look is the CONTRAST against the amber plates, not the skin colour itself. + public static readonly Color SkinColor = Hex(0x24, 0x1B, 0x15); + public static readonly Color MembraneColor = Hex(0xB8, 0x5F, 0x5C); + + /// + /// The tint ramp IS the visual progression. Same carapace silhouette at every tier, aged + /// by colour: pale washed sand, then full amber, then dark amber, then black with a red + /// burn at Fader. Zero new assets. Index 0 unused. + /// + /// + /// A YOUNG insect is not a small adult, and the ramp says so. The early tiers are violet - + /// the soft, pale, not-yet-hardened shell of something freshly moulted - and the amber of + /// the reference photograph is where the race ARRIVES rather than where it starts. The + /// last two tiers darken out of amber into near black, which is what gives Emberform's red + /// something to burn through. + /// + /// Index 0 unused. + /// + public static readonly Color[] CarapaceTintByState = + { + Color.white, + Hex(0xB0, 0xA3, 0xC8), // 1 pale violet - newly moulted, soft + Hex(0x9B, 0x88, 0xB8), // 2 + Hex(0x86, 0x70, 0x9F), // 3 violet, deepening + Hex(0x7C, 0x60, 0x79), // 4 mauve: the turn towards amber begins + Hex(0x8A, 0x62, 0x49), // 5 + Hex(0x8B, 0x5E, 0x34), // 6 full amber - the colour of the photograph + Hex(0x4A, 0x32, 0x20), // 7 dark amber + Hex(0x14, 0x10, 0x0C), // 8 near black; Emberform adds the red + }; + + // ─── Emberform ─────────────────────────────────────────────────────── + // The hue at full strength, dimmed by EmberGlowStrength below. Split in two for the same + // reason AswidVisuals splits its eye colour: the hue and the brightness are tuned against + // different things, and mixing them into one HDR value makes every adjustment a guess. + // + // The first version shipped this at (3.2, 0.30, 0.06) applied directly, and it came out + // blinding - which is the Aswid's lesson arriving late and at ten times the surface area. + // Two glowing spheres on a face can carry an HDR value past 3; a whole chest, both legs + // and a helmet cannot. Past the bloom threshold the extra brightness buys a bigger white + // area and LESS red, so the fix is downward, not sideways. + public static readonly Color EmberEmission = new Color(3.2f, 0.30f, 0.06f, 1f); + + /// + /// How much of that hue actually reaches the material. + /// + /// Tuned downward twice, in game, and the trend is the whole lesson: full HDR was blinding, + /// 0.25 was still too strong, and 0.0625 is where it stopped looking like a lamp. That puts + /// the red at 0.2 - well under the clip - which on a surface the size of a whole body is + /// plenty. Two glowing eyes and a glowing torso are not the same problem and do not take + /// the same number. + /// + /// Live from the .cfg, because this is a number only an eye can settle. + /// + public static readonly float EmberGlowStrength = 0.0625f; + + // Glowing eyes, same geometry as the Aswid's. Placement constants live in the head bone's + // own local space, which is why the state-7 +10% needs no special case: a child transform + // rides its parent's scale for free. + public static readonly Color EyeColor = new Color(3.4f, 0.12f, 0.08f, 1f); + public static readonly float EyeGlowStrength = 0.22f; + + // ─── The colony (stub - see SvermHive when that half is written) ───── + /// Two nests per square mile. A square mile is 2.59 km2; the circle of equal area has r = 908 m. + public static readonly float HiveDensityRadius = 908f; + public const int HiveDensityMax = 2; + + /// The Elder. Before that the Sverm is a body and nothing else. + public const int HiveUnlockState = 3; + + // ─── Colony caps ───────────────────────────────────────────────────── + // The DEFAULTS. What is actually enforced comes from SvermConfigManagement, which binds + // these into the .cfg so a machine that cannot carry nineteen creatures can say so without + // a rebuild. Only the nest density stays out of reach - two per square mile is a rule + // about the world, not a comfort setting. + public const int CapBrood = 8; + public const int CapSeeker = 6; + public const int CapSoldier = 3; + public const int CapGjall = 2; + public const int CapBlisterTick = 10; + + /// Two separate pools, nine workers alive at most. Farmers come from the infected + /// beehives, haulers from the nest after Bonemass, and neither can starve the other. + public const int CapFarmers = 6; + public const int CapHaulers = 3; + + // ─── The aura and the beehives in it ───────────────────────────────── + public static readonly float HiveAuraRadius = 10f; + public const int HiveAuraBeehiveMax = 10; + + /// Not every frame: it walks a sphere of colliders and nothing here is urgent. + public static readonly float HiveAuraSweepInterval = 5f; + + /// How long a beehive must stand in the aura before the colony takes it. + public static readonly float BeehiveInfectionSeconds = 60f; + + public static readonly float BeehiveSpeedMultiplier = 2f; // twice as fast + public static readonly float BeehiveCapacityMultiplier = 3f; // three times the honey + + /// + /// Vanilla's own cap, written down because m_maxHoney is an instance field and by the time + /// we read it on a hive we may already have changed it. Multiplying what we find would + /// treble the trebled number on the next sweep. + /// + public const int BeehiveBaseMaxHoney = 4; + + /// After Yagluth the colony makes royal jelly instead of honey. + public const int RoyalJellyHiveState = 6; + + // The mark of a taken hive. SeekerEgg is a real prefab - unlike Wing_gib, which was not. + // The first pass shipped a 35 cm egg at 90 cm and nobody could see it: too small, and high + // enough above the hive's origin to float clear of the roof instead of sitting on it. Both + // numbers are in the .cfg now, because where a thing sits on another thing is decided by + // an eye and not by arithmetic. + public const string HiveEggPrefab = "SeekerEgg"; + public static readonly float HiveEggSize = 0.55f; // metres + public static readonly float HiveEggHeight = 0.45f; // above the hive's own origin + + /// The nest's own size. 0.75 is the quarter off that the first placement asked for. + public static readonly float HiveScale = 0.75f; + + // ─── What the colony looks like from outside ───────────────────────── + // How big the swarm of flies and the green reek are on each thing that wears them. Metres, + // near enough - the holder is scaled by these and the particles ride it. Both are first + // guesses and both are in the .cfg, because nobody can settle a cloud of flies on paper. + public static readonly float NestVfxScale = 1.5f; + public static readonly float BeehiveVfxScale = 0.5f; + + // The two hives bolted to the nest: the stomach at its foot, the market up top. Sizes are + // in metres and heights are metres up the trunk from the ground. Both sizes are also the + // width of the sphere you press, so a mouth that is too small is a mouth that is hard to + // point at as well as hard to see - the stomach is the bigger of the two because it is the + // one you use every time you come home. + public static readonly float StomachSize = 1.4f; + public static readonly float StomachHeight = 0f; + /// + /// The Hive Market bench's own scale. It is a BUILDING now, not a mouth on the nest. + /// + /// Two heights were tried while it still hung on the trunk and neither could work: the + /// measured crown put it eight metres over the player's head, and the number that replaced + /// it lost to the zero already written in everyone's .cfg, which dropped it inside the + /// stomach's own sphere. A counter you raise where you like has no such argument to lose. + /// + public static readonly float MarketSize = 1.6f; // metres, the borrowed model's largest side + + // ─── Seeker Worker ─────────────────────────────────────────────────── + public const string WorkerDisplayName = "Seeker Worker"; + public static readonly float WorkerScale = 0.5f; + public static readonly float WorkerHealthFraction = 0.5f; + public static readonly float WorkerDamageFraction = 0.5f; + + /// One out of every infected beehive on this timer, until the pool is full. + public static readonly float WorkerSpawnInterval = 120f; + + /// Haulers only start after Bonemass. + public const int HaulerUnlockState = 4; + + /// Ten metres. Also the radius it keeps in repair. + public static readonly float WorkerLeashRange = 10f; + + /// How far a worker reaches to mend, and how often it mends one thing. + public static readonly float WorkerRepairRange = 10f; + public static readonly float WorkerRepairInterval = 5f; + + /// How far from its anchor a worker looks for chests. + public static readonly float WorkerChestRange = 3f; + + /// How often a worker does a round of its trade. + public static readonly float WorkerRoundInterval = 4f; + + /// Plants per infected beehive, once the farmer's job lands. + public const int PlantsPerBeehive = 15; + + // ─── Biomass ───────────────────────────────────────────────────────── + public static readonly float BiomassTankBase = 1000f; + + /// Section 10.1: 1000 / 1500 / 2000 / 2500 across the four stages. + public static readonly float BiomassTankPerStage = 500f; + + /// + /// Headroom over the document's tank, on every stage: 1500 / 2000 / 2500 / 3000. + /// + /// FOUND IN PLAY, and it is a real hole rather than a balance opinion. A stage costs exactly + /// the tankful of the stage below it, so with the tank and the price being the same number + /// the hive had to be full TO THE GRAM before it could grow - and it never was. Biomass + /// arrives in whole items: with three units of room left, a log worth five does not fit, so + /// the last few points can never be filled and the price is never reached. + /// + /// The prices are untouched. This is the room above them. + /// + public static readonly float BiomassTankHeadroom = 500f; + + public static readonly float WoodBiomassValue = 5f; + + /// + /// How big the nest is at the last stage, as a multiple of how it was built. + /// + /// SECTION 9 SAYS TRIPLE and triple was wrong on screen: the trunk measures about eight + /// metres as placed, so a Hive Citadel stood twenty-four metres tall and read as a bug + /// rather than as a building. 1.75 keeps the growth legible - each stage is visibly bigger + /// than the last - without the last one swallowing the base. In the .cfg because this is a + /// number only an eye can settle. + /// + public static readonly float HiveStageGrowth = 1.75f; + + /// Section 20.4's day between purchases, in game days. + public static readonly float UpgradeCooldownDays = 1f; + + // ─── Brood eggs and troops ─────────────────────────────────────────── + /// Section 10.2: one egg every twenty seconds, five plus the stage in the clutch. + public static readonly float EggInterval = 20f; + public const int EggCapBase = 5; + + /// How far a troop wanders from the nest when nobody is leading it. + public static readonly float TroopLeashRange = 12f; + + /// How long a troop outlives the nest that hatched it, in seconds. + public static readonly float TroopWitherSeconds = 60f; + + /// How close a troop has to be to see whether its nest is still standing. + public static readonly float TroopHomeCheckRange = 25f; + + // ─── Blister Tick ──────────────────────────────────────────────────── + /// Section 12: fifty a slot, and the slot is permanent. + public static readonly float TickPrice = 50f; + + /// How close it gets before it bursts, in metres. + public static readonly float TickBurstRange = 2.5f; + + /// How long the nest waits before growing a replacement, in seconds. + public static readonly float TickRespawnSeconds = 30f; + + /// From this nest stage on, the blast is the elite blob's. Section 12's two tiers. + public const int TickLateBlastStage = 3; + + /// Only used if the blob projectiles are not in this build - see SvermBlisterTick. + public static readonly float TickFallbackDamage = 30f; + + // ─── Medicine ──────────────────────────────────────────────────────── + /// + /// Section 19.4: what a jar heals when it is given to one of the colony's insects instead of + /// eaten. They stopped counting as biomass to become this. + /// + public static readonly float HoneyHealing = 40f; + public static readonly float RoyalJellyHealing = 90f; + + // No Venom Coil numbers. Section 13's turret was built, seen and rejected, so its price, its + // Bonemass gate and its scale are gone with it rather than left here looking pending. + + /// + /// How much biomass moves from digestion into the spendable bank each second. + /// + /// NOT A NUMBER FROM THE DESIGN DOCUMENT - the digestion is described there, its speed is + /// not. Five a second empties a full stage-one tank in a little over three minutes, which + /// is long enough that a hive cannot be filled and spent in the same breath and short + /// enough that nobody stands there waiting. It is in the .cfg because it is the first thing + /// a play test will want to argue with. + /// + public static readonly float BiomassDigestRate = 5f; + + // ─── Helpers ───────────────────────────────────────────────────────── + private static Color Hex(int r, int g, int b) + { + return new Color(r / 255f, g / 255f, b / 255f, 1f); + } + } +} diff --git a/JotunnModStub/Sverm/SvermConfigManagement.cs b/JotunnModStub/Sverm/SvermConfigManagement.cs new file mode 100644 index 0000000..0480f26 --- /dev/null +++ b/JotunnModStub/Sverm/SvermConfigManagement.cs @@ -0,0 +1,271 @@ +using BepInEx.Configuration; + +namespace RacesOfValheim +{ + /// + /// The BepInEx-configurable slice of the Sverm's numbers, bound as ConfigEntry so they can be + /// retuned without a rebuild - see CONFIGURATION-MANAGER-HOWTO.md. Bound once, from + /// RacesOfValheim.Awake(). + /// + /// Configuration Manager is a convenience, not a requirement: these land in + /// BepInEx/config/com.nandor.racesofvalheim.cfg as plain text and can be edited with a text + /// editor and picked up on the next launch. + /// + /// WHAT IS IN HERE AND WHAT IS NOT, on the same boundary DvergarConfigManagement draws: + /// SvermConfig keeps the identity constants that must never change once a character exists + /// (RaceId, status effect names) and the per-tier tables. What lives here is the handful of + /// numbers that can only be judged by looking at them on screen - where the claws sit on the + /// hand, how wide the wings open - because those are guesses until someone sees them, and a + /// guess that needs a rebuild to correct is a guess that gets corrected slowly. + /// + public static class SvermConfigManagement + { + // No claw entries. They were here for one build, while the claws were a model bolted to + // the hand bones and their angle was a guess only an eye could settle. They are a real + // equipped item now (SvermClawSlot), so the game's own attach point decides where they sit + // and there is nothing left to tune. + + // ─── Dorsal spines ─────────────────────────────────────────────────── + public static ConfigEntry SpineSizeSmall; + public static ConfigEntry SpineSizeFull; + public static ConfigEntry SpineBoneName; + public static ConfigEntry SpineRotationX; + public static ConfigEntry SpineRotationY; + public static ConfigEntry SpineRotationZ; + + // ─── Emberform ─────────────────────────────────────────────────────── + public static ConfigEntry EmberGlowStrength; + + // ─── Keybinds ──────────────────────────────────────────────────────── + public static ConfigEntry StingerKey; + + // ─── Stinger Morph, the model ──────────────────────────────────────── + public static ConfigEntry StingerScaleMultiplier; + public static ConfigEntry StingerYawDegrees; + + // ─── Colony caps ───────────────────────────────────────────────────── + // Every ceiling on how many things the colony can have alive at once, in one section, so + // the "is this too many creatures for my machine" question has exactly one place to be + // answered - and can be answered without a rebuild. + // + // The nest density limit is deliberately NOT here. Two per square mile is a rule about + // what the world may look like rather than a comfort setting, and PieceDensityLimit reads + // it once when the piece registers. + public static ConfigEntry CapBrood; + public static ConfigEntry CapSeeker; + public static ConfigEntry CapSoldier; + public static ConfigEntry CapGjall; + public static ConfigEntry CapBlisterTick; + public static ConfigEntry CapFarmers; + public static ConfigEntry CapHaulers; + public static ConfigEntry CapBeehives; + + // ─── The nest and its mark ─────────────────────────────────────────── + public static ConfigEntry WorkerChestRangeValue; + public static ConfigEntry WorkerDebugValue; + public static ConfigEntry HiveScaleValue; + public static ConfigEntry EggSizeValue; + public static ConfigEntry EggHeightValue; + public static ConfigEntry DigestRateValue; + public static ConfigEntry StomachSizeValue; + public static ConfigEntry StomachHeightValue; + public static ConfigEntry MarketSizeValue; + public static ConfigEntry StageGrowthValue; + public static ConfigEntry NestVfxScaleValue; + public static ConfigEntry BeehiveVfxScaleValue; + + public static void Bind(ConfigFile config) + { + const string spines = "Sverm - Dorsal Spines"; + const string ember = "Sverm - Emberform"; + const string keybinds = "Sverm - Keybinds"; + + // G, like every other first transformation in the mod - the Aswid's bat, the Fenrir's + // wolf, the Dvergar's ping. A character only ever has one race, so they never collide. + StingerKey = config.Bind(keybinds, "Stinger Morph", new KeyboardShortcut(UnityEngine.KeyCode.G), + "Turns into a Deathsquito, and back. Unlocked at Yagluth."); + + const string stinger = "Sverm - Stinger Morph"; + + StingerScaleMultiplier = config.Bind(stinger, "Scale", 1f, + "Multiplies the deathsquito model's OWN authored scale. 1 means 'the size the " + + "game draws one'. Raise it if the insect reads as too small to be you."); + + const string nest = "Sverm - Nest"; + + HiveScaleValue = config.Bind(nest, "Nest Scale", SvermConfig.HiveScale, + "How big the nest is. Only affects nests placed AFTER the change - the ones already " + + "standing keep the size they were built at, like every other building."); + + EggSizeValue = config.Bind(nest, "Infection Egg Size", SvermConfig.HiveEggSize, + "How big the egg on a taken beehive is, in metres. The first pass used 0.35 and it " + + "was invisible in play."); + + EggHeightValue = config.Bind(nest, "Infection Egg Height", SvermConfig.HiveEggHeight, + "How far above the beehive's own origin the egg sits, in metres. Too high and it " + + "floats clear of the roof; too low and it sinks into the mesh."); + + // The two hives you press. Sizes are also how wide the sphere you point at is, so these + // decide how easy each mouth is to hit as much as how it looks. Read once, when the + // piece is registered: a change here shows up on the next launch, not on nests already + // standing. + StomachSizeValue = config.Bind(nest, "Stomach Size", SvermConfig.StomachSize, + "How big the hive at the foot of the nest is, in metres. It is the one you feed: " + + "press E on it and a whole stack goes in."); + + StomachHeightValue = config.Bind(nest, "Stomach Height", SvermConfig.StomachHeight, + "How far up the trunk the stomach sits, in metres. Zero puts it on the ground."); + + // NOT "Market Size" - that key already exists in everyone's .cfg holding the size of the + // mouth that used to hang on the trunk, and a key that is read back from a file laughs + // at a changed default. The market is a building of its own now and this is its scale, + // so it gets a name of its own too; the two old lines are orphans and are ignored. + StageGrowthValue = config.Bind(nest, "Growth At Last Stage", SvermConfig.HiveStageGrowth, + "How big a Hive Citadel is compared to the Brood Mound it started as, with the two " + + "middle stages spread evenly between. Applies to nests already standing, since it " + + "is worked out from the stage rather than baked in at placement."); + + NestVfxScaleValue = config.Bind(nest, "Nest Swarm Scale", SvermConfig.NestVfxScale, + "How big the cloud of flies over the nest is, and the green reek it gives off while " + + "it is digesting. The reek only shows when there is something going down."); + + BeehiveVfxScaleValue = config.Bind(nest, "Beehive Swarm Scale", SvermConfig.BeehiveVfxScale, + "The same two marks on a taken beehive, which wants a smaller cloud than the nest. " + + "Its gas shows when the hive is full of honey."); + + MarketSizeValue = config.Bind(nest, "Market Bench Size", SvermConfig.MarketSize, + "How big the Hive Market bench is, in metres. It is a building you raise inside a " + + "hive's ten metres, not a part of the nest."); + + DigestRateValue = config.Bind(nest, "Digestion Rate", SvermConfig.BiomassDigestRate, + "How much biomass moves from digestion into the hive's spendable bank each second. " + + "What you sell the hive is not spendable until it has gone down. At the default a " + + "full stage-one tank takes a little over three minutes. Measured against the world " + + "clock, so a hive nobody is watching digests at the same speed."); + + const string workers = "Sverm - Workers"; + + WorkerChestRangeValue = config.Bind(workers, "Chest Range", SvermConfig.WorkerChestRange, + "How far from the nest or the beehive a worker will look for a chest, in metres. " + + "Three is the design figure; widen it if your storage will not fit that close."); + + WorkerDebugValue = config.Bind(workers, "Log Rounds", false, + "Writes a line to the log when a worker finishes a round and found nothing to do. " + + "Off by default because a worker works every few seconds and would bury the log."); + + const string caps = "Sverm - Colony Caps"; + + CapBrood = config.Bind(caps, "Brood", SvermConfig.CapBrood, + "How many Seeker Brood the colony can keep alive at once."); + CapSeeker = config.Bind(caps, "Seeker", SvermConfig.CapSeeker, + "How many Seekers the colony can keep alive at once."); + CapSoldier = config.Bind(caps, "Soldier", SvermConfig.CapSoldier, + "How many Seeker Soldiers the colony can keep alive at once."); + CapGjall = config.Bind(caps, "Gjall", SvermConfig.CapGjall, + "How many Gjall the colony can keep alive at once."); + + CapBlisterTick = config.Bind(caps, "Blister Ticks", SvermConfig.CapBlisterTick, + "How many bomb ticks the colony can keep alive at once. They respawn for free, so " + + "this number is also how many explosions are in the air at any moment."); + + CapFarmers = config.Bind(caps, "Worker - Farmers", SvermConfig.CapFarmers, + "Seeker Workers produced by infected beehives, the ones that plant and harvest. " + + "Separate pool from the haulers."); + CapHaulers = config.Bind(caps, "Worker - Haulers", SvermConfig.CapHaulers, + "Seeker Workers produced by the nest after Bonemass, the ones that carry food from " + + "nearby chests into the hive. Separate pool from the farmers."); + + CapBeehives = config.Bind(caps, "Beehives per Aura", SvermConfig.HiveAuraBeehiveMax, + "How many beehives may stand in one nest's ten metres. Every one of them ends up " + + "infected and producing a worker, so this is the number that really decides how " + + "busy a base gets."); + + StingerYawDegrees = config.Bind(stinger, "Yaw", 180f, + "Turns the model on the vertical axis, in degrees. The creature's forward is not " + + "the player's, so without this it flies looking back at you. 180 is the usual " + + "answer; try 90 or -90 if it comes out sideways."); + + EmberGlowStrength = config.Bind(ember, "Glow Strength", SvermConfig.EmberGlowStrength, + "How hot the chitin burns at Fader. This multiplies an HDR colour and it is applied " + + "to the chest, the legs and the helmet at once, so it goes a very long way. Settled " + + "in game at 0.0625 after 1.0 blinded and 0.25 was still too bright. Above the bloom " + + "threshold more brightness buys a bigger white area and less red, so tune downward."); + + SpineSizeSmall = config.Bind(spines, "Size Vestigial", SvermConfig.SpineSizeSmall, + "How tall the dorsal spines stand, in metres, from Moder to the Queen."); + + SpineSizeFull = config.Bind(spines, "Size Full", SvermConfig.SpineSizeFull, + "How tall they stand from the Queen on."); + + SpineBoneName = config.Bind(spines, "Bone", SvermConfig.SpineBoneName, + "Which bone the spines ride. This bone and no other - there is no fallback, so a " + + "name that is not in the rig means no crest at all. Leave it blank to use " + + "Spine3."); + + // Defaults are the values found in game with the crest on screen, not zeroes: changing + // nothing here now reproduces the placement that was actually approved. + SpineRotationX = config.Bind(spines, "Rotation X", SvermConfig.SpineRotationX, "Pitch of the spines, in degrees."); + SpineRotationY = config.Bind(spines, "Rotation Y", SvermConfig.SpineRotationY, "Yaw of the spines, in degrees."); + SpineRotationZ = config.Bind(spines, "Rotation Z", SvermConfig.SpineRotationZ, "Roll of the spines, in degrees."); + } + + // ─── Live reads ────────────────────────────────────────────────────── + // Null-guarded so the placement code works whether or not Bind has run - the main-menu + // character preview can build a body before Awake has finished on a slow load. + + public static UnityEngine.Quaternion SpineRotation() + { + return UnityEngine.Quaternion.Euler( + SpineRotationX?.Value ?? SvermConfig.SpineRotationX, + SpineRotationY?.Value ?? SvermConfig.SpineRotationY, + SpineRotationZ?.Value ?? SvermConfig.SpineRotationZ); + } + + public static float EmberStrength => EmberGlowStrength?.Value ?? SvermConfig.EmberGlowStrength; + + public static int Brood => CapBrood?.Value ?? SvermConfig.CapBrood; + public static int Seeker => CapSeeker?.Value ?? SvermConfig.CapSeeker; + public static int Soldier => CapSoldier?.Value ?? SvermConfig.CapSoldier; + public static int Gjall => CapGjall?.Value ?? SvermConfig.CapGjall; + public static int BlisterTick => CapBlisterTick?.Value ?? SvermConfig.CapBlisterTick; + public static int Farmers => CapFarmers?.Value ?? SvermConfig.CapFarmers; + public static int Haulers => CapHaulers?.Value ?? SvermConfig.CapHaulers; + public static int Beehives => CapBeehives?.Value ?? SvermConfig.HiveAuraBeehiveMax; + + public static float ChestRange => WorkerChestRangeValue?.Value ?? SvermConfig.WorkerChestRange; + public static bool WorkerDebug => WorkerDebugValue?.Value ?? false; + + public static float HiveScale => HiveScaleValue?.Value ?? SvermConfig.HiveScale; + public static float EggSize => EggSizeValue?.Value ?? SvermConfig.HiveEggSize; + public static float EggHeight => EggHeightValue?.Value ?? SvermConfig.HiveEggHeight; + public static float DigestRate => DigestRateValue?.Value ?? SvermConfig.BiomassDigestRate; + public static float StomachSize => StomachSizeValue?.Value ?? SvermConfig.StomachSize; + public static float StomachHeight => StomachHeightValue?.Value ?? SvermConfig.StomachHeight; + public static float MarketSize => MarketSizeValue?.Value ?? SvermConfig.MarketSize; + public static float StageGrowth => StageGrowthValue?.Value ?? SvermConfig.HiveStageGrowth; + public static float NestVfxScale => NestVfxScaleValue?.Value ?? SvermConfig.NestVfxScale; + public static float BeehiveVfxScale => BeehiveVfxScaleValue?.Value ?? SvermConfig.BeehiveVfxScale; + + public static float StingerScale => StingerScaleMultiplier?.Value ?? 1f; + public static float StingerYaw => StingerYawDegrees?.Value ?? 180f; + + public static float SizeSmall => SpineSizeSmall?.Value ?? SvermConfig.SpineSizeSmall; + public static float SizeFull => SpineSizeFull?.Value ?? SvermConfig.SpineSizeFull; + /// + /// The bone name, never blank. + /// + /// An empty string is not "no preference": FindBone's loose match asks whether a bone's + /// name CONTAINS the wanted string, and every string contains the empty one - so a blank + /// entry silently mounted the crest on the first bone of the armature. Clearing the field + /// while experimenting is an obvious thing to do, so it has to mean "the default". + /// + public static string Bone + { + get + { + string configured = SpineBoneName?.Value; + return string.IsNullOrWhiteSpace(configured) ? SvermConfig.SpineBoneName : configured; + } + } + } +} diff --git a/JotunnModStub/Sverm/SvermFood.cs b/JotunnModStub/Sverm/SvermFood.cs new file mode 100644 index 0000000..dad338b --- /dev/null +++ b/JotunnModStub/Sverm/SvermFood.cs @@ -0,0 +1,273 @@ +using System.Collections.Generic; +using HarmonyLib; +using Jotunn.Entities; +using Jotunn.Managers; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// Insect Metabolism: raw meat is nearly as good as cooked, seeds are food, and honey and royal + /// jelly are worth twice what anyone else gets out of them. + /// + /// THE ONE RULE THAT SHAPES THIS FILE: never write to a vanilla item's m_shared. That object is + /// shared by every instance of the item in the game, for every player and every race - setting + /// RoyalJelly.m_food would make royal jelly edible for a Skeleton too, permanently, and a + /// Sverm's 70% raw meat would be everyone's 70% raw meat. + /// + /// So each edible gets a HIDDEN CLONE carrying the Sverm's numbers. When a Sverm right-clicks + /// the real item, the clone is what gets eaten and one of the real item is removed. The player + /// never sees the clone and the vanilla item is never touched. This is DraughFoodPatches' + /// EdibleUncooked_ trick, and it is here for the same reason it is there. + /// + public static class SvermFood + { + private const string ClonePrefix = "SvermMeal_"; + + /// Every real prefab we intercept, mapped to the clone that carries our numbers. + private static readonly Dictionary meals = new Dictionary(); + + /// Seeds are gated behind The Elder, everything else is live from tier 1. + private static readonly HashSet gatedSeeds = new HashSet(); + + private static bool registered; + + // ─── The tables ────────────────────────────────────────────────────── + + /// + /// Seeds by biome, and the numbers are deliberately modest. + /// + /// This is grinding, not cooking: raw bulk with no buff attached. The buff on a seed is + /// Trenta's whole feature (TrentaConfig.AwakenedSeedFood), and two races eating the same + /// ingredient for the same reward would cost one of them its identity. + /// + /// AncientSeed is deliberately absent. It is the offering that summons The Elder, not a + /// seed, and eating one would be an expensive accident. + /// + private struct SeedFood + { + public string Prefab; + public float Health, Stamina, Eitr, Duration, Regen; + + public SeedFood(string prefab, float health, float stamina, float eitr, float duration, float regen) + { + Prefab = prefab; Health = health; Stamina = stamina; Eitr = eitr; Duration = duration; Regen = regen; + } + } + + private static readonly SeedFood[] Seeds = + { + // Meadows - the weakest thing that still counts as a meal + new SeedFood("CarrotSeeds", 8f, 12f, 0f, 900f, 1f), + new SeedFood("TurnipSeeds", 8f, 12f, 0f, 900f, 1f), + new SeedFood("BeechSeeds", 8f, 10f, 0f, 900f, 1f), + new SeedFood("BirchSeeds", 8f, 10f, 0f, 900f, 1f), + + // Black Forest - nuts and cones, denser + new SeedFood("Acorn", 12f, 16f, 0f, 1000f, 1f), + new SeedFood("FirCone", 12f, 16f, 0f, 1000f, 1f), + new SeedFood("PineCone", 12f, 16f, 0f, 1000f, 1f), + + // Plains + new SeedFood("OnionSeeds", 16f, 20f, 0f, 1200f, 1f), + + // Mistlands - the only seeds with eitr in them, which is what makes going that far pay + new SeedFood("VineberrySeeds",20f, 24f, 8f, 1200f, 2f), + new SeedFood("VineGreenSeeds",20f, 24f, 8f, 1200f, 2f), + }; + + // ─── Registration ──────────────────────────────────────────────────── + + /// + /// Builds every clone. Driven from SvermRace.CreateModAssets, which runs on + /// PrefabManager.OnVanillaPrefabsAvailable - the one moment Jotunn accepts new items. + /// + public static void Register() + { + if (registered) return; + registered = true; + + // RAW MEAT. The raw-to-cooked table is Draugh's, borrowed on purpose rather than + // copied: which raw item becomes which cooked one is a fact about Valheim, not an + // opinion of either race, and a second copy would only drift out of step with the + // first the next time the game adds a meat. + foreach (KeyValuePair pair in DraughFoodPatches.rawToCookedMapping) + { + ItemDrop.ItemData.SharedData cooked = SharedOf(pair.Value); + if (cooked == null) continue; + + BuildMeal(pair.Key, + cooked.m_food * SvermConfig.RawMeatFraction, + cooked.m_foodStamina * SvermConfig.RawMeatFraction, + cooked.m_foodEitr * SvermConfig.RawMeatFraction, + cooked.m_foodBurnTime, + cooked.m_foodRegen, + "raw meat"); + } + + // SEEDS. Gated behind The Elder in the UseItem hook, not here: the clone can exist all + // along, it simply is not reachable before tier 3. + foreach (SeedFood seed in Seeds) + { + if (BuildMeal(seed.Prefab, seed.Health, seed.Stamina, seed.Eitr, seed.Duration, seed.Regen, "seed")) + { + gatedSeeds.Add(seed.Prefab); + } + } + + // HONEY, doubled. Read at runtime and multiplied rather than transcribed, so a patch + // that rebalances honey rebalances the Sverm with it. + ItemDrop.ItemData.SharedData honey = SharedOf("Honey"); + if (honey != null) + { + BuildMeal("Honey", + honey.m_food * SvermConfig.HoneyMultiplier, + honey.m_foodStamina * SvermConfig.HoneyMultiplier, + honey.m_foodEitr * SvermConfig.HoneyMultiplier, + honey.m_foodBurnTime * SvermConfig.HoneyMultiplier, + honey.m_foodRegen, + "honey"); + } + + // ROYAL JELLY. Not a food in vanilla at all - it is crafting material - so there is + // nothing to double and the numbers are the ones the design settled on. They are + // already the doubled figures; they are not multiplied again. + BuildMeal(SvermConfig.RoyalJellyPrefab, + SvermConfig.RoyalJellyHealth, + SvermConfig.RoyalJellyStamina, + SvermConfig.RoyalJellyEitr, + SvermConfig.RoyalJellyDuration, + SvermConfig.RoyalJellyRegen, + "royal jelly"); + + Jotunn.Logger.LogInfo($"[Sverm] Insect Metabolism: {meals.Count} edibles registered."); + } + + private static ItemDrop.ItemData.SharedData SharedOf(string prefabName) + { + ItemDrop drop = PrefabManager.Cache.GetPrefab(prefabName); + return drop != null && drop.m_itemData != null ? drop.m_itemData.m_shared : null; + } + + /// + /// One hidden clone of one real item, carrying the Sverm's numbers. + /// + /// The clone is made a Consumable whatever the original was - a seed is Material in vanilla + /// and would otherwise be refused by EatFood before it got to look at the numbers. + /// + private static bool BuildMeal(string sourcePrefab, float health, float stamina, float eitr, + float duration, float regen, string label) + { + GameObject source = PrefabManager.Cache.GetPrefab(sourcePrefab); + if (source == null) + { + Jotunn.Logger.LogWarning($"[Sverm] No '{sourcePrefab}' to build a {label} from; skipped."); + return false; + } + + string cloneName = ClonePrefix + sourcePrefab; + GameObject clone = PrefabManager.Instance.CreateClonedPrefab(cloneName, source); + if (clone == null) return false; + + ItemDrop drop = clone.GetComponent(); + if (drop == null || drop.m_itemData == null || drop.m_itemData.m_shared == null) return false; + + ItemDrop.ItemData.SharedData shared = drop.m_itemData.m_shared; + shared.m_itemType = ItemDrop.ItemData.ItemType.Consumable; + shared.m_food = health; + shared.m_foodStamina = stamina; + shared.m_foodEitr = eitr; + shared.m_foodBurnTime = duration; + shared.m_foodRegen = regen; + + // The name is what Player.Food compares on when it decides whether you are eating the + // same thing twice, so it must stay the ORIGINAL's name - otherwise raw meat and its + // clone would occupy two food slots at once. + // m_maxStackSize left alone; nothing ever holds one of these. + + ItemManager.Instance.AddItem(new CustomItem(clone, fixReference: false)); + meals[sourcePrefab] = cloneName; + return true; + } + + // ─── Eating ────────────────────────────────────────────────────────── + + /// Which clone answers for this item, or null when we do not cover it. + private static string MealFor(ItemDrop.ItemData item, int state) + { + if (item == null || item.m_shared == null) return null; + + string prefabName = item.m_dropPrefab != null ? item.m_dropPrefab.name : null; + if (string.IsNullOrEmpty(prefabName)) return null; + + if (gatedSeeds.Contains(prefabName) && state < SvermConfig.SeedsEdibleState) return null; + + return meals.TryGetValue(prefabName, out string clone) ? clone : null; + } + + public static bool IsGatedSeed(string prefabName) => gatedSeeds.Contains(prefabName); + + /// + /// Swaps the real item for its clone at the moment of eating. + /// + /// A prefix on UseItem rather than on EatFood, and that is what lets seeds and royal jelly + /// work at all: they are Material in vanilla, so by the time EatFood is reached the game + /// has already decided they are not food. UseItem runs before that judgement. + /// + [HarmonyPatch(typeof(Humanoid), "UseItem")] + public static class Sverm_UseItem_Patch + { + 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 (!SvermVisuals.IsSvermPlayer(player)) return true; + if (item == null || item.m_shared == null) return true; + + // MEDICINE BEFORE FOOD, and called from here rather than from a prefix of its own: + // honey and royal jelly are both a meal and the colony's medicine, and which one a + // press means is decided by whether the player is looking at one of our insects. + // Two prefixes both wanting to answer that first would be a coin toss. + if (SvermMedicine.TryAdminister(player, item)) return false; + + // The one thing a Sverm may not eat. Blocked here rather than left to fail + // silently, so the refusal says why. + if (item.m_dropPrefab != null && item.m_dropPrefab.name.StartsWith("SvermMeal_") == false + && IsAswidBlood(item)) + { + player.Message(MessageHud.MessageType.Center, "Alchemical blood is not food."); + return false; + } + + string cloneName = MealFor(item, BossProgressionManager.GetCurrentProgressionState()); + if (cloneName == null) return true; + + GameObject clonePrefab = ObjectDB.instance != null ? ObjectDB.instance.GetItemPrefab(cloneName) : null; + ItemDrop cloneDrop = clonePrefab != null ? clonePrefab.GetComponent() : null; + if (cloneDrop == null) return true; // registration failed; let vanilla decide + + if (!player.EatFood(cloneDrop.m_itemData)) return false; // full, or too soon - vanilla already said so + + if (inventory != null) inventory.RemoveItem(item, 1); + + EffectList consume = Traverse.Create(player).Field("m_consumeItemEffects").Value; + if (consume != null) consume.Create(player.transform.position, Quaternion.identity, player.transform, 1f, -1); + + ZSyncAnimation anim = Traverse.Create(player).Field("m_zanim").Value; + if (anim != null) anim.SetTrigger("eat"); + + return false; // handled + } + + /// + /// The Aswid's alchemical blood, recognised without a hard dependency on that race's + /// tables: everything it makes carries its own prefix. + /// + private static bool IsAswidBlood(ItemDrop.ItemData item) + { + string name = item.m_dropPrefab != null ? item.m_dropPrefab.name : ""; + return name.StartsWith("Aswid") || name == "BloodEssence" || name.Contains("BloodPotion"); + } + } + } +} diff --git a/JotunnModStub/Sverm/SvermHive.cs b/JotunnModStub/Sverm/SvermHive.cs new file mode 100644 index 0000000..f5ed0ca --- /dev/null +++ b/JotunnModStub/Sverm/SvermHive.cs @@ -0,0 +1,621 @@ +using System.Collections.Generic; +using Jotunn.Configs; +using Jotunn.Entities; +using Jotunn.Managers; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// The nest itself: the piece, its gate, and the ten metres of ground it claims. + /// + /// GATED ON THE ELDER, and that gate is the whole point of the revision. The colony used to + /// open at tier 1 and arrive all at once; now the early game is spent as a body, and the first + /// nest is a thing you earn. What the boss decides is WHEN you may plant one - how fast it + /// grows after that is still bought with biomass, four stages at the shop, exactly as before. + /// + /// THE AURA is what makes it read as a colony rather than as a machine. Inside ten metres the + /// Sverm may raise up to ten vanilla beehives, and they cost only wood - no queen bee, because + /// a colony that has to go hunting for someone else's queen is telling the wrong story. Left + /// alone for a minute, each hive is taken over: an egg pushes out through the roof, and from + /// then on it works twice as fast and holds three times as much. + /// + /// This file owns the piece and the aura. Biomass, eggs, troops and the shop are + /// SvermHiveBehaviour's; the workers are SvermWorker's. + /// + public static class SvermHive + { + public const string PieceName = SvermHiveNames.PieceName; + public const string DisplayName = SvermHiveNames.PieceDisplayName; + + /// + /// What the nest borrows its body from, best first. + /// + /// "Hive" WAS the first entry and it was a disaster. The name is in the game's manifest and + /// it sounds exactly right, so it went in unchecked - and it turned out to carry a + /// Character. Building it did not place a nest, it SPAWNED A CREATURE, and because a Piece + /// and a WearNTear had been bolted on top without removing anything, the health the console + /// tried to take off was not the health holding it up. A giant immortal Bonemass, from a + /// name that read as scenery. + /// + /// Everything in this list now is a CreepProp - the game's own word for "this is a prop" - + /// and IsSafeScenery below refuses anything alive whatever the list says. + /// + private static readonly string[] SourceCandidates = + { + "CreepProp_pillar01", + "CreepProp_egg_hanging01", + "Creeppillar", + "CreepProp_hanging01", + }; + + public static void Register() + { + GameObject prefab = null; + string sourcePrefab = null; + + foreach (string candidate in SourceCandidates) + { + GameObject source = PrefabManager.Cache.GetPrefab(candidate); + if (source == null) continue; + + if (!IsSafeScenery(source, candidate)) continue; + + prefab = PrefabManager.Instance.CreateClonedPrefab(PieceName, source); + if (prefab == null) continue; + + sourcePrefab = candidate; + break; + } + + if (prefab == null) + { + Jotunn.Logger.LogWarning("[Sverm] No safe scenery to build the nest from (" + + string.Join(", ", SourceCandidates) + "); the nest is not registered. " + + "Not registering is the correct outcome: a nest nobody can build beats " + + "a nest that turns out to be alive."); + return; + } + + // Belt as well as braces: anything that could still make this act like a creature comes + // off the COPY. The guard above should mean there is nothing to find, and this is what + // makes that true rather than hoped for. + StripLife(prefab); + + // Set on the PREFAB, so every nest ever placed comes out this size and the value is + // baked into the piece rather than chased at runtime. It follows that changing it in + // the .cfg only affects nests placed afterwards - the ones already standing keep the + // size they were built at, which is how every other building in the game behaves. + float scale = SvermConfigManagement.HiveScale; + prefab.transform.localScale = new Vector3(scale, scale, scale); + + // A hive in the world is scenery, not a building: it arrives with no Piece and no + // WearNTear, and the hammer needs both. Added rather than assumed - the clone is + // whatever the game shipped, and asking for a component that is not there is how a + // station ends up unplaceable with no error. + Piece piece = prefab.GetComponent() ?? prefab.AddComponent(); + piece.m_name = DisplayName; + piece.m_description = "The colony begins here. Everything else grows out of it."; + piece.m_groundPiece = true; + piece.m_groundOnly = true; + piece.m_cultivatedGroundOnly = false; + piece.m_canBeRemoved = true; + + if (prefab.GetComponent() == null) + { + WearNTear wear = prefab.AddComponent(); + wear.m_health = 1500f; + wear.m_noRoofWear = true; + wear.m_noSupportWear = true; + wear.m_destroyedEffect = new EffectList(); + wear.m_hitEffect = new EffectList(); + } + + if (prefab.GetComponent() == null) prefab.AddComponent(); + prefab.AddComponent(); + + MountMouths(prefab); + + PieceManager.Instance.AddPiece(new CustomPiece(prefab, fixReference: false, new PieceConfig + { + Name = DisplayName, + Description = piece.m_description, + PieceTable = PieceTables.Hammer, + Category = "Crafting", + + // NOT OPTIONAL. Jotunn refuses a piece with no icon outright - "CustomPiece has no + // icon" followed by "is not valid" - and the piece simply never reaches the + // hammer. Borrowed off a trophy, the way SkeletonBonePile does. + Icon = BorrowIcon("TrophySeekerBrute") ?? BorrowIcon("TrophySeeker") ?? BorrowIcon("Honey"), + Requirements = new[] + { + new RequirementConfig { Item = "Wood", Amount = 40, Recover = true }, + new RequirementConfig { Item = "Resin", Amount = 20, Recover = true }, + }, + })); + + // Two per square mile, as before. The radius is 908 m because that is the circle of + // equal area, and PieceDensityLimit counts over ZDOs rather than loaded objects. + PieceDensityLimit.Register(PieceName, SvermConfig.HiveDensityRadius, SvermConfig.HiveDensityMax, + "There is already a hive holding this ground."); + + // The gate. Race first, then the boss - two separate refusals, because "you are not a + // Sverm" and "you have not killed The Elder" are different problems and a player who + // gets the wrong message goes looking in the wrong place. + PieceDensityLimit.RegisterGate(PieceName, (player, position) => + { + if (player == null) return false; + + if (!SvermVisuals.IsSvermPlayer(player)) + { + player.Message(MessageHud.MessageType.Center, "Only the Sverm can raise a hive."); + return false; + } + + if (BossProgressionManager.GetCurrentProgressionState() < SvermConfig.HiveUnlockState) + { + player.Message(MessageHud.MessageType.Center, "The colony will not wake until the Elder falls."); + return false; + } + + return true; + }); + + Jotunn.Logger.LogInfo($"[Sverm] Registered '{PieceName}' from '{sourcePrefab}'."); + } + + /// + /// What the two mouths borrow their look from, best first. SCENERY ONLY. + /// + /// "Hive" WAS ON THIS LIST for one build, on the reasoning that ModelBorrow strips a copy + /// down to its renderers so borrowing a living prefab is safe. IT IS NOT, and the game said + /// so in one line nobody had asked it for: + /// + /// Can't remove Humanoid (Script) because CharacterDrop (Script) depends on it + /// + /// ModelBorrow's strip is a single pass in component order. Unity REFUSES to destroy a + /// component another one still requires, so Humanoid survived on both mouths - and from then + /// on every placement ghost woke a Humanoid, registered it in Character.s_characters and + /// tore it down again, until Character.GetCharactersInRange threw on the wreckage inside + /// Player.UpdatePlacementGhost. The hammer stopped working. FOR EVERY PIECE IN THE GAME, not + /// just this one. + /// + /// Which is house rule one, twice over: ask the prefab whether it has a Character, and do + /// not trust a helper to have asked for you. IsSafeScenery below now runs on the source + /// BEFORE anything is borrowed from it. + /// + private static readonly string[] MouthCandidates = + { + "TheHive", + "CreepProp_egg_hanging01", + "CreepProp_egg_hanging02", + "SeekerEgg", + "CreepProp_hanging01", + }; + + /// + /// The stomach: the hive at the nest's foot that a press feeds. + /// + /// A MOUTH AND NOT A MENU, at the player's call, after a sell panel inside the vanilla store + /// came up empty and unclickable in game. Feeding is a press on a thing you can see, which + /// needs no UI to be right. + /// + /// THERE WAS A SECOND MOUTH UP THE TRUNK, the shop, and it is gone: it never had a height + /// that worked. On the measured crown it was eight metres over the player's head; at the + /// number that replaced it the .cfg still held the old zero, so it sat inside the stomach's + /// own sphere and the ray always found the stomach first. The shop is its own building now - + /// SvermHiveMarketPiece - which is how the Dvergar bench and the Trol totem already do it. + /// + /// The mouth gets a SPHERE OF ITS OWN because Player.FindHoverObject picks what you are + /// pointing at from the first collider the ray meets and reads the Hoverable off THAT + /// collider's own GameObject. A mouth sharing the trunk's collider would not be a mouth. The + /// sphere is as wide as the model, so it stands clear of the trunk rather than hiding inside + /// it - the one thing that would make it unreachable. + /// + private static void MountMouths(GameObject prefab) + { + // Measured BEFORE the mouths are hung, or it would be measuring them too. This is the + // trunk's own height, in the piece's local space, and it is what "up top" means when + // nobody has typed a number into the .cfg. + float trunk = ModelBorrow.HeightOf(prefab); + + GameObject source = null; + string sourceName = null; + foreach (string candidate in MouthCandidates) + { + GameObject found = PrefabManager.Cache.GetPrefab(candidate); + if (found == null) continue; + + // The same question the piece itself has to answer, asked again here: a model is + // borrowed from this, and a borrowed model that turns out to be alive is what broke + // the hammer. + if (!IsSafeScenery(found, candidate)) continue; + + source = found; + sourceName = candidate; + break; + } + + if (source == null) + { + Jotunn.Logger.LogWarning("[Sverm] No safe scenery to borrow the nest's mouths from (" + + string.Join(", ", MouthCandidates) + "); they are mounted " + + "anyway, invisible but pressable, rather than leaving the " + + "nest with no way to be fed."); + } + + // The trunk is REPORTED and not used as a height: it measured 10.59 m, which is the + // number that made the old market unreachable. Kept in the log because it is the only + // way anyone can tell where there is room to put something on this piece. + Jotunn.Logger.LogInfo($"[Sverm] Nest stomach borrowed from '{sourceName ?? "nothing"}'; the trunk " + + $"measures {trunk:0.##} m and the stomach sits at " + + $"{SvermConfigManagement.StomachHeight:0.##} m."); + + MountMouth(prefab, source, "SvermHiveStomach", + SvermConfigManagement.StomachSize, SvermConfigManagement.StomachHeight); + } + + private static void MountMouth(GameObject prefab, GameObject source, string holderName, + float size, float height) where T : SvermHiveMouth + { + GameObject holder = ModelBorrow.Attach(prefab.transform, holderName, source, + new Vector3(0f, height, 0f), Quaternion.identity, size, "Sverm"); + + // The piece's own layer, because that is the layer the player's interact raycast looks + // at. A GameObject built from scratch comes up on Default, and Default is not it. + holder.layer = prefab.layer; + + // Centred half a size up: ModelBorrow grounds a borrowed model on the holder's origin, + // so the holder's origin is the model's FOOT and not its middle. + SphereCollider ball = holder.AddComponent(); + ball.center = new Vector3(0f, size * 0.5f, 0f); + ball.radius = size * 0.5f; + + holder.AddComponent(); + } + + /// + /// Refuses to build a building out of anything that is alive. + /// + /// This is the check that was missing, and its absence cost a giant immortal Bonemass in + /// somebody's base. A name in the asset manifest says nothing about what a prefab DOES - + /// "Hive" carried a Character - and the only way to know is to ask the prefab itself. + /// + /// It logs what it found rather than failing quietly, because the next person to add a + /// station from a borrowed prefab needs to be told which one to stop trusting. + /// + internal static bool IsSafeScenery(GameObject source, string name) + { + if (source.GetComponentInChildren(true) != null) + { + Jotunn.Logger.LogWarning($"[Sverm] '{name}' carries a Character - it is a CREATURE, not scenery. " + + "Refusing to make a building out of it."); + return false; + } + + if (source.GetComponentInChildren(true) != null) + { + Jotunn.Logger.LogWarning($"[Sverm] '{name}' carries a BaseAI; refusing to make a building out of it."); + return false; + } + + if (source.GetComponentInChildren(true) != null) + { + Jotunn.Logger.LogWarning($"[Sverm] '{name}' is a spawner; refusing to make a building out of it."); + return false; + } + + return true; + } + + /// + /// Takes everything that could still behave like a creature off the copy. + /// + /// Order matters for the same reason it does in ModelBorrow: behaviours first, then the + /// things they hold references to. + /// + internal static void StripLife(GameObject copy) + { + foreach (BaseAI ai in copy.GetComponentsInChildren(true)) + { + if (ai != null) Object.DestroyImmediate(ai); + } + foreach (Character character in copy.GetComponentsInChildren(true)) + { + if (character != null) Object.DestroyImmediate(character); + } + foreach (CharacterDrop drop in copy.GetComponentsInChildren(true)) + { + if (drop != null) Object.DestroyImmediate(drop); + } + foreach (SpawnArea spawner in copy.GetComponentsInChildren(true)) + { + if (spawner != null) Object.DestroyImmediate(spawner); + } + foreach (Rigidbody body in copy.GetComponentsInChildren(true)) + { + if (body != null) Object.DestroyImmediate(body); + } + } + + /// + /// The nest this point belongs to, or null. + /// + /// Loaded objects and not ZDOs, deliberately: the only caller is the market bench, which is + /// standing inside the nest's ten metres or it would not have been allowed to exist. A nest + /// that close is loaded by definition, and the cheap answer is the right one. + /// + internal static SvermHiveBehaviour NearestNest(Vector3 position, float radius) + { + SvermHiveBehaviour closest = null; + float best = radius; + + foreach (SvermHiveBehaviour nest in Object.FindObjectsOfType()) + { + if (nest == null) continue; + + float distance = Vector3.Distance(nest.transform.position, position); + if (distance > best) continue; + + best = distance; + closest = nest; + } + + return closest; + } + + /// An item's inventory icon, or null. Same helper shape as SkeletonBonePile's. + internal static Sprite BorrowIcon(string prefabName) + { + ItemDrop drop = PrefabManager.Cache.GetPrefab(prefabName); + if (drop == null || drop.m_itemData == null || drop.m_itemData.m_shared == null) return null; + if (drop.m_itemData.m_shared.m_icons == null || drop.m_itemData.m_shared.m_icons.Length == 0) return null; + return drop.m_itemData.m_shared.m_icons[0]; + } + } + + /// + /// The nest's own upkeep. Today that is the aura and the beehives inside it; biomass, eggs, + /// troops and the shop land here next. + /// + public class SvermHiveBehaviour : MonoBehaviour, Hoverable, Interactable + { + /// + /// The trunk feeds, exactly like the stomach at its foot. + /// + /// IT USED TO TAKE WHAT WAS IN YOUR HAND, which could not be made to work: food is a + /// consumable, it never reaches the weapon slot, and the meat the player thought they were + /// offering was simply eaten by the player. It reads the inventory now. + /// + /// The trunk is the widest thing to point at, so it does the thing you do most rather than + /// being a dead spot between the two mouths. The store has one way in and it is the hive up + /// top - see SvermHiveMarket. + /// + public bool Interact(Humanoid user, bool hold, bool alt) + { + if (hold) return false; + + Player player = user as Player; + if (player == null || player != Player.m_localPlayer) return false; + + if (!SvermVisuals.IsSvermPlayer(player)) + { + player.Message(MessageHud.MessageType.Center, "The hive does not know you."); + return true; + } + + return SvermHiveStore.FeedOneStack(this, player); + } + + public bool UseItem(Humanoid user, ItemDrop.ItemData item) => false; + + /// + /// What the nest says when you look at it. + /// + /// The tank had no readout at all in the first pass, which made every other part of the + /// colony unfalsifiable: a hauler that was not working and a hauler that was working + /// looked exactly the same. A number on the hive is the cheapest possible test of the + /// whole chain. + /// + public string GetHoverText() + { + int beehives = SvermBeehive.CountInAura(transform.position); + int infected = SvermBeehive.CountInfectedInAura(transform.position); + + // Both numbers, always, even when nothing is going down. A line that appears and + // disappears is one the player has to notice twice before they believe it. + return $"{SvermHiveStage.NameOf(SvermHiveStage.Of(transform))}\n" + + SvermHiveReadout.Tank(transform) + + $"Beehives {infected} taken of {beehives} in range\n" + + "[$KEY_Use] Feed it a stack"; + } + + public string GetHoverName() => SvermHiveStage.NameOf(SvermHiveStage.Of(transform)); + + private ZNetView nview; + private float nextSweep; + private float nextHauler; + private float nextDigest; + private float nextTick; + private float nextVfx; + + /// + /// The size this nest was built at, before any growth is applied on top. + /// + /// Read at Awake and kept, rather than taken from the config each time: the piece is + /// registered at the configured scale, so what the transform holds when it loads IS the size + /// this particular nest was placed at - which is the promise the config makes, that changing + /// it never resizes nests already standing. + /// + private Vector3 builtScale = Vector3.one; + private float shownScale = -1f; + + private void Awake() + { + nview = GetComponent(); + builtScale = transform.localScale; + + // A station, in the same sense the Draugh spawner and the Dvergar bank are: this is what + // the troops bound to it look for to decide they are not orphans. Without it the whole + // garrison would wither a minute after it hatched. + RaisedThrall.RegisterStation(transform); + + // Before the first frame is drawn, or a grown nest pops from small to large in front of + // whoever is standing there when it loads. + ApplyStageScale(); + } + + private void OnDestroy() + { + // StationStandsAt cleans destroyed transforms out of its own list, so this is belt as + // well as braces - but a nest that is torn down should stop being a home the same frame, + // not the next time somebody asks. + RaisedThrall.UnregisterStation(transform); + } + + /// + /// Puts the stage on screen. Every client does this off the ZDO, so nobody has to own the + /// nest to see it the right size - section 9.1's "la scala va sul ZDO", by derivation rather + /// than by a second synced field. + /// + private void ApplyStageScale() + { + if (nview == null || !nview.IsValid()) return; + + // The SCALE and not the stage is what is remembered, so that retuning the growth in the + // .cfg moves the nests already standing instead of waiting for a stage they may never + // buy again. + float wanted = SvermHiveStage.ScaleOf(SvermHiveStage.Of(transform)); + if (Mathf.Approximately(wanted, shownScale)) return; + + shownScale = wanted; + transform.localScale = builtScale * wanted; + } + + private void Update() + { + // ABOVE the owner check, and that is the point of it: the client who bought the stage is + // not necessarily the client who owns the nest, and everyone has to see it grow. + ApplyStageScale(); + + // Same reason, same place. The flies hang over the nest always; the green reek only + // while there is something going down, which makes the digestion a thing you can see + // from across the field instead of a number on a hover text. + if (Time.time >= nextVfx) + { + nextVfx = Time.time + 2f; + + float scale = SvermConfigManagement.NestVfxScale; + SvermHiveVfx.EnsureFlies(transform, scale); + SvermHiveVfx.SetGas(transform, SvermBiomass.Digesting(transform) > 0f, scale); + + // The taken beehives wear the same two marks, smaller. Driven from here rather than + // from the sweep because the sweep is the OWNER's round and these have to show up on + // every client. + SvermBeehive.DressInfected(transform.position); + } + + // Only the owner runs the colony. Every client seeing this nest would otherwise infect + // the same beehives over and over, each writing its own answer to the same ZDO. + if (nview == null || !nview.IsValid() || !nview.IsOwner()) return; + + // Ahead of the sweep gate and on a clock of its own: the sweep walks a sphere of + // colliders and can afford to wait five seconds, while a number the player is standing + // there watching should move about as often as they can see it move. What is actually + // digested comes from the world clock, so this interval only decides how smooth the + // readout is, never how fast the hive works. + if (Time.time >= nextDigest) + { + nextDigest = Time.time + 1f; + SvermBiomass.Digest(transform); + + // Eggs work themselves out from the world clock, so this only writes down what has + // already happened - which is what keeps the number the other clients read close to + // the truth. + SvermBroodEggs.Settle(transform); + } + + // The ticks' free respawn, on its own half-minute clock: an empty paid slot grows a new + // one, one per pass, so a wiped-out swarm trickles back rather than arriving all at once. + if (Time.time >= nextTick) + { + nextTick = Time.time + SvermConfig.TickRespawnSeconds; + SvermBlisterTick.Replace(this); + } + + if (Time.time < nextSweep) return; + nextSweep = Time.time + SvermConfig.HiveAuraSweepInterval; + + SvermBeehive.SweepAura(transform.position); + + Haul(); + + // Haulers come out of the NEST, and only after Bonemass. The farmers are the beehives' + // business, not the nest's - see SvermBeehive. + if (BossProgressionManager.GetCurrentProgressionState() >= SvermConfig.HaulerUnlockState && + Time.time >= nextHauler && + SvermWorker.HasRoom(SvermWorker.Job.Hauler)) + { + nextHauler = Time.time + SvermConfig.WorkerSpawnInterval; + SvermWorker.Spawn(SvermWorker.Job.Hauler, transform); + } + } + + /// + /// The nest eats out of the chests around it, once per living hauler per sweep. + /// + /// THE WORK MOVED HERE FROM THE WORKERS, and that is the fix rather than a shortcut. A + /// hauler is a creature: it wanders, it picks fights, it dies, and every one of those took + /// the whole supply chain with it - chests stayed full and the tank stayed at zero with + /// nothing to point at. The nest never moves and is always exactly where the chests are. + /// + /// The haulers still matter: no hauler, no hauling. They are the reason the nest can do + /// it, and they defend the chests they feed from - which is what they were always meant to + /// be doing. What they are no longer is a single point of failure for the economy. + /// + private void Haul() + { + int hands = SvermWorker.Count(SvermWorker.Job.Hauler); + if (hands <= 0) return; + + float range = SvermConfigManagement.ChestRange; + + foreach (Container container in Object.FindObjectsOfType()) + { + if (container == null) continue; + if (Vector3.Distance(container.transform.position, transform.position) > range) continue; + + Inventory inventory = container.GetInventory(); + if (inventory == null) continue; + + foreach (ItemDrop.ItemData item in new List(inventory.GetAllItems())) + { + if (item == null || item.m_shared == null) continue; + if (!SvermBiomass.IsFuel(item)) continue; + + float taken = SvermBiomass.Deposit(transform, item); + if (taken <= 0f) return; // tank full: leave everything where it is + + inventory.RemoveItem(item, 1); + + // Container.Save is private in the shipped assembly, so the write is pushed + // through reflection. Without it the chest empties on this client and refills + // from the server's copy, which reads as nothing having happened. + ZNetView cview = container.GetComponent(); + if (cview != null && cview.IsValid()) + { + HarmonyLib.Traverse.Create(container).Method("Save").GetValue(); + } + + if (--hands <= 0) return; + } + } + } + + /// How many beehives are already claimed by this nest. Used by the build gate. + public int CountBeehives() + { + return SvermBeehive.CountInAura(transform.position); + } + } +} diff --git a/JotunnModStub/Sverm/SvermHiveGoods.cs b/JotunnModStub/Sverm/SvermHiveGoods.cs new file mode 100644 index 0000000..7962d3c --- /dev/null +++ b/JotunnModStub/Sverm/SvermHiveGoods.cs @@ -0,0 +1,499 @@ +using System; +using System.Collections.Generic; +using HarmonyLib; +using TMPro; +using UnityEngine; +using UnityEngine.UI; + +namespace RacesOfValheim +{ + /// + /// What the Hive Market sells, and the column it is sold from. + /// + /// THE VANILLA BUY LIST CANNOT CARRY THIS. StoreGui's own column is a list of + /// Trader.TradeItem, every one of which is an ItemDrop that lands in your inventory when you pay + /// coin for it. The hive sells no items: it sells a stage of growth, which is a number on its + /// own ZDO. So the goods hang in a column of our own, cloned from the store's list element - + /// exactly what TrolTotemStore does for its warbands, down to sitting at m_listRoot's own + /// position and switching itself off when the window belongs to somebody else. + /// + /// That position matters and it is the correction of a failed attempt: the first version of the + /// hive's panel put its column at m_listRoot's position PLUS 260 px, which is outside the panel + /// that clips it. It drew perfectly and nobody could see or click a single row of it. + /// + /// PRICES ARE THE DOCUMENT'S, unchanged: 1000, 1500, 2000, each one the full tank of the stage + /// it buys you out of, so growing always empties the hive. + /// + public static class SvermHiveGoods + { + /// One thing the market sells. + public class Good + { + public string Id; + public string Name; + public float Price; + public string Icon; + public string Description; + + /// Why this cannot be bought right now, or null when it can. + public Func Refusal; + + /// Hands over the goods. Only ever called after the price has been taken. + public Action Deliver; + + /// + /// How long before another of these, in seconds. A function and not a number because the + /// upgrades wait a GAME DAY, and how long a game day is belongs to the world rather than + /// to this table. + /// + public Func Cooldown; + } + + /// + /// The shelf: three stages, two stars, four troops. + /// + /// NO VENOM COIL. Section 13's serpent turret was built and then taken out again at the + /// player's call - it is not on this shelf, there is no prefab for it, and it is not a thing + /// waiting to be finished. If it ever comes back it comes back as a new decision. + /// + /// Stages first, because they are what unlocks the rest of the list. + /// + public static readonly List Shelf = BuildShelf(); + + private static List BuildShelf() + { + List shelf = new List + { + StageUpgrade(2, "TrophySeeker"), + StageUpgrade(3, "TrophySeekerBrute"), + StageUpgrade(4, "TrophySeekerQueen"), + + Star(1, "Surrenal Glands", 800f, "TrophySeeker", + "Every troop hatched from now on is born with one star.\n\n" + + "It does nothing for the ones already walking around: what is born is born."), + + Star(2, "Hyperplasia", 1600f, "TrophySeekerQueen", + "Every troop hatched from now on is born with two stars.\n\n" + + "The colony has to have grown the glands first."), + }; + + foreach (SvermBrood.Kind kind in SvermBrood.Roster) shelf.Add(Troop(kind)); + + shelf.Add(BlisterTick()); + + return shelf; + } + + /// + /// The bomb tick, which is the only thing on this shelf you buy ONCE and keep having. + /// Section 12: fifty biomass and an egg buy a slot, the slot is permanent, and whatever + /// stands in it comes back for free half a minute after it bursts. + /// + private static Good BlisterTick() + { + return new Good + { + Id = "blistertick", + Name = SvermBlisterTick.DisplayName, + Price = SvermConfig.TickPrice, + Icon = "TrophyTick", + Description = "Buys a PERMANENT slot in the colony. What stands in it runs at whatever " + + "the colony is fighting and bursts, and thirty seconds later the nest " + + "grows another one - no egg, no biomass, forever.\n\n" + + "The blast spares you, your tames and the rest of the colony.", + + Refusal = hive => + { + int slots = SvermBlisterTick.SlotsOf(hive.transform); + if (slots >= SvermConfigManagement.BlisterTick) + { + return $"The colony already keeps {slots} of them."; + } + + if (SvermBroodEggs.Count(hive.transform) < 1) return "No brood egg ready."; + + return null; + }, + + Deliver = hive => + { + if (!SvermBroodEggs.Take(hive.transform, 1)) + { + SvermBiomass.Refund(hive.transform, SvermConfig.TickPrice); + return; + } + + SvermBlisterTick.BuySlot(hive.transform); + SvermBlisterTick.Hatch(hive); + }, + + // The tick has no queue of its own: the wait is the thirty seconds it takes to come + // back, and that is enforced at the nest rather than at the counter. + Cooldown = () => 0f, + }; + } + + /// + /// One step up the four stages. The price is the tank it empties, from section 10.1. + /// + private static Good StageUpgrade(int target, string icon) + { + int from = target - 1; + + return new Good + { + Id = "stage" + target, + Name = SvermHiveStage.NameOf(target), + Price = SvermHiveStage.PriceToLeave(from), + Icon = icon, + Description = $"Grows the nest into a {SvermHiveStage.NameOf(target)}: it holds " + + $"{SvermHiveStage.Capacity(target):0} biomass instead of " + + $"{SvermHiveStage.Capacity(from):0}, and stands half again as tall.\n\n" + + "It costs this stage's whole tankful, so it leaves the hive all but " + + "empty. Grow or field an army - never both in the same breath.", + + Refusal = hive => + { + int stage = SvermHiveStage.Of(hive.transform); + if (stage > from) return "Already grown past this."; + if (stage < from) return $"The nest has to be a {SvermHiveStage.NameOf(from)} first."; + return null; + }, + + Deliver = hive => SvermHiveStage.Advance(hive.transform), + + Cooldown = () => DayLength() * SvermConfig.UpgradeCooldownDays, + }; + } + + /// + /// One of the two permanent star upgrades. They are a ladder: the glands before the + /// hyperplasia. + /// + /// THE LADDER IS AN INVENTION. The document prices them separately and says nothing about + /// needing one for the other - but without it the cheap path to two stars is to skip the + /// eight hundred entirely, which makes the first upgrade a thing only a mistake buys. + /// + private static Good Star(int stars, string name, float price, string icon, string description) + { + return new Good + { + Id = "stars" + stars, + Name = name, + Price = price, + Icon = icon, + Description = description, + + Refusal = hive => + { + int have = SvermBroodStars.Of(hive.transform); + if (have >= stars) return "The colony already breeds like this."; + if (have < stars - 1) return "One star at a time."; + return null; + }, + + Deliver = hive => SvermBroodStars.Set(hive.transform, stars), + + Cooldown = () => DayLength() * SvermConfig.UpgradeCooldownDays, + }; + } + + /// + /// One rung of the roster on sale. Costs biomass AND a brood egg, which is section 10.2's + /// two resources in parallel: the egg is the slot and grows back, the biomass is the price + /// and does not. + /// + private static Good Troop(SvermBrood.Kind kind) + { + return new Good + { + Id = "troop_" + kind.Id, + Name = kind.Display, + Price = kind.Price, + Icon = kind.Icon, + Description = $"Hatches a {kind.Display}, bound to this nest: it follows when you ask, " + + $"walks home when you let it go, and mends itself.\n\n" + + $"Costs one brood egg as well as the biomass. At most {kind.Cap} of them alive at once.", + + Refusal = hive => + { + int stage = SvermHiveStage.Of(hive.transform); + if (stage < kind.Stage) + { + return $"The nest has to be a {SvermHiveStage.NameOf(kind.Stage)} first."; + } + + int alive = SvermBrood.CountAlive(hive, kind); + if (alive >= kind.Cap) return $"The colony is already keeping {alive} of them."; + + if (SvermBroodEggs.Count(hive.transform) < 1) return "No brood egg ready."; + + return null; + }, + + Deliver = hive => + { + // The egg is taken here rather than in Buy, because it is this good's price and + // not every good's: an upgrade costs biomass and nothing else. + // + // And if the egg is gone between the refusal check and this line - which only two + // players at one nest can manage - the biomass goes back. A purchase that took + // the price and handed over nothing is the one outcome worth writing code for. + if (!SvermBroodEggs.Take(hive.transform, 1)) + { + SvermBiomass.Refund(hive.transform, kind.Price); + return; + } + + if (!SvermBrood.Hatch(hive, kind)) + { + SvermBiomass.Refund(hive.transform, kind.Price); + } + }, + + Cooldown = () => kind.Cooldown, + }; + } + + // ─── Buying ────────────────────────────────────────────────────────── + + /// + /// Why this good is greyed out, or null when it can be bought. + /// + /// The order of the questions is the order the player would ask them: can I have it at all, + /// is it too soon, can I afford it. + /// + public static string RefusalFor(Good good, SvermHiveBehaviour hive) + { + if (good == null || hive == null) return "No hive."; + + string ownRefusal = good.Refusal != null ? good.Refusal(hive) : null; + if (ownRefusal != null) return ownRefusal; + + long waitingSeconds = CooldownLeft(hive.transform, good); + if (waitingSeconds > 0L) + { + return waitingSeconds >= 60L + ? $"The hive is still working on the last one ({waitingSeconds / 60}m)." + : $"The hive is still working on the last one ({waitingSeconds}s)."; + } + + if (SvermBiomass.Bank(hive.transform) < good.Price) return "Not enough biomass in the bank."; + + return null; + } + + public static bool Buy(Good good, SvermHiveBehaviour hive, Player player) + { + string refusal = RefusalFor(good, hive); + if (refusal != null) + { + player?.Message(MessageHud.MessageType.Center, refusal); + return false; + } + + // Paid first and delivered second, and never the other way round: Spend is the only + // thing here that can fail on a race with another client, and a hive that hands over a + // stage it was not paid for cannot be undone. + if (!SvermBiomass.Spend(hive.transform, good.Price)) + { + player?.Message(MessageHud.MessageType.Center, "Not enough biomass in the bank."); + return false; + } + + good.Deliver?.Invoke(hive); + StampCooldown(hive.transform, good.Id); + + player?.Message(MessageHud.MessageType.Center, good.Name); + return true; + } + + // ─── The day between purchases ─────────────────────────────────────── + + /// + /// How long this good still has to wait, on the world clock. + /// + /// Section 20.4 asks for two different clocks and this is both of them: a GAME DAY between + /// upgrades, and a wait of its own for every troop - ten minutes for a Gjall, the rest + /// scaled by price. On the three stage upgrades nobody will ever see it, since each of them + /// can only be bought once; on the troops it is the pacing. + /// + private static long CooldownLeft(Transform nest, Good good) + { + ZNetView nview = nest != null ? nest.GetComponent() : null; + if (nview == null || !nview.IsValid()) return 0L; + + long stamped = nview.GetZDO().GetLong(CooldownKey(good.Id), 0L); + if (stamped <= 0L) return 0L; + + float wait = good.Cooldown != null ? good.Cooldown() : 0f; + if (wait <= 0f) return 0L; + + long ready = stamped + (long)wait; + long now = WorldSecond(); + return now >= ready ? 0L : ready - now; + } + + private static void StampCooldown(Transform nest, string id) + { + ZNetView nview = nest != null ? nest.GetComponent() : null; + if (nview == null || !nview.IsValid()) return; + + if (!nview.IsOwner()) nview.ClaimOwnership(); + nview.GetZDO().Set(CooldownKey(id), WorldSecond()); + } + + private static string CooldownKey(string id) => "RacesOfValheim_SvermBought_" + id; + + /// A day of game time in seconds. The world's own setting, not a hardcoded 1800. + private static float DayLength() + { + return EnvMan.instance != null ? EnvMan.instance.m_dayLengthSec : 1800f; + } + + private static long WorldSecond() + { + return ZNet.instance != null ? (long)ZNet.instance.GetTimeSeconds() : 0L; + } + } + + // ─── The column ────────────────────────────────────────────────────────── + + [HarmonyPatch(typeof(StoreGui), "Awake")] + public static class SvermHiveGoodsSetupPatch + { + public static void Postfix(StoreGui __instance) => SvermHiveGoodsPanel.Create(__instance); + } + + [HarmonyPatch(typeof(StoreGui), "FillList")] + public static class SvermHiveGoodsFillPatch + { + public static void Postfix(StoreGui __instance) => SvermHiveGoodsPanel.Refresh(__instance); + } + + [HarmonyPatch(typeof(StoreGui), "Hide")] + public static class SvermHiveGoodsHidePatch + { + public static void Postfix() => SvermHiveGoodsPanel.Clear(); + } + + /// + /// The market's shelf on screen. Built the way TrolTotemStore builds the war totem's, which is + /// the one column in this mod that is known to draw where a player can see it. + /// + public static class SvermHiveGoodsPanel + { + private static RectTransform _root; + private static readonly List _rows = new List(); + + public static void Create(StoreGui gui) + { + if (gui == null || gui.m_listRoot == null) + { + Jotunn.Logger.LogWarning("[Sverm] StoreGui has no m_listRoot; the market's shelf cannot be built."); + return; + } + if (_root != null) return; + + GameObject clone = UnityEngine.Object.Instantiate(gui.m_listRoot.gameObject, gui.m_listRoot.parent); + clone.name = "SvermHiveGoodsList"; + _root = clone.GetComponent(); + + // The vanilla list's OWN position. An offset from it - 260 px was the first guess - puts + // the column outside the panel that clips it, where it draws perfectly and invisibly. + _root.anchoredPosition = gui.m_listRoot.anchoredPosition; + + foreach (Transform child in _root) UnityEngine.Object.Destroy(child.gameObject); + _root.gameObject.SetActive(false); + } + + public static void Clear() + { + foreach (GameObject row in _rows) if (row != null) UnityEngine.Object.Destroy(row); + _rows.Clear(); + + if (_root != null) _root.gameObject.SetActive(false); + } + + public static void Refresh(StoreGui gui) + { + Clear(); + + SvermHiveBehaviour hive = SvermHiveStore.ActiveHive(gui); + if (hive == null) return; // an ordinary merchant, or the war totem. Not ours. + + if (_root == null) + { + Jotunn.Logger.LogWarning("[Sverm] The market's shelf was never built (did the patch on " + + "StoreGui.Awake fail?), so nothing can be drawn into it."); + return; + } + + _root.gameObject.SetActive(true); + + int row = 0; + foreach (SvermHiveGoods.Good good in SvermHiveGoods.Shelf) + { + BuildRow(gui, hive, good, row++); + } + + float baseSize = Traverse.Create(gui).Field("m_itemlistBaseSize").GetValue(); + _root.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, Mathf.Max(baseSize, row * gui.m_itemSpacing)); + } + + private static void BuildRow(StoreGui gui, SvermHiveBehaviour hive, SvermHiveGoods.Good good, int rowIndex) + { + GameObject element = UnityEngine.Object.Instantiate(gui.m_listElement, _root); + element.SetActive(true); + + RectTransform rt = (RectTransform)element.transform; + float offset = (_root.rect.width - rt.rect.width) / 2f; + rt.anchoredPosition = new Vector2(offset, rowIndex * -gui.m_itemSpacing - offset); + + string refusal = SvermHiveGoods.RefusalFor(good, hive); + bool available = refusal == null; + + Sprite icon = SvermHive.BorrowIcon(good.Icon) ?? SvermHive.BorrowIcon("Honey"); + Image iconImage = element.transform.Find("icon").GetComponent(); + if (icon != null) iconImage.sprite = icon; + iconImage.color = available ? Color.white : Color.grey; + + TMP_Text nameLabel = element.transform.Find("name").GetComponent(); + nameLabel.text = good.Name; + nameLabel.color = available ? Color.white : Color.grey; + + TMP_Text price = FindDescendant(element.transform, "price"); + if (price != null) + { + price.text = good.Price.ToString("0"); + price.color = available ? Color.white : Color.grey; + } + + UITooltip tooltip = element.GetComponent(); + if (tooltip != null) + { + string body = available ? good.Description : refusal + "\n\n" + good.Description; + tooltip.Set(good.Name, body, gui.m_tooltipAnchor, default(Vector2)); + } + + Button button = element.GetComponent