warvulture

This commit is contained in:
Ferdinando 2026-08-11 16:30:20 +02:00
commit 1d66b00374
29 changed files with 7236 additions and 4 deletions

View file

@ -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<GameObject>(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);
}
/// <summary>
/// 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.
/// </summary>
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<GameObject>(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;

View file

@ -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);
}
/// <summary>
/// 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.
/// </summary>
private static void AppendWarVulture(Dictionary<string, string> 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();
}
/// <summary>
/// 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.
/// </summary>
private static void GenerateSvermText(Dictionary<string, string> 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();
}
/// <summary>
@ -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();
}

View file

@ -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;
}
}
}
}
}

View file

@ -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)

View file

@ -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<DraughRace>();
gameObject.AddComponent<DvergarRace>();
gameObject.AddComponent<TrentaRace>();
gameObject.AddComponent<SvermRace>();
// 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<RaceCaveBuilding>();
@ -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<ZNetView>();
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<VisEquipment>();
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<ItemDrop>("TrophySeekerBrute")?.gameObject;
if (prefab == null) prefab = PrefabManager.Cache.GetPrefab<ItemDrop>("TrophySeeker")?.gameObject;
if (prefab == null) prefab = PrefabManager.Cache.GetPrefab<ItemDrop>("Chitin")?.gameObject;
if (prefab != null)
{
ItemDrop drop = prefab.GetComponent<ItemDrop>();
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<ItemDrop>("HelmetDverger")?.gameObject;

View file

@ -0,0 +1,170 @@
using System.Collections.Generic;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// 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.
/// </summary>
public static class SvermAntennae
{
private const string LightName = "SvermAntennaeLight";
private static readonly Dictionary<Character, GameObject> lights = new Dictionary<Character, GameObject>();
private static readonly List<Character> stale = new List<Character>();
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<Character> inRange = new HashSet<Character>();
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<Light>();
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<Character, GameObject> 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);
}
}
/// <summary>
/// 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.
/// </summary>
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;
}
/// <summary>
/// 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.
/// </summary>
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>();
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;
}
/// <summary>Puts out every light. Called when the perk stops applying, and on death.</summary>
public static void ClearAll()
{
if (lights.Count == 0) return;
foreach (KeyValuePair<Character, GameObject> pair in lights)
{
if (pair.Value != null) Object.Destroy(pair.Value);
}
lights.Clear();
}
}
}

View file

@ -0,0 +1,197 @@
using System.Collections.Generic;
using Jotunn.Managers;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// 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.
/// </summary>
public static class SvermBeehive
{
/// <summary>Written on the hive's own ZDO, so the takeover survives a reload.</summary>
private const string InfectedKey = "RacesOfValheim_SvermInfected";
/// <summary>When this hive first came under an aura, so the minute can be counted.</summary>
private const string ClaimedAtKey = "RacesOfValheim_SvermClaimedAt";
private const string EggName = "SvermHiveEgg";
/// <summary>Values captured before we touched them, so a hive can be handed back intact.</summary>
private static readonly Dictionary<Beehive, float> originalSecPerUnit = new Dictionary<Beehive, float>();
// ─── The sweep ───────────────────────────────────────────────────────
/// <summary>
/// Called by the nest, on a timer. Claims what is in range and ripens what has waited.
/// </summary>
public static void SweepAura(Vector3 nest)
{
foreach (Beehive hive in Find(nest))
{
ZNetView nview = hive.GetComponent<ZNetView>();
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.");
}
}
/// <summary>
/// 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.
/// </summary>
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<ItemDrop>(wantedItem);
if (replacement != null) hive.m_honeyItem = replacement;
}
EnsureEgg(hive.transform);
}
/// <summary>
/// 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.
/// </summary>
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 ─────────────────────────────────────────────────────────
/// <summary>Every beehive standing inside a nest's aura.</summary>
public static List<Beehive> Find(Vector3 nest)
{
List<Beehive> found = new List<Beehive>();
foreach (Collider collider in Physics.OverlapSphere(nest, SvermConfig.HiveAuraRadius))
{
if (collider == null) continue;
Beehive hive = collider.GetComponentInParent<Beehive>();
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;
}
/// <summary>
/// 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.
/// </summary>
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);
}
}
/// <summary>
/// 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.
/// </summary>
private static bool IsFull(Beehive hive)
{
if (hive == null) return false;
int level = HarmonyLib.Traverse.Create(hive).Method("GetHoneyLevel").GetValue<int>();
return level >= hive.m_maxHoney;
}
public static bool IsInfected(Beehive hive)
{
ZNetView nview = hive != null ? hive.GetComponent<ZNetView>() : null;
return nview != null && nview.IsValid() && nview.GetZDO().GetBool(InfectedKey, false);
}
}
}

View file

@ -0,0 +1,243 @@
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// 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.
/// </summary>
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;
}
/// <summary>
/// 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.
/// </summary>
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";
}
/// <summary>What one of this item is worth in the tank.</summary>
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
/// <summary>What the hive can actually spend.</summary>
public static float Bank(Transform nest)
{
ZDO zdo = Zdo(nest);
return zdo != null ? zdo.GetFloat(BankKey, 0f) : 0f;
}
/// <summary>Eaten but not yet spendable.</summary>
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));
}
/// <summary>How much more the hive can hold, digested or not.</summary>
public static float Space(Transform nest)
{
return Mathf.Max(0f, Capacity(nest) - Bank(nest) - Digesting(nest));
}
/// <summary>Adds one item's worth. Returns what actually fitted.</summary>
public static float Deposit(Transform nest, ItemDrop.ItemData item)
{
return Swallow(nest, ValueOf(item));
}
/// <summary>
/// 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.
/// </summary>
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;
}
/// <summary>
/// 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.
/// </summary>
public static void Digest(Transform nest)
{
ZNetView nview = nest != null ? nest.GetComponent<ZNetView>() : 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);
}
/// <summary>
/// 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.
/// </summary>
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)));
}
/// <summary>Takes from the bank if there is enough. All or nothing.</summary>
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<ZNetView>() : null;
return nview != null && nview.IsValid() ? nview.GetZDO() : null;
}
/// <summary>
/// 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.
/// </summary>
private static ZNetView Claim(Transform nest)
{
ZNetView nview = nest != null ? nest.GetComponent<ZNetView>() : null;
if (nview == null || !nview.IsValid()) return null;
if (!nview.IsOwner()) nview.ClaimOwnership();
return nview;
}
/// <summary>
/// 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.
/// </summary>
private static long WorldSecond()
{
return ZNet.instance != null ? (long)ZNet.instance.GetTimeSeconds() : 0L;
}
}
}

View file

@ -0,0 +1,289 @@
using Jotunn.Managers;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// 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.
/// </summary>
public static class SvermBlisterTick
{
public const string PrefabName = "SvermBlisterTick";
public const string DisplayName = "Blister Tick";
private const string SourcePrefab = "Tick";
/// <summary>How many slots this nest has bought. Permanent, and the respawn reads it.</summary>
private const string SlotKey = "RacesOfValheim_SvermTickSlots";
/// <summary>The blast, in rising order of nastiness. Both are verified manifest names.</summary>
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<GameObject>(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<Character>();
if (character != null) character.m_name = DisplayName;
BaseAI ai = prefab.GetComponent<BaseAI>();
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<CharacterDrop>(true))
{
if (drops != null) Object.DestroyImmediate(drops);
}
RaisedThrall thrall = prefab.AddComponent<RaisedThrall>();
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<SvermBlisterTickBehaviour>();
ReadBlastDamage();
PrefabManager.Instance.AddPrefab(prefab);
Jotunn.Logger.LogInfo($"[Sverm] Registered '{PrefabName}' from '{SourcePrefab}'.");
}
/// <summary>
/// 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.
/// </summary>
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<GameObject>(projectileName);
Projectile projectile = prefab != null ? prefab.GetComponent<Projectile>() : 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;
}
/// <summary>What one blast does, at this nest's stage. Section 12's two tiers.</summary>
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<GameObject>(BlastEffect);
}
// ─── The slots ───────────────────────────────────────────────────────
public static int SlotsOf(Transform nest)
{
ZNetView nview = nest != null ? nest.GetComponent<ZNetView>() : 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<ZNetView>() : null;
if (nview == null || !nview.IsValid()) return;
if (!nview.IsOwner()) nview.ClaimOwnership();
nview.GetZDO().Set(SlotKey, SlotsOf(nest) + 1);
}
/// <summary>How many are alive right now, counted off the nest the way the roster is.</summary>
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;
}
/// <summary>
/// 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.
/// </summary>
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<Character>();
if (character != null)
{
int stars = SvermBroodStars.Of(hive.transform);
if (stars > 0) character.SetLevel(1 + stars);
}
RaisedThrall thrall = spawned.GetComponent<RaisedThrall>();
if (thrall != null) thrall.Bind(hive.transform.position);
return true;
}
}
/// <summary>
/// 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.
/// </summary>
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<Character>();
m_ai = GetComponent<MonsterAI>();
m_nview = GetComponent<ZNetView>();
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<RaisedThrall>();
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<Character>();
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);
}
}
}

View file

@ -0,0 +1,293 @@
using System.Collections.Generic;
using Jotunn.Managers;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// 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.
/// </summary>
public static class SvermBrood
{
/// <summary>
/// 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.
/// </summary>
public const string PrefabPrefix = "SvermTroop_";
/// <summary>One rung of the ladder, from section 11's table.</summary>
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);
}
/// <summary>
/// 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.
/// </summary>
public static readonly List<Kind> Roster = new List<Kind>
{
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);
}
/// <summary>
/// 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.
/// </summary>
private static void RegisterOne(Kind kind)
{
GameObject source = PrefabManager.Cache.GetPrefab<GameObject>(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<BaseAI>();
if (ai != null) ai.m_randomMoveRange = SvermConfig.TroopLeashRange;
foreach (CharacterDrop drops in prefab.GetComponentsInChildren<CharacterDrop>(true))
{
if (drops != null) Object.DestroyImmediate(drops);
}
RaisedThrall thrall = prefab.AddComponent<RaisedThrall>();
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<SkeletonSentryBehaviour>();
PrefabManager.Instance.AddPrefab(prefab);
Jotunn.Logger.LogInfo($"[Sverm] Registered '{kind.PrefabName}' for the {kind.Display}.");
}
// ─── Counting and hatching ───────────────────────────────────────────
/// <summary>
/// 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.
/// </summary>
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;
}
/// <summary>
/// Puts one on the ground beside the nest, bound to it and born at whatever star the colony
/// has bought.
/// </summary>
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<Character>();
if (character != null)
{
int stars = SvermBroodStars.Of(hive.transform);
if (stars > 0) character.SetLevel(1 + stars);
}
RaisedThrall thrall = spawned.GetComponent<RaisedThrall>();
if (thrall != null) thrall.Bind(hive.transform.position);
return true;
}
}
/// <summary>
/// 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.
/// </summary>
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);
}
/// <summary>What the clutch holds right now, without writing anything.</summary>
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));
}
/// <summary>
/// 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.
/// </summary>
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());
}
/// <summary>Takes eggs out of the clutch. All or nothing.</summary>
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<ZNetView>() : null;
return nview != null && nview.IsValid() ? nview : null;
}
private static long WorldSecond()
{
return ZNet.instance != null ? (long)ZNet.instance.GetTimeSeconds() : 0L;
}
}
/// <summary>
/// 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.
/// </summary>
public static class SvermBroodStars
{
private const string StarKey = "RacesOfValheim_SvermStars";
public static int Of(Transform nest)
{
ZNetView nview = nest != null ? nest.GetComponent<ZNetView>() : 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<ZNetView>() : null;
if (nview == null || !nview.IsValid()) return;
if (!nview.IsOwner()) nview.ClaimOwnership();
nview.GetZDO().Set(StarKey, Mathf.Clamp(stars, 0, 2));
}
}
}

View file

@ -0,0 +1,133 @@
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// 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.
/// </summary>
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;
/// <summary>
/// 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.
/// </summary>
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;
}
/// <summary>Armour of one vanilla piece at the reference quality, or 0 with a warning.</summary>
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<ItemDrop>();
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;
}
/// <summary>
/// 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.
/// </summary>
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<ItemDrop>() : 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;
}
/// <summary>True when this slot is taken by the carapace and cannot hold anything else.</summary>
public static bool IsSealedSlot(ItemDrop.ItemData.ItemType type)
{
foreach (ItemDrop.ItemData.ItemType sealedType in SvermConfig.SealedSlots)
{
if (sealedType == type) return true;
}
return false;
}
/// <summary>The tint the carapace, the helmet and the claws all share at this tier.</summary>
public static Color GetTint(int state)
{
state = Mathf.Clamp(state, BossProgressionManager.MinState, BossProgressionManager.MaxState);
return SvermConfig.CarapaceTintByState[state];
}
}
}

View file

@ -0,0 +1,283 @@
using System.Collections.Generic;
using HarmonyLib;
using Jotunn.Managers;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// 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.
/// </summary>
public static class SvermClawSlot
{
public const string ItemName = "SvermMaulclaws";
public const string ItemDisplayName = "Vilebone Maulclaws";
/// <summary>Row in the reserved column the claws sit on. The other three await the carapace.</summary>
private const int ClawRow = 0;
private static bool registered;
// ─── Registration ────────────────────────────────────────────────────
/// <summary>
/// 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.
/// </summary>
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<ItemDrop>();
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 ──────────────────────────────────────────────
/// <summary>
/// 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.
/// </summary>
/// <summary>
/// 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.
/// </summary>
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<ItemDrop.ItemData>("m_rightItem").Value;
if (held == null && !player.InAttack() && !player.IsDead())
{
player.EquipItem(claws, false);
}
}
/// <summary>
/// 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.
/// </summary>
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 ─────────────────────────────────────────────────────────────
/// <summary>
/// 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.
/// </summary>
[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);
}
}
/// <summary>
/// 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.
/// </summary>
[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<ItemDrop.ItemData>("m_rightItem").Value;
return !SvermClawSlot.IsClaws(held);
}
}
/// <summary>
/// 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.
/// </summary>
[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;
}
}
}

View file

@ -0,0 +1,154 @@
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// 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.
/// </summary>
public static class SvermClaws
{
private static GameObject resolved;
private static bool resolveAttempted;
private static HitData.DamageTypes referenceDamage;
private static bool referenceRead;
/// <summary>
/// The claw prefab, or null. Resolution happens once, inside a world, because ObjectDB is
/// empty when the plugin wakes.
/// </summary>
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<GameObject>(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;
}
/// <summary>
/// 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.
/// </summary>
private static HitData.DamageTypes GetReferenceDamage()
{
if (referenceRead) return referenceDamage;
GameObject prefab = GetPrefab();
ItemDrop drop = prefab != null ? prefab.GetComponent<ItemDrop>() : 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;
}
/// <summary>Fraction of the reference damage the bare hands hit for at this tier.</summary>
public static float GetDamagePercent(int state)
{
state = Mathf.Clamp(state, BossProgressionManager.MinState, BossProgressionManager.MaxState);
return SvermConfig.ClawDamagePercentByState[state];
}
/// <summary>
/// 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.
/// </summary>
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;
}
}
}
}

View file

@ -0,0 +1,535 @@
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// 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.
/// </summary>
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
};
/// <summary>Quality the reference set is priced at. Valheim: armor + (q-1) * armorPerLevel.</summary>
public const int ArmorReferenceQuality = 4;
/// <summary>
/// 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.
/// </summary>
public static readonly float FaderArmorBonus = 10f;
/// <summary>Slots the carapace occupies and therefore forbids.</summary>
public static readonly ItemDrop.ItemData.ItemType[] SealedSlots =
{
ItemDrop.ItemData.ItemType.Chest,
ItemDrop.ItemData.ItemType.Legs,
ItemDrop.ItemData.ItemType.Helmet,
};
/// <summary>What the carapace LOOKS like, at every tier. The value changes, the shape does not.</summary>
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",
};
/// <summary>Length in METRES from the back of the hand to the tip. ModelBorrow sizes in metres.</summary>
public static readonly float ClawLength = 0.22f;
/// <summary>
/// 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.
/// </summary>
public static readonly float[] ClawDamagePercentByState =
{
0f, 0.35f, 0.45f, 0.55f, 0.70f, 0.85f, 0.95f, 1.00f, 1.00f
};
/// <summary>Fire added at Fader, as a fraction of the claws' physical total.</summary>
public static readonly float ClawFireFraction = 0.30f;
// ─── Insect Metabolism ───────────────────────────────────────────────
/// <summary>Raw meat is worth this much of its cooked counterpart.</summary>
public static readonly float RawMeatFraction = 0.70f;
/// <summary>Honey and royal jelly: bonus and duration both multiplied by this.</summary>
public static readonly float HoneyMultiplier = 2f;
/// <summary>Seeds become food from this state on (The Elder).</summary>
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) ──────────────────────────────────────────
/// <summary>Poison added to every blow, per state above the unlock.</summary>
public static readonly float VenomPerState = 6f;
// ─── Acid Hemolymph (state 4) ────────────────────────────────────────
/// <summary>Poison dealt back to whoever lands a melee blow, per state above the unlock.</summary>
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+
/// <summary>
/// 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.
/// </summary>
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;
/// <summary>
/// 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.
/// </summary>
public const string GlideMotesPrefab = "FireFlies";
// ─── Eitr Sacs (state 6) ─────────────────────────────────────────────
/// <summary>Fraction of the eitr-weave set's regeneration the carapace gives back.</summary>
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;
/// <summary>
/// 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.
/// </summary>
public static readonly float StingerFragility = 2.5f;
// ─── The escort ──────────────────────────────────────────────────────
/// <summary>
/// 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.
/// </summary>
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);
/// <summary>
/// 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.
/// </summary>
/// <summary>
/// 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.
/// </summary>
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);
/// <summary>
/// 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.
/// </summary>
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) ─────
/// <summary>Two nests per square mile. A square mile is 2.59 km2; the circle of equal area has r = 908 m.</summary>
public static readonly float HiveDensityRadius = 908f;
public const int HiveDensityMax = 2;
/// <summary>The Elder. Before that the Sverm is a body and nothing else.</summary>
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;
/// <summary>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.</summary>
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;
/// <summary>Not every frame: it walks a sphere of colliders and nothing here is urgent.</summary>
public static readonly float HiveAuraSweepInterval = 5f;
/// <summary>How long a beehive must stand in the aura before the colony takes it.</summary>
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
/// <summary>
/// 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.
/// </summary>
public const int BeehiveBaseMaxHoney = 4;
/// <summary>After Yagluth the colony makes royal jelly instead of honey.</summary>
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
/// <summary>The nest's own size. 0.75 is the quarter off that the first placement asked for.</summary>
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;
/// <summary>
/// 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.
/// </summary>
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;
/// <summary>One out of every infected beehive on this timer, until the pool is full.</summary>
public static readonly float WorkerSpawnInterval = 120f;
/// <summary>Haulers only start after Bonemass.</summary>
public const int HaulerUnlockState = 4;
/// <summary>Ten metres. Also the radius it keeps in repair.</summary>
public static readonly float WorkerLeashRange = 10f;
/// <summary>How far a worker reaches to mend, and how often it mends one thing.</summary>
public static readonly float WorkerRepairRange = 10f;
public static readonly float WorkerRepairInterval = 5f;
/// <summary>How far from its anchor a worker looks for chests.</summary>
public static readonly float WorkerChestRange = 3f;
/// <summary>How often a worker does a round of its trade.</summary>
public static readonly float WorkerRoundInterval = 4f;
/// <summary>Plants per infected beehive, once the farmer's job lands.</summary>
public const int PlantsPerBeehive = 15;
// ─── Biomass ─────────────────────────────────────────────────────────
public static readonly float BiomassTankBase = 1000f;
/// <summary>Section 10.1: 1000 / 1500 / 2000 / 2500 across the four stages.</summary>
public static readonly float BiomassTankPerStage = 500f;
/// <summary>
/// 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.
/// </summary>
public static readonly float BiomassTankHeadroom = 500f;
public static readonly float WoodBiomassValue = 5f;
/// <summary>
/// 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.
/// </summary>
public static readonly float HiveStageGrowth = 1.75f;
/// <summary>Section 20.4's day between purchases, in game days.</summary>
public static readonly float UpgradeCooldownDays = 1f;
// ─── Brood eggs and troops ───────────────────────────────────────────
/// <summary>Section 10.2: one egg every twenty seconds, five plus the stage in the clutch.</summary>
public static readonly float EggInterval = 20f;
public const int EggCapBase = 5;
/// <summary>How far a troop wanders from the nest when nobody is leading it.</summary>
public static readonly float TroopLeashRange = 12f;
/// <summary>How long a troop outlives the nest that hatched it, in seconds.</summary>
public static readonly float TroopWitherSeconds = 60f;
/// <summary>How close a troop has to be to see whether its nest is still standing.</summary>
public static readonly float TroopHomeCheckRange = 25f;
// ─── Blister Tick ────────────────────────────────────────────────────
/// <summary>Section 12: fifty a slot, and the slot is permanent.</summary>
public static readonly float TickPrice = 50f;
/// <summary>How close it gets before it bursts, in metres.</summary>
public static readonly float TickBurstRange = 2.5f;
/// <summary>How long the nest waits before growing a replacement, in seconds.</summary>
public static readonly float TickRespawnSeconds = 30f;
/// <summary>From this nest stage on, the blast is the elite blob's. Section 12's two tiers.</summary>
public const int TickLateBlastStage = 3;
/// <summary>Only used if the blob projectiles are not in this build - see SvermBlisterTick.</summary>
public static readonly float TickFallbackDamage = 30f;
// ─── Medicine ────────────────────────────────────────────────────────
/// <summary>
/// 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.
/// </summary>
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.
/// <summary>
/// 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.
/// </summary>
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);
}
}
}

View file

@ -0,0 +1,271 @@
using BepInEx.Configuration;
namespace RacesOfValheim
{
/// <summary>
/// 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.
/// </summary>
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<float> SpineSizeSmall;
public static ConfigEntry<float> SpineSizeFull;
public static ConfigEntry<string> SpineBoneName;
public static ConfigEntry<float> SpineRotationX;
public static ConfigEntry<float> SpineRotationY;
public static ConfigEntry<float> SpineRotationZ;
// ─── Emberform ───────────────────────────────────────────────────────
public static ConfigEntry<float> EmberGlowStrength;
// ─── Keybinds ────────────────────────────────────────────────────────
public static ConfigEntry<KeyboardShortcut> StingerKey;
// ─── Stinger Morph, the model ────────────────────────────────────────
public static ConfigEntry<float> StingerScaleMultiplier;
public static ConfigEntry<float> 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<int> CapBrood;
public static ConfigEntry<int> CapSeeker;
public static ConfigEntry<int> CapSoldier;
public static ConfigEntry<int> CapGjall;
public static ConfigEntry<int> CapBlisterTick;
public static ConfigEntry<int> CapFarmers;
public static ConfigEntry<int> CapHaulers;
public static ConfigEntry<int> CapBeehives;
// ─── The nest and its mark ───────────────────────────────────────────
public static ConfigEntry<float> WorkerChestRangeValue;
public static ConfigEntry<bool> WorkerDebugValue;
public static ConfigEntry<float> HiveScaleValue;
public static ConfigEntry<float> EggSizeValue;
public static ConfigEntry<float> EggHeightValue;
public static ConfigEntry<float> DigestRateValue;
public static ConfigEntry<float> StomachSizeValue;
public static ConfigEntry<float> StomachHeightValue;
public static ConfigEntry<float> MarketSizeValue;
public static ConfigEntry<float> StageGrowthValue;
public static ConfigEntry<float> NestVfxScaleValue;
public static ConfigEntry<float> 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;
/// <summary>
/// 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".
/// </summary>
public static string Bone
{
get
{
string configured = SpineBoneName?.Value;
return string.IsNullOrWhiteSpace(configured) ? SvermConfig.SpineBoneName : configured;
}
}
}
}

View file

@ -0,0 +1,273 @@
using System.Collections.Generic;
using HarmonyLib;
using Jotunn.Entities;
using Jotunn.Managers;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// 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.
/// </summary>
public static class SvermFood
{
private const string ClonePrefix = "SvermMeal_";
/// <summary>Every real prefab we intercept, mapped to the clone that carries our numbers.</summary>
private static readonly Dictionary<string, string> meals = new Dictionary<string, string>();
/// <summary>Seeds are gated behind The Elder, everything else is live from tier 1.</summary>
private static readonly HashSet<string> gatedSeeds = new HashSet<string>();
private static bool registered;
// ─── The tables ──────────────────────────────────────────────────────
/// <summary>
/// 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.
/// </summary>
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 ────────────────────────────────────────────────────
/// <summary>
/// Builds every clone. Driven from SvermRace.CreateModAssets, which runs on
/// PrefabManager.OnVanillaPrefabsAvailable - the one moment Jotunn accepts new items.
/// </summary>
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<string, string> 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<ItemDrop>(prefabName);
return drop != null && drop.m_itemData != null ? drop.m_itemData.m_shared : null;
}
/// <summary>
/// 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.
/// </summary>
private static bool BuildMeal(string sourcePrefab, float health, float stamina, float eitr,
float duration, float regen, string label)
{
GameObject source = PrefabManager.Cache.GetPrefab<GameObject>(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<ItemDrop>();
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 ──────────────────────────────────────────────────────────
/// <summary>Which clone answers for this item, or null when we do not cover it.</summary>
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);
/// <summary>
/// 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.
/// </summary>
[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<ItemDrop>() : 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<EffectList>("m_consumeItemEffects").Value;
if (consume != null) consume.Create(player.transform.position, Quaternion.identity, player.transform, 1f, -1);
ZSyncAnimation anim = Traverse.Create(player).Field<ZSyncAnimation>("m_zanim").Value;
if (anim != null) anim.SetTrigger("eat");
return false; // handled
}
/// <summary>
/// The Aswid's alchemical blood, recognised without a hard dependency on that race's
/// tables: everything it makes carries its own prefix.
/// </summary>
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");
}
}
}
}

View file

@ -0,0 +1,621 @@
using System.Collections.Generic;
using Jotunn.Configs;
using Jotunn.Entities;
using Jotunn.Managers;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// 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.
/// </summary>
public static class SvermHive
{
public const string PieceName = SvermHiveNames.PieceName;
public const string DisplayName = SvermHiveNames.PieceDisplayName;
/// <summary>
/// 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.
/// </summary>
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<GameObject>(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<Piece>() ?? prefab.AddComponent<Piece>();
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<WearNTear>() == null)
{
WearNTear wear = prefab.AddComponent<WearNTear>();
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<ZNetView>() == null) prefab.AddComponent<ZNetView>();
prefab.AddComponent<SvermHiveBehaviour>();
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}'.");
}
/// <summary>
/// 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.
/// </summary>
private static readonly string[] MouthCandidates =
{
"TheHive",
"CreepProp_egg_hanging01",
"CreepProp_egg_hanging02",
"SeekerEgg",
"CreepProp_hanging01",
};
/// <summary>
/// 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.
/// </summary>
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<GameObject>(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<SvermHiveStomach>(prefab, source, "SvermHiveStomach",
SvermConfigManagement.StomachSize, SvermConfigManagement.StomachHeight);
}
private static void MountMouth<T>(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<SphereCollider>();
ball.center = new Vector3(0f, size * 0.5f, 0f);
ball.radius = size * 0.5f;
holder.AddComponent<T>();
}
/// <summary>
/// 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.
/// </summary>
internal static bool IsSafeScenery(GameObject source, string name)
{
if (source.GetComponentInChildren<Character>(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<BaseAI>(true) != null)
{
Jotunn.Logger.LogWarning($"[Sverm] '{name}' carries a BaseAI; refusing to make a building out of it.");
return false;
}
if (source.GetComponentInChildren<SpawnArea>(true) != null)
{
Jotunn.Logger.LogWarning($"[Sverm] '{name}' is a spawner; refusing to make a building out of it.");
return false;
}
return true;
}
/// <summary>
/// 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.
/// </summary>
internal static void StripLife(GameObject copy)
{
foreach (BaseAI ai in copy.GetComponentsInChildren<BaseAI>(true))
{
if (ai != null) Object.DestroyImmediate(ai);
}
foreach (Character character in copy.GetComponentsInChildren<Character>(true))
{
if (character != null) Object.DestroyImmediate(character);
}
foreach (CharacterDrop drop in copy.GetComponentsInChildren<CharacterDrop>(true))
{
if (drop != null) Object.DestroyImmediate(drop);
}
foreach (SpawnArea spawner in copy.GetComponentsInChildren<SpawnArea>(true))
{
if (spawner != null) Object.DestroyImmediate(spawner);
}
foreach (Rigidbody body in copy.GetComponentsInChildren<Rigidbody>(true))
{
if (body != null) Object.DestroyImmediate(body);
}
}
/// <summary>
/// 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.
/// </summary>
internal static SvermHiveBehaviour NearestNest(Vector3 position, float radius)
{
SvermHiveBehaviour closest = null;
float best = radius;
foreach (SvermHiveBehaviour nest in Object.FindObjectsOfType<SvermHiveBehaviour>())
{
if (nest == null) continue;
float distance = Vector3.Distance(nest.transform.position, position);
if (distance > best) continue;
best = distance;
closest = nest;
}
return closest;
}
/// <summary>An item's inventory icon, or null. Same helper shape as SkeletonBonePile's.</summary>
internal static Sprite BorrowIcon(string prefabName)
{
ItemDrop drop = PrefabManager.Cache.GetPrefab<ItemDrop>(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];
}
}
/// <summary>
/// The nest's own upkeep. Today that is the aura and the beehives inside it; biomass, eggs,
/// troops and the shop land here next.
/// </summary>
public class SvermHiveBehaviour : MonoBehaviour, Hoverable, Interactable
{
/// <summary>
/// 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.
/// </summary>
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;
/// <summary>
/// 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.
/// </summary>
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" +
"[<color=yellow><b>$KEY_Use</b></color>] 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;
/// <summary>
/// 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.
/// </summary>
private Vector3 builtScale = Vector3.one;
private float shownScale = -1f;
private void Awake()
{
nview = GetComponent<ZNetView>();
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);
}
/// <summary>
/// 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.
/// </summary>
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);
}
}
/// <summary>
/// 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.
/// </summary>
private void Haul()
{
int hands = SvermWorker.Count(SvermWorker.Job.Hauler);
if (hands <= 0) return;
float range = SvermConfigManagement.ChestRange;
foreach (Container container in Object.FindObjectsOfType<Container>())
{
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<ItemDrop.ItemData>(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<ZNetView>();
if (cview != null && cview.IsValid())
{
HarmonyLib.Traverse.Create(container).Method("Save").GetValue();
}
if (--hands <= 0) return;
}
}
}
/// <summary>How many beehives are already claimed by this nest. Used by the build gate.</summary>
public int CountBeehives()
{
return SvermBeehive.CountInAura(transform.position);
}
}
}

View file

@ -0,0 +1,499 @@
using System;
using System.Collections.Generic;
using HarmonyLib;
using TMPro;
using UnityEngine;
using UnityEngine.UI;
namespace RacesOfValheim
{
/// <summary>
/// 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.
/// </summary>
public static class SvermHiveGoods
{
/// <summary>One thing the market sells.</summary>
public class Good
{
public string Id;
public string Name;
public float Price;
public string Icon;
public string Description;
/// <summary>Why this cannot be bought right now, or null when it can.</summary>
public Func<SvermHiveBehaviour, string> Refusal;
/// <summary>Hands over the goods. Only ever called after the price has been taken.</summary>
public Action<SvermHiveBehaviour> Deliver;
/// <summary>
/// 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.
/// </summary>
public Func<float> Cooldown;
}
/// <summary>
/// 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.
/// </summary>
public static readonly List<Good> Shelf = BuildShelf();
private static List<Good> BuildShelf()
{
List<Good> shelf = new List<Good>
{
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;
}
/// <summary>
/// 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.
/// </summary>
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,
};
}
/// <summary>
/// One step up the four stages. The price is the tank it empties, from section 10.1.
/// </summary>
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,
};
}
/// <summary>
/// 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.
/// </summary>
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,
};
}
/// <summary>
/// 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.
/// </summary>
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 ──────────────────────────────────────────────────────────
/// <summary>
/// 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.
/// </summary>
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 ───────────────────────────────────────
/// <summary>
/// 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.
/// </summary>
private static long CooldownLeft(Transform nest, Good good)
{
ZNetView nview = nest != null ? nest.GetComponent<ZNetView>() : 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<ZNetView>() : 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;
/// <summary>A day of game time in seconds. The world's own setting, not a hardcoded 1800.</summary>
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();
}
/// <summary>
/// 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.
/// </summary>
public static class SvermHiveGoodsPanel
{
private static RectTransform _root;
private static readonly List<GameObject> _rows = new List<GameObject>();
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<RectTransform>();
// 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<float>();
_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<Image>();
if (icon != null) iconImage.sprite = icon;
iconImage.color = available ? Color.white : Color.grey;
TMP_Text nameLabel = element.transform.Find("name").GetComponent<TMP_Text>();
nameLabel.text = good.Name;
nameLabel.color = available ? Color.white : Color.grey;
TMP_Text price = FindDescendant<TMP_Text>(element.transform, "price");
if (price != null)
{
price.text = good.Price.ToString("0");
price.color = available ? Color.white : Color.grey;
}
UITooltip tooltip = element.GetComponent<UITooltip>();
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<Button>();
button.interactable = available;
button.onClick.AddListener(() =>
{
SvermHiveGoods.Buy(good, hive, Player.m_localPlayer);
Traverse.Create(gui).Method("FillList").GetValue(); // repaints the shelf
});
_rows.Add(element);
}
private static T FindDescendant<T>(Transform root, string childName) where T : Component
{
foreach (T candidate in root.GetComponentsInChildren<T>(true))
{
if (candidate.gameObject.name == childName) return candidate;
}
return null;
}
}
}

View file

@ -0,0 +1,106 @@
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// How far the nest has grown: one number on its ZDO, and everything that number decides.
///
/// Four stages, and each one is BOUGHT at the market for exactly the tankful the current stage
/// holds - so a stage change always leaves the hive empty. That is the design's own line and it
/// is the whole tension of the colony: you either grow or you field an army, never both at once.
///
/// The stage lives on the ZDO and not in a field because everything downstream of it has to
/// agree across a reload, a zone unload and every other player standing there - the tank's
/// ceiling, the name over the nest, and its size on screen. Size especially: a nest that grew on
/// one client and stayed small on every other one is the bug section 9.1 wrote down in advance.
/// Deriving the scale from the ZDO on each client costs nothing and cannot disagree with itself.
///
/// WHAT GROWTH DOES NOT DO, deliberately: it breaks nothing around it. Section 9.1 leaves "what
/// may a growth spurt destroy" open, and an unanswered question about destroying other people's
/// buildings is not one to answer by guessing - on a server it would be a weapon.
/// </summary>
public static class SvermHiveStage
{
private const string StageKey = "RacesOfValheim_SvermStage";
public const int First = 1;
public const int Last = 4;
/// <summary>The four names from section 2. The piece is registered under the first one.</summary>
public static readonly string[] Names =
{
"Brood Mound",
"Gorged Hive",
"Nesting Spire",
"Hive Citadel",
};
public static int Of(Transform nest)
{
ZNetView nview = nest != null ? nest.GetComponent<ZNetView>() : null;
if (nview == null || !nview.IsValid()) return First;
return Mathf.Clamp(nview.GetZDO().GetInt(StageKey, First), First, Last);
}
public static string NameOf(int stage)
{
return Names[Mathf.Clamp(stage, First, Last) - 1];
}
/// <summary>
/// What the tank holds: the document's 1000 / 1500 / 2000 / 2500 plus 500 of headroom on
/// each, so 1500 / 2000 / 2500 / 3000.
///
/// THE CEILING AND THE PRICE USED TO BE THE SAME NUMBER and that made growing impossible in
/// practice - see SvermConfig.BiomassTankHeadroom. They are two different questions now:
/// this is how much the hive can hold, PriceToLeave is what a stage costs.
/// </summary>
public static float Capacity(int stage)
{
return Tankful(stage) + SvermConfig.BiomassTankHeadroom;
}
/// <summary>
/// What a stage costs: the document's tankful of the stage it is bought out of.
///
/// Still "one full tank" in the sense section 14 meant it - it is the whole of what that
/// stage was designed to hold, and paying it leaves the hive with almost nothing. What it no
/// longer is is the LAST possible point of biomass, which is what nobody could ever reach.
/// </summary>
public static float PriceToLeave(int stage)
{
return Tankful(stage);
}
/// <summary>Section 10.1's own figure: 1000 / 1500 / 2000 / 2500.</summary>
private static float Tankful(int stage)
{
return SvermConfig.BiomassTankBase +
SvermConfig.BiomassTankPerStage * (Mathf.Clamp(stage, First, Last) - First);
}
/// <summary>x1 at the first stage, the configured multiple at the last, evenly between.</summary>
public static float ScaleOf(int stage)
{
float step = (Mathf.Clamp(stage, First, Last) - First) / (float)(Last - First);
return Mathf.Lerp(1f, SvermConfigManagement.StageGrowth, step);
}
/// <summary>Moves the nest up one stage. Returns false if it is already at the top.</summary>
public static bool Advance(Transform nest)
{
ZNetView nview = nest != null ? nest.GetComponent<ZNetView>() : null;
if (nview == null || !nview.IsValid()) return false;
int stage = Of(nest);
if (stage >= Last) return false;
// Claimed before the write for the same reason the tank claims: a write to a ZDO
// somebody else owns lives only until their copy comes back over the wire.
if (!nview.IsOwner()) nview.ClaimOwnership();
nview.GetZDO().Set(StageKey, stage + 1);
return true;
}
}
}

View file

@ -0,0 +1,518 @@
using System.Collections.Generic;
using HarmonyLib;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The two mouths of the nest, and the window behind one of them.
///
/// FIRST PASS, AND WHY IT WAS THROWN AWAY. Feeding used to be a button in a second column of
/// the vanilla store, cloned the way FactionMerchantSellPanel clones one. In game the window
/// came up EMPTY and the button did nothing you could click - the column is drawn outside the
/// panel that clips it, and that panel's own sell button sells for coins, which a hive does not
/// have. Both problems disappear if the feeding never goes through a UI at all.
///
/// So the nest wears two hives instead. The one at its foot is the STOMACH: press E and it
/// takes a whole stack out of your inventory. The one up top is the MARKET: press E and the
/// vanilla store opens, which is where the upgrades of 20.4 will hang when they are written.
/// The store's own sell button is switched off while a hive's window is open.
///
/// Feeding reads the INVENTORY and never the hand, which was the point of section 20.1: food is
/// a consumable, it never reaches the weapon slot, and "press E holding meat" only ever fed the
/// player.
/// </summary>
public static class SvermHiveStore
{
/// <summary>
/// Opens the store standing at <paramref name="host"/>, spending the tank of
/// <paramref name="hive"/>.
///
/// THE TRADER LIVES ON THE BENCH AND NOT ON THE NEST, and that is not tidiness either.
/// StoreGui.Update measures the player against the TRADER's transform and closes the window
/// past m_hideDistance - so a trader left on the nest would slam the window shut the moment
/// you used a bench standing anywhere but on top of it. The bench carries the trader; the
/// nest it points at carries the biomass.
///
/// It goes on a CHILD of the bench for a second reason: Trader is an Interactable and so is
/// the bench, and vanilla Player.Interact resolves its target with
/// GetComponentInParent&lt;Interactable&gt;, which returns whichever implementation happens to
/// sit first in the component list. The Factions module lost a day to exactly that ambiguity
/// (see FactionMerchantInteractPatch). A child with no collider is never the hovered object,
/// so it never enters the race.
/// </summary>
public static bool Open(GameObject host, SvermHiveBehaviour hive, Player player)
{
if (host == null || hive == null || player == null || StoreGui.instance == null) return false;
Trader trader = Mount(host, hive);
if (trader == null) return false;
StoreGui.instance.Show(trader);
return true;
}
private static Trader Mount(GameObject host, SvermHiveBehaviour hive)
{
SvermHiveShop shop = host.GetComponentInChildren<SvermHiveShop>(true);
if (shop != null)
{
// Re-bound on every visit: the nest a bench answers to is whichever one is nearest
// TODAY, and nests can be torn down and raised again around a bench that never moved.
shop.Hive = hive;
return shop.GetComponent<Trader>();
}
GameObject holder = new GameObject("SvermHiveMerchant");
holder.transform.SetParent(host.transform, false);
shop = holder.AddComponent<SvermHiveShop>();
shop.Hive = hive;
Trader trader = holder.AddComponent<Trader>();
trader.m_name = SvermHive.DisplayName;
// DISABLED ON PURPOSE, and this is the load-bearing line of the file. Trader was written
// for Haldor, who is a creature with an animator: Trader.Update() calls
// m_animator.SetBool("Stand", false) with no null check whenever no player is nearby, and
// Trader.Start() calls InvokeRepeating("RandomTalk", m_randomTalkInterval, ...) with an
// interval of zero on a component nobody authored in the editor. On a building both of
// those throw. A disabled component runs neither - and StoreGui needs neither, because
// Show() only reads fields off the Trader and asks it for its item list.
trader.enabled = false;
// Filled rather than assumed: these are serialized fields, and what a runtime
// AddComponent leaves in them is the constructor's business, not the editor's.
trader.m_items = new List<Trader.TradeItem>();
trader.m_useItems = new List<Trader.TraderUseItem>();
trader.m_randomTalk = new List<string>();
trader.m_randomGreets = new List<string>();
trader.m_randomGoodbye = new List<string>();
trader.m_randomStartTrade = new List<string>();
trader.m_randomBuy = new List<string>();
trader.m_randomSell = new List<string>();
return trader;
}
/// <summary>The nest behind the store window, or null if the window is not a hive's.</summary>
public static SvermHiveBehaviour ActiveHive(StoreGui gui)
{
Trader trader = FactionMerchantRuntime.GetActiveTrader(gui);
if (trader == null) return null;
SvermHiveShop shop = ((Component)trader).GetComponent<SvermHiveShop>();
return shop != null ? shop.Hive : null;
}
// ─── Feeding ─────────────────────────────────────────────────────────
/// <summary>
/// One press, one stack.
///
/// A stack and not the whole pack: the player can see what left, one press at a time, and a
/// misplaced E costs a stack of wood rather than the larder. The first thing in the
/// inventory the hive will eat is the thing it takes, so the order on screen is the order it
/// goes in.
///
/// Returns true if it did anything at all - the messages are the honest part, since a nest
/// that quietly does nothing is what sent the last pass back.
/// </summary>
public static bool FeedOneStack(SvermHiveBehaviour hive, Player player)
{
if (hive == null || player == null) return false;
Inventory inventory = player.GetInventory();
if (inventory == null) return false;
float room = SvermBiomass.Space(hive.transform);
if (room <= 0f)
{
player.Message(MessageHud.MessageType.Center, "The hive is full. Give it time to digest.");
return true;
}
foreach (ItemDrop.ItemData item in new List<ItemDrop.ItemData>(inventory.GetAllItems()))
{
if (item == null || item.m_stack <= 0) continue;
float perUnit = SvermBiomass.ValueOf(item);
if (perUnit <= 0f) continue;
// Not "does the stack fit" but "how much of it does": one royal jelly's worth of room
// should still take one royal jelly.
int units = Mathf.Min(item.m_stack, Mathf.FloorToInt(room / perUnit));
if (units <= 0) continue;
string name = Localization.instance.Localize(item.m_shared.m_name);
float fed = SvermBiomass.Swallow(hive.transform, units * perUnit);
inventory.RemoveItem(item, units);
player.Message(MessageHud.MessageType.TopLeft,
$"{name} x{units} -> +{fed:0} biomass, digesting");
return true;
}
player.Message(MessageHud.MessageType.Center,
"Nothing here it will eat. Food, wood and resin - honey and royal jelly are medicine.");
return true;
}
}
/// <summary>
/// Marker on the child that carries the nest's Trader. Everything else reads it to answer "is
/// the open store window a hive's, and if so, whose".
/// </summary>
public class SvermHiveShop : MonoBehaviour
{
public SvermHiveBehaviour Hive;
}
// ─── The two mouths ──────────────────────────────────────────────────────
/// <summary>
/// Shared half of the two hives bolted to the nest: find the nest, refuse anyone who is not a
/// Sverm, and show the tank.
///
/// EACH MOUTH NEEDS ITS OWN COLLIDER, and that is not decoration. Player.FindHoverObject asks
/// hit.collider.GetComponent&lt;Hoverable&gt; - GetComponent on the collider's own GameObject, not
/// GetComponentInParent - and stops at the first collider the ray meets. So what the player is
/// pointing at is decided entirely by which collider is in front, and a mouth with no collider
/// of its own can never be pointed at. SvermHive.MountMouth gives each one a sphere wide enough
/// to stand clear of the trunk.
/// </summary>
public abstract class SvermHiveMouth : MonoBehaviour, Hoverable, Interactable
{
protected SvermHiveBehaviour Hive => GetComponentInParent<SvermHiveBehaviour>();
protected abstract string Title { get; }
protected abstract string Prompt { get; }
protected abstract bool Use(SvermHiveBehaviour hive, Player player);
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;
SvermHiveBehaviour hive = Hive;
if (hive == null) return false;
if (!SvermVisuals.IsSvermPlayer(player))
{
player.Message(MessageHud.MessageType.Center, "The hive does not know you.");
return true;
}
return Use(hive, player);
}
public bool UseItem(Humanoid user, ItemDrop.ItemData item) => false;
public string GetHoverName() => Title;
public string GetHoverText()
{
SvermHiveBehaviour hive = Hive;
if (hive == null) return Title;
return $"{Title}\n" +
SvermHiveReadout.Tank(hive.transform) +
$"[<color=yellow><b>$KEY_Use</b></color>] {Prompt}";
}
}
/// <summary>The hive at the foot of the nest. Press E, a stack goes in.</summary>
public class SvermHiveStomach : SvermHiveMouth
{
protected override string Title => "Hive Stomach";
protected override string Prompt => "Feed it a stack";
protected override bool Use(SvermHiveBehaviour hive, Player player)
{
return SvermHiveStore.FeedOneStack(hive, player);
}
}
// ─── The market, a building of its own ───────────────────────────────────
/// <summary>
/// The Hive Market: a bench you raise inside a nest's ten metres, and the only door to the shop.
///
/// IT WAS A SECOND MOUTH ON THE NEST and it never worked. On the trunk's measured crown it stood
/// eight metres above the player; moved to a reachable height, the .cfg still held the old zero
/// from the launch before, so it sat inside the stomach's sphere and the ray found the stomach
/// every time. The lesson is not the numbers - it is that a mouth on a shared body is always a
/// race between colliders, and this mod already has two stores that avoided that race by being
/// their own building: DvergarBanco and TrolTotem.
///
/// It owns no biomass. It finds the nest it stands in and spends THAT tank, so the serbatoio
/// stays one number in one place no matter how many benches end up around it.
/// </summary>
public static class SvermHiveMarketPiece
{
public const string PieceName = "SvermHiveMarket";
public const string DisplayName = "Hive Market";
/// <summary>Scenery only, and checked rather than trusted - see SvermHive.MouthCandidates.</summary>
private static readonly string[] SourceCandidates =
{
"CreepProp_egg_hanging01",
"CreepProp_egg_hanging02",
"Creeppillar_half_shorttendrils",
"CreepProp_hanging01",
};
public static void Register()
{
// A REAL PIECE as the body and a BORROWED MODEL as the look, which is TrolTotem's recipe
// line for line - the one store-building in this mod that is known to work in game.
// Cloning scenery instead would have meant taking whatever pivot its author used: a
// hanging egg sac hangs, and a hanging thing used as a ground piece floats or sinks.
// ModelBorrow measures the mesh and stands it on the piece's own origin, so "on the
// ground" needs no guess.
GameObject prefab = Jotunn.Managers.PrefabManager.Instance.CreateClonedPrefab(PieceName, "piece_workbench");
if (prefab == null)
{
Jotunn.Logger.LogWarning("[Sverm] Could not clone piece_workbench; the market is not registered.");
return;
}
// Down to a placeable shell: no station, no crafting, no furniture.
foreach (MonoBehaviour behaviour in prefab.GetComponentsInChildren<MonoBehaviour>(true))
{
if (behaviour == null) continue;
if (behaviour is Piece || behaviour is ZNetView || behaviour is WearNTear) continue;
Object.DestroyImmediate(behaviour);
}
foreach (Renderer renderer in prefab.GetComponentsInChildren<Renderer>(true))
{
if (renderer != null) renderer.enabled = false; // the bench's own mesh, hidden
}
AswidBloodRefinery.StripOffensive(prefab, PieceName);
string sourceName = null;
foreach (string candidate in SourceCandidates)
{
GameObject source = Jotunn.Managers.PrefabManager.Cache.GetPrefab<GameObject>(candidate);
if (source == null) continue;
if (!SvermHive.IsSafeScenery(source, candidate)) continue;
sourceName = candidate;
break;
}
if (sourceName == null)
{
Jotunn.Logger.LogWarning("[Sverm] No safe scenery to dress the market with (" +
string.Join(", ", SourceCandidates) + "); it is registered " +
"anyway and will be an invisible counter rather than none.");
}
else
{
ModelBorrow.Attach(prefab.transform, "MarketModel", sourceName,
Vector3.zero, Quaternion.identity, SvermConfigManagement.MarketSize, "Sverm");
}
Piece piece = prefab.GetComponent<Piece>() ?? prefab.AddComponent<Piece>();
piece.m_craftingStation = null;
piece.m_resources = new Piece.Requirement[0];
piece.m_name = DisplayName;
piece.m_description = "Where the colony trades. It spends the tank of the nest it stands in.";
piece.m_groundPiece = true;
piece.m_groundOnly = true;
piece.m_canBeRemoved = true;
if (prefab.GetComponent<WearNTear>() == null)
{
WearNTear wear = prefab.AddComponent<WearNTear>();
wear.m_health = 500f;
wear.m_noRoofWear = true;
wear.m_noSupportWear = true;
wear.m_destroyedEffect = new EffectList();
wear.m_hitEffect = new EffectList();
}
if (prefab.GetComponent<ZNetView>() == null) prefab.AddComponent<ZNetView>();
prefab.AddComponent<SvermHiveMarket>();
Jotunn.Managers.PieceManager.Instance.AddPiece(new Jotunn.Entities.CustomPiece(prefab, fixReference: false,
new Jotunn.Configs.PieceConfig
{
Name = DisplayName,
Description = piece.m_description,
PieceTable = Jotunn.Configs.PieceTables.Hammer,
Category = "Crafting",
Icon = SvermHive.BorrowIcon("TrophySeeker") ?? SvermHive.BorrowIcon("TrophySeekerBrute") ??
SvermHive.BorrowIcon("Honey"),
// Cheap on purpose, and these two numbers are INVENTED - the design document
// never had this building in it. The market is not a gate on anything: the nest
// is the achievement, this is the counter you trade over.
Requirements = new[]
{
new Jotunn.Configs.RequirementConfig { Item = "Wood", Amount = 10, Recover = true },
new Jotunn.Configs.RequirementConfig { Item = "Resin", Amount = 5, Recover = true },
},
}));
// One counter to a nest. The radius is the nest's own aura, so "another market too close"
// and "inside this nest's ten metres" are the same circle measured from opposite ends.
PieceDensityLimit.Register(PieceName, SvermConfig.HiveAuraRadius, 1,
"This hive already has a market.");
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 market.");
return false;
}
if (SvermHive.NearestNest(position, SvermConfig.HiveAuraRadius) == null)
{
player.Message(MessageHud.MessageType.Center,
"A market has to stand within ten metres of a hive.");
return false;
}
return true;
});
Jotunn.Logger.LogInfo($"[Sverm] Registered '{PieceName}' from '{sourceName}'.");
}
}
/// <summary>The bench itself. Press E, the store opens on the nest it stands in.</summary>
public class SvermHiveMarket : MonoBehaviour, Hoverable, Interactable
{
private SvermHiveBehaviour Nest => SvermHive.NearestNest(transform.position, SvermConfig.HiveAuraRadius);
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;
}
// Asked again at every press rather than remembered: the nest this counter answered to
// last week may have been torn down since, and a market quietly spending a tank that no
// longer exists is worse than one that says so.
SvermHiveBehaviour nest = Nest;
if (nest == null)
{
player.Message(MessageHud.MessageType.Center, "No hive within ten metres. This counter is dead.");
return true;
}
return SvermHiveStore.Open(gameObject, nest, player);
}
public bool UseItem(Humanoid user, ItemDrop.ItemData item) => false;
public string GetHoverName() => SvermHiveMarketPiece.DisplayName;
public string GetHoverText()
{
SvermHiveBehaviour nest = Nest;
if (nest == null) return $"{SvermHiveMarketPiece.DisplayName}\nNo hive within ten metres.";
return $"{SvermHiveMarketPiece.DisplayName}\n" +
SvermHiveReadout.Tank(nest.transform) +
"[<color=yellow><b>$KEY_Use</b></color>] Trade with the hive";
}
}
/// <summary>The tank, worded once, for every mouth and for the trunk between them.</summary>
public static class SvermHiveReadout
{
public static string Tank(Transform nest)
{
return $"Biomass {SvermBiomass.Bank(nest):0} / {SvermBiomass.Capacity(nest):0}\n" +
$"Digesting {SvermBiomass.Digesting(nest):0}\n" +
$"Brood eggs {SvermBroodEggs.Count(nest)} / {SvermBroodEggs.Cap(nest)}\n";
}
}
// ─── The store window, made fit for a hive ───────────────────────────────
/// <summary>
/// Two edits to the vanilla window while a hive owns it, and no new UI whatsoever.
///
/// THE SELL BUTTON IS SWITCHED OFF, at the player's call and for a good reason of its own: it
/// sells the first valuable thing in the pack for COINS, which is nonsense against a hive that
/// has no coins and never wanted the amber. Switched off rather than destroyed - StoreGui is one
/// object shared with Haldor, the faction merchants and the war totem, so it has to come back
/// the moment the window belongs to somebody else.
///
/// WHERE THE COINS GO, the hive's own three numbers go instead. StoreGui.Update writes the coin
/// count into that label every frame, so this writes over it afterwards.
/// </summary>
[HarmonyPatch(typeof(StoreGui), "Update")]
public static class SvermHiveStoreWindowPatch
{
public static void Postfix(StoreGui __instance)
{
SvermHiveBehaviour hive = SvermHiveStore.ActiveHive(__instance);
if (__instance.m_sellButton != null)
{
GameObject button = __instance.m_sellButton.gameObject;
bool wanted = hive == null;
if (button.activeSelf != wanted) button.SetActive(wanted);
}
if (hive == null || __instance.m_coinText == null) return;
float bank = SvermBiomass.Bank(hive.transform);
float digesting = SvermBiomass.Digesting(hive.transform);
float capacity = SvermBiomass.Capacity(hive.transform);
__instance.m_coinText.text = digesting > 0f
? $"{bank:0} / {capacity:0} (+{digesting:0})"
: $"{bank:0} / {capacity:0}";
}
}
/// <summary>The same refusal at the other end, for a gamepad that reaches the sell action anyway.</summary>
[HarmonyPatch(typeof(StoreGui), "SellItem")]
public static class SvermHiveStoreSellItemPatch
{
public static bool Prefix(StoreGui __instance)
{
return SvermHiveStore.ActiveHive(__instance) == null;
}
}
/// <summary>
/// Belt as well as braces on the disabled Trader in SvermHiveStore.Mount: if anything ever
/// enables that component - a mod, a future edit here - Trader.Update() would start
/// dereferencing an animator the nest does not have, every frame. One component lookup removes
/// the whole class of failure.
/// </summary>
[HarmonyPatch(typeof(Trader), "Update")]
public static class SvermHiveStoreTraderUpdatePatch
{
public static bool Prefix(Trader __instance)
{
return ((Component)__instance).GetComponent<SvermHiveShop>() == null;
}
}
// The empty-catalogue crash that used to kill the whole window is NOT guarded here: the war
// totem hit it first and StoreGuiEmptyCatalogueGuardPatch in Trol/TrolTotemStore.cs already
// covers every trader in the game, this one included. It is the reason the hive's window opens
// at all with nothing in its buy list, and a second prefix doing the same job would only make
// the log lie about who is holding the door.
}

View file

@ -0,0 +1,150 @@
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// What the colony looks like from across the field: flies over anything the hive owns, and a
/// green reek that only rises when something is actually going on inside.
///
/// THE FLIES ARE THE DRAUGH'S, borrowed the same way DraughVisuals borrows them - the looping
/// particle systems off the Draugr prefab, the ones with "flies" in the name. That file already
/// proved the technique in game, and the filter it uses is the important part: LOOPING is what
/// separates a creature's ambient rot from its one-shot hit and death effects.
///
/// THE GAS IS TOLD WHAT COLOUR TO BE. Its shape is borrowed off whichever poisonous thing this
/// build has, but the colour is set here rather than inherited, so "green smoke" is green
/// whether it came from a blob, a gjall or a draugr's rot.
///
/// NOTHING HERE IS NETWORKED and none of it needs to be: every client can read the nest's ZDO
/// and grow its own particles, exactly as every client grows its own Draugh aura. Which is also
/// why all of this runs ABOVE the owner check - a nest digesting is a thing everybody sees.
/// </summary>
public static class SvermHiveVfx
{
private const string FliesName = "SvermFliesVFX";
private const string GasName = "SvermGasVFX";
private const string FliesSource = "Draugr";
/// <summary>Anything with a looping smoke on it, best first. Only its shape is kept.</summary>
private static readonly string[] GasSources = { "Blob", "BlobElite", "Gjall", "Draugr" };
/// <summary>The reek of a stomach at work. Alpha low, or it reads as a wall rather than a haze.</summary>
private static readonly Color GasColor = new Color(0.35f, 0.85f, 0.25f, 0.5f);
// ─── The flies ───────────────────────────────────────────────────────
public static void EnsureFlies(Transform host, float scale)
{
if (host == null || host.Find(FliesName) != null) return;
GameObject source = Jotunn.Managers.PrefabManager.Cache.GetPrefab<GameObject>(FliesSource);
if (source == null) return;
GameObject swarm = new GameObject(FliesName);
swarm.transform.SetParent(host, false);
swarm.transform.localPosition = new Vector3(0f, scale, 0f);
swarm.transform.localScale = new Vector3(scale, scale, scale);
int taken = 0;
foreach (ParticleSystem ps in source.GetComponentsInChildren<ParticleSystem>(true))
{
if (!ps.main.loop) continue;
if (!ps.gameObject.name.ToLowerInvariant().Contains("flies")) continue;
GameObject copy = Object.Instantiate(ps.gameObject, swarm.transform);
copy.name = ps.gameObject.name;
copy.SetActive(true);
copy.transform.localPosition = Vector3.zero;
// Hierarchy scaling, or the holder's scale is ignored and every swarm is the size
// the Draugr wears it at, whatever it is hanging on.
ParticleSystem.MainModule main = copy.GetComponent<ParticleSystem>().main;
main.scalingMode = ParticleSystemScalingMode.Hierarchy;
taken++;
}
if (taken == 0)
{
Jotunn.Logger.LogWarning($"[Sverm] No looping 'flies' particles on '{FliesSource}'; " +
"the colony gets no swarm.");
}
}
// ─── The gas ─────────────────────────────────────────────────────────
/// <summary>
/// Turns the reek on or off, building it the first time it is asked for. Safe to call every
/// couple of seconds: after the first pass this is a Find and a SetActive.
/// </summary>
public static void SetGas(Transform host, bool on, float scale)
{
if (host == null) return;
Transform existing = host.Find(GasName);
if (existing == null)
{
if (!on) return; // nothing to switch off, and no reason to build it yet
existing = BuildGas(host, scale);
if (existing == null) return;
}
if (existing.gameObject.activeSelf != on) existing.gameObject.SetActive(on);
}
private static Transform BuildGas(Transform host, float scale)
{
GameObject cloud = new GameObject(GasName);
cloud.transform.SetParent(host, false);
cloud.transform.localPosition = new Vector3(0f, scale * 0.5f, 0f);
cloud.transform.localScale = new Vector3(scale, scale, scale);
int taken = 0;
foreach (string candidate in GasSources)
{
GameObject source = Jotunn.Managers.PrefabManager.Cache.GetPrefab<GameObject>(candidate);
if (source == null) continue;
foreach (ParticleSystem ps in source.GetComponentsInChildren<ParticleSystem>(true))
{
if (!ps.main.loop) continue;
string name = ps.gameObject.name.ToLowerInvariant();
// Flies are the other half of this file, and dripping water reads as rain.
if (name.Contains("flies")) continue;
if (name.Contains("drip") || name.Contains("drop") || name.Contains("rain") ||
name.Contains("splash")) continue;
GameObject copy = Object.Instantiate(ps.gameObject, cloud.transform);
copy.name = ps.gameObject.name;
copy.SetActive(true);
copy.transform.localPosition = Vector3.zero;
ParticleSystem.MainModule main = copy.GetComponent<ParticleSystem>().main;
main.scalingMode = ParticleSystemScalingMode.Hierarchy;
main.startColor = new ParticleSystem.MinMaxGradient(GasColor);
taken++;
}
if (taken > 0)
{
Jotunn.Logger.LogInfo($"[Sverm] Hive gas built from '{candidate}' ({taken} systems).");
break;
}
}
if (taken == 0)
{
Jotunn.Logger.LogWarning("[Sverm] Nothing to build the hive's gas from (" +
string.Join(", ", GasSources) + "); it will digest quietly.");
Object.Destroy(cloud);
return null;
}
return cloud.transform;
}
}
}

View file

@ -0,0 +1,114 @@
using HarmonyLib;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// Honey and royal jelly, pointed at one of the colony's own insects instead of eaten.
///
/// SECTION 19.4, and it closes a hole this branch opened itself. The two of them were taken OUT
/// of the biomass on purpose - feeding the hive its own medicine would be the worst kind of bug,
/// quiet and expensive - and until now that left them doing nothing for the colony at all.
///
/// HOW IT IS GIVEN: hold the jar in the hotbar, look at the insect, press the slot. Not a new
/// key, not a new UI, and no aiming mode - pressing a hotbar slot already runs Humanoid.UseItem,
/// and the game already knows which creature the player is looking at.
///
/// NOT A SECOND PREFIX. SvermFood already owns a prefix on Humanoid.UseItem (it swaps a real
/// item for the hidden clone that carries the Sverm's food numbers), and two prefixes on one
/// method that both want to be first is a coin toss - the same class of trap as the two
/// Interactables on the nest. This is called FROM that one, at the top, so the order is written
/// down rather than hoped for.
///
/// Aiming at nothing, or at anything that is not ours, falls through and the honey is eaten as
/// usual: honey is still food, and at double value, which is the whole of section 4.
/// </summary>
public static class SvermMedicine
{
/// <summary>
/// How far the medicine reaches. Player.m_hoveringCreature has NO range cap of its own - it
/// is set from a fifty metre raycast - so without this a jar of honey would heal a seeker
/// most of a field away.
/// </summary>
private const float Reach = 5f;
/// <summary>
/// Tries to use this item as medicine. True means it was handled and nothing else should
/// happen to it.
/// </summary>
public static bool TryAdminister(Player player, ItemDrop.ItemData item)
{
if (player == null) return false;
float healing = HealingOf(item);
if (healing <= 0f) return false;
Character patient = HoveredInsect(player);
if (patient == null) return false; // not pointed at one of ours: it is food again
if (patient.GetHealth() >= patient.GetMaxHealth())
{
// Refused rather than eaten. Somebody looking straight at their own seeker while
// pressing the honey meant to heal it, and swallowing it instead is the wrong
// surprise - especially at ninety points a jar of royal jelly.
// Localized, because a creature's m_name is a token: printing it raw would put
// "$enemy_seeker is not hurt" on the screen.
string who = Localization.instance.Localize(patient.m_name);
player.Message(MessageHud.MessageType.Center, $"{who} is not hurt.");
return true;
}
patient.Heal(healing, true);
Inventory inventory = player.GetInventory();
if (inventory != null) inventory.RemoveItem(item, 1);
// The same feedback eating gives, for the same reason: something has to say it worked.
EffectList consume = Traverse.Create((Humanoid)player).Field<EffectList>("m_consumeItemEffects").Value;
if (consume != null)
{
consume.Create(player.transform.position, Quaternion.identity, player.transform, 1f, -1);
}
return true;
}
/// <summary>What one of this heals, or zero if it is not medicine.</summary>
private static float HealingOf(ItemDrop.ItemData item)
{
if (item == null || item.m_shared == null) return 0f;
string prefabName = item.m_dropPrefab != null ? item.m_dropPrefab.name : "";
if (prefabName == "Honey") return SvermConfig.HoneyHealing;
if (prefabName == SvermConfig.RoyalJellyPrefab) return SvermConfig.RoyalJellyHealing;
return 0f;
}
/// <summary>
/// The colony insect the player is looking at, or null.
///
/// OURS AND NOT EVERY INSECT: a worker, or a troop hatched at a hive. A tamed seeker
/// somebody else raised is not the colony's business, and neither is a wild one.
/// </summary>
private static Character HoveredInsect(Player player)
{
// m_hoveringCreature is private in the assembly this project compiles against - the same
// field, read the same way, as FactionMerchantHoverPatch.
Character hovering = Traverse.Create(player).Field("m_hoveringCreature").GetValue<Character>();
if (hovering == null || hovering.IsDead()) return null;
if (Vector3.Distance(player.transform.position, hovering.transform.position) > Reach) return null;
if (hovering.GetComponent<SvermWorkerBehaviour>() != null) return hovering;
RaisedThrall thrall = hovering.GetComponent<RaisedThrall>();
if (thrall != null && !string.IsNullOrEmpty(thrall.Kind) && thrall.Kind.StartsWith(SvermBrood.PrefabPrefix))
{
return hovering;
}
return null;
}
}
}

View file

@ -0,0 +1,337 @@
using System.Collections.Generic;
using HarmonyLib;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// Every Harmony hook the Sverm body needs.
///
/// What is NOT here is worth saying, because it looked like it would be:
///
/// - "the carapace never slows you down" needs no patch at all. In vanilla the pieces that
/// carry a movement penalty ARE the chest, the legs and the helmet, and a Sverm cannot
/// wear any of them. Sealing the slots delivers the perk for free; a
/// GetEquipmentMovementModifier patch would have been a hook that changed nothing.
///
/// - carry weight, stamina on running and jumping, fall damage, eitr regeneration and the
/// discrete damage modifiers all live on SE_SvermStats, because Valheim already routes
/// them through status effects.
///
/// So what is left is the four things the game gives no other way in to: the armour value, the
/// sealed slots, exact damage scaling, and the per-frame cosmetic upkeep.
/// </summary>
public static class SvermPatches
{
// ─── Armour ──────────────────────────────────────────────────────────
/// <summary>
/// The carapace's armour, added on top of whatever the player is actually wearing - which
/// for the three sealed slots is nothing, so in practice this IS the player's armour.
/// Cape and trinket still count normally, and still stack, which is deliberate: they are
/// the two slots the race is allowed to shop for.
/// </summary>
[HarmonyPatch(typeof(Player), nameof(Player.GetBodyArmor))]
public static class Sverm_GetBodyArmor_Patch
{
public static void Postfix(Player __instance, ref float __result)
{
if (__instance == null || !SvermVisuals.IsSvermPlayer(__instance)) return;
__result += SvermCarapace.GetArmor(SvermVisuals.GetRenderState(__instance));
}
}
// ─── Sealed slots ────────────────────────────────────────────────────
/// <summary>
/// Chest, legs and helmet cannot be worn. The carapace is already in them.
///
/// A prefix that refuses rather than a filter on the inventory, so the item stays where it
/// is and the player gets told why. Returning false also stops the equip effects and the
/// visual rebuild, which is what keeps the carapace on screen.
/// </summary>
[HarmonyPatch(typeof(Humanoid), nameof(Humanoid.EquipItem))]
public static class Sverm_EquipItem_Patch
{
public static bool Prefix(Humanoid __instance, ItemDrop.ItemData item, ref bool __result)
{
if (item == null || item.m_shared == null) return true;
Player player = __instance as Player;
if (player == null || !SvermVisuals.IsSvermPlayer(player)) return true;
if (!SvermCarapace.IsSealedSlot(item.m_shared.m_itemType)) return true;
if (player == Player.m_localPlayer)
{
player.Message(MessageHud.MessageType.Center, "Your carapace has no room for that.");
}
__result = false;
return false;
}
}
// ─── Damage ──────────────────────────────────────────────────────────
/// <summary>
/// Both directions of the Sverm's combat maths, in one prefix because both are edits to
/// the same HitData before Valheim reads it.
///
/// OUTGOING - a bare-handed blow is rewritten into a claw blow, and Venom Glands adds
/// poison to every hit whatever is in your hands.
///
/// INCOMING - blunt and fire are scaled by an exact fraction. They are NOT in the status
/// effect's m_mods for a concrete reason: HitData.DamageModifier is a discrete enum whose
/// nearest rung, Weak, is a flat +50%, and the race is specced at +40%. Annealed Chitin
/// then flips the fire term negative at Fader, so one number walks the whole arc.
/// </summary>
[HarmonyPatch(typeof(Character), "Damage")]
public static class Sverm_Damage_Patch
{
// Acid Hemolymph answers a blow with a blow, and that answer re-enters this same
// prefix. Harmless today - the attacker is not usually a Sverm - but a Sverm hitting
// a Sverm would ping-pong, so the reflection is switched off while it is being dealt.
private static bool reflecting;
public static void Prefix(Character __instance, HitData hit)
{
if (hit == null) return;
Character attacker = hit.GetAttacker();
// ── Outgoing
if (attacker is Player attackingPlayer && SvermVisuals.IsSvermPlayer(attackingPlayer))
{
int state = SvermVisuals.GetRenderState(attackingPlayer);
SvermProgression.SvermRules rules = SvermProgression.GetRules(state);
if (hit.m_skill == Skills.SkillType.Unarmed)
{
// In Stinger Morph the hands are gone and what lands is a needle. The
// deathsquito's own figure is read off the creature, so it stays whatever
// vanilla says a deathsquito is worth; if it could not be read it comes
// back as zeroes and the claws answer instead.
HitData.DamageTypes sting = SvermStingerForm.IsActive
? SvermStingerForm.GetStingDamage()
: default(HitData.DamageTypes);
if (sting.m_pierce + sting.m_slash + sting.m_blunt > 0f)
{
hit.m_damage.m_pierce = sting.m_pierce;
hit.m_damage.m_slash = sting.m_slash;
hit.m_damage.m_blunt = sting.m_blunt;
}
else
{
SvermClaws.ApplyToUnarmedHit(hit, state);
}
}
if (rules.VenomOnHit > 0f)
{
hit.m_damage.m_poison += rules.VenomOnHit;
}
}
// ── Incoming
Player victim = __instance as Player;
if (victim == null || !SvermVisuals.IsSvermPlayer(victim)) return;
SvermProgression.SvermRules victimRules = SvermProgression.GetRules(SvermVisuals.GetRenderState(victim));
// The whole price of the form: out of the shell, a Sverm is an insect. Applied
// before the blunt and fire terms so it multiplies everything, not just the two
// types the carapace was ever weak to.
if (SvermStingerForm.IsActive)
{
hit.m_damage.Modify(SvermConfig.StingerFragility);
}
if (victimRules.BluntWeakness != 0f && hit.m_damage.m_blunt > 0f)
{
hit.m_damage.m_blunt *= 1f + victimRules.BluntWeakness;
}
// Negative once Annealed Chitin inverts it, which turns the same multiply into a
// resistance without a second branch.
if (victimRules.FireWeakness != 0f && hit.m_damage.m_fire > 0f)
{
hit.m_damage.m_fire *= 1f + victimRules.FireWeakness;
}
// ── Acid Hemolymph
if (victimRules.AcidHemolymph <= 0f || reflecting) return;
if (attacker == null || attacker == victim) return;
if (Vector3.Distance(attacker.transform.position, victim.transform.position) > SvermConfig.HemolymphRange) return;
reflecting = true;
try
{
HitData splash = new HitData();
splash.m_damage.m_poison = victimRules.AcidHemolymph;
splash.m_point = attacker.GetCenterPoint();
splash.m_dir = (attacker.transform.position - victim.transform.position).normalized;
splash.SetAttacker(victim);
attacker.Damage(splash);
}
finally
{
reflecting = false;
}
}
}
// ─── Skin ────────────────────────────────────────────────────────────
/// <summary>
/// The only thing that actually colours a player.
///
/// DvergarPatches documents the dead end this avoids: SetSkinColor followed by
/// UpdateColors does nothing, because UpdateColors is what REBUILDS the body material from
/// Valheim's own values and throws any earlier write away. Writing _SkinColor here, after
/// it has run, is the only order that survives.
/// </summary>
[HarmonyPatch(typeof(VisEquipment), "UpdateColors")]
public static class Sverm_UpdateColors_Patch
{
public static void Postfix(VisEquipment __instance)
{
if (__instance == null || __instance.m_bodyModel == null) return;
Player player = __instance.GetComponent<Player>();
if (player == null || !SvermVisuals.IsSvermPlayer(player)) return;
Material material = __instance.m_bodyModel.material;
if (material != null && material.HasProperty("_SkinColor"))
{
material.SetColor("_SkinColor", SvermVisuals.GetSkinColor(player));
}
}
}
/// <summary>
/// Puts the carapace back the same frame the game takes it off.
///
/// Valheim rebuilds the equipment instances on every equipment change, from the REAL
/// contents of the slots - which for a Sverm are empty. Waiting for the throttled cosmetic
/// pass in Player.Update meant up to half a second of bare chest every time anything was
/// unequipped, which is precisely the flicker that got reported.
///
/// This is a mitigation and not the cure. The cure is real items in reserved inventory
/// slots, so the game is rebuilding from something that is actually there and there is
/// nothing to put back; until that lands, this closes the window to a single frame.
///
/// The guard is not optional: SetChestItem and its siblings mark the visuals dirty, so
/// ApplyCarapace can re-enter this postfix through the game's own refresh.
/// </summary>
[HarmonyPatch(typeof(VisEquipment), "UpdateVisuals")]
public static class Sverm_UpdateVisuals_Patch
{
private static bool reentering;
public static void Postfix(VisEquipment __instance)
{
if (__instance == null || reentering) return;
Player player = __instance.GetComponent<Player>();
if (player == null || !SvermVisuals.IsSvermPlayer(player)) return;
reentering = true;
try { SvermVisuals.ApplyCarapace(player); }
finally { reentering = false; }
}
}
// ─── Per-frame upkeep ────────────────────────────────────────────────
/// <summary>
/// Scale, eyes, claws, wings and the carapace, kept in step.
///
/// On Player.Update because that is the one place body scale survives - Trol's own postfix
/// forces every non-Trol player's visual back to 1 on the same frame, so a scale applied
/// from anywhere else is simply overwritten. RaceScale keeps the two from undoing each
/// other.
///
/// The cosmetics are throttled rather than run every frame: each of them walks a renderer
/// tree, and Valheim rebuilds equipment instances only on an equipment change. Half a
/// second is well under the time it takes to notice a stale tint and well over the cost of
/// doing it sixty times a second.
/// </summary>
[HarmonyPatch(typeof(Player), "Update")]
public static class Sverm_PlayerUpdate_Patch
{
private static readonly Dictionary<Player, float> nextCosmeticPass = new Dictionary<Player, float>();
private const float CosmeticInterval = 0.5f;
public static void Postfix(Player __instance)
{
if (__instance == null) return;
bool isSverm = SvermVisuals.IsSvermPlayer(__instance);
SvermVisuals.ApplyScale(__instance, isSverm);
if (!nextCosmeticPass.TryGetValue(__instance, out float due) || Time.time >= due)
{
nextCosmeticPass[__instance] = Time.time + CosmeticInterval;
SvermVisuals.ApplyEyes(__instance);
SvermVisuals.ApplyClaws(__instance); // cleanup of the retired cosmetic path
SvermVisuals.ApplySpines(__instance);
SvermVisuals.ApplyGlideMotes(__instance);
if (isSverm) SvermVisuals.ApplyCarapace(__instance);
// Issues the claws if they are missing and puts them back in hand whenever
// both hands are free. On the same throttle rather than every frame: it is a
// handful of checks that all short-circuit once the claws exist.
if (isSverm) SvermClawSlot.Maintain(__instance);
}
if (!isSverm || __instance != Player.m_localPlayer) return;
// Carapace Regeneration. A flat trickle rather than a multiplier on the vanilla
// regeneration, so it keeps working while the player is starving - which is the
// whole point of a shell that knits itself back together.
float regen = SvermProgression.Current.CarapaceRegenPerSecond;
if (regen > 0f && !__instance.IsDead() && __instance.GetHealth() < __instance.GetMaxHealth())
{
__instance.Heal(regen * Time.deltaTime, false);
}
}
}
// ─── Spawn ───────────────────────────────────────────────────────────
/// <summary>
/// Puts the passive back on after a load or a death, and publishes the tier on the ZDO so
/// other clients can render a remote Sverm at ITS tier rather than at theirs.
/// </summary>
[HarmonyPatch(typeof(Player), "OnSpawned")]
public static class Sverm_OnSpawned_Patch
{
public static void Postfix(Player __instance)
{
if (__instance == null || __instance != Player.m_localPlayer) return;
if (!SvermVisuals.IsSvermPlayer(__instance)) return;
__instance.GetSEMan().AddStatusEffect(SvermConfig.StatsSE.GetStableHashCode(), true);
PublishState(__instance);
}
}
public static void PublishState(Player player)
{
if (player == null) return;
ZNetView nview = player.GetComponent<ZNetView>();
if (nview == null || !nview.IsValid()) return;
int state = BossProgressionManager.GetCurrentProgressionState();
if (nview.GetZDO().GetInt(SvermConfig.StateZdoKey, 0) != state)
{
nview.GetZDO().Set(SvermConfig.StateZdoKey, state);
}
}
}
}

View file

@ -0,0 +1,116 @@
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// Turns a boss progression state into the set of Sverm perks active at that tier, the same way
/// DvergarProgression and SkeletonProgression do for their races.
///
/// Nothing is decided here - every figure comes out of SvermConfig - so the tuning pass can
/// happen without touching a single patch.
///
/// ONE THING IS DELIBERATELY NOT IN THE STRUCT: the carapace's armour value and the eitr
/// regeneration. Both are read off ObjectDB, which is empty until a world loads, so caching
/// them in a rules struct built on the first call would freeze a zero into every later tier.
/// They live in SvermCarapace, which caches per state and only once ObjectDB answers. Ask for
/// them there.
/// </summary>
public static class SvermProgression
{
public struct SvermRules
{
/// <summary>Extra fraction of blunt damage taken. 0.40 means a mace hits for 140%.</summary>
public float BluntWeakness;
/// <summary>
/// Extra fraction of fire damage taken, NEGATIVE once Annealed Chitin inverts it at
/// Fader. One number for both halves of the arc, because it is one arc.
/// </summary>
public float FireWeakness;
/// <summary>Fraction of the Maulclaws' quality-4 damage a bare-handed blow lands for.</summary>
public float ClawDamagePercent;
public bool MetabolicSurge; // cheaper running and jumping, higher jump
public float CarryWeightBonus; // Ventral Pouches
public bool SeedsEdible; // Grinding Mandibles
public bool SensoryAntennae; // creature sense through terrain
public float VenomOnHit; // Venom Glands: poison added to every blow
public float AcidHemolymph; // poison dealt back to a melee attacker
/// <summary>-1 is "no fall damage at all", matching FenrirProgression's convention.</summary>
public float FallDamageModifier;
/// <summary>How tall the dorsal spines stand, in metres. 0 before they grow.</summary>
public float SpineSize;
public bool StingerMorph; // the Deathsquito form is unlocked
public float BodyScale; // Surrenal Glands
public float CarapaceRegenPerSecond;
public bool Emberform; // black chitin, red burn, burning claws
}
// GetRules runs from Update loops and from damage patches, so the per-state result is
// built once and handed back on every later call.
private static readonly SvermRules[] cache = new SvermRules[BossProgressionManager.MaxState + 1];
private static readonly bool[] cached = new bool[BossProgressionManager.MaxState + 1];
public static SvermRules GetRules(int state)
{
state = Mathf.Clamp(state, BossProgressionManager.MinState, BossProgressionManager.MaxState);
if (cached[state]) return cache[state];
bool annealed = state >= SvermConfig.AnnealedChitinState;
SvermRules rules = new SvermRules
{
BluntWeakness = SvermConfig.BluntWeakness,
// The whole point of the race's arc: the defect that defined it for seven tiers is
// burned out by the last boss and comes back as a resistance.
FireWeakness = annealed
? -SvermConfig.FireResistanceAtFader
: SvermConfig.FireWeakness,
ClawDamagePercent = SvermConfig.ClawDamagePercentByState[state],
MetabolicSurge = state >= SvermConfig.MetabolicSurgeState,
CarryWeightBonus = state >= SvermConfig.VentralPouchesState ? SvermConfig.CarryWeightBonus : 0f,
SeedsEdible = state >= SvermConfig.SeedsEdibleState,
SensoryAntennae = state >= SvermConfig.SensoryAntennaeState,
VenomOnHit = state >= SvermConfig.VenomGlandsState
? SvermConfig.VenomPerState * (state - SvermConfig.VenomGlandsState + 1)
: 0f,
AcidHemolymph = state >= SvermConfig.AcidHemolymphState
? SvermConfig.HemolymphPerState * (state - SvermConfig.AcidHemolymphState + 1)
: 0f,
FallDamageModifier = state >= SvermConfig.VestigialWingsState ? -1f : 0f,
SpineSize = state >= SvermConfig.FullWingspanState ? SvermConfig.SpineSizeFull
: state >= SvermConfig.VestigialWingsState ? SvermConfig.SpineSizeSmall
: 0f,
StingerMorph = state >= SvermConfig.StingerMorphState,
BodyScale = state >= SvermConfig.SurrenalGlandsState ? SvermConfig.BodyScaleAtQueen : 1f,
CarapaceRegenPerSecond = state >= SvermConfig.CarapaceRegenState
? SvermConfig.CarapaceRegenPerSecond
: 0f,
Emberform = annealed,
};
cache[state] = rules;
cached[state] = true;
return rules;
}
/// <summary>Rules for whatever tier the local player is currently on.</summary>
public static SvermRules Current => GetRules(BossProgressionManager.GetCurrentProgressionState());
}
}

View file

@ -0,0 +1,102 @@
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// Driver for the Sverm: an armoured insect that never dresses, never disarms, and grows a
/// colony instead of a wardrobe.
///
/// Only the per-frame upkeep that does not belong to a Harmony hook lives here. The perks are
/// SvermPatches, the passive is SE_SvermStats, the numbers are SvermConfig by way of
/// SvermProgression, and the look is SvermVisuals.
/// </summary>
public class SvermRace : MonoBehaviour
{
public static SvermRace Instance;
private float nextStatePublish;
private void Awake()
{
Instance = this;
}
public void CreateModAssets()
{
SvermStatusEffects.RegisterStatusEffects();
// Registered HERE and not lazily at spawn: this method runs on
// PrefabManager.OnVanillaPrefabsAvailable, which is the one moment Jotunn will take a
// new item into ObjectDB. Registering later builds a prefab nobody can spawn.
SvermClawSlot.EnsureRegistered();
// Same window, same reason: every edible is a cloned item, and Jotunn only takes new
// items here.
SvermFood.Register();
// Same window again: the worker is a cloned creature prefab.
SvermWorker.Register();
// And the four troops, which are cloned creatures too - Jotunn only takes a new prefab
// in this window, so a roster registered later is a roster nothing can spawn.
SvermBrood.Register();
// The bomb tick is a cloned creature too, and its blast is priced off two vanilla
// projectiles it reads at registration.
SvermBlisterTick.Register();
// The nest, its density cap and its Elder gate all live in SvermHive now.
//
// HONEST LIMIT on that cap, and it is PieceDensityLimit's own: a client holds only the
// ZDOs the server has sent it, and 908 m is far outside the loaded zones. Exact in
// singleplayer and on the host; on a remote client it can undercount and let a third
// nest through far from the other two. It still closes the case that matters.
SvermHive.Register();
// The shop counter, a building of its own rather than a second mouth on the nest - two
// launches proved a mouth on a shared body is a race between colliders. It has to come
// after the nest: its placement gate asks whether one is standing nearby.
SvermHiveMarketPiece.Register();
}
public static bool IsSverm()
{
return Player.m_localPlayer != null &&
Player.m_localPlayer.m_customData.ContainsKey("Race") &&
Player.m_localPlayer.m_customData["Race"] == SvermConfig.RaceId;
}
private void Update()
{
// Antennae first and outside the race guard: it has to be able to put its own lights
// out when the player stops being a Sverm, and a guard above it would leave them lit
// on every creature in range forever.
SvermAntennae.Tick(Player.m_localPlayer);
// Also outside the race guard, and for the same reason: it has to be able to drop the
// form and give the player their body back if they stop being a Sverm mid-flight.
SvermStingerForm.Tick(Player.m_localPlayer);
if (Player.m_localPlayer == null || !IsSverm()) return;
// Republished on a timer rather than only at spawn: the tier changes the moment a boss
// dies, and a remote Sverm that still reads as tier 4 renders in the wrong colour with
// the wrong wings until it next loads.
if (Time.time >= nextStatePublish)
{
nextStatePublish = Time.time + 5f;
SvermPatches.PublishState(Player.m_localPlayer);
}
}
}
/// <summary>
/// Names the colony half will register, declared here so the body half can cap the hive before
/// that half exists. One string, one place, no duplicate literal to drift.
/// </summary>
public static class SvermHiveNames
{
public const string PieceName = "SvermBroodMound";
public const string PieceDisplayName = "Brood Mound";
}
}

View file

@ -0,0 +1,161 @@
using System.Collections.Generic;
using Jotunn.Entities;
using Jotunn.Managers;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// Passive carrier for the Sverm. Everything Valheim already routes through a status effect
/// lives here - carry weight, stamina on running and jumping, fall damage, eitr and health
/// regeneration, and the discrete damage modifiers - so there is nothing to intercept with a
/// patch for any of it.
///
/// The two damage numbers that are NOT here are blunt and fire. HitData.DamageModifier is a
/// discrete enum: Weak is a flat +50% and there is no rung at +40%. Those two run through a
/// Character.Damage prefix in SvermPatches instead, which is how Aswid, Draugh and Dvergar
/// already scale damage exactly.
///
/// The rebuild-per-state dance is copied from SE_SkeletonStats and is not optional. Setup runs
/// once, when the effect is first applied - normally at spawn, before any boss is dead - so
/// anything written there is frozen at tier 1 forever. That is exactly how the Skeleton lost
/// its poison immunity. Re-checking every tick is free because the state comparison short-
/// circuits.
/// </summary>
public class SE_SvermStats : SE_Stats
{
private int m_appliedState = -1;
public override void Setup(Character character)
{
base.Setup(character);
name = SvermConfig.StatsSE;
m_name = "Chitin Plating";
m_tooltip = "Armoured, venomous, and never alone.";
RebuildForState();
}
public override void UpdateStatusEffect(float dt)
{
base.UpdateStatusEffect(dt);
RebuildForState();
}
private void RebuildForState()
{
int state = BossProgressionManager.GetCurrentProgressionState();
if (state == m_appliedState) return;
m_appliedState = state;
SvermProgression.SvermRules rules = SvermProgression.GetRules(state);
// Written on the LIVE effect, not on the registered template: SEMan.AddStatusEffect
// clones what it is given and adds the clone, so anything set on the template
// afterwards reaches nobody.
m_addMaxCarryWeight = rules.CarryWeightBonus;
m_fallDamageModifier = rules.FallDamageModifier;
if (rules.MetabolicSurge)
{
m_runStaminaDrainModifier = -SvermConfig.RunStaminaDiscount;
m_jumpStaminaUseModifier = -SvermConfig.JumpStaminaDiscount;
// Vector3, not a float: Valheim scales the jump per axis. Only the vertical
// component is wanted - a Sverm jumps higher, not further sideways.
m_jumpModifier = new Vector3(0f, SvermConfig.JumpBonus, 0f);
}
else
{
m_runStaminaDrainModifier = 0f;
m_jumpStaminaUseModifier = 0f;
m_jumpModifier = Vector3.zero;
}
// Eitr Sacs. GetEitrRegenBonus returns the fraction the eitr-weave set would have
// given, halved; the field wants a multiplier, so 0.15 becomes 1.15. It reads 0 until
// ObjectDB answers, and the next tick picks the real value up - which is another
// reason this rebuild is not a one-shot.
float eitrBonus = SvermCarapace.GetEitrRegenBonus(state);
m_eitrRegenMultiplier = 1f + eitrBonus;
// Carapace Regeneration is a flat trickle rather than a multiplier, so it is applied
// by hand in SvermRace.Update. The multiplier stays neutral here.
m_healthRegenMultiplier = 1f;
// Chitin resists a point and shrugs off poison entirely. Blunt and fire are handled in
// the damage prefix, deliberately absent from this list.
m_mods = new List<HitData.DamageModPair>
{
new HitData.DamageModPair { m_type = HitData.DamageType.Pierce, m_modifier = HitData.DamageModifier.Resistant },
new HitData.DamageModPair { m_type = HitData.DamageType.Poison, m_modifier = HitData.DamageModifier.Immune },
};
}
}
/// <summary>
/// Stinger Morph's cooldown. Purely a marker with a countdown, the way
/// SE_DvergarAbilityCooldown is: Valheim prints the remaining time of any effect with a m_ttl,
/// so the HUD comes for free.
/// </summary>
public class SE_SvermStingerCooldown : StatusEffect
{
public override void Setup(Character character)
{
base.Setup(character);
m_name = "Stinger Morph Cooldown";
m_tooltip = "The wings are spent. They will carry you again soon.";
m_ttl = SvermConfig.StingerCooldownSeconds;
}
}
/// <summary>Held while the Deathsquito form is up, so anything can ask "am I a bug right now".</summary>
public class SE_SvermStingerForm : StatusEffect
{
public override void Setup(Character character)
{
base.Setup(character);
m_name = "Stinger Morph";
m_tooltip = "Wings, a needle, and nothing to hide behind.";
}
}
public static class SvermStatusEffects
{
public static SE_SvermStats StatsSE { get; private set; }
public static void RegisterStatusEffects()
{
Sprite icon = GetItemIcon("TrophySeekerBrute")
?? GetItemIcon("TrophySeeker")
?? GetItemIcon("Chitin");
var stats = ScriptableObject.CreateInstance<SE_SvermStats>();
stats.name = SvermConfig.StatsSE;
stats.m_name = "Chitin Plating";
stats.m_icon = icon;
CustomStatusEffect customStats = new CustomStatusEffect(stats, fixReference: false);
ItemManager.Instance.AddStatusEffect(customStats);
StatsSE = customStats.StatusEffect as SE_SvermStats;
var form = ScriptableObject.CreateInstance<SE_SvermStingerForm>();
form.name = SvermConfig.StingerSE;
form.m_name = "Stinger Morph";
form.m_icon = icon;
ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(form, fixReference: false));
var cooldown = ScriptableObject.CreateInstance<SE_SvermStingerCooldown>();
cooldown.name = SvermConfig.StingerCdSE;
cooldown.m_name = "Stinger Morph Cooldown";
cooldown.m_icon = icon;
ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(cooldown, fixReference: false));
}
private static Sprite GetItemIcon(string prefabName)
{
GameObject prefab = PrefabManager.Cache.GetPrefab<GameObject>(prefabName);
ItemDrop drop = prefab != null ? prefab.GetComponent<ItemDrop>() : null;
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];
}
}
}

View file

@ -0,0 +1,375 @@
using HarmonyLib;
using Jotunn.Managers;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// Stinger Morph: from Yagluth on, a Sverm can become a Deathsquito for two minutes.
///
/// It is the one thing in the race that is not armour. Everything else the Sverm has says
/// "stand there and survive"; this says the opposite, and it is deliberate that the two do not
/// overlap - in form there is no carapace, no claws, no inventory and no hammer, only a needle
/// and the ability to leave. A glass cannon that flies is the role the tank was missing.
///
/// Built on two things that already work: BatFormBehavior for flight (Valheim's own
/// m_debugFly, held on every frame) and PlayerVisualHider for swapping the body out. The
/// duration and cooldown follow FenrirProgression.FormRules' shape - a timer and a status
/// effect the HUD can count down - without borrowing that race's tables.
/// </summary>
public static class SvermStingerForm
{
public static bool IsActive { get; private set; }
private static GameObject model;
private static float expiresAt;
private static float nextAllowedAt;
private static HitData.DamageTypes stingerDamage;
private static bool stingerDamageRead;
// ─── Driver ──────────────────────────────────────────────────────────
public static void Tick(Player player)
{
if (player == null || player != Player.m_localPlayer)
{
return;
}
// Death ends it immediately, and so does ceasing to be a Sverm. Both leave a body
// hidden and a bug that is very hard to read, so they are checked before anything else.
if (IsActive && (player.IsDead() || !SvermVisuals.IsSvermPlayer(player)))
{
Exit(player, spendCooldown: false);
return;
}
if (IsActive && Time.time >= expiresAt)
{
Exit(player, spendCooldown: true);
player.Message(MessageHud.MessageType.Center, "The wings fold away.");
return;
}
if (!SvermConfigManagement.StingerKey.Value.IsDown()) return;
if (!SvermVisuals.IsSvermPlayer(player)) return;
if (IsActive)
{
Exit(player, spendCooldown: true);
return;
}
if (!SvermProgression.Current.StingerMorph)
{
player.Message(MessageHud.MessageType.Center, "Your wings are still vestigial.");
return;
}
if (Time.time < nextAllowedAt)
{
player.Message(MessageHud.MessageType.Center, "The wings are spent.");
return;
}
Enter(player);
}
// ─── Enter and leave ─────────────────────────────────────────────────
private static void Enter(Player player)
{
// THE CLAWS STAY ON, and everything else comes off.
//
// The first version emptied the hands completely and the form could not attack: with
// nothing equipped there is no weapon to swing, and Valheim's bare fist is not the
// thing this form is supposed to be throwing. Leaving the Maulclaws equipped makes the
// sting an ordinary weapon attack - which works - and costs nothing visually, because
// the whole body is hidden a line later. Fist weapons report Skills.SkillType.Unarmed,
// so the damage patch still recognises the blow and swaps the deathsquito's figure in.
ItemDrop.ItemData held = Traverse.Create((Humanoid)player).Field<ItemDrop.ItemData>("m_rightItem").Value;
if (held != null && !SvermClawSlot.IsClaws(held))
{
player.UnequipItem(held, false);
SvermClawSlot.Maintain(player); // hands back the claws in its place
}
IsActive = true;
expiresAt = Time.time + SvermConfig.StingerDurationSeconds;
player.GetSEMan().AddStatusEffect(SvermConfig.StingerSE.GetStableHashCode(), true);
Transform visual = player.transform.Find("Visual");
PlayerVisualHider.Hide(visual, "sverm-stinger");
GameObject source = PrefabManager.Cache.GetPrefab<GameObject>(SvermConfig.StingerCreature);
GameObject animated = source != null ? source.GetComponentInChildren<Animator>()?.gameObject : null;
if (animated != null)
{
model = Object.Instantiate(animated, player.transform.position, player.transform.rotation, player.transform);
model.transform.localPosition = Vector3.zero;
// SCALE COMES FROM THE SOURCE, not from 1.
//
// Forcing Vector3.one is what the Aswid does for the bat and it happens to be
// right there, because a bat's animated child is authored at 1. A deathsquito's is
// not - forcing 1 blew it up to something the size of a house. Keeping the source's
// own scale means the model arrives the size the game draws it, and the multiplier
// is there only for taste.
model.transform.localScale = animated.transform.localScale * SvermConfigManagement.StingerScale;
// AND IT FACES THE WRONG WAY without this. The creature's own forward is not the
// player's, so the model arrived looking back at the camera. Which way to turn it
// is a thing only an eye can settle, so it is a config value and not a constant.
model.transform.localRotation = Quaternion.Euler(0f, SvermConfigManagement.StingerYaw, 0f);
model.AddComponent<StingerFormBehavior>();
}
else
{
// No model is survivable - you fly as an invisible insect - but it is worth saying
// out loud rather than leaving someone to wonder why they turned into nothing.
Jotunn.Logger.LogWarning($"[Sverm] No '{SvermConfig.StingerCreature}' model to wear; " +
"Stinger Morph flies without a body.");
GameObject bare = new GameObject("SvermStingerFlight");
bare.transform.SetParent(player.transform, false);
bare.AddComponent<StingerFormBehavior>();
model = bare;
}
PlayEffect(SvermConfig.MorphInEffects, player.transform.position);
SummonEscort(player);
player.Message(MessageHud.MessageType.Center, "You take to the air.");
}
/// <summary>
/// Two deathsquitoes, tamed, that outlive the form by a minute.
///
/// They are NOT tied to the form's lifetime and that is the point: the form ends where it
/// ends, usually mid-air, and the player becomes a slow armoured thing halfway through a
/// fall. The escort covers exactly that minute and then dies on its own.
///
/// Tamed rather than merely friendly, because tamed is the one state every part of the
/// game already understands - they will not be attacked by the player, they will not
/// attack the player, and BaseAI already knows to fight what fights them.
/// </summary>
private static void SummonEscort(Player player)
{
GameObject prefab = PrefabManager.Cache.GetPrefab<GameObject>(SvermConfig.StingerCreature);
if (prefab == null) return;
for (int i = 0; i < SvermConfig.EscortCount; i++)
{
// Spread them apart, and above: spawning two creatures inside each other and
// inside the player is how you get three things shoved through the floor.
float angle = 360f / Mathf.Max(1, SvermConfig.EscortCount) * i;
Vector3 offset = Quaternion.Euler(0f, angle, 0f) * Vector3.forward * SvermConfig.EscortSpawnSpread;
Vector3 where = player.transform.position + offset + Vector3.up * 1.5f;
GameObject spawned = Object.Instantiate(prefab, where, Quaternion.identity);
if (spawned == null) continue;
Character character = spawned.GetComponent<Character>();
if (character != null) character.SetTamed(true);
// Nothing to farm: an escort that dropped trophies would be a deathsquito printer
// on an eight minute cooldown. Same reasoning as the thralls' stripped drop tables.
CharacterDrop drop = spawned.GetComponent<CharacterDrop>();
if (drop != null) Object.Destroy(drop);
spawned.AddComponent<SvermEscortLife>().Expires = Time.time + SvermConfig.EscortLifetimeSeconds;
}
}
private static void PlayEffect(string[] candidates, Vector3 where)
{
foreach (string name in candidates)
{
GameObject fx = PrefabManager.Cache.GetPrefab<GameObject>(name);
if (fx == null) continue;
Object.Instantiate(fx, where, Quaternion.identity);
return;
}
}
private static void Exit(Player player, bool spendCooldown)
{
IsActive = false;
PlayEffect(SvermConfig.MorphOutEffects, player.transform.position);
// The escort is deliberately NOT dismissed here. It has its own minute left to run.
if (model != null)
{
Object.Destroy(model);
model = null;
}
player.GetSEMan().RemoveStatusEffect(SvermConfig.StingerSE.GetStableHashCode());
Transform visual = player.transform.Find("Visual");
PlayerVisualHider.Show(visual, "sverm-stinger-revert");
if (spendCooldown)
{
nextAllowedAt = Time.time + SvermConfig.StingerCooldownSeconds;
player.GetSEMan().AddStatusEffect(SvermConfig.StingerCdSE.GetStableHashCode(), true);
}
}
// ─── The sting ───────────────────────────────────────────────────────
/// <summary>
/// The Deathsquito's own damage, read off the creature rather than invented.
///
/// Vanilla's deathsquito hits harder per blow than anything else in the Plains, and that
/// number is the entire reason the form is worth its cooldown. Reading it means the form
/// tracks whatever the game says a deathsquito is worth, forever.
/// </summary>
public static HitData.DamageTypes GetStingDamage()
{
if (stingerDamageRead) return stingerDamage;
GameObject creature = PrefabManager.Cache.GetPrefab<GameObject>(SvermConfig.StingerCreature);
Humanoid humanoid = creature != null ? creature.GetComponent<Humanoid>() : null;
if (humanoid != null && humanoid.m_defaultItems != null)
{
foreach (GameObject weapon in humanoid.m_defaultItems)
{
ItemDrop drop = weapon != null ? weapon.GetComponent<ItemDrop>() : null;
if (drop == null || drop.m_itemData == null || drop.m_itemData.m_shared == null) continue;
stingerDamage = drop.m_itemData.m_shared.m_damages;
stingerDamageRead = true;
Jotunn.Logger.LogInfo($"[Sverm] Stinger reads {stingerDamage.m_pierce:0.#} pierce " +
$"off '{weapon.name}'.");
return stingerDamage;
}
}
Jotunn.Logger.LogWarning($"[Sverm] Could not read a weapon off '{SvermConfig.StingerCreature}'; " +
"the sting falls back to the Maulclaws.");
stingerDamageRead = true;
return stingerDamage; // all zeroes: the damage patch then leaves the claw values alone
}
// ─── What the form may not do ────────────────────────────────────────
/// <summary>
/// No weapons in form, which also means no hammer - so "cannot build" needs no patch of
/// its own, it falls out of having nothing to build with.
/// </summary>
[HarmonyPatch(typeof(Humanoid), nameof(Humanoid.EquipItem))]
public static class Sverm_StingerEquip_Patch
{
public static bool Prefix(Humanoid __instance, ItemDrop.ItemData item, ref bool __result)
{
if (!IsActive) return true;
Player player = __instance as Player;
if (player == null || player != Player.m_localPlayer) return true;
// The claws are the exception, and they have to be: they are what the form
// attacks with, and SvermClawSlot.Maintain hands them back whenever the hands go
// empty. Refusing them here would fight that loop every half second.
if (SvermClawSlot.IsClaws(item)) return true;
player.Message(MessageHud.MessageType.Center, "An insect carries nothing.");
__result = false;
return false;
}
}
/// <summary>No food, no mead, no potions. The form is meant to be survived, not sustained.</summary>
[HarmonyPatch(typeof(Humanoid), "UseItem")]
public static class Sverm_StingerUseItem_Patch
{
public static bool Prefix(Humanoid __instance)
{
if (!IsActive) return true;
return !(__instance is Player player) || player != Player.m_localPlayer;
}
}
}
/// <summary>
/// An escort deathsquito's own clock.
///
/// It dies rather than vanishing - Character.Damage with enough to finish it - so the death
/// plays its effects and reads as the summon running out rather than as a creature popping out
/// of existence. The drop table was stripped at spawn, so dying costs the world nothing.
/// </summary>
public class SvermEscortLife : MonoBehaviour
{
public float Expires;
private void Update()
{
if (Time.time < Expires) return;
Character character = GetComponent<Character>();
if (character == null || character.IsDead())
{
Destroy(gameObject);
return;
}
HitData hit = new HitData();
hit.m_damage.m_damage = character.GetMaxHealth() * 10f;
hit.m_point = character.GetCenterPoint();
character.Damage(hit);
enabled = false; // the death takes a moment; do not queue another blow every frame
}
}
/// <summary>
/// Flight, held on every frame.
///
/// m_debugFly is Valheim's own free-flight switch and it is re-asserted every Update rather
/// than set once, because plenty of things in the game turn it back off - the same reason
/// BatFormBehavior does it that way. OnDestroy putting it back is what stops a Sverm from
/// walking on air after the form ends.
/// </summary>
public class StingerFormBehavior : MonoBehaviour
{
private Animator anim;
private void Start()
{
anim = GetComponentInChildren<Animator>();
SetFly(true);
}
private void Update()
{
if (Player.m_localPlayer == null || Player.m_localPlayer.IsDead()) return;
SetFly(true);
if (anim == null) return;
Vector3 velocity = Player.m_localPlayer.GetVelocity();
velocity.y = 0f;
anim.SetFloat("forward_speed", velocity.magnitude);
anim.SetBool("flying", true);
}
private void OnDestroy()
{
SetFly(false);
}
private static void SetFly(bool on)
{
if (Player.m_localPlayer == null) return;
Traverse.Create(Player.m_localPlayer).Field("m_debugFly").SetValue(on);
}
}
}

View file

@ -0,0 +1,780 @@
using System.Collections.Generic;
using HarmonyLib;
using Jotunn.Managers;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// Everything a Sverm looks like, and every bit of it grown from vanilla assets.
///
/// THE TINT RAMP IS THE PROGRESSION. The carapace silhouette never changes - it is the
/// Mistlands carapace set at every tier, because the bronze set retinted brown is still bronze
/// in its SHAPE while the carapace is already modelled chitin. What changes is the colour, and
/// it tells the age of the animal: pale violet while the shell is still soft, full amber once
/// it has hardened, near black with a red burn at Fader. No new assets, and the character
/// matures on screen as it advances.
///
/// What gets mounted, all of it borrowed from vanilla:
/// the claws - the Vilebone Maulclaws, on both hands, always;
/// the spines - UndeadBjornRibcage worn spine-up, a static crest, from tier 5;
/// the eyes - two emissive spheres, the Aswid's geometry unchanged;
/// the motes - a firefly swarm under the body, only while falling;
/// the ember - emission written into the carapace materials at Fader.
///
/// Runs for local and remote players alike, which is why every entry point takes a Player
/// rather than reading Player.m_localPlayer: the race is on the ZDO, so each client can grow
/// the right body for everyone it can see.
/// </summary>
public static class SvermVisuals
{
private const string EyesName = "SvermEyes";
private const string ClawsName = "SvermClaw";
private const string SpinesName = "SvermSpines";
// The Aswid's tuning on this same rig, carried over unchanged. That is not laziness: the
// offsets live in the head bone's OWN local space, so the scale cancels and the same
// numbers land on the same part of the face at any size - which is also why Surrenal
// Glands' +10% at tier 7 needs no special case here.
private const float EyeSeparation = 0.032f;
private const float EyeForward = 0.081f;
private const float EyeHeight = 0.181f;
private const float EyeSize = 0.062f;
/// <summary>
/// 1, not the Dvergar's 0.85.
///
/// That 0.85 is a HUMAN face correction: a skull is not flat, so two eyes placed
/// symmetrically in bone space do not read as symmetrical, and the Dvergar shrinks one to
/// compensate. An insect's eyes are a matched pair and are supposed to look like one, so
/// the correction is not just unnecessary here - it is the defect. Both eyes take the
/// larger size.
/// </summary>
private const float LeftEyeSizeMultiplier = 1f;
private const string HeadBoneName = "Head";
private const string RightHandBoneName = "RightHand";
private const string LeftHandBoneName = "LeftHand";
// ─── Race check ──────────────────────────────────────────────────────
/// <summary>
/// Reads the race off the ZDO so remote players render correctly, falling back to
/// m_customData for the main-menu preview, which has no ZNetView but does have the saved
/// custom data. Same shape as SkeletonVisuals.GetPlayerRace.
/// </summary>
public static string GetPlayerRace(Player player)
{
if (player == null) return "Human";
ZNetView nview = player.GetComponent<ZNetView>();
if (nview != null && nview.IsValid())
{
string race = nview.GetZDO().GetString("RacesOfValheim_Race", "");
if (!string.IsNullOrEmpty(race)) return race;
}
if (player.m_customData != null && player.m_customData.TryGetValue("Race", out string custom))
{
return custom;
}
return "Human";
}
public static bool IsSvermPlayer(Player player) => GetPlayerRace(player) == SvermConfig.RaceId;
/// <summary>
/// The tier to render this player at.
///
/// For the local player that is simply the progression state. For a remote player the
/// local progression is the wrong answer - it is OUR tier, not theirs - so the ZDO is
/// asked first. Races that never wrote the key fall back to the local state, which is what
/// every other race in the mod already does and is right far more often than it is wrong.
/// </summary>
public static int GetRenderState(Player player)
{
if (player != null && player != Player.m_localPlayer)
{
ZNetView nview = player.GetComponent<ZNetView>();
if (nview != null && nview.IsValid())
{
int remote = nview.GetZDO().GetInt(SvermConfig.StateZdoKey, 0);
if (remote > 0) return Mathf.Clamp(remote, BossProgressionManager.MinState, BossProgressionManager.MaxState);
}
}
return BossProgressionManager.GetCurrentProgressionState();
}
public static Color GetSkinColor(Player player) => SvermConfig.SkinColor;
// ─── Scale ───────────────────────────────────────────────────────────
/// <summary>
/// Surrenal Glands: +10% from the Queen on.
///
/// The "Visual" child, never the root - the root carries the collider and the camera
/// pivot. Only ever undoes ITS OWN scale, because another race may legitimately be sizing
/// this player and RaceScale exists precisely so the two do not fight.
/// </summary>
public static void ApplyScale(Player player, bool isSverm)
{
if (player == null) return;
GameObject visual = Traverse.Create(player).Field("m_visual").GetValue<GameObject>();
if (visual == null) return;
float target = isSverm ? SvermProgression.GetRules(GetRenderState(player)).BodyScale : 1f;
if (!isSverm)
{
// Do not stamp on a Trol or a Furling: only reset a scale that looks like ours.
if (Mathf.Abs(visual.transform.localScale.x - SvermConfig.BodyScaleAtQueen) > 0.001f) return;
target = 1f;
}
if (Mathf.Abs(visual.transform.localScale.x - target) > 0.001f)
{
visual.transform.localScale = new Vector3(target, target, target);
}
}
// ─── Eyes ────────────────────────────────────────────────────────────
/// <summary>
/// Records which way the skull faces, worked out once when the eyes are built.
/// </summary>
private class EyeFrame : MonoBehaviour
{
public Vector3 LocalForward = Vector3.forward;
public Vector3 LocalUp = Vector3.up;
public Vector3 LocalRight = Vector3.right;
}
private static Shader cachedGlowShader;
private static bool glowShaderResolved;
/// <summary>
/// Two small emissive spheres burning over the painted-on eyes.
///
/// This is AswidVisuals.ApplyEyes ported across, not re-derived, and the first version of
/// this file paid for re-deriving it. Two things it was missing and both are fatal on
/// their own:
///
/// THE DIVIDE BY lossyScale. The player armature is authored at scale 100, so an offset
/// of 0.081 written straight into the head bone's local space puts the eye eight metres
/// in front of the face and eyeballs the size of a house. Everything here is expressed
/// in metres and converted with 1/lossyScale, which is what makes the constants mean
/// what they say.
///
/// THE SHADER. A primitive sphere arrives with whatever the default material is, and
/// Valheim's build has no reason to carry one that renders past 1 - so the sphere either
/// comes out flat pink or does not render at all. ResolveGlowShader picks one that will
/// take an HDR colour so the bloom pass has something to find.
/// </summary>
public static void ApplyEyes(Player player)
{
if (player == null) return;
Transform headBone = FindBone(player, HeadBoneName);
if (headBone == null) return; // rig not up yet; try again next frame
Transform eyes = headBone.Find(EyesName);
if (!IsSvermPlayer(player) || player.IsDead())
{
if (eyes != null)
{
// Renamed first: Destroy is deferred to the end of the frame, and every call
// until then would otherwise find it again.
eyes.name = EyesName + "_Removed";
Object.Destroy(eyes.gameObject);
}
return;
}
if (eyes == null) eyes = BuildEyes(headBone);
if (eyes == null) return; // already logged once by the resolver
PlaceEyes(player, headBone, eyes);
Color glow = SvermConfig.EyeColor * SvermConfig.EyeGlowStrength;
foreach (Renderer renderer in eyes.GetComponentsInChildren<Renderer>(true))
{
Material material = renderer.material;
if (material == null) continue;
material.color = glow;
if (material.HasProperty("_EmissionColor"))
{
material.SetColor("_EmissionColor", glow);
// Custom/Creature is a LIT shader, unlike the Unlit/Color the first version
// resolved to. On a lit shader the glow comes from emission and emission is
// gated behind a keyword, so writing the colour without this leaves two dull
// grey beads.
material.EnableKeyword("_EMISSION");
}
}
}
/// <summary>
/// Puts the two eyes where the face is, in the head bone's own coordinates, every pass.
///
/// The scale term looks like it handles Surrenal Glands' +10% and it does not: lossyScale
/// already contains the player's scale, so the multiply and the divide cancel and the
/// local offset is simply config/100 at any size. Growth is handled by the parenting.
/// It is kept because it is honest about intent and because that is how the Aswid's
/// version reads.
/// </summary>
private static void PlaceEyes(Player player, Transform headBone, Transform holder)
{
float lossy = headBone.lossyScale.x;
if (Mathf.Abs(lossy) < 0.0001f) return;
float toLocal = 1f / lossy;
EyeFrame frame = holder.GetComponent<EyeFrame>();
if (frame == null) return;
float scale = player.transform.localScale.x;
Vector3 baseLocal = frame.LocalForward * (EyeForward * scale * toLocal)
+ frame.LocalUp * (EyeHeight * scale * toLocal);
float eyeLocalSize = EyeSize * scale * toLocal;
for (int i = 0; i < holder.childCount; i++)
{
Transform eye = holder.GetChild(i);
// Index 0 is offset against the right axis, so it is the model's left eye.
float side = i == 0 ? -1f : 1f;
float size = i == 0 ? eyeLocalSize * LeftEyeSizeMultiplier : eyeLocalSize;
eye.localPosition = baseLocal + frame.LocalRight * (side * EyeSeparation * scale * toLocal);
eye.localScale = Vector3.one * size;
}
}
private static Transform BuildEyes(Transform headBone)
{
Shader glow = ResolveGlowShader();
if (glow == null) return null;
GameObject holder = new GameObject(EyesName);
holder.transform.SetParent(headBone, false);
holder.transform.localPosition = Vector3.zero;
holder.transform.localRotation = Quaternion.identity;
holder.transform.localScale = Vector3.one;
// Ask the rig which way it faces, once, and ROUND the answer to the skull's own axes.
// The raw, unrounded measurement puts the eyes on the jaw - DvergarVisuals found that
// out first.
Transform root = headBone.root;
EyeFrame frame = holder.AddComponent<EyeFrame>();
frame.LocalForward = SnapToAxis(headBone.InverseTransformDirection(root.forward));
frame.LocalUp = SnapToAxis(headBone.InverseTransformDirection(root.up));
frame.LocalRight = Vector3.Cross(frame.LocalUp, frame.LocalForward).normalized;
for (int i = 0; i < 2; i++)
{
// Spheres, not quads: a quad seen edge-on is a line and vanishes. A sphere reads
// the same from every direction and is properly hidden by the skull.
GameObject eye = GameObject.CreatePrimitive(PrimitiveType.Sphere);
eye.name = "Eye" + i;
foreach (Collider collider in eye.GetComponents<Collider>())
{
Object.Destroy(collider);
}
eye.transform.SetParent(holder.transform, false);
eye.transform.localPosition = Vector3.zero;
eye.transform.localRotation = Quaternion.identity;
eye.transform.localScale = Vector3.zero; // PlaceEyes runs immediately after this
Renderer renderer = eye.GetComponent<Renderer>();
renderer.material = new Material(glow);
renderer.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off;
renderer.receiveShadows = false;
}
return holder.transform;
}
/// <summary>Rounds a direction to the nearest of the six axis directions, sign included.</summary>
private static Vector3 SnapToAxis(Vector3 direction)
{
float x = Mathf.Abs(direction.x);
float y = Mathf.Abs(direction.y);
float z = Mathf.Abs(direction.z);
if (x >= y && x >= z) return new Vector3(Mathf.Sign(direction.x), 0f, 0f);
if (y >= z) return new Vector3(0f, Mathf.Sign(direction.y), 0f);
return new Vector3(0f, 0f, Mathf.Sign(direction.z));
}
/// <summary>
/// A shader that will render a colour past 1 so the bloom pass picks it up, AND that fades
/// with the body.
///
/// CUSTOM/CREATURE FIRST, and that is the fix for the second inherited defect. Valheim
/// dithers the player away when the camera gets inside them, but the dither lives in the
/// game's own shaders - so eyes on Unlit/Color stayed solid while the face around them
/// dissolved, and two red dots hung in the air. FurlingPatches.cs:175 hit exactly this with
/// a borrowed trophy and answered it the same way: keep the material, change the shader to
/// one that knows about the camera.
///
/// The rest of the list is unchanged and still opaque-first: a transparent shader with
/// depth writing off draws over the head from angles that should hide it.
/// </summary>
private static Shader ResolveGlowShader()
{
if (glowShaderResolved) return cachedGlowShader;
glowShaderResolved = true;
string[] candidates = { "Custom/Creature", "Unlit/Color", "Standard", "Particles/Standard Unlit", "Sprites/Default", "UI/Default" };
foreach (string name in candidates)
{
Shader shader = Shader.Find(name);
if (shader == null) continue;
Jotunn.Logger.LogInfo($"[Sverm] Eye glow shader resolved to '{name}'.");
cachedGlowShader = shader;
return cachedGlowShader;
}
Jotunn.Logger.LogWarning(
"[Sverm] No glow shader resolved (" + string.Join(", ", candidates) + "); eyes stay unlit.");
return null;
}
// ─── Claws ───────────────────────────────────────────────────────────
/// <summary>
/// RETIRED, and kept only to clean up after itself.
///
/// The claws used to be a model bolted to the hand bones, so they could stay on while the
/// player held something else. That worked, but it put the claws and the carapace on the
/// same losing footing: the game rebuilds equipment visuals from what is REALLY in the
/// slots, so anything faked has to be put back after every rebuild, one frame late and
/// visibly. They are a real equipped item now - see SvermClawSlot - and this walks both
/// hand bones removing any holder the old path left behind.
/// </summary>
public static void ApplyClaws(Player player)
{
if (player == null) return;
RemoveLegacyClaw(player, RightHandBoneName);
RemoveLegacyClaw(player, LeftHandBoneName);
}
private static void RemoveLegacyClaw(Player player, string boneName)
{
Transform bone = FindBone(player, boneName);
Transform existing = bone != null ? bone.Find(ClawsName) : null;
if (existing == null) return;
// Renamed first: Destroy is deferred to the end of the frame, and every call until
// then would otherwise find it again.
existing.name = ClawsName + "_Removed";
Object.Destroy(existing.gameObject);
}
// ─── Dorsal spines ───────────────────────────────────────────────────
/// <summary>
/// A ribcage worn spine-up: a ridge of bone standing out of the back, xenomorph rather
/// than bird.
///
/// This replaced wings, and the reason is worth keeping. Wing_gib was never a prefab - it
/// is a child buried in somebody's death effect, reachable only by walking a hierarchy and
/// guessing at the parent - and a wing that cannot flap is a prop no matter how well it is
/// placed. UndeadBjornRibcage resolves by name like any other prefab and is MEANT to be
/// still, so being static stops being a compromise and starts being the point.
///
/// Small at tier 5, full crest from the Queen on.
/// </summary>
public static void ApplySpines(Player player)
{
if (player == null) return;
// This bone or nothing. The fallback chain that used to be here degraded to "somewhere
// on the back, roughly", which is worthless for a crest whose angle was found by eye
// against one specific bone.
Transform bone = FindBone(player, SvermConfigManagement.Bone);
if (bone == null)
{
WarnMissingSpineBone();
return;
}
// Size is read from the .cfg here rather than off the cached rules struct: that cache
// is built per state on first use, so a size edited between two sessions would not be
// picked up until a relog. Which tier gets which size is still the rules' decision -
// only the two numbers are live.
int state = GetRenderState(player);
float wanted = 0f;
if (IsSvermPlayer(player) && !player.IsDead() && SvermProgression.GetRules(state).SpineSize > 0f)
{
wanted = state >= SvermConfig.FullWingspanState
? SvermConfigManagement.SizeFull
: SvermConfigManagement.SizeSmall;
}
Transform existing = bone.Find(SpinesName);
if (wanted <= 0f)
{
if (existing != null)
{
existing.name = SpinesName + "_Removed";
Object.Destroy(existing.gameObject);
}
return;
}
// ROTATION IS PART OF THE COMPARISON, not just size, and that is what makes the crest
// tunable while the game is running. ModelBorrow rotates the copy FIRST and then
// measures and grounds it, so the fit belongs to that rotation - turning an
// already-fitted model afterwards would leave it floating or buried. A rebuild is the
// only honest way to change the angle, and at 0.5 s a pass it is imperceptible.
//
// A size change needs a rebuild for the same reason: re-fitting an already-fitted copy
// compounds the two scales instead of replacing one with the other. The tag records
// metres and degrees - what was ASKED for - not bone-local numbers.
Quaternion wantedRotation = SvermConfigManagement.SpineRotation();
SvermSpineTag tag = existing != null ? existing.GetComponent<SvermSpineTag>() : null;
if (existing != null && (tag == null
|| !Mathf.Approximately(tag.Size, wanted)
|| Quaternion.Angle(tag.Rotation, wantedRotation) > 0.5f))
{
existing.name = SpinesName + "_Removed";
Object.Destroy(existing.gameObject);
existing = null;
}
if (existing == null)
{
// Same rig-scale conversion as the claws: metres in, bone units out.
float lossy = bone.lossyScale.x;
if (Mathf.Abs(lossy) < 0.0001f) return;
GameObject holder = ModelBorrow.Attach(
bone,
SpinesName,
SvermConfig.SpinesPrefab,
Vector3.zero,
wantedRotation,
wanted / lossy,
"Sverm");
if (holder == null) return;
SvermSpineTag built = holder.AddComponent<SvermSpineTag>();
built.Size = wanted;
built.Rotation = wantedRotation;
existing = holder.transform;
}
TintBorrowed(existing.gameObject, state);
}
private static bool warnedMissingSpineBone;
/// <summary>
/// Said once, not forty times a minute. The cosmetic pass runs on a timer, so an
/// unqualified LogWarning here would bury the log in the time it takes to read it.
/// </summary>
private static void WarnMissingSpineBone()
{
if (warnedMissingSpineBone) return;
warnedMissingSpineBone = true;
// The bone names are listed too, because the first time this fired the answer was that
// the rig simply has no Spine3 - it counts Spine, Spine1, Spine2 - and there was no
// way to know that from a warning that only said what was missing.
System.Text.StringBuilder spine = new System.Text.StringBuilder();
Player local = Player.m_localPlayer;
VisEquipment visEq = local != null ? local.GetComponent<VisEquipment>() : null;
if (visEq != null && visEq.m_bodyModel != null && visEq.m_bodyModel.bones != null)
{
foreach (Transform b in visEq.m_bodyModel.bones)
{
if (b != null && b.name.ToLowerInvariant().Contains("spine")) spine.Append(b.name).Append(' ');
}
}
Jotunn.Logger.LogWarning($"[Sverm] No bone called '{SvermConfigManagement.Bone}' in this rig; " +
"the crest has nowhere to sit. Spine bones this rig actually has: " +
(spine.Length > 0 ? spine.ToString().Trim() : "none found") +
". Set one of those in the Bone key under [Sverm - Dorsal Spines].");
}
/// <summary>
/// What a mounted crest was built with, so "has the setting changed?" is a comparison
/// rather than a guess. This is the whole mechanism behind tuning the crest live from
/// Configuration Manager.
/// </summary>
public class SvermSpineTag : MonoBehaviour
{
public float Size;
public Quaternion Rotation = Quaternion.identity;
}
// ─── Glide motes ─────────────────────────────────────────────────────
private const string MotesName = "SvermGlideMotes";
/// <summary>
/// What holds a falling Sverm up: a swarm of fireflies boiling up under the body, on
/// screen for exactly as long as the fall lasts.
///
/// Vestigial Wings is otherwise an invisible perk - the fall damage is simply not there,
/// and nothing tells the player why. This is the perk made visible, and it costs one
/// vanilla particle system.
///
/// Built once and then switched on and off. Rebuilding a particle system every time the
/// player leaves the ground would restart its emission from nothing and show a swarm that
/// is always just beginning.
/// </summary>
public static void ApplyGlideMotes(Player player)
{
if (player == null) return;
GameObject visual = Traverse.Create(player).Field("m_visual").GetValue<GameObject>();
if (visual == null) return;
bool eligible = IsSvermPlayer(player)
&& !player.IsDead()
&& SvermProgression.GetRules(GetRenderState(player)).FallDamageModifier < 0f;
Transform existing = visual.transform.Find(MotesName);
if (!eligible)
{
if (existing != null)
{
existing.name = MotesName + "_Removed";
Object.Destroy(existing.gameObject);
}
return;
}
if (existing == null)
{
existing = BuildGlideMotes(visual.transform);
if (existing == null) return;
}
// Airborne and going down. Rising - a jump, a launch - is not what the perk answers,
// so the swarm stays out of it and only appears when there is a fall to soften.
bool falling = !player.IsOnGround() && !player.IsSwimming() && player.GetVelocity().y < -0.5f;
if (existing.gameObject.activeSelf != falling)
{
existing.gameObject.SetActive(falling);
}
if (falling) TintBorrowed(existing.gameObject, GetRenderState(player));
}
/// <summary>
/// Instantiates the vanilla firefly swarm under the player.
///
/// Deliberately NOT through ModelBorrow: that helper measures a mesh in order to size it,
/// and a particle system has no mesh to measure - it would log a warning about an
/// unreadable model on every build and then leave the scale alone anyway. The one trick
/// worth borrowing is the inactive holder, so nothing on the copy wakes before its
/// networking has been stripped off.
/// </summary>
private static Transform BuildGlideMotes(Transform parent)
{
GameObject source = PrefabManager.Cache.GetPrefab<GameObject>(SvermConfig.GlideMotesPrefab);
if (source == null)
{
Jotunn.Logger.LogWarning($"[Sverm] No '{SvermConfig.GlideMotesPrefab}' to borrow; falls stay unlit.");
return null;
}
GameObject holder = new GameObject(MotesName);
holder.transform.SetParent(parent, false);
holder.transform.localPosition = Vector3.zero;
holder.SetActive(false);
GameObject copy = Object.Instantiate(source, holder.transform);
copy.name = "motes";
copy.transform.localPosition = Vector3.zero;
copy.transform.localRotation = Quaternion.identity;
foreach (MonoBehaviour behaviour in copy.GetComponentsInChildren<MonoBehaviour>(true))
{
if (behaviour != null) Object.DestroyImmediate(behaviour);
}
foreach (Collider collider in copy.GetComponentsInChildren<Collider>(true))
{
if (collider != null) Object.DestroyImmediate(collider);
}
foreach (ZNetView nview in copy.GetComponentsInChildren<ZNetView>(true))
{
if (nview != null) Object.DestroyImmediate(nview);
}
Jotunn.Logger.LogInfo($"[Sverm] Glide motes built from '{SvermConfig.GlideMotesPrefab}'.");
return holder.transform;
}
// ─── The carapace, and the ramp ──────────────────────────────────────
/// <summary>
/// Forces the three sealed slots to render as carapace whatever the player is carrying,
/// then paints every piece with the tier's tint.
///
/// Called from the UpdateVisuals postfix rather than once at spawn, because Valheim
/// rebuilds these instances on every equipment change and hands back plain white models.
/// </summary>
public static void ApplyCarapace(Player player)
{
if (player == null) return;
VisEquipment visEq = player.GetComponent<VisEquipment>();
if (visEq == null) return;
if (!IsSvermPlayer(player)) return;
visEq.SetChestItem(SvermConfig.CarapaceChestVisual);
visEq.SetLegItem(SvermConfig.CarapaceLegsVisual);
visEq.SetHelmetItem(SvermConfig.CarapaceHelmetVisual);
int state = GetRenderState(player);
TintInstances(Traverse.Create(visEq).Field("m_chestItemInstances").GetValue(), state);
TintInstances(Traverse.Create(visEq).Field("m_legItemInstances").GetValue(), state);
TintInstances(Traverse.Create(visEq).Field("m_helmetItemInstance").GetValue(), state);
}
private static void TintInstances(object value, int state)
{
if (value is GameObject single)
{
Tint(single, state);
}
else if (value is List<GameObject> list)
{
foreach (GameObject instance in list) Tint(instance, state);
}
}
/// <summary>
/// Emberform's emission: the hue, dimmed to something a whole body can wear.
///
/// Kept as one call rather than two literals so the carapace and the borrowed pieces can
/// never drift apart, and so the strength has exactly one place to be turned down - which
/// it already had to be once, after the first version went out at full HDR and blinded
/// anyone standing next to it.
/// </summary>
private static Color EmberColor()
{
return SvermConfig.EmberEmission * SvermConfigManagement.EmberStrength;
}
/// <summary>
/// The ramp, written onto whatever renderers the piece happens to have.
///
/// _Color rather than _SkinColor: these are equipment materials, not the body, and the
/// body's Custom/Player shader is the only thing in the game that answers to _SkinColor.
/// Both are tried because armour pieces do not all use the same shader.
///
/// At Fader the same call also writes emission, which is the entire Emberform effect: the
/// chitin has already ramped to near black by then, so the red burn has something dark to
/// come through.
/// </summary>
private static void Tint(GameObject instance, int state)
{
if (instance == null) return;
Color tint = SvermCarapace.GetTint(state);
bool ember = SvermProgression.GetRules(state).Emberform;
foreach (Renderer renderer in instance.GetComponentsInChildren<Renderer>(true))
{
foreach (Material material in renderer.materials)
{
if (material == null) continue;
if (material.HasProperty("_Color")) material.SetColor("_Color", tint);
if (material.HasProperty("_SkinColor")) material.SetColor("_SkinColor", tint);
if (material.HasProperty("_EmissionColor"))
{
material.SetColor("_EmissionColor", ember ? EmberColor() : Color.black);
if (ember) material.EnableKeyword("_EMISSION");
}
}
}
}
/// <summary>
/// Same tint for a model borrowed onto a bone, plus the dither shader.
///
/// The body material cannot be applied to a foreign mesh - the UVs do not match and the
/// object simply vanishes, which is the trap FurlingPatches documents. The original
/// material is kept and only its SHADER is swapped, to Custom/Creature, so the piece fades
/// with the camera like everything else on the player.
/// </summary>
private static void TintBorrowed(GameObject holder, int state)
{
if (holder == null) return;
Color tint = SvermCarapace.GetTint(state);
bool ember = SvermProgression.GetRules(state).Emberform;
Shader dither = Shader.Find("Custom/Creature");
foreach (Renderer renderer in holder.GetComponentsInChildren<Renderer>(true))
{
foreach (Material material in renderer.materials)
{
if (material == null) continue;
if (dither != null) material.shader = dither;
if (material.HasProperty("_Color")) material.SetColor("_Color", tint);
if (material.HasProperty("_EmissionColor"))
{
material.SetColor("_EmissionColor", ember ? EmberColor() : Color.black);
if (ember) material.EnableKeyword("_EMISSION");
}
}
}
}
// ─── Bones ───────────────────────────────────────────────────────────
/// <summary>
/// The bone the body mesh is actually skinned to, not the Animator's avatar bone.
///
/// DvergarVisuals learned this the expensive way: the avatar's Head moves with the player
/// but is not the transform the head animation drives, so anything parented to it ignored
/// every idle bob. VisEquipment.m_bodyModel.bones is the rig that moves.
/// </summary>
private static Transform FindBone(Player player, string boneName)
{
VisEquipment visEq = player.GetComponent<VisEquipment>();
if (visEq == null || visEq.m_bodyModel == null || visEq.m_bodyModel.bones == null) return null;
foreach (Transform bone in visEq.m_bodyModel.bones)
{
if (bone != null && bone.name == boneName) return bone;
}
// Loose match, because rigs are not consistent about capitalisation or prefixes.
string wanted = boneName.ToLowerInvariant();
foreach (Transform bone in visEq.m_bodyModel.bones)
{
if (bone != null && bone.name.ToLowerInvariant().Contains(wanted)) return bone;
}
return null;
}
}
}

View file

@ -0,0 +1,238 @@
using System.Collections.Generic;
using Jotunn.Managers;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The Seeker Worker: half a Seeker, and the reason the colony feels like a colony rather than
/// like a barracks.
///
/// TWO JOBS, TWO POOLS, and the pools do not share. Farmers come out of the infected beehives
/// and work the ground; haulers come out of the nest after Bonemass and carry food into it.
/// Nine alive at most between them, and neither trade can starve the other of hands - which is
/// the whole reason they are counted separately instead of out of one number.
///
/// They are FREE. No biomass, no egg, and they are replaced when they die. That is deliberate:
/// they are labour, not army. Nothing they do competes with Brood, Seeker, Soldier or Gjall for
/// the tank, and nothing about them is commandable - they stay where they were born, defend
/// what is there, and never follow.
///
/// Half size, half health, half damage. The size and health are set on the prefab; the damage
/// is halved in the damage patch, because a creature's blow comes from its default weapon and
/// that weapon's shared data belongs to every Seeker in the world.
/// </summary>
public static class SvermWorker
{
public const string PrefabName = "SvermSeekerWorker";
private const string SourcePrefab = "Seeker";
/// <summary>Which trade a given worker was born into. Kept on the worker itself.</summary>
public enum Job { Farmer, Hauler }
private static bool registered;
// Live workers, by job. Rebuilt lazily rather than tracked with events: a creature can die
// in ways nothing tells us about, so the honest count is the one taken by looking.
private static readonly List<SvermWorkerBehaviour> live = new List<SvermWorkerBehaviour>();
// ─── Registration ────────────────────────────────────────────────────
public static void Register()
{
if (registered) return;
GameObject source = PrefabManager.Cache.GetPrefab<GameObject>(SourcePrefab);
if (source == null)
{
Jotunn.Logger.LogWarning($"[Sverm] No '{SourcePrefab}' to build the worker from; no workers.");
return;
}
GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(PrefabName, source);
if (prefab == null) return;
registered = true;
prefab.transform.localScale = source.transform.localScale * SvermConfig.WorkerScale;
Character character = prefab.GetComponent<Character>();
if (character != null)
{
character.m_health = character.m_health * SvermConfig.WorkerHealthFraction;
character.m_name = SvermConfig.WorkerDisplayName;
}
// Nothing to farm. A worker that dropped Seeker parts would turn a free, self-replacing
// labourer into a trophy printer - the same reasoning that strips the thralls' tables.
CharacterDrop drop = prefab.GetComponent<CharacterDrop>();
if (drop != null) Object.DestroyImmediate(drop);
prefab.AddComponent<SvermWorkerBehaviour>();
PrefabManager.Instance.AddPrefab(prefab);
Jotunn.Logger.LogInfo($"[Sverm] Registered '{PrefabName}' at {SvermConfig.WorkerScale:P0} of a Seeker.");
}
// ─── Counting and spawning ───────────────────────────────────────────
/// <summary>How many of this trade are alive right now. Public: the nest hauls at a rate
/// set by how many haulers it has, so it has to be able to ask.</summary>
public static int Count(Job job) => CountLive(job);
private static int CountLive(Job job)
{
live.RemoveAll(w => w == null || w.Dead);
int count = 0;
foreach (SvermWorkerBehaviour worker in live)
{
if (worker.Trade == job) count++;
}
return count;
}
public static int Cap(Job job)
{
return job == Job.Farmer ? SvermConfigManagement.Farmers : SvermConfigManagement.Haulers;
}
public static bool HasRoom(Job job) => CountLive(job) < Cap(job);
/// <summary>
/// Puts one worker on the ground and ties it to whatever produced it.
///
/// The anchor is not decoration: it is where the worker idles, what it defends, and the
/// centre of the three metres it searches for chests. A worker with no anchor has no job.
/// </summary>
public static void Spawn(Job job, Transform anchor)
{
if (anchor == null || !HasRoom(job)) return;
GameObject prefab = ZNetScene.instance != null ? ZNetScene.instance.GetPrefab(PrefabName) : null;
if (prefab == null) return;
Vector3 where = anchor.position + Vector3.up * 0.5f + Random.insideUnitSphere * 0.5f;
where.y = anchor.position.y + 0.5f;
GameObject spawned = Object.Instantiate(prefab, where, Quaternion.identity);
if (spawned == null) return;
Character character = spawned.GetComponent<Character>();
if (character != null) character.SetTamed(true);
SvermWorkerBehaviour behaviour = spawned.GetComponent<SvermWorkerBehaviour>()
?? spawned.AddComponent<SvermWorkerBehaviour>();
behaviour.Trade = job;
behaviour.Anchor = anchor;
live.Add(behaviour);
}
public static bool IsWorker(Character character)
{
return character != null && character.GetComponent<SvermWorkerBehaviour>() != null;
}
}
/// <summary>
/// One worker's whole life: stay home, mend what the player built, and fight what comes.
///
/// THIS IS THE THIRD DESIGN AND THE FIRST HONEST ONE. The first two hung the colony's economy
/// on a creature that walks: workers carried food from chests to the hive, and every time one
/// wandered off or got killed the supply chain went with it - chests full, tank at zero, and
/// nothing in the log to blame. Hauling belongs to something that cannot walk away, and
/// feeding the hive is now the player's own job through the shop.
///
/// What is left is what a creature is actually good at: being somewhere, keeping it in repair,
/// and defending it. No carrying, no farming, no orders.
/// </summary>
public class SvermWorkerBehaviour : MonoBehaviour
{
public SvermWorker.Job Trade;
public Transform Anchor;
public bool Dead => m_character == null || m_character.IsDead();
private Character m_character;
private MonsterAI m_ai;
private float m_nextHomeCheck;
private float m_nextRepair;
private void Awake()
{
m_character = GetComponent<Character>();
m_ai = GetComponent<MonsterAI>();
}
private void Update()
{
if (Dead || Anchor == null) return;
KeepHome();
if (Time.time < m_nextRepair) return;
m_nextRepair = Time.time + SvermConfig.WorkerRepairInterval;
RepairRound();
}
/// <summary>
/// Ten metres, and told to the AI rather than forced on the transform.
///
/// Writing transform.position does not hold a Valheim Character - a Rigidbody and a
/// ZSyncTransform both overwrite it on the next frame, which is why the earlier leash did
/// nothing at all and the workers kept wandering off to die. A patrol point is the game's
/// own way of saying "this is where you live": the AI walks back on its own pathfinding.
///
/// SetPatrolPoint takes no argument and posts the creature where it currently STANDS, so
/// it is put in place first. That raw write does not survive the frame, but it survives
/// long enough for this one call to read it - and the patrol point is what holds afterwards.
/// </summary>
private void KeepHome()
{
if (m_ai == null || Time.time < m_nextHomeCheck) return;
m_nextHomeCheck = Time.time + 2f;
if (m_ai.GetFollowTarget() != null) m_ai.SetFollowTarget(null);
if (Vector3.Distance(transform.position, Anchor.position) > SvermConfig.WorkerLeashRange)
{
transform.position = Anchor.position + Vector3.up * 0.5f;
}
m_ai.SetPatrolPoint();
}
/// <summary>
/// Mends whatever the player built, near where it stands, the way a hammer would.
///
/// ONLY WHAT A PLAYER PLACED. Repairing everything would also mend the ruins, the abandoned
/// buildings and anything else in the world with a WearNTear on it, which is both wrong and
/// a great deal of work every few seconds. Piece.IsPlacedByPlayer is the game's own answer
/// to "is this somebody's house".
///
/// One piece per round, deliberately. A worker that healed everything in ten metres in a
/// single frame would read as a cheat rather than as somebody working.
/// </summary>
private void RepairRound()
{
foreach (Collider collider in Physics.OverlapSphere(transform.position, SvermConfig.WorkerRepairRange))
{
if (collider == null) continue;
WearNTear wear = collider.GetComponentInParent<WearNTear>();
if (wear == null) continue;
Piece piece = wear.GetComponent<Piece>();
if (piece == null || !piece.IsPlacedByPlayer()) continue;
// Repair returns false when there was nothing to mend, which is how the round
// moves on to the next piece instead of stopping at the first healthy wall.
if (!wear.Repair()) continue;
return;
}
}
}
}