Merge branch 'war-vulture' into main

Sverm Ravager Strain (replacing the Stinger Morph), Trenta Elder Root, the
Trol food and Black Forest truce work, and the faction FindEnemy patch.

Conflicts resolved:

- FactionHostilityPatch.cs: both sides added a class at the same spot and
  they cover different holes, so both are kept - FactionStaticTargetPatch
  (main, stops same-faction mobs smashing structures) and
  FactionHuntPlayerPatch (war-vulture, closes the HuntPlayer fall-through).

- RaceCompendium.cs: both branches independently fixed the same off-by-one
  in the Trol's progression gates. Took main's wording, which matches the
  code - Axes are in the melee bonus (TrolDamagePatches sends them to
  m_slash), the 4th food slot has no gate at all, and Yagluth is +5 not +10
  (TrolConfig.YagluthMeleeBonus). Kept war-vulture's two new lines, the
  Kindling fire weakness and the Black Forest truce.

- Package/manifest.json: 1.4.8, which is what the root manifest and
  PluginVersion already said.

RacesOfValheim.cs referenced SvermConfig.StingerSE/StingerCdSE, which
war-vulture renamed to Ravager. Git merged those lines without a conflict
and the result did not compile; renamed.

Also in this commit:

- Factions on/off switches (FactionsConfig): "Faction truce" and "Faction
  merchants", both default on, both read live so they take effect without a
  restart. The truce gates its three postfixes; the merchants gate the
  Character.Awake setup plus every behavioural patch, so turning them off
  drops the prompt and the trade window on mobs already awake.

- SerpentMeat sells for 200 instead of 1 at the Fuling bench, moved to keep
  the list's ascending price order (the sell panel renders it as declared).

- DraughFoodPatches mapped "SerpentMeatRaw", which is not a prefab; the
  internal id is SerpentMeat, so serpent meat never cooked for a Draugh.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
Ferdinando 2026-08-25 18:52:10 +02:00
commit 34bdf35325
33 changed files with 1829 additions and 573 deletions

View file

@ -18,7 +18,7 @@ namespace RacesOfValheim
{ "NeckTail", "NeckTailGrilled" },
{ "FishRaw", "FishCooked" },
{ "LoxMeat", "CookedLoxMeat" },
{ "SerpentMeatRaw", "SerpentMeatCooked" },
{ "SerpentMeat", "SerpentMeatCooked" },
{ "WolfMeat", "CookedWolfMeat" },
{ "DeerMeat", "CookedDeerMeat" },
{ "HareMeat", "CookedHareMeat" },

View file

@ -70,15 +70,36 @@ namespace RacesOfValheim
public static bool IsSameFaction(Player player, Character monster)
{
if (player == null || monster == null) return false;
if (!player.m_customData.TryGetValue("Race", out string race)) return false;
string race = GetPlayerRace(player);
if (race == null) return false;
if (!RaceFactionMobs.TryGetValue(race, out HashSet<string> mobs)) return false;
string prefabName = monster.gameObject.name.Replace("(Clone)", "").Trim();
return mobs.Contains(prefabName);
}
// m_customData is the local save file's dictionary: it is only ever populated for
// the client's own m_localPlayer, so IsEnemy running on a remote AI owner (a
// dedicated server, or any other nearby player who ends up owning the mob's ZDO)
// read an empty dictionary here and treated every truce as hostile. Every other
// race-aware patch in this project reads "RacesOfValheim_Race" off the ZDO instead
// because that field actually replicates - check it first, and only fall back to
// m_customData for the single-player/local-owner case where the ZDO hasn't been
// written yet (e.g. brand new character before the race pick's Set() call runs).
public static string GetPlayerRace(Player player)
{
ZNetView nview = player.GetComponent<ZNetView>();
if (nview != null && nview.IsValid())
{
string zdoRace = nview.GetZDO().GetString("RacesOfValheim_Race", "");
if (!string.IsNullOrEmpty(zdoRace)) return zdoRace;
}
return player.m_customData.TryGetValue("Race", out string race) ? race : null;
}
public static void Postfix(Character a, Character b, ref bool __result)
{
if (!FactionsConfig.Hostility) return;
if (!__result) return; // already not enemies, nothing to add
if (a == null || b == null) return;
@ -116,6 +137,7 @@ namespace RacesOfValheim
public static void Postfix(MonsterAI __instance)
{
if (!FactionsConfig.Hostility) return;
Traverse targetStatic = Traverse.Create(__instance).Field("m_targetStatic");
if (targetStatic.GetValue() == null) return;
@ -132,4 +154,32 @@ namespace RacesOfValheim
}
}
}
// IsEnemy is not the only way a mob picks the player, and the other way ignores it
// completely. BaseAI.FindEnemy() walks every character asking IsEnemy - which both truce
// patches above answer - but when that walk comes up empty and the creature HuntPlayer()s,
// it falls through to Player.GetClosestPlayer(transform.position, 200f) and returns whoever
// it finds, without asking anything about factions.
//
// That fall-through is why the Black Forest truce looked broken to the Trol's testers:
// MonsterAI.UpdateAI turns hunting on for every IsEventCreature() while an event is running,
// and the events that reach a Trol are "the forest is moving" (Greydwarves), "you are being
// hunted" (Trolls) and the Fuling army - the exact three they named. Anything a SpawnSystem
// entry or a TriggerSpawner flags with huntPlayer arrives by the same door.
//
// Filtering the RESULT rather than restating the rule keeps one source of truth: the public
// instance IsEnemy(Character) calls the static overload both postfixes above hook, so this
// honours whatever the faction sets and RaceHostilityManager's per-race lists already agree
// on. Retaliation is untouched - a mob the player hits is targeted through
// BaseAI.OnDamaged/SetTarget, which never goes near FindEnemy.
[HarmonyPatch(typeof(BaseAI), "FindEnemy")]
public static class FactionHuntPlayerPatch
{
public static void Postfix(BaseAI __instance, ref Character __result)
{
if (!FactionsConfig.Hostility) return;
if (__result == null || !__result.IsPlayer()) return;
if (!__instance.IsEnemy(__result)) __result = null;
}
}
}

View file

@ -117,7 +117,6 @@ namespace RacesOfValheim
{
new CatalogEntry("BlackMetalScrap", 1),
new CatalogEntry("LoxMeat", 1),
new CatalogEntry("SerpentMeat", 1),
new CatalogEntry("SerpentScale", 1),
new CatalogEntry("LoxPelt", 2),
new CatalogEntry("Flax", 5),
@ -133,6 +132,7 @@ namespace RacesOfValheim
// runtime, so hovering a Fuling merchant once will name them in the log.
new CatalogEntry("Tuna", 50),
new CatalogEntry("CoralCod", 70),
new CatalogEntry("SerpentMeat", 200),
new CatalogEntry("GoblinTotem", 350),
new CatalogEntry("TrophyGoblin", 350),
new CatalogEntry("TrophyGoblinShaman", 350),

View file

@ -33,7 +33,7 @@ namespace RacesOfValheim
public static bool Prefix(Trader __instance)
{
if (((Component)__instance).GetComponent<FactionMerchant>() != null)
if (FactionsConfig.Merchants && ((Component)__instance).GetComponent<FactionMerchant>() != null)
{
return false;
}
@ -63,6 +63,7 @@ namespace RacesOfValheim
{
public static void Postfix(Trader __instance)
{
if (!FactionsConfig.Merchants) return;
if (((Component)__instance).GetComponent<FactionMerchant>() == null) return;
__instance.CancelInvoke("RandomTalk");
}
@ -88,6 +89,7 @@ namespace RacesOfValheim
public static void Postfix(Player __instance)
{
if (!FactionsConfig.Merchants) return;
// Both fields are private in the assembly this project compiles against.
var traverse = Traverse.Create(__instance);
Character hovering = traverse.Field("m_hoveringCreature").GetValue<Character>();
@ -117,7 +119,7 @@ namespace RacesOfValheim
{
public static bool Prefix(Player __instance, GameObject go, bool hold, bool alt)
{
if (go == null) return true;
if (go == null || !FactionsConfig.Merchants) return true;
FactionMerchant merchant = go.GetComponentInParent<FactionMerchant>();
if (merchant == null) return true; // not ours - let vanilla's own resolution run
@ -141,6 +143,7 @@ namespace RacesOfValheim
{
public static bool Prefix(MonsterAI __instance, ref bool __result)
{
if (!FactionsConfig.Merchants) return true;
// BaseAI.m_character is private in the assembly this project compiles against.
Character character = Traverse.Create(__instance).Field("m_character").GetValue<Character>();
if (FactionMerchantRuntime.IsProtected(character))
@ -160,7 +163,7 @@ namespace RacesOfValheim
{
public static bool Prefix(Character __instance, HitData hit)
{
if (hit != null && hit.GetAttacker() == Player.m_localPlayer && FactionMerchantRuntime.IsProtected(__instance))
if (FactionsConfig.Merchants && hit != null && hit.GetAttacker() == Player.m_localPlayer && FactionMerchantRuntime.IsProtected(__instance))
{
return false;
}

View file

@ -22,6 +22,7 @@ namespace RacesOfValheim
public static void Postfix(Character __instance)
{
if (!FactionsConfig.Merchants) return;
if (__instance == null) return;
GameObject go = ((Component)__instance).gameObject;
if (go.GetComponent<FactionMerchant>() != null) return; // already set up

View file

@ -0,0 +1,50 @@
using BepInEx.Configuration;
namespace RacesOfValheim
{
/// <summary>
/// The two switches that turn the Factions feature off, bound as BepInEx ConfigEntry so they
/// show up in Configuration Manager - same shape as WarVultureConfig, which is the house model.
///
/// Two switches rather than one because the halves fail differently. The truce is invisible
/// when it works and only shows up as mobs that ignore you; the merchants are a whole second
/// interaction bolted onto creatures that vanilla never meant to talk. Anyone hunting a mod
/// conflict wants to rule out one without losing the other.
///
/// Both read live, on every call, rather than being cached at patch time: the patches stay
/// installed and answer "not my business" while a switch is off. That costs one bool read per
/// call and buys a toggle that takes effect without restarting the game - with one asymmetry
/// worth knowing about, spelled out on Merchants below.
/// </summary>
public static class FactionsConfig
{
public static ConfigEntry<bool> HostilityEnabled;
public static ConfigEntry<bool> MerchantsEnabled;
// Null-safe, defaulting to ON, for the same reason WarVultureConfig guards its own reads:
// a patch that somehow runs before Bind() should behave like the shipped default rather
// than throw. Awake() binds before harmony.PatchAll(), so this should never fire.
public static bool Hostility => HostilityEnabled?.Value ?? true;
public static bool Merchants => MerchantsEnabled?.Value ?? true;
public static void Bind(ConfigFile config)
{
const string factions = "Factions";
HostilityEnabled = config.Bind(factions, "Faction truce", true,
new ConfigDescription("Mobs of your race's faction leave you alone - they will not open a fight, " +
"hunt you during events, or smash structures near you. Turn this off and every " +
"creature treats you exactly as vanilla would. Does not touch the older per-race " +
"truces in RaceHostilityManager (Fenrir, Aswid, Draugh, Trenta), which have no " +
"switch of their own. Hitting a mob still starts a fight either way: retaliation " +
"runs through BaseAI.OnDamaged, which no truce has a say over."));
MerchantsEnabled = config.Bind(factions, "Faction merchants", true,
new ConfigDescription("Certain mobs of your own faction can be traded with - 'E - Talk' opens a shop " +
"where you sell them what their kind wants. Turn this off and they are ordinary " +
"creatures again. Takes effect immediately for the prompt, the trade window and " +
"the no-hit protection; the hidden Trader component already grafted onto mobs " +
"that woke up earlier stays until they unload, but nothing will read it."));
}
}
}

View file

@ -1,7 +1,7 @@
{
"name": "RacesOfValheim",
"description": "A Valheim mod that adds ten custom playable races (Aswid, Draugh, Dvergar, Fenrir, Furling, Skadi, Skeleton, Sverm, Trenta, Trol) each with unique abilities, traits, and a deep boss-driven progression system.",
"version_number": "1.4.2",
"description": "A Valheim mod that adds ten custom playable races (Aswid, Draugh, Dvergar, Fenrir, Furling, Skadi, Skeleton, Sverm, Trenta, Trol) each with unique abilities, traits, race stations and a deep boss-driven progression system.",
"version_number": "1.4.8",
"website_url": "",
"dependencies": [
"denikson-BepInExPack_Valheim-5.4.2333",

View file

@ -163,8 +163,8 @@ namespace RacesOfValheim
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.RavagerForm)
sb.AppendLine($"[Yagluth Unlock] Ravager Strain ('{SvermConfigManagement.RavagerKey.Value}' Key): Become a Seeker Brute. The claws still fight, the carapace is worth double, and nothing about it flies. It is how you hold a fight, not how you leave one.\n");
if (rules.BodyScale > 1f)
sb.AppendLine("[Queen Unlock] Surrenal Glands: You stand a tenth larger, and the carapace takes its greatest leap.\n");
@ -334,6 +334,18 @@ namespace RacesOfValheim
sb.AppendLine($"Base Passive: You are natively 20% larger than a human with immense strength. You have +200 Max Carry Weight, gain +3 Armor per boss defeated, and carry a 4th food slot from your very first meal - no boss required.\n");
// Written from the config so a retuned multiplier can't leave the compendium lying.
// It was missing outright, which made the Trol the only race whose one drawback was
// nowhere in its own entry - the Sverm and the Skeleton both name theirs.
sb.AppendLine($"Base Weakness - Kindling: Fire finds you where nothing else does. Every burn you take lands for {(TrolConfig.FireWeaknessMultiplier.Value - 1f) * 100f:0}% more than it would on anyone else, and no armor or resistance changes that.\n");
sb.AppendLine("Base Passive: Black Forest kin. Greydwarves, Fulings and Trolls have no quarrel with you and will not open a fight - though hitting one still buys you the answer you asked for.\n");
// These gates were each one tier early: BossProgressionManager starts at MinState = 1
// with NO boss down, so state 2 is Eikthyr and state 8 is Fader - which is what every
// other race's entry in this file uses, and what the Trol's own patches check. A fresh
// Trol was being promised the Eikthyr XP bonus before killing anything, then finding
// TrolSkillPatches (state >= 2) refusing it, and the same slip ran the whole ladder.
if (state >= 2)
sb.AppendLine("Eikthyr Defeated: Increased XP gain for physical labor and blunt combat (Clubs, Unarmed, Axes, Pickaxes, WoodCutting).\n");

View file

@ -24,19 +24,24 @@ namespace RacesOfValheim
Player p = playerCharacter as Player;
if (p != null)
{
// Reads the ZDO copy of the race first - see GetPlayerRace's comment in
// FactionHostilityPatch for why m_customData alone breaks this for anyone
// but the local client (e.g. a dedicated server owning the mob's AI).
string playerRace = FactionHostilityPatch.GetPlayerRace(p);
// Fenrir Race Logic
if (p.m_customData.ContainsKey("Race") && p.m_customData["Race"] == "Fenrir")
if (playerRace == "Fenrir")
{
string prefabName = monster.gameObject.name.ToLower();
if (prefabName.Contains("wolf") || prefabName.Contains("fenring") ||
if (prefabName.Contains("wolf") || prefabName.Contains("fenring") ||
prefabName.Contains("ulv") || prefabName.Contains("cultist"))
{
__result = false;
}
}
// Aswid Race Logic
if (p.m_customData.ContainsKey("Race") && p.m_customData["Race"] == "Aswid")
if (playerRace == "Aswid")
{
string prefabName = monster.gameObject.name.ToLower();
int state = BossProgressionManager.GetCurrentProgressionState();
@ -51,7 +56,7 @@ namespace RacesOfValheim
}
// Draugh Race Logic
if (p.m_customData.ContainsKey("Race") && p.m_customData["Race"] == "Draugh")
if (playerRace == "Draugh")
{
string prefabName = monster.gameObject.name.ToLower();
if (prefabName.Contains("skeleton") || prefabName.Contains("draugr") ||
@ -71,7 +76,7 @@ namespace RacesOfValheim
// Fuling/Troll "choose" not to fight one - but there is no third state to code
// for: vanilla's own damage-response AI already makes any of them retaliate if
// the Trenta strikes first, same as it does for Fenrir's wolves above.
if (p.m_customData.ContainsKey("Race") && p.m_customData["Race"] == TrentaConfig.RaceId)
if (playerRace == TrentaConfig.RaceId)
{
string prefabName = monster.gameObject.name.ToLower();
@ -105,7 +110,7 @@ namespace RacesOfValheim
//
// 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)
if (playerRace == SvermConfig.RaceId)
{
string prefabName = monster.gameObject.name.ToLower();

View file

@ -280,12 +280,18 @@ namespace RacesOfValheim
Refresh();
});
AddButton("ResetBtn", "Reset Race", new Vector2(0, -110), new Color(0.5f, 0.25f, 0.2f, 1f), () =>
AddButton("ResetRaceBtn", "Reset Race", new Vector2(-170, -110), new Color(0.5f, 0.25f, 0.2f, 1f), () =>
{
Close();
RacesOfValheim.ResetRace();
});
AddButton("ResetProgressionBtn", "Reset Progression", new Vector2(170, -110), new Color(0.5f, 0.4f, 0.2f, 1f), () =>
{
RacesOfValheim.ResetProgression();
Refresh();
});
AddButton("CloseBtn", "Close", new Vector2(0, -200), new Color(0.3f, 0.3f, 0.3f, 1f), Close);
GUIManager.BlockInput(true);

View file

@ -15,7 +15,7 @@ namespace RacesOfValheim
{
public const string PluginGUID = "com.nandor.racesofvalheim";
public const string PluginName = "Races Of Valheim";
public const string PluginVersion = "1.4.5";
public const string PluginVersion = "1.4.8";
private readonly Harmony harmony = new Harmony(PluginGUID);
@ -49,6 +49,9 @@ namespace RacesOfValheim
// Not a race either: the Claws skill Aswid and Fenrir share, so it binds here rather
// than inside either race's run.
RaceClawsConfig.Bind(Config);
// Not a race either: the faction truce and the faction merchants, which cut across
// every race at once, so they bind last rather than inside the alphabetical run above.
FactionsConfig.Bind(Config);
harmony.PatchAll();
gameObject.AddComponent<FenrirRace>();
gameObject.AddComponent<SkadiRace>();
@ -124,8 +127,8 @@ namespace RacesOfValheim
player.GetSEMan().RemoveStatusEffect(TrentaConfig.PurpleRainCdSE.GetStableHashCode());
player.GetSEMan().RemoveStatusEffect(TrentaConfig.PortalCdSE.GetStableHashCode());
player.GetSEMan().RemoveStatusEffect(SvermConfig.StatsSE.GetStableHashCode());
player.GetSEMan().RemoveStatusEffect(SvermConfig.StingerSE.GetStableHashCode());
player.GetSEMan().RemoveStatusEffect(SvermConfig.StingerCdSE.GetStableHashCode());
player.GetSEMan().RemoveStatusEffect(SvermConfig.RavagerSE.GetStableHashCode());
player.GetSEMan().RemoveStatusEffect(SvermConfig.RavagerCdSE.GetStableHashCode());
// COLD, which is not one of ours at all - and that is exactly why it has to go.
//
@ -155,6 +158,25 @@ namespace RacesOfValheim
}
}
/// <summary>
/// Clears the boss-progression override and falls back to the natural world state.
/// Shared by the resetprogression console command and the Race Menu Ward.
/// </summary>
public static int ResetProgression()
{
BossProgressionManager.DebugState = -1;
int state = BossProgressionManager.GetCurrentProgressionState();
Player player = Player.m_localPlayer;
if (player != null)
{
player.Message(MessageHud.MessageType.Center, $"Progression reset to: {state}");
Traverse.Create(player).Method("SetupEquipment").GetValue();
}
return state;
}
/// <summary>
/// Strips whatever body-part weapon the outgoing race grew. The Aswid/Fenrir claws
/// (RaceClawSet) and the Sverm's Chitin Claws (SvermClawSlot) are quest items a player can
@ -332,7 +354,7 @@ namespace RacesOfValheim
// Row 2 (y = -20)
CreateRaceButtonWithConfirm("Aswid", new Vector2(-450, -20), GetAswidIcon(), "Fierce night stalker. Strong and resilient, transforms into a bat.", SelectAswid);
CreateRaceButtonWithConfirm("Furling", new Vector2(-150, -20), GetFurlingIcon(), "Cunning goblin-like creatures. Agile and resourceful.", SelectFurling);
CreateRaceButtonWithConfirm("Trol", new Vector2(150, -20), GetTrolIcon(), "Massive brute strength. Towering over others but slow to react.", SelectTrol);
CreateRaceButtonWithConfirm("Trol", new Vector2(150, -20), GetTrolIcon(), $"Massive brute strength. Towering over others, at peace with the Black Forest - but fire burns a Trol {(TrolConfig.FireWeaknessMultiplier.Value - 1f) * 100f:0}% harder than anyone else.", SelectTrol);
CreateRaceButtonWithConfirm("Draugh", new Vector2(450, -20), GetDraughIcon(), "A decaying undead warrior fueled by dark magic and extreme metal.", SelectDraugh);
// Row 3 (y = -140)
@ -1112,6 +1134,14 @@ namespace RacesOfValheim
{
Jotunn.Logger.LogInfo($" param: {param.name} ({param.type})");
}
// Every clip the controller can play. Parameters only say what CAN be driven,
// not what actually exists to play - a wrong trigger name silently plays nothing,
// so this is the list to check a guessed name against.
foreach (AnimationClip clip in animator.runtimeAnimatorController.animationClips)
{
if (clip != null) Jotunn.Logger.LogInfo($" clip: {clip.name}");
}
}
if (!anyAnimator) Jotunn.Logger.LogInfo(" (no Animator found anywhere in the hierarchy)");
@ -1119,7 +1149,20 @@ namespace RacesOfValheim
Humanoid humanoid = prefab.GetComponent<Humanoid>();
if (humanoid == null)
{
Jotunn.Logger.LogInfo(" (no Humanoid component on the prefab root)");
// Not every prefab worth checking is a creature - a registered weapon clone
// (e.g. `dumpelder SvermRavagerBite`) is an item on its own, and this is the only
// way to see what a runtime mutation (Attack.Clone() plus field edits) actually
// left on it, as opposed to what the SOURCE creature's own copy still says.
ItemDrop directItem = prefab.GetComponent<ItemDrop>();
if (directItem != null)
{
Jotunn.Logger.LogInfo(" (no Humanoid - dumping the prefab's own ItemDrop instead)");
DumpWeaponAttacks(prefab);
}
else
{
Jotunn.Logger.LogInfo(" (no Humanoid component and no ItemDrop on the prefab root)");
}
}
else
{
@ -1150,21 +1193,44 @@ namespace RacesOfValheim
if (drop == null || drop.m_itemData == null || drop.m_itemData.m_shared == null) return;
ItemDrop.ItemData.SharedData shared = drop.m_itemData.m_shared;
Jotunn.Logger.LogInfo($" weapon '{itemPrefab.name}' ({shared.m_name}): damages={DumpDamageTypes(shared.m_damages)}");
Jotunn.Logger.LogInfo($" weapon '{itemPrefab.name}' ({shared.m_name}): damages={DumpDamageTypes(shared.m_damages)} " +
$"skill={shared.m_skillType}");
DumpAttack("primary", shared.m_attack);
DumpAttack("secondary", shared.m_secondaryAttack);
}
/// <summary>
/// Every field an "identical" replica would need: the hitbox shape (melee reach, angle,
/// height, offset, ray width), how the damage lands (multiplier, multi-hit, through
/// walls, force), the animation, and every VFX slot Attack.Start can fire - start, trail,
/// hit, hit-on-terrain, trigger, burst, plus anything it spawns on top of the swing.
/// </summary>
private static void DumpAttack(string label, Attack attack)
{
if (attack == null) return;
Jotunn.Logger.LogInfo(
$" {label}: animation='{attack.m_attackAnimation}' randomAnimations={attack.m_attackRandomAnimations} " +
$"chainLevels={attack.m_attackChainLevels} damageMultiplier={attack.m_damageMultiplier} " +
$"type={attack.m_attackType} range={attack.m_attackRange} angle={attack.m_attackAngle} " +
$"spawnOnTrigger='{(attack.m_spawnOnTrigger != null ? attack.m_spawnOnTrigger.name : "none")}' " +
$"type={attack.m_attackType}");
Jotunn.Logger.LogInfo(
$" hitbox: range={attack.m_attackRange} angle={attack.m_attackAngle} " +
$"height={attack.m_attackHeight} offset={attack.m_attackOffset} rayWidth={attack.m_attackRayWidth} " +
$"originJoint='{attack.m_attackOriginJoint}' multiHit={attack.m_multiHit} " +
$"hitThroughWalls={attack.m_hitThroughWalls} hitFriendly={attack.m_hitFriendly} " +
$"hitTerrain={attack.m_hitTerrain} forceMultiplier={attack.m_forceMultiplier} " +
$"recoilPushback={attack.m_recoilPushback}");
Jotunn.Logger.LogInfo(
$" spawnOnTrigger='{(attack.m_spawnOnTrigger != null ? attack.m_spawnOnTrigger.name : "none")}' " +
$"spawnOnHit='{(attack.m_spawnOnHit != null ? attack.m_spawnOnHit.name : "none")}' " +
$"projectile='{(attack.m_attackProjectile != null ? attack.m_attackProjectile.name : "none")}'");
DumpEffectList("startEffect", attack.m_startEffect);
DumpEffectList("trailStartEffect", attack.m_trailStartEffect);
DumpEffectList("hitEffect", attack.m_hitEffect);
DumpEffectList("hitTerrainEffect", attack.m_hitTerrainEffect);
DumpEffectList("triggerEffect", attack.m_triggerEffect);
DumpEffectList("burstEffect", attack.m_burstEffect);
if (attack.m_attackProjectile != null)
{
Projectile proj = attack.m_attackProjectile.GetComponent<Projectile>();
@ -1180,6 +1246,18 @@ namespace RacesOfValheim
}
}
private static void DumpEffectList(string label, EffectList effects)
{
if (effects == null || effects.m_effectPrefabs == null || effects.m_effectPrefabs.Length == 0) return;
foreach (EffectList.EffectData data in effects.m_effectPrefabs)
{
if (data == null || data.m_prefab == null) continue;
Jotunn.Logger.LogInfo($" {label}: '{data.m_prefab.name}' attach={data.m_attach} " +
$"follow={data.m_follow} childTransform='{data.m_childTransform}'");
}
}
private static string DumpDamageTypes(HitData.DamageTypes d)
{
if (d == null) return "none";
@ -1220,14 +1298,8 @@ namespace RacesOfValheim
public override void Run(string[] args)
{
BossProgressionManager.DebugState = -1;
int state = BossProgressionManager.GetCurrentProgressionState();
int state = RacesOfValheim.ResetProgression();
Console.instance.Print($"[DEBUG] Progression state reset to natural world state: {state}");
if (Player.m_localPlayer != null)
{
Player.m_localPlayer.Message(MessageHud.MessageType.Center, $"Progression reset to: {state}");
Traverse.Create(Player.m_localPlayer).Method("SetupEquipment").GetValue();
}
}
}
}

View file

@ -36,6 +36,7 @@ namespace RacesOfValheim
public float Price;
public int Stage; // the nest stage it becomes available at
public float Cooldown; // seconds between two of these
public float SpawnHeight = 0.5f; // how far above the nest it is put down
public string PrefabName => PrefabPrefix + Source;
public int Cap => CapOf(Id);
@ -53,7 +54,7 @@ namespace RacesOfValheim
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 },
new Kind { Id = "gjall", Display = "Gjall", Source = "Gjall", Icon = "TrophyGjall", Price = 1000f, Stage = 4, Cooldown = 600f, SpawnHeight = 10f },
};
private static int CapOf(string id)
@ -141,7 +142,7 @@ namespace RacesOfValheim
}
/// <summary>
/// Puts one on the ground beside the nest, bound to it and born at whatever star the colony
/// Puts one down beside the nest, bound to it and born at whatever star the colony
/// has bought.
/// </summary>
public static bool Hatch(SvermHiveBehaviour hive, Kind kind)
@ -156,9 +157,7 @@ namespace RacesOfValheim
return false;
}
Vector3 offset = Random.insideUnitSphere * 2f;
offset.y = 0f;
Vector3 where = hive.transform.position + offset + Vector3.up * 0.5f;
Vector3 where = SpawnSpot(hive, kind);
GameObject spawned = Object.Instantiate(prefab, where, Quaternion.Euler(0f, Random.Range(0, 360), 0f));
if (spawned == null) return false;
@ -179,6 +178,73 @@ namespace RacesOfValheim
return true;
}
/// <summary>How much open ground is left between the nest's own skirt and a newborn.</summary>
private const float SpawnClearance = 2.5f;
/// <summary>
/// Where the newborn is put down: on a ring OUTSIDE the nest, never in the middle of it.
///
/// Troops were hatching at the nest's own position and half a metre up, which is inside a
/// building several metres wide - so they came out wedged in its collider. This walks a ring
/// from a random angle, takes the first spot with nothing standing on it, and drops the
/// creature on the TERRAIN height there, so a nest on a slope does not bury anyone either.
/// The per-kind height goes on top, which is what keeps the Gjall in the air.
/// </summary>
private static Vector3 SpawnSpot(SvermHiveBehaviour hive, Kind kind)
{
Vector3 centre = hive.transform.position;
float radius = RingRadius(hive);
int obstacleMask = LayerMask.GetMask("Default", "static_solid", "Default_small", "piece", "vehicle");
float start = Random.Range(0f, 360f);
for (int i = 0; i < 12; i++)
{
float angle = (start + i * (360f / 12f)) * Mathf.Deg2Rad;
Vector3 candidate = centre + new Vector3(Mathf.Cos(angle), 0f, Mathf.Sin(angle)) * radius;
if (ZoneSystem.instance != null) candidate.y = ZoneSystem.instance.GetGroundHeight(candidate);
if (Physics.CheckSphere(candidate + Vector3.up * 1.5f, 1f, obstacleMask)) continue;
return candidate + Vector3.up * kind.SpawnHeight;
}
// Twelve tries and everything is built up: due south on the ring anyway. Still outside
// the nest, which is the thing this is here to guarantee.
Vector3 fallback = centre + new Vector3(0f, 0f, -radius);
if (ZoneSystem.instance != null) fallback.y = ZoneSystem.instance.GetGroundHeight(fallback);
return fallback + Vector3.up * kind.SpawnHeight;
}
/// <summary>
/// How wide the ring is: the nest's own footprint plus a couple of metres.
///
/// MEASURED and not a number, because the nest grows with its stage - a stage four nest is
/// several times the width of the one that was placed, so any fixed radius that clears the
/// small one hatches troops inside the big one. Only solid meshes are measured; the hive's
/// particle effects have bounds of their own and would report a ring the size of a field.
/// </summary>
private static float RingRadius(SvermHiveBehaviour hive)
{
Vector3 centre = hive.transform.position;
float widest = 0f;
foreach (Renderer renderer in hive.GetComponentsInChildren<Renderer>(true))
{
if (renderer == null) continue;
if (!(renderer is MeshRenderer) && !(renderer is SkinnedMeshRenderer)) continue;
Bounds bounds = renderer.bounds; // world space, so the stage's growth is already in it
float reach = Mathf.Max(Mathf.Abs(bounds.center.x - centre.x) + bounds.extents.x,
Mathf.Abs(bounds.center.z - centre.z) + bounds.extents.z);
if (reach > widest) widest = reach;
}
// Nothing readable means nothing to be stuck in either, but the floor keeps a newborn off
// the nest's own doorstep, and the ceiling stops one measuring mistake spawning troops
// half a zone away.
return Mathf.Clamp(widest, 2f, 20f) + SpawnClearance;
}
}
/// <summary>

View file

@ -24,8 +24,8 @@ namespace RacesOfValheim
public const string RaceId = "Sverm";
public const string StatsSE = "SE_SvermStats";
public const string StingerSE = "SE_SvermStingerForm";
public const string StingerCdSE = "SE_SvermStingerCooldown";
public const string RavagerSE = "SE_SvermRavagerForm";
public const string RavagerCdSE = "SE_SvermRavagerCooldown";
// 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.
@ -144,7 +144,7 @@ namespace RacesOfValheim
public const int VenomGlandsState = 4;
public const int AcidHemolymphState = 4;
public const int VestigialWingsState = 5;
public const int StingerMorphState = 6;
public const int RavagerFormState = 6;
public const int EitrSacsState = 6;
public const int MajesticCarapaceState = 7;
public const int SurrenalGlandsState = 7;
@ -231,38 +231,60 @@ namespace RacesOfValheim
// ─── 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;
// ─── Ravager Strain (state 6) ────────────────────────────────────────
// Replaces the old Stinger Morph (a Deathsquito flight form). Players found that form's
// glass-cannon trade too strong for what it cost; this is the opposite shape - no flight,
// no summons, and the fragility multiplier is gone, replaced by a straight armour buff.
// Same duration and cooldown as the form it replaces.
public const string RavagerCreature = "SeekerBrute";
public static readonly float RavagerDurationSeconds = 120f; // 2 minutes
public static readonly float RavagerCooldownSeconds = 300f; // 5 minutes
// The Brute's four real attack items, named and verified with `dumpelder SeekerBrute` in
// a live world - not guessed. Their numbers are read once by SvermRavagerAttacks and
// applied by hand in RavagerFormBehavior's own attack coroutines (Physics.OverlapSphere,
// the same method Fenrir and Skadi's forms already use); nothing here is cloned or
// equipped any more.
public const string RavagerBiteWeapon = "SeekerBrute_bite"; // slash 100, left click
public const string RavagerRamWeapon = "SeekerBrute_ram"; // blunt/chop/pickaxe 100, right click / G
public const string RavagerSlamWeapon = "SeekerBrute_groundslam"; // AoE stomp, blunt/chop/pickaxe 120-100-100, middle click
/// <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.
/// The Brute's roar. type=None on the real creature - it lands no hit there - but the
/// item still carries real numbers (slash 80, chop 10) nobody ever wired to a hitbox.
/// Players asked for a use for it: a short-cooldown AoE around the player rather than a
/// forward swing, bound to G once G stopped being needed for anything else.
/// </summary>
public static readonly float StingerFragility = 2.5f;
public const string RavagerTauntWeapon = "SeekerBrute_Taunt";
// ─── 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.
/// What the carapace's own armour value (SvermCarapace.GetArmor) is multiplied by while
/// the form is up. 2 means the tank doubles its damage reduction for the same two minutes
/// the old form spent being nearly one-shot by anything.
/// </summary>
public const int EscortCount = 2;
public static readonly float EscortLifetimeSeconds = 180f;
public static readonly float EscortSpawnSpread = 2.5f;
public static readonly float RavagerArmorMultiplier = 2f;
// ─── The taunt (G) ───────────────────────────────────────────────────
/// <summary>Its own cooldown, short and separate from the main three attacks' own lock timing.</summary>
public static readonly float RavagerTauntCooldownSeconds = 10f;
/// <summary>Centred on the player, not projected forward like a swing - a roar goes out, not in.</summary>
public static readonly float RavagerTauntRadius = 3f;
// Candidates tried in order, same PlayEffect pattern MorphIn/MorphOutEffects already use:
// a wrong guess is silently skipped rather than an error. Not confirmed to exist - the
// Brute's own Attack effect slots were all empty when dumped, so if a roar sound exists
// at all it lives somewhere this file has not found yet.
public static readonly string[] RavagerTauntSoundEffects = { "sfx_seeker_brute_taunt", "sfx_seekerbrute_taunt", "sfx_seeker_taunt" };
// ─── 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" };
// The Seeker's own spawn and death bursts are the verified fallback - carried over from
// the old Stinger Morph, which used them successfully. A Brute-specific pair is tried
// first on the chance this build has one; PlayEffect already skips silently past any name
// that does not resolve, so a wrong guess here costs nothing. vfx_boar_death is the last
// resort because it is what the Aswid uses and is certain to exist.
public static readonly string[] RavagerMorphInEffects = { "fx_seeker_brute_spawn", "fx_seeker_spawn", "vfx_boar_death" };
public static readonly string[] RavagerMorphOutEffects = { "fx_seeker_brute_death", "fx_seeker_death", "vfx_boar_death" };
// ─── Palette ─────────────────────────────────────────────────────────
// Read off a Seeker Soldier. The exposed skin is almost black and matte: what makes the

View file

@ -37,11 +37,12 @@ namespace RacesOfValheim
public static ConfigEntry<float> EmberGlowStrength;
// ─── Keybinds ────────────────────────────────────────────────────────
public static ConfigEntry<KeyboardShortcut> StingerKey;
public static ConfigEntry<KeyboardShortcut> RavagerKey;
// ─── Stinger Morph, the model ────────────────────────────────────────
public static ConfigEntry<float> StingerScaleMultiplier;
public static ConfigEntry<float> StingerYawDegrees;
// ─── Ravager Strain, the model ───────────────────────────────────────
public static ConfigEntry<float> RavagerScaleMultiplier;
public static ConfigEntry<float> RavagerYawDegrees;
public static ConfigEntry<float> RavagerAttackOffsetValue;
// ─── Colony caps ─────────────────────────────────────────────────────
// Every ceiling on how many things the colony can have alive at once, in one section, so
@ -82,14 +83,15 @@ namespace RacesOfValheim
// 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.");
RavagerKey = config.Bind(keybinds, "Ravager Strain", new KeyboardShortcut(UnityEngine.KeyCode.G),
"Turns into a Seeker Brute, and back. Unlocked at Yagluth.");
const string stinger = "Sverm - Stinger Morph";
const string ravager = "Sverm - Ravager Strain";
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.");
RavagerScaleMultiplier = config.Bind(ravager, "Scale", 1f,
"Multiplies the Seeker Brute model's OWN authored scale. 1 means 'the full size " +
"the game draws one, bulk and all' - the form is meant to be worn at the " +
"creature's own size, not shrunk to fit.");
const string nest = "Sverm - Nest";
@ -180,10 +182,24 @@ namespace RacesOfValheim
"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.");
// FOUND IN PLAY: 180, the figure that fixed the flying Deathsquito, faces the Seeker
// Brute straight at the camera - its own forward already matches the player's, unlike
// the Deathsquito's. Different source rig, different answer; 0 is correct here.
RavagerYawDegrees = config.Bind(ravager, "Yaw", 0f,
"Turns the model on the vertical axis, in degrees. 0 is correct for the Seeker " +
"Brute; try 180 (or 90 / -90) if a future model swap ends up facing the wrong way.");
// FOUND IN PLAY: the hit itself lands where the PLAYER'S own body is, at the Brute's
// native scale (RavagerScale) the visible mouth/claws sit well forward of that - so
// the swing visibly connects a metre or more short of where the model appears to
// bite. Attack.m_attackOffset pushes the hit-detection origin forward from the
// player before m_attackRange is measured out from it; 1.5 is a first guess sized
// against the model's own scale, not a verified figure, so it lives here to be
// walked in by eye rather than baked into SvermConfig as if it were.
RavagerAttackOffsetValue = config.Bind(ravager, "Attack Reach Offset", 1.5f,
"How far forward of the player, in metres, the Brute's attacks are measured from. " +
"Raise it if a swing visibly connects short of the model's mouth/claws; lower it " +
"if it connects well past them.");
EmberGlowStrength = config.Bind(ember, "Glow Strength", SvermConfig.EmberGlowStrength,
"How hot the chitin burns at Fader. This multiplies an HDR colour and it is applied " +
@ -246,8 +262,9 @@ namespace RacesOfValheim
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 RavagerScale => RavagerScaleMultiplier?.Value ?? 1f;
public static float RavagerYaw => RavagerYawDegrees?.Value ?? 0f;
public static float RavagerAttackOffset => RavagerAttackOffsetValue?.Value ?? 1.5f;
public static float SizeSmall => SpineSizeSmall?.Value ?? SvermConfig.SpineSizeSmall;
public static float SizeFull => SpineSizeFull?.Value ?? SvermConfig.SpineSizeFull;

View file

@ -111,7 +111,25 @@ namespace RacesOfValheim
wear.m_hitEffect = new EffectList();
}
if (prefab.GetComponent<ZNetView>() == null) prefab.AddComponent<ZNetView>();
// PERSISTENT, EXPLICITLY, and this is the whole reason a nest could vanish at world
// load. Every other station in the mod is cloned from a real building - a workbench, a
// barrel, a cartography table - and inherits a ZNetView that is already persistent. The
// nest is the one piece built out of SCENERY, and a CreepProp is not saved with the
// world: it belongs to the location that placed it and is put back by the location, so
// its ZNetView (or the bare one added here, which defaults to false) marks the ZDO as
// throwaway. The hive stood, worked, took biomass - and was not written to the save.
// Next load, no ZDO, no nest.
//
// m_syncInitialScale stays OFF on purpose. It looks like the obvious partner to this
// line and it would be a bug: the stage growth is applied to the transform at runtime,
// so a ZNetView that stored the scale would restore the GROWN size, Awake would read it
// back as builtScale, and the nest would multiply itself by its stage again every
// reload. The size is derived from the stage on the ZDO instead, by every client.
ZNetView view = prefab.GetComponent<ZNetView>() ?? prefab.AddComponent<ZNetView>();
view.m_persistent = true;
view.m_distant = false;
view.m_type = ZDO.ObjectType.Default;
prefab.AddComponent<SvermHiveBehaviour>();
MountMouths(prefab);

View file

@ -336,7 +336,13 @@ namespace RacesOfValheim
wear.m_hitEffect = new EffectList();
}
if (prefab.GetComponent<ZNetView>() == null) prefab.AddComponent<ZNetView>();
// The workbench this is cloned from brings a persistent ZNetView with it, so this is
// belt as well as braces - but it is the line the NEST turned out to need after players
// reported hives gone at world load, and a counter that saves only because of what
// it was copied from is one refactor away from not saving at all.
ZNetView view = prefab.GetComponent<ZNetView>() ?? prefab.AddComponent<ZNetView>();
view.m_persistent = true;
prefab.AddComponent<SvermHiveMarket>();
Jotunn.Managers.PieceManager.Instance.AddPiece(new Jotunn.Entities.CustomPiece(prefab, fixReference: false,

View file

@ -37,7 +37,19 @@ namespace RacesOfValheim
public static void Postfix(Player __instance, ref float __result)
{
if (__instance == null || !SvermVisuals.IsSvermPlayer(__instance)) return;
__result += SvermCarapace.GetArmor(SvermVisuals.GetRenderState(__instance));
float carapace = SvermCarapace.GetArmor(SvermVisuals.GetRenderState(__instance));
// Ravager Strain's whole benefit: the carapace is worth double for as long as the
// form holds. Multiplying only the carapace's own contribution, not the total,
// keeps a cape or trinket's armour honest instead of doubling gear the form had
// nothing to do with.
if (SvermRavagerForm.IsActive)
{
carapace *= SvermConfig.RavagerArmorMultiplier;
}
__result += carapace;
}
}
@ -106,26 +118,13 @@ namespace RacesOfValheim
int state = SvermVisuals.GetRenderState(attackingPlayer);
SvermProgression.SvermRules rules = SvermProgression.GetRules(state);
// Unarmed only - the claws' own tier-scaled blow. Ravager Strain's own hits
// (RavagerFormBehavior.ExecuteDamage) are built with Skills.SkillType.Swords
// on purpose, specifically so they never reach this branch and get overwritten
// by the claws' numbers - the Brute's own damage is meant to stand as-is.
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);
}
SvermClaws.ApplyToUnarmedHit(hit, state);
}
if (rules.VenomOnHit > 0f)
@ -140,13 +139,9 @@ namespace RacesOfValheim
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);
}
// Ravager Strain no longer touches incoming damage directly - its whole benefit is
// the doubled carapace armour applied in Sverm_GetBodyArmor_Patch below, which
// Valheim's own armour formula turns into reduced damage the normal way.
if (victimRules.BluntWeakness != 0f && hit.m_damage.m_blunt > 0f)
{

View file

@ -45,7 +45,7 @@ namespace RacesOfValheim
/// <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 bool RavagerForm; // the Seeker Brute form is unlocked
public float BodyScale; // Surrenal Glands
public float CarapaceRegenPerSecond;
public bool Emberform; // black chitin, red burn, burning claws
@ -94,7 +94,7 @@ namespace RacesOfValheim
: state >= SvermConfig.VestigialWingsState ? SvermConfig.SpineSizeSmall
: 0f,
StingerMorph = state >= SvermConfig.StingerMorphState,
RavagerForm = state >= SvermConfig.RavagerFormState,
BodyScale = state >= SvermConfig.SurrenalGlandsState ? SvermConfig.BodyScaleAtQueen : 1f,

View file

@ -57,6 +57,10 @@ namespace RacesOfValheim
// 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();
// Ravager Strain's worn model, stripped down to a costume here because this is the
// one safe moment to do it - see SvermRavagerForm.BuildTemplate.
SvermRavagerForm.BuildTemplate();
}
public static bool IsSverm()
@ -74,8 +78,8 @@ namespace RacesOfValheim
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);
// form and give the player their body back if they stop being a Sverm mid-transformation.
SvermRavagerForm.Tick(Player.m_localPlayer);
if (Player.m_localPlayer == null || !IsSverm()) return;

View file

@ -0,0 +1,88 @@
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The Seeker Brute's three real damage profiles - a trigger name and a set of real damage
/// numbers, read once from the Brute's own weapons and cached. Nothing is cloned, registered
/// or equipped.
///
/// THIS REPLACES A WHOLE FILE (SvermRavagerWeapons.cs) THAT TRIED TO EQUIP THE REAL ITEMS AND
/// LET VALHEIM'S OWN Attack.Start RUN. It fought the game at every turn: Humanoid.
/// GetCurrentBlocker routed right-click into a parry because the source items were
/// m_blockable; player.InAttack() stopped rooting the player before the visible clip on the
/// model had actually finished; wiring a working secondary attack meant cloning and mutating
/// Attack objects by hand. None of that is necessary, because this mod already has two
/// working examples of "become a creature and attack" - FenrirBehaviors.cs and
/// DrakeFormBehavior.cs - and NEITHER of them equips anything. A trigger on the model's own
/// Animator plus a timed Physics.OverlapSphere, the same two calls every other transformation
/// in this mod already uses, is the whole mechanism. See RavagerFormBehavior.AttackRoutine.
/// </summary>
public static class SvermRavagerAttacks
{
public struct Profile
{
public string Trigger;
public HitData.DamageTypes Damage;
}
private static Profile bite;
private static Profile ram;
private static Profile slam;
private static Profile taunt;
private static bool read;
public static Profile Bite { get { EnsureRead(); return bite; } }
public static Profile Ram { get { EnsureRead(); return ram; } }
public static Profile Slam { get { EnsureRead(); return slam; } }
/// <summary>
/// type=None on the real Brute, so its Attack fields (range/angle/hitbox) were never
/// meant to land a hit - only m_attackAnimation and m_damages are trustworthy here, which
/// is why the taunt is handled by its own AoE routine rather than folded into
/// AttackRoutine's forward-swing shape.
/// </summary>
public static Profile Taunt { get { EnsureRead(); return taunt; } }
private static void EnsureRead()
{
if (read) return;
read = true;
bite = ReadOne(SvermConfig.RavagerBiteWeapon);
ram = ReadOne(SvermConfig.RavagerRamWeapon);
slam = ReadOne(SvermConfig.RavagerSlamWeapon);
taunt = ReadOne(SvermConfig.RavagerTauntWeapon);
}
private static Profile ReadOne(string sourcePrefabName)
{
GameObject source = Jotunn.Managers.PrefabManager.Cache.GetPrefab<GameObject>(sourcePrefabName);
ItemDrop drop = source != null ? source.GetComponent<ItemDrop>() : null;
ItemDrop.ItemData.SharedData shared = drop != null ? drop.m_itemData?.m_shared : null;
if (shared == null)
{
Jotunn.Logger.LogWarning($"[Sverm] No '{sourcePrefabName}' to read Ravager Strain damage " +
"from; that attack will land for nothing.");
return default;
}
Profile profile = new Profile
{
Trigger = shared.m_attack != null ? (shared.m_attack.m_attackAnimation ?? "") : "",
Damage = shared.m_damages,
};
Jotunn.Logger.LogInfo($"[Sverm] Ravager Strain reads '{profile.Trigger}' off '{sourcePrefabName}' - " +
$"{DumpDamage(profile.Damage)}.");
return profile;
}
private static string DumpDamage(HitData.DamageTypes d)
{
return $"blunt={d.m_blunt:0.#} slash={d.m_slash:0.#} pierce={d.m_pierce:0.#} " +
$"chop={d.m_chop:0.#} pickaxe={d.m_pickaxe:0.#}";
}
}
}

View file

@ -0,0 +1,718 @@
using HarmonyLib;
using Jotunn.Managers;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// Ravager Strain: from Yagluth on, a Sverm can become a Seeker Brute for two minutes.
///
/// Replaces the earlier Stinger Morph (a Deathsquito flight form). Players found that form's
/// glass-cannon shape too strong for what it cost, so this is the opposite trade: no flight,
/// no summons, and the carapace is worth twice as much for as long as the form holds - the
/// carapace itself is never removed. Same duration, same cooldown as the form it replaces;
/// only the shape of the trade changed.
///
/// COMBAT FOLLOWS FENRIR AND SKADI'S OWN PATTERN, not Valheim's weapon system. Nothing gets
/// equipped. Humanoid.StartAttack is blocked outright for as long as the form is up, and
/// RavagerFormBehavior runs its own attack coroutines instead - a trigger on the model's
/// Animator, a timed Physics.OverlapSphere, real damage numbers borrowed from
/// SvermRavagerAttacks. The earlier version tried to clone the Brute's own weapons and let
/// them run through Valheim's real Attack.Start, and it never stopped fighting the game:
/// GetCurrentBlocker turning right-click into a parry, player.InAttack() ending before the
/// visible clip did, wiring a working secondary attack by hand. Left click bites, right click
/// rams, middle click slams, G roars - a short-cooldown AoE around the player rather than a
/// fourth forward swing, since the Brute's own taunt was never a hit in the first place.
/// </summary>
public static class SvermRavagerForm
{
public static bool IsActive { get; private set; }
private static GameObject model;
private static float expiresAt;
private static float nextAllowedAt;
// Guards the ~1.1s "gpower" gesture in EnterRoutine, and separately the shrink in
// ExitRoutine: without them, a second key press mid-gesture would start a second routine
// on top of the first, the same double-transform bug Aswid's own isTransformingSequence
// flag exists to prevent.
private static bool transforming;
private static bool exiting;
private static GameObject template;
private static bool templateBuildAttempted;
// ─── The template ───────────────────────────────────────────────────
/// <summary>
/// Strips the Seeker Brute's borrowed model down to a costume, once, from a moment where
/// that is safe to do - the same rule ModelBorrow exists to enforce, and the same one
/// WarVultureVisual.BuildTemplate follows for its own borrowed bird. Call it from a
/// CreateAllModAssets-time hook; it no-ops on every call after the first.
///
/// FOUND IN PLAY: the old code instantiated the source's Animator sub-object directly at
/// Enter() time, mid-gameplay, and never stripped it. The Brute's own footstep-effect
/// script came along for the ride, alive, and spent every frame of the form logging
/// "FAiled to find foot:l.backfoot" because the bones it wanted only exist on the
/// source's own untouched rig - along with whatever else survived (Character, MonsterAI,
/// a Rigidbody, a ZNetView) that this class never meant to carry.
///
/// DestroyImmediate only, and only because the holder is inactive before the Instantiate
/// below: an active clone would Awake every one of those scripts for a frame before the
/// strip could remove them, which is the exact bug ModelBorrow's own docstring names.
/// Object.Destroy (deferred) would not be safe here for the same reason - by the time it
/// actually runs, the frame that mattered has already passed.
/// </summary>
public static void BuildTemplate()
{
if (template != null || templateBuildAttempted) return;
templateBuildAttempted = true;
GameObject source = PrefabManager.Cache.GetPrefab<GameObject>(SvermConfig.RavagerCreature);
GameObject animated = source != null ? source.GetComponentInChildren<Animator>()?.gameObject : null;
if (animated == null)
{
Jotunn.Logger.LogWarning($"[Sverm] No '{SvermConfig.RavagerCreature}' model to build the " +
"Ravager Strain template from; the form will run without a body.");
return;
}
GameObject holder = new GameObject("SvermRavagerTemplate");
Object.DontDestroyOnLoad(holder);
holder.SetActive(false); // BEFORE Instantiate: nothing on the copy gets to Awake.
GameObject copy = Object.Instantiate(animated, holder.transform);
copy.name = "model";
copy.transform.localPosition = Vector3.zero;
copy.transform.localRotation = Quaternion.identity;
copy.transform.localScale = animated.transform.localScale;
// Everything that is not a Renderer or a Transform. Animator is a Behaviour, not a
// MonoBehaviour, so it is never touched by the first loop and survives on purpose -
// it is the one live thing this costume is allowed to keep.
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 (Rigidbody body in copy.GetComponentsInChildren<Rigidbody>(true))
{
if (body != null) Object.DestroyImmediate(body);
}
foreach (ZNetView nview in copy.GetComponentsInChildren<ZNetView>(true))
{
if (nview != null) Object.DestroyImmediate(nview);
}
template = copy;
Jotunn.Logger.LogInfo($"[Sverm] Ravager Strain template built from '{SvermConfig.RavagerCreature}'.");
}
// ─── Driver ──────────────────────────────────────────────────────────
public static void Tick(Player player)
{
if (player == null || player != Player.m_localPlayer)
{
return;
}
// While the entry gesture (EnterRoutine) or the exit shrink (ExitRoutine) is still
// playing, nothing below should react to a key press or a death mid-sequence.
if (transforming || exiting) 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 - and neither one gets the graceful shrink, on purpose: a corpse or a race
// change is not the moment for a half-second animation, it is the moment to clean up.
if (IsActive && (player.IsDead() || !SvermVisuals.IsSvermPlayer(player)))
{
Exit(player, spendCooldown: false);
return;
}
if (IsActive && Time.time >= expiresAt)
{
RunExit(player, spendCooldown: true, "The shell recedes.");
return;
}
// No manual cancel: the form is short (two minutes) on purpose, and letting G end it
// early meant a stray press mid-fight burned the whole cooldown for a form that had
// barely started. While IsActive, the key does nothing at all - the timer is the only
// way out, same as death or losing the race.
if (IsActive) return;
if (!SvermConfigManagement.RavagerKey.Value.IsDown()) return;
if (!SvermVisuals.IsSvermPlayer(player)) return;
if (!SvermProgression.Current.RavagerForm)
{
player.Message(MessageHud.MessageType.Center, "The strain has not taken yet.");
return;
}
if (Time.time < nextAllowedAt)
{
player.Message(MessageHud.MessageType.Center, "The strain is spent.");
return;
}
if (SvermRace.Instance != null)
{
SvermRace.Instance.StartCoroutine(EnterRoutine(player));
}
else
{
// No host to run the gesture on - a state that should not happen outside a very
// early loading frame, but the form working ungestured beats it not working at
// all.
Enter(player);
}
}
/// <summary>
/// The transformation's own animation: the same "gpower" arms-raised gesture Aswid,
/// Skadi and Fenrir all borrow for their own transformations (RaceInput's own comment
/// names all three), suppressed so it never fires the player's real Guardian Power. The
/// actual state change - IsActive, the weapons, the hidden body, the worn model - waits
/// out the gesture first, the same order TransformIntoBatRoutine uses in AswidRace.cs.
/// </summary>
private static System.Collections.IEnumerator EnterRoutine(Player player)
{
transforming = true;
ZSyncAnimation zAnim = player.GetComponent<ZSyncAnimation>();
if (zAnim != null)
{
RaceInput.SuppressGuardianPowerBriefly();
zAnim.SetTrigger("gpower");
}
yield return new WaitForSeconds(1.1f);
// The gesture takes over a second; a lot can happen to the player in that window.
if (player == null || player != Player.m_localPlayer || player.IsDead() || !SvermVisuals.IsSvermPlayer(player))
{
transforming = false;
yield break;
}
Enter(player);
transforming = false;
}
// ─── Enter and leave ─────────────────────────────────────────────────
private static void Enter(Player player)
{
IsActive = true;
expiresAt = Time.time + SvermConfig.RavagerDurationSeconds;
player.GetSEMan().AddStatusEffect(SvermConfig.RavagerSE.GetStableHashCode(), true);
Transform visual = player.transform.Find("Visual");
PlayerVisualHider.Hide(visual, "sverm-ravager");
// BuildTemplate is NOT called from here. Enter() runs from Tick(), inside Update, and
// the strip needs DestroyImmediate on an inactive object - safe only from the
// CreateAllModAssets-time hook that actually builds this. If that hook never ran, the
// template stays null and the form falls back to a bare body below rather than
// risking an unsafe strip mid-gameplay.
if (template != null)
{
// A plain Instantiate of an already-stripped template - safe in this context
// (mid-gameplay, inside Update) precisely because nothing left on it can Awake
// into anything. See BuildTemplate for why that matters.
model = Object.Instantiate(template, player.transform.position, player.transform.rotation, player.transform);
model.transform.localPosition = Vector3.zero;
// SCALE COMES FROM THE SOURCE, not from 1 - same reasoning as the old Stinger
// Morph. The multiplier defaults to 1 (the Brute's own authored size, full bulk,
// by design) and is only there for an eye to correct it against.
Vector3 fullScale = template.transform.localScale * SvermConfigManagement.RavagerScale;
// Grows in rather than popping to full size at once, starting at half scale and
// reaching full over half a second - the entrance the transformation itself was
// missing. ScaleTween owns the model reference for that half second, not Enter,
// so nothing here needs to wait on it.
model.transform.localScale = fullScale * 0.5f;
if (SvermRace.Instance != null)
{
SvermRace.Instance.StartCoroutine(ScaleTween(model, fullScale * 0.5f, fullScale, 0.5f));
}
else
{
model.transform.localScale = fullScale;
}
// Which way the model faces is a thing only an eye can settle, so it is a config
// value and not a constant - same as the old form.
model.transform.localRotation = Quaternion.Euler(0f, SvermConfigManagement.RavagerYaw, 0f);
model.AddComponent<RavagerFormBehavior>();
}
else
{
// No model is survivable - the carapace and the armour buff still apply - but it
// is worth saying out loud rather than leaving someone to wonder why they turned
// into nothing.
GameObject bare = new GameObject("SvermRavagerBody");
bare.transform.SetParent(player.transform, false);
bare.AddComponent<RavagerFormBehavior>();
model = bare;
}
PlayEffect(SvermConfig.RavagerMorphInEffects, player.transform.position);
player.Message(MessageHud.MessageType.Center, "The Ravager Strain takes hold.");
}
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.RavagerMorphOutEffects, player.transform.position);
// Nothing was ever equipped for this form - see the class doc for why - so there is
// nothing to hand back here. SvermClawSlot's own throttled pass (Sverm_PlayerUpdate_Patch)
// keeps the claws maintained regardless of Ravager Strain, on its own schedule.
if (model != null)
{
// FOUND IN PLAY: Object.Destroy is deferred to the end of the frame, so
// RavagerFormBehavior's own LateUpdate - the one that re-hides the player's
// Visual every frame to kill the equipment-swap flicker - was still firing AFTER
// Show() ran a few lines below, undoing it the instant it happened. Nothing called
// Show() again afterward, so the player (and whatever VisEquipment had just
// rebuilt while unequipping the Ravager weapon above - the carapace included)
// stayed hidden for good. SetActive(false) makes Unity skip every further
// Update/LateUpdate on this GameObject for the rest of the frame even though the
// object itself is not gone yet, which is the only part of "destroyed" that
// actually matters here.
model.SetActive(false);
Object.Destroy(model);
model = null;
}
player.GetSEMan().RemoveStatusEffect(SvermConfig.RavagerSE.GetStableHashCode());
Transform visual = player.transform.Find("Visual");
PlayerVisualHider.Show(visual, "sverm-ravager-revert");
if (spendCooldown)
{
nextAllowedAt = Time.time + SvermConfig.RavagerCooldownSeconds;
player.GetSEMan().AddStatusEffect(SvermConfig.RavagerCdSE.GetStableHashCode(), true);
}
}
/// <summary>Kicks off the graceful exit (shrink, then Exit) if there is a host to run it on.</summary>
private static void RunExit(Player player, bool spendCooldown, string message)
{
if (SvermRace.Instance != null)
{
SvermRace.Instance.StartCoroutine(ExitRoutine(player, spendCooldown, message));
}
else
{
Exit(player, spendCooldown);
if (message != null) player.Message(MessageHud.MessageType.Center, message);
}
}
/// <summary>
/// The mirror of EnterRoutine's grow-in: the model shrinks to half its current scale over
/// half a second before Exit() actually tears anything down, so the form has a send-off
/// instead of a hard cut. Used for the two GRACEFUL exits only (timeout, manual toggle) -
/// death and a race change go through Exit() directly, immediately, on purpose.
/// </summary>
private static System.Collections.IEnumerator ExitRoutine(Player player, bool spendCooldown, string message)
{
exiting = true;
if (model != null)
{
Vector3 current = model.transform.localScale;
yield return ScaleTween(model, current, current * 0.5f, 0.5f);
}
Exit(player, spendCooldown);
if (message != null) player.Message(MessageHud.MessageType.Center, message);
exiting = false;
}
/// <summary>
/// Linear scale from <paramref name="from"/> to <paramref name="to"/> over
/// <paramref name="duration"/> seconds. Bails cleanly if the target disappears mid-tween
/// rather than assuming it cannot - Exit() is free to destroy the model while this is
/// still yielding.
/// </summary>
private static System.Collections.IEnumerator ScaleTween(GameObject target, Vector3 from, Vector3 to, float duration)
{
if (target == null) yield break;
float elapsed = 0f;
while (elapsed < duration)
{
if (target == null) yield break;
elapsed += Time.deltaTime;
target.transform.localScale = Vector3.Lerp(from, to, elapsed / duration);
yield return null;
}
if (target != null) target.transform.localScale = to;
}
// ─── The three attacks ───────────────────────────────────────────────
/// <summary>
/// Blocks Valheim's own attack system outright for the whole form, the same way
/// SkadiAttackPatch blocks it for the dragon forms. Whatever the player happens to have
/// equipped never swings and never deals damage while this is up; RavagerFormBehavior's
/// own coroutines are the only thing that can land a hit.
/// </summary>
[HarmonyPatch(typeof(Humanoid), "StartAttack")]
public static class Sverm_RavagerBlockNativeAttack_Patch
{
public static bool Prefix(Humanoid __instance)
{
if (__instance != Player.m_localPlayer) return true;
return !IsActive;
}
}
/// <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_RavagerUseItem_Patch
{
public static bool Prefix(Humanoid __instance)
{
if (!IsActive) return true;
return !(__instance is Player player) || player != Player.m_localPlayer;
}
}
}
/// <summary>
/// Locomotion AND combat, both held on every frame while the form is up - built on the same
/// method FenrirFormBehavior and DrakeFormBehavior already use for their own transformations,
/// not on Valheim's weapon system. See SvermRavagerAttacks for why.
///
/// UNLIKE THE OLD STINGER MORPH, this never touches m_debugFly - the whole point of Ravager
/// Strain is that it stays on the ground. The player moves exactly as they always do; this
/// component only feeds the worn model's own Animator whatever standard Valheim monster
/// parameters it actually has - forward_speed and onGround, the same pair DrakeFormBehavior
/// drives - plus a jump cue IF the Brute's controller turns out to carry one, checked once at
/// Start rather than assumed. Every SetFloat/SetBool/SetTrigger is guarded by that check, the
/// same pattern WarVultureVisual.Has uses: driving a parameter name the controller does not
/// have is a silent no-op in Unity, but the guard is what makes "does it have one" an answer
/// this logs instead of a guess nobody can see.
/// </summary>
public class RavagerFormBehavior : MonoBehaviour
{
private Animator anim;
private bool hasForwardSpeed;
private bool hasOnGround;
private bool hasJumpTrigger;
private bool hasJumpBool;
private bool wasGrounded = true;
// While true, Update skips both the locomotion sync and any new attack input - the same
// gate FenrirFormBehavior's own isAttacking flag uses, and the direct answer to "the
// animation has to finish before the Brute can move": nothing here can start moving the
// model again, or start a second attack, until the coroutine below clears it.
private bool isAttacking;
// The taunt's own cooldown - short, and tracked separately from the other three, which
// have no cooldown of their own beyond their own lock duration.
private float nextTauntAt;
// Every distinct trigger name that has been checked against this Animator and found
// present, so PlayAttack does not pass a name to SetTrigger the controller cannot use.
private readonly System.Collections.Generic.HashSet<string> knownTriggers = new System.Collections.Generic.HashSet<string>();
private void Start()
{
anim = GetComponentInChildren<Animator>();
if (anim == null || anim.runtimeAnimatorController == null) return;
// The same three settings WarVultureVisual.PrepareAnimator uses on its own borrowed
// model, for the same reasons. applyRootMotion=false: the slam's clip carries real
// baked motion, and left at the default Unity would walk the COSTUME out from under
// its wearer - the model has no collider and no gameplay meaning, only the player
// does, and the player already moves through Valheim's own code, not an animation
// clip. fireEvents=false: attack clips carry animation events aimed at
// CharacterAnimEvent, which BuildTemplate already stripped off this model, so left on
// every swing would log "has no receiver" for nothing. cullingMode: keeps the model
// animating even when it is partly off the bottom of the screen, the way a body
// standing close to the camera often is.
anim.applyRootMotion = false;
anim.fireEvents = false;
anim.cullingMode = AnimatorCullingMode.AlwaysAnimate;
foreach (AnimatorControllerParameter param in anim.parameters)
{
if (param.type == AnimatorControllerParameterType.Float && param.name == "forward_speed")
hasForwardSpeed = true;
else if (param.type == AnimatorControllerParameterType.Bool && param.name == "onGround")
hasOnGround = true;
else if (param.type == AnimatorControllerParameterType.Trigger && param.name == "jump")
hasJumpTrigger = true;
else if (param.type == AnimatorControllerParameterType.Bool && param.name == "jump")
hasJumpBool = true;
else if (param.type == AnimatorControllerParameterType.Trigger)
knownTriggers.Add(param.name);
}
Jotunn.Logger.LogInfo($"[Sverm] Ravager Strain model animator: forward_speed={hasForwardSpeed}, " +
$"onGround={hasOnGround}, jump=" +
(hasJumpTrigger ? "trigger" : hasJumpBool ? "bool" : "none") + ".");
}
/// <summary>
/// FOUND IN PLAY: the real body flickered into view on every equipment change elsewhere
/// in the game (a nearby player's gear, a tamed animal, anything that shares
/// VisEquipment's rebuild path) - PlayerVisualHider's own comment already says gear
/// changes make hidden things visible again, which is why it re-sweeps on a timer rather
/// than hiding once. That timer is 0.25s, long enough to be noticed.
///
/// LateUpdate, not Update: Unity runs every component's Update before any component's
/// LateUpdate in a given frame, so this always runs after whatever rebuilt visuals
/// earlier in the same frame, rather than racing it. Re-hiding every single frame the
/// form is up closes the gap the 0.25s timer leaves open, without touching
/// PlayerVisualHider's own interval, which every other race's hidden body still relies on.
/// </summary>
private void LateUpdate()
{
Player player = Player.m_localPlayer;
if (player == null) return;
Transform visual = player.transform.Find("Visual");
PlayerVisualHider.Hide(visual, "sverm-ravager");
}
private void Update()
{
Player player = Player.m_localPlayer;
if (player == null || player.IsDead()) return;
if (isAttacking) return;
bool grounded = player.IsOnGround();
if (hasForwardSpeed)
{
Vector3 velocity = player.GetVelocity();
velocity.y = 0f;
anim.SetFloat("forward_speed", velocity.magnitude);
}
if (hasOnGround) anim.SetBool("onGround", grounded);
if (hasJumpTrigger)
{
// The rising edge only, so a trigger fires once per jump rather than once per
// frame spent airborne.
if (!grounded && wasGrounded) anim.SetTrigger("jump");
}
else if (hasJumpBool)
{
anim.SetBool("jump", !grounded);
}
wasGrounded = grounded;
if (!RaceInput.Allowed || !grounded) return;
// Right click rams, left click bites, middle click slams. All three read raw
// UnityEngine.Input rather than going anywhere near Humanoid.StartAttack, which
// Sverm_RavagerBlockNativeAttack_Patch refuses outright for the whole form - see the
// class doc for why that turned out to be the only reliable option.
if (Input.GetMouseButtonDown(1))
{
StartCoroutine(AttackRoutine(SvermRavagerAttacks.Ram, 2f, 0.3f, 0.7f));
}
else if (Input.GetMouseButtonDown(0))
{
StartCoroutine(AttackRoutine(SvermRavagerAttacks.Bite, 2f, 0.3f, 0.6f));
}
else if (Input.GetMouseButtonDown(2))
{
StartCoroutine(AttackRoutine(SvermRavagerAttacks.Slam, 1.2f, 0.4f, 1.0f));
}
else if (SvermConfigManagement.RavagerKey.Value.IsDown() && Time.time >= nextTauntAt)
{
nextTauntAt = Time.time + SvermConfig.RavagerTauntCooldownSeconds;
StartCoroutine(TauntRoutine());
}
}
/// <summary>
/// One swing: play the clip, wait for the moment it should land, hit whatever is there,
/// then hold isAttacking until the swing is fully spent. FenrirFormBehavior.ClawRoutine in
/// every particular except the damage itself, which here is the Brute's own real numbers
/// (SvermRavagerAttacks) instead of one tuned float.
/// </summary>
private System.Collections.IEnumerator AttackRoutine(SvermRavagerAttacks.Profile profile, float radius,
float hitDelay, float lockDuration)
{
isAttacking = true;
if (hasForwardSpeed) anim.SetFloat("forward_speed", 0f);
if (!string.IsNullOrEmpty(profile.Trigger) && knownTriggers.Contains(profile.Trigger))
{
anim.SetTrigger(profile.Trigger);
}
yield return new WaitForSeconds(hitDelay);
ExecuteDamage(profile, radius);
float remaining = lockDuration - hitDelay;
if (remaining > 0f) yield return new WaitForSeconds(remaining);
isAttacking = false;
}
/// <summary>
/// The taunt, played as a short-cooldown AoE around the player rather than a forward
/// swing - the roar reaches out in every direction, so the sphere is centred on the
/// player instead of offset ahead of them the way AttackRoutine's three do. Deliberately
/// silent: no message, no status effect, nothing in a corner of the screen - just the
/// animation, the sound if one resolves, and the hit.
/// </summary>
private System.Collections.IEnumerator TauntRoutine()
{
isAttacking = true;
SvermRavagerAttacks.Profile profile = SvermRavagerAttacks.Taunt;
if (hasForwardSpeed) anim.SetFloat("forward_speed", 0f);
if (!string.IsNullOrEmpty(profile.Trigger) && knownTriggers.Contains(profile.Trigger))
{
anim.SetTrigger(profile.Trigger);
}
PlaySound(SvermConfig.RavagerTauntSoundEffects);
yield return new WaitForSeconds(0.3f);
Player player = Player.m_localPlayer;
if (player != null)
{
ApplyDamageInSphere(player.transform.position + Vector3.up, SvermConfig.RavagerTauntRadius, profile.Damage);
}
yield return new WaitForSeconds(0.4f);
isAttacking = false;
}
/// <summary>Tries each candidate in order and plays the first that resolves, same as SvermRavagerForm.PlayEffect.</summary>
private static void PlaySound(string[] candidates)
{
Player player = Player.m_localPlayer;
if (player == null) return;
foreach (string name in candidates)
{
GameObject prefab = Jotunn.Managers.PrefabManager.Cache.GetPrefab<GameObject>(name);
if (prefab == null) continue;
Object.Instantiate(prefab, player.transform.position, Quaternion.identity);
return;
}
}
/// <summary>
/// FenrirBehaviors.ExecuteClawDamage, unchanged in shape: a sphere swept against the same
/// broad layer mask every melee form in this mod already uses.
/// </summary>
private void ExecuteDamage(SvermRavagerAttacks.Profile profile, float radius)
{
Player player = Player.m_localPlayer;
if (player == null) return;
float reach = SvermConfigManagement.RavagerAttackOffset;
Vector3 attackPoint = player.transform.position + player.transform.forward * reach + Vector3.up;
ApplyDamageInSphere(attackPoint, radius, profile.Damage);
}
/// <summary>
/// The actual sweep, shared by every attack this form has (the three forward swings and
/// the taunt's own AoE) - only the sphere's centre and radius differ between them.
///
/// m_skill is Swords, deliberately NOT Unarmed: Sverm_Damage_Patch rewrites any Unarmed
/// hit from a Sverm into the Chitin Claws' own tier damage, and that patch fires for THIS
/// call too, since it hooks Character.Damage itself rather than caring who dealt the hit.
/// Swords keeps that rewrite from overwriting the Brute's real numbers with the claws'.
/// </summary>
private static void ApplyDamageInSphere(Vector3 center, float radius, HitData.DamageTypes damage)
{
Player player = Player.m_localPlayer;
if (player == null) return;
int layerMask = LayerMask.GetMask("Default", "static_solid", "Default_small", "piece",
"piece_nonsolid", "terrain", "character", "character_net", "character_ghost",
"hitbox", "character_noenv", "vehicle");
Collider[] hits = Physics.OverlapSphere(center, radius, layerMask);
var hitObjects = new System.Collections.Generic.HashSet<GameObject>();
foreach (Collider hit in hits)
{
if (hit.gameObject == player.gameObject) continue;
if (hit.attachedRigidbody != null && hit.attachedRigidbody.gameObject == player.gameObject) continue;
IDestructible target = hit.GetComponentInParent<IDestructible>();
if (target == null) continue;
if (target is Character characterTarget && characterTarget == player) continue;
GameObject targetObj = (target as MonoBehaviour)?.gameObject;
if (targetObj != null)
{
if (hitObjects.Contains(targetObj)) continue;
hitObjects.Add(targetObj);
}
Vector3 targetCenter = hit.bounds.center;
Vector3 dirToTarget = (targetCenter - player.transform.position).normalized;
HitData hitData = new HitData();
hitData.m_damage = damage;
hitData.m_point = targetCenter;
hitData.m_dir = dirToTarget;
hitData.m_pushForce = 40f;
hitData.m_skill = Skills.SkillType.Swords;
hitData.m_dodgeable = true;
hitData.m_blockable = true;
hitData.m_hitType = HitData.HitType.PlayerHit;
hitData.m_toolTier = 100;
hitData.SetAttacker(player);
target.Damage(hitData);
}
}
}
}

View file

@ -92,29 +92,37 @@ namespace RacesOfValheim
}
/// <summary>
/// Stinger Morph's cooldown. Purely a marker with a countdown, the way
/// Ravager Strain'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 class SE_SvermRavagerCooldown : 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;
m_name = "Ravager Strain Cooldown";
m_tooltip = "The strain is spent. It will take again soon.";
m_ttl = SvermConfig.RavagerCooldownSeconds;
}
}
/// <summary>Held while the Deathsquito form is up, so anything can ask "am I a bug right now".</summary>
public class SE_SvermStingerForm : StatusEffect
/// <summary>
/// Held while the Seeker Brute form is up, so anything can ask "am I wearing the Brute right
/// now". FOUND IN PLAY: without m_ttl, this icon showed with no countdown at all while the
/// cooldown icon right next to it did - the same top-right corner telling two different
/// stories about how a timer works. Setting it means the HUD counts the form down to zero the
/// same way it already counts the cooldown down, and the two hand off from one to the other
/// exactly as SvermRavagerForm.Exit/Enter's own timers do.
/// </summary>
public class SE_SvermRavagerForm : StatusEffect
{
public override void Setup(Character character)
{
base.Setup(character);
m_name = "Stinger Morph";
m_tooltip = "Wings, a needle, and nothing to hide behind.";
m_name = "Ravager Strain";
m_tooltip = "The shell doubles, and nothing that hits it lands the same again.";
m_ttl = SvermConfig.RavagerDurationSeconds;
}
}
@ -136,15 +144,15 @@ namespace RacesOfValheim
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";
var form = ScriptableObject.CreateInstance<SE_SvermRavagerForm>();
form.name = SvermConfig.RavagerSE;
form.m_name = "Ravager Strain";
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";
var cooldown = ScriptableObject.CreateInstance<SE_SvermRavagerCooldown>();
cooldown.name = SvermConfig.RavagerCdSE;
cooldown.m_name = "Ravager Strain Cooldown";
cooldown.m_icon = icon;
ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(cooldown, fixReference: false));
}

View file

@ -1,384 +0,0 @@
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 Chitin Claws equipped makes the
// sting an ordinary weapon attack - which works - and costs nothing visually, because
// the whole body is hidden a line later. Fist weapons report Skills.SkillType.Unarmed,
// so the damage patch still recognises the blow and swaps the deathsquito's figure in.
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 Chitin Claws.");
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())
{
// ZNetScene.Destroy, NEVER Object.Destroy, and this line was the teleport crash.
//
// An escort is a real networked creature, and ZNetView.OnDestroy - read out of the
// assembly, not assumed - only releases asset references: it does not take the
// object out of ZNetScene.m_instances. A plain Object.Destroy therefore left the
// scene holding a dead ZNetView, and the next time the world unloaded around the
// player, which is exactly what a teleport is, ZNetScene.RemoveObjects walked that
// entry and threw. See ZNetSceneOrphanPatch.cs for the whole chain.
if (ZNetScene.instance != null) ZNetScene.instance.Destroy(gameObject);
else 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

@ -461,6 +461,7 @@ namespace RacesOfValheim
if (__instance != Player.m_localPlayer) return;
TrentaComposter.EnsureKnown(__instance);
TrentaHeartwoodGrove.EnsureKnown(__instance);
TrentaElderRoot.EnsureKnown(__instance);
FurlingCrops.EnsureKnown(__instance);
}
}

View file

@ -444,6 +444,65 @@ namespace RacesOfValheim
public static readonly Color RotSeedTint = new Color(0.16f, 0.12f, 0.08f, 1f);
// ─── Root of the Elder (item progression, defensive) ──────────────────
// Race-locked, hammer-only, permanent: a piece that heals itself and, once a minute, heals
// every player-built thing within reach of it too. Full design in Trenta_ElderRoot.txt.
//
// No crafting station, same reasoning as the Composter/Grove chain's own station-free entry
// point would need if it had one: this is a race identity piece, not a purchase from
// someone else's bench (see the War Totem's own note on the same choice).
public const string ElderRootPieceName = "TrentaElderRoot";
public const string ElderRootDisplayName = "Root of the Elder";
public const int ElderRootUnlockState = 3; // The Elder dead
public const string ElderRootRecipeGuck = "Guck";
public const int ElderRootRecipeGuckAmount = 5;
public const string ElderRootRecipeFineWood = "FineWood";
public const int ElderRootRecipeFineWoodAmount = 10;
// Source of the borrowed model - swamp scenery, already safe to strip under ModelBorrow's
// rules (no MonoBehaviour worth stripping in the first place, unlike a living prefab).
// THE ELDER'S SUMMONED ROOT - the thing that claws its way out of the ground and attacks
// whoever comes near during the boss fight. Verified by its path in manifest_extended:
// Assets/Characters/Greydwarf_king/TentaRoot
// "Assets/Characters/..." means CREATURE (the same path convention Trol_WarTotem.txt sez.
// 2.1 wrote down after the GoblinTotem item/piece mix-up), and "Greydwarf_king" is The
// Elder. Its whole kit sits in the same folder - misc/spawn_roots (the emergence),
// misc/tentaroot_attack, animation/tentaroot, fx_tentaroot_death, sfx_tentaroot_attack.
// The Mistlands Staff of Green Roots summons the same creature (staff_greenroots_tentaroot),
// which is the second confirmation that this is a summon and not decoration.
//
// TWO WRONG PICKS BEFORE THIS ONE, both found by searching the manifest for a word instead
// of asking what the boss actually spawns:
// "Vines" - unrelated swamp scenery, inert.
// "gdking_root_projectile" - the spike the Elder SHOOTS. A projectile/vfx, not the
// summon. Still correctly used further down for Muspell's
// ranged attack, which is what it really is.
//
// BORROWING FROM THIS IS NOT LIKE BORROWING SCENERY: it carries a Character, and
// ModelBorrow strips in a single pass, which is the exact shape of the bug that once broke
// the hammer for every piece in the game. TrentaElderRoot.ResolveModelSource walks to the
// "Visual" child first - the same thing FenrirRace and SkadiRace do for their forms - so
// no Character is ever handed to ModelBorrow.
public const string ElderRootModelSourcePrefab = "TentaRoot";
/// <summary>Child of a creature prefab that holds only mesh and animator, no Character.</summary>
public const string CreatureVisualChildName = "Visual";
// Height in metres of the borrowed model's largest dimension. NOT a guess any more: the
// mesh measures (0.48, 4.51, 0.47) at native size - a tall, thin root - and the first two
// tries in game (1.2 then 1.6) both came out about 70% too short. 2.7 m is roughly 60% of
// the creature's own height and stands a good head above the player.
public const float ElderRootModelSize = 2.7f;
// Forward to TrentaConfigManagement (BepInEx ConfigEntry) - see that class.
public static float ElderRootHealth => TrentaConfigManagement.ElderRootHealth.Value;
public static float ElderRootSelfHealDelay => TrentaConfigManagement.ElderRootSelfHealDelay.Value;
public static float ElderRootSelfHealPercentPerSecond => TrentaConfigManagement.ElderRootSelfHealPercentPerSecond.Value;
public static float ElderRootRepairRadius => TrentaConfigManagement.ElderRootRepairRadius.Value;
public static float ElderRootRepairInterval => TrentaConfigManagement.ElderRootRepairInterval.Value;
// ─── Heartwood Grove (item progression, tier 2) ──────────────────────
// Plant a seed, wait, and the tree that comes up fertilises what surrounds it, stings what
// approaches it, and fills a chest with honey. Three independent functions on one piece.

View file

@ -50,6 +50,13 @@ namespace RacesOfValheim
public static ConfigEntry<float> LastStandMaxArmorBonus;
public static ConfigEntry<float> ThornsReflectPercent;
// ─── Root of the Elder (tier 3+, defensive piece) ─────────────────────
public static ConfigEntry<float> ElderRootHealth;
public static ConfigEntry<float> ElderRootSelfHealDelay;
public static ConfigEntry<float> ElderRootSelfHealPercentPerSecond;
public static ConfigEntry<float> ElderRootRepairRadius;
public static ConfigEntry<float> ElderRootRepairInterval;
// ─── Homecoming Portal (tier 6+) ──────────────────────────────────────
public static ConfigEntry<float> PortalCooldown;
public static ConfigEntry<float> PortalLifetime;
@ -113,6 +120,18 @@ namespace RacesOfValheim
ThornsReflectPercent = config.Bind(lastStand, "Thorns Reflect Percent", 0.2f,
new ConfigDescription("Fraction of every hit taken reflected back at the attacker, tier 5+.", new AcceptableValueRange<float>(0f, 1f)));
const string elderRoot = "Trenta - Root of the Elder";
ElderRootHealth = config.Bind(elderRoot, "Health", 300f,
new ConfigDescription("Max structural health of the piece itself.", new AcceptableValueRange<float>(50f, 2000f)));
ElderRootSelfHealDelay = config.Bind(elderRoot, "Self-Heal Delay", 10f,
new ConfigDescription("Seconds without taking a hit before the piece starts healing itself.", new AcceptableValueRange<float>(0f, 60f)));
ElderRootSelfHealPercentPerSecond = config.Bind(elderRoot, "Self-Heal Percent Per Second", 0.02f,
new ConfigDescription("Fraction of max health regained per second once healing starts.", new AcceptableValueRange<float>(0f, 1f)));
ElderRootRepairRadius = config.Bind(elderRoot, "Repair Radius", 5f,
new ConfigDescription("Meters from the piece within which every player-built thing gets repaired.", new AcceptableValueRange<float>(1f, 30f)));
ElderRootRepairInterval = config.Bind(elderRoot, "Repair Interval", 60f,
new ConfigDescription("Seconds between repair pulses.", new AcceptableValueRange<float>(5f, 600f)));
const string portal = "Trenta - Homecoming Portal";
PortalCooldown = config.Bind(portal, "Cooldown", 300f,
new ConfigDescription("Seconds between casts, tier 6+.", new AcceptableValueRange<float>(0f, 3600f)));

View file

@ -0,0 +1,306 @@
using HarmonyLib;
using Jotunn.Configs;
using Jotunn.Entities;
using Jotunn.Managers;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The Trenta's defensive piece: a gnarled root left over from the Elder, permanent once
/// planted, that heals itself and, once a minute, heals everything a player built within reach
/// of it too.
///
/// Full design in Trenta_ElderRoot.txt. Two facts from that document matter for reading this
/// file:
///
/// - WearNTear.Repair() and WearNTear.ApplyDamage(float, HitData) are both read from IL, not
/// guessed. Repair() is the same full-heal-and-broadcast the hammer itself uses.
/// ApplyDamage subtracts its float argument from current health and broadcasts the result -
/// a NEGATIVE amount heals, which is how the self-heal below works without a second RPC.
/// - Piece.IsPlacedByPlayer() is the filter, copied from Sverm/SvermWorker.cs (the mod's own
/// precedent for "heal player buildings in a radius"). Without it this piece would also try
/// to mend ruins, troll-cave walls and any other scenery that happens to carry a WearNTear.
///
/// The clone base and the strip pattern are TrolTotem's, unchanged: piece_workbench is a real
/// Piece (unlike the item-prefab trap that piece's own file documents), stripped to
/// Piece/ZNetView/WearNTear and given a borrowed look instead of the bench's own mesh.
/// </summary>
public static class TrentaElderRoot
{
public static void Register()
{
GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(
TrentaConfig.ElderRootPieceName, "piece_workbench");
if (prefab == null)
{
Jotunn.Logger.LogWarning("[Trenta] Could not clone piece_workbench; the Root of the Elder is not registered.");
return;
}
// Strip the workbench down to a placeable shell: no station, no crafting, no furniture.
// The look comes from the borrowed Vines model below.
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, TrentaConfig.ElderRootPieceName);
GameObject modelSource = ResolveModelSource();
if (modelSource != null)
{
ModelBorrow.Attach(prefab.transform, "RootModel", modelSource,
Vector3.zero, Quaternion.identity, TrentaConfig.ElderRootModelSize, "Trenta");
}
// Belt as well as braces, exactly as SvermHive.Register does after its own guard: even
// though ResolveModelSource never hands a Character to ModelBorrow, anything that could
// still act alive comes off the finished piece. This is the line that keeps the
// hammer-breaking failure (see ResolveModelSource) impossible rather than merely
// unlikely.
SvermHive.StripLife(prefab);
WearNTear wear = prefab.GetComponent<WearNTear>();
if (wear != null)
{
wear.m_health = TrentaConfig.ElderRootHealth;
wear.m_materialType = WearNTear.MaterialType.Wood;
}
prefab.AddComponent<TrentaElderRootBehaviour>();
Sprite icon = BorrowIcon(TrentaConfig.ElderRootRecipeGuck);
Piece piece = prefab.GetComponent<Piece>() ?? prefab.AddComponent<Piece>();
piece.m_craftingStation = null;
piece.m_resources = new Piece.Requirement[0];
piece.m_name = TrentaConfig.ElderRootDisplayName;
piece.m_canBeRemoved = true;
piece.m_groundPiece = true;
piece.m_groundOnly = true;
piece.m_icon = icon;
Piece template = PrefabManager.Cache.GetPrefab<Piece>("piece_workbench");
if (template != null && template.m_placeEffect != null) piece.m_placeEffect = template.m_placeEffect;
PieceManager.Instance.AddPiece(new CustomPiece(prefab, fixReference: false, new PieceConfig
{
Name = TrentaConfig.ElderRootDisplayName,
Description = "What the Elder left behind, still growing. Mends itself, and " +
"everything a player built close enough to it.",
PieceTable = PieceTables.Hammer,
Category = PieceCategories.Crafting,
Icon = icon,
Requirements = new[]
{
new RequirementConfig(TrentaConfig.ElderRootRecipeGuck, TrentaConfig.ElderRootRecipeGuckAmount, 0, true),
new RequirementConfig(TrentaConfig.ElderRootRecipeFineWood, TrentaConfig.ElderRootRecipeFineWoodAmount, 0, true),
}
}));
Jotunn.Logger.LogInfo($"[Trenta] Registered '{TrentaConfig.ElderRootPieceName}' " +
$"({TrentaConfig.ElderRootDisplayName}) on the hammer's Crafting page.");
}
/// <summary>
/// The model to borrow, with the creature carefully left behind.
///
/// TentaRoot is a CHARACTER (verified by its manifest path, Assets/Characters/...), and
/// handing a Character to ModelBorrow is the precise bug that once stopped the hammer
/// working for every piece in the game: ModelBorrow strips in ONE pass over
/// GetComponentsInChildren&lt;MonoBehaviour&gt;, and Unity refuses to destroy a component
/// another one still requires - "Can't remove Humanoid because CharacterDrop depends on
/// it". The Humanoid survives, every placement ghost wakes one, and
/// Character.GetCharactersInRange throws inside Player.UpdatePlacementGhost.
///
/// So the creature is never borrowed from directly. Its "Visual" child is - the node that
/// holds mesh and animator and nothing alive - which is the same route FenrirRace and
/// SkadiRace already take for every one of their transformations. If that child is missing
/// the answer is to attach nothing and say so, NOT to fall back to the creature: an
/// invisible piece is a cosmetic bug, a live Humanoid on a building is a broken hammer.
/// </summary>
private static GameObject ResolveModelSource()
{
string sourceName = TrentaConfig.ElderRootModelSourcePrefab;
GameObject source = PrefabManager.Cache.GetPrefab<GameObject>(sourceName);
if (source == null)
{
Jotunn.Logger.LogWarning($"[Trenta] No '{sourceName}' to borrow the Root's model from; " +
"the piece is registered without a model.");
return null;
}
Transform visual = source.transform.Find(TrentaConfig.CreatureVisualChildName);
if (visual != null)
{
Jotunn.Logger.LogInfo($"[Trenta] Root model taken from '{sourceName}/" +
$"{TrentaConfig.CreatureVisualChildName}' - the creature itself is left alone.");
return visual.gameObject;
}
// No Visual child. If the prefab is harmless scenery after all we can still use it;
// if it is alive we refuse, loudly, and the piece comes up invisible.
if (SvermHive.IsSafeScenery(source, sourceName))
{
Jotunn.Logger.LogInfo($"[Trenta] '{sourceName}' has no '{TrentaConfig.CreatureVisualChildName}' " +
"child but carries nothing alive; borrowing from it whole.");
return source;
}
Jotunn.Logger.LogWarning($"[Trenta] '{sourceName}' is alive and has no " +
$"'{TrentaConfig.CreatureVisualChildName}' child to borrow safely. " +
"The Root is registered WITHOUT a model rather than risking a live " +
"Character on a building - run `dumpelder " + sourceName + "` in the " +
"console to see its real hierarchy and name the right child here.");
return null;
}
private static Sprite BorrowIcon(string prefabName)
{
ItemDrop drop = PrefabManager.Cache.GetPrefab<ItemDrop>(prefabName);
Sprite[] icons = drop != null && drop.m_itemData != null && drop.m_itemData.m_shared != null
? drop.m_itemData.m_shared.m_icons
: null;
return icons != null && icons.Length > 0 ? icons[0] : null;
}
/// <summary>
/// Teaches the piece to the local player. Every dynamically cloned hammer piece in this mod
/// needs this - see the shared OnSpawned postfix in TrentaComposter.cs, which now calls this
/// too.
/// </summary>
public static void EnsureKnown(Player player)
{
if (player == null) return;
GameObject prefab = PrefabManager.Instance.GetPrefab(TrentaConfig.ElderRootPieceName);
Piece piece = prefab != null ? prefab.GetComponent<Piece>() : null;
if (piece == null) return;
Traverse traverse = Traverse.Create(player);
traverse.Method("AddKnownPiece", piece).GetValue();
traverse.Method("UpdateAvailablePiecesList").GetValue();
}
}
/// <summary>
/// Lives on the placed piece. Two independent jobs, both on the same tick cadence rules as the
/// rest of the mod: no coroutine, just Time.time comparisons in Update.
/// </summary>
public class TrentaElderRootBehaviour : MonoBehaviour
{
private WearNTear m_wear;
private float m_lastHitTime = -9999f;
private float m_nextRepairTick;
private void Start()
{
m_wear = GetComponent<WearNTear>();
if (m_wear != null) m_wear.m_onDamaged += OnHit;
m_nextRepairTick = Time.time + TrentaConfig.ElderRootRepairInterval;
}
private void OnDestroy()
{
if (m_wear != null) m_wear.m_onDamaged -= OnHit;
}
private void OnHit()
{
m_lastHitTime = Time.time;
}
private void Update()
{
TickSelfHeal();
if (Time.time >= m_nextRepairTick)
{
m_nextRepairTick = Time.time + TrentaConfig.ElderRootRepairInterval;
RunRepairPulse();
}
}
/// <summary>
/// The piece's own regeneration: unhurt for a while, then a fraction of max health back
/// every second. Cannot reuse SkeletonSentryBehaviour - that class heals a Character, and
/// this is a WearNTear, exactly the distinction SkeletonSentry.cs's own header explains for
/// why the Bound Sentry is cloned from a live creature rather than built as a piece.
///
/// ApplyDamage(float, HitData) has no built-in cap against m_health (read from its IL), so
/// the clamp against the remaining gap happens here, not inside the engine call.
/// </summary>
private void TickSelfHeal()
{
if (m_wear == null) return;
ZNetView nview = m_wear.GetComponent<ZNetView>();
if (nview == null || !nview.IsValid() || !nview.IsOwner()) return;
if (Time.time - m_lastHitTime < TrentaConfig.ElderRootSelfHealDelay) return;
float current = nview.GetZDO().GetFloat(ZDOVars.s_health, m_wear.m_health);
if (current >= m_wear.m_health) return;
float healThisFrame = TrentaConfig.ElderRootSelfHealPercentPerSecond * m_wear.m_health * Time.deltaTime;
healThisFrame = Mathf.Min(healThisFrame, m_wear.m_health - current);
if (healThisFrame > 0f) m_wear.ApplyDamage(-healThisFrame, null);
}
/// <summary>
/// Everything in range, in one pass - deliberately not the one-piece-per-tick pacing
/// Sverm/SvermWorker.cs uses for the same kind of aura. Kept different on purpose; see
/// Trenta_ElderRoot.txt sez. 4.2 before "fixing" this to match that precedent.
/// </summary>
private void RunRepairPulse()
{
foreach (Collider collider in Physics.OverlapSphere(transform.position, TrentaConfig.ElderRootRepairRadius))
{
if (collider == null) continue;
WearNTear otherWear = collider.GetComponentInParent<WearNTear>();
if (otherWear == null || otherWear == m_wear) continue;
Piece piece = otherWear.GetComponent<Piece>();
if (piece == null || !piece.IsPlacedByPlayer()) continue;
otherWear.Repair();
}
}
}
/// <summary>
/// Race lock plus the boss gate, in one prefix - same shape as TrolTotemRaceLockPatch, with a
/// second refusal added for the progression check the Root also needs.
/// </summary>
[HarmonyPatch(typeof(Player), "PlacePiece",
new[] { typeof(Piece), typeof(Vector3), typeof(Quaternion), typeof(bool) })]
public static class TrentaElderRootPlacementPatch
{
public static bool Prefix(Player __instance, Piece __0)
{
if (__instance != Player.m_localPlayer || __0 == null) return true;
if (Utils.GetPrefabName(__0.gameObject) != TrentaConfig.ElderRootPieceName) return true;
if (!TrentaRace.IsTrenta())
{
__instance.Message(MessageHud.MessageType.Center, "The root will not take hold for you.");
return false;
}
if (BossProgressionManager.GetCurrentProgressionState() < TrentaConfig.ElderRootUnlockState)
{
__instance.Message(MessageHud.MessageType.Center, "The Elder has not fallen yet.");
return false;
}
return true;
}
}
}

View file

@ -34,6 +34,7 @@ namespace RacesOfValheim
// before that catalogue is read.
TrentaComposter.Register();
TrentaHeartwoodGrove.Register();
TrentaElderRoot.Register();
}
/// <summary>

View file

@ -1,100 +1,163 @@
using System.Collections.Generic;
using System.Globalization;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The Trol's 4th and 5th stomach. The runtime side is two dictionaries; the persistent side
/// is four keys in Player.m_customData, which is the only per-character store Valheim writes
/// to disk (Player.Save/Player.Load pack it into the profile).
///
/// Two rules hold this file together, and both exist because breaking them ate people's food:
///
/// 1. Never write to m_customData from a path that cannot prove what it is looking at.
/// Removing a key here is not "failing to load" - it is a deletion from the save file.
/// 2. The two slots are independent. Slot 5 is not a continuation of slot 4 and must never
/// be gated behind slot 4 having something in it.
/// </summary>
public static class TrolFoodManager
{
// Runtime dictionary holding the 4th food slot per player
// Runtime dictionaries holding the 4th and 5th food slot per player
public static Dictionary<Player, Player.Food> ExtraFoods = new Dictionary<Player, Player.Food>();
public static Dictionary<Player, Player.Food> ExtraFoods5 = new Dictionary<Player, Player.Food>();
// Called when player spawns to load the 4th and 5th food from custom data
private const string Slot4Prefab = "TrolFood_Prefab";
private const string Slot4Time = "TrolFood_Time";
private const string Slot5Prefab = "TrolFood5_Prefab";
private const string Slot5Time = "TrolFood5_Time";
// Called when the player spawns, to restore both extra stomachs from custom data.
public static void LoadFood(Player player)
{
if (player == null) return;
// If they are no longer a Trol, clear it out
if (!TrolRace.IsTrol())
// GetPlayerRace returns null when the race cannot be read at all - ZDO empty AND no
// m_customData entry - and that is the case this method used to get catastrophically
// wrong. It asked TrolRace.IsTrol(), which answered a flat "no" during the spawn frame
// (see IsTrol's comment for why), and then called ClearFood on that "no", deleting all
// four keys. Every reload dropped the Trol's 4th and 5th stomach on the floor.
//
// Now only a race we actually READ, and that is not ours, may touch the save file.
// "I cannot tell yet" drops the runtime entries and leaves the disk alone.
string race = FactionHostilityPatch.GetPlayerRace(player);
if (race != "Trol")
{
ClearFood(player);
ExtraFoods.Remove(player);
ExtraFoods5.Remove(player);
if (race != null) ClearFood(player);
return;
}
if (!player.m_customData.ContainsKey("TrolFood_Prefab")) return;
LoadSlot(player, ExtraFoods, Slot4Prefab, Slot4Time);
LoadSlot(player, ExtraFoods5, Slot5Prefab, Slot5Time);
}
/// <summary>
/// Restores one slot. Called once per slot rather than once for both: slot 5 used to sit
/// inside slot 4's early return, so a Trol carrying food in the 5th stomach and nothing in
/// the 4th lost the 5th on every load, independently of everything else wrong here.
/// </summary>
private static void LoadSlot(Player player, Dictionary<Player, Player.Food> dict, string prefabKey, string timeKey)
{
dict.Remove(player);
if (!player.m_customData.TryGetValue(prefabKey, out string prefabName)) return;
if (ObjectDB.instance == null) return;
string prefabName = player.m_customData["TrolFood_Prefab"];
GameObject prefab = ObjectDB.instance.GetItemPrefab(prefabName);
if (prefab == null) return;
ItemDrop itemDrop = prefab.GetComponent<ItemDrop>();
if (itemDrop == null) return;
// Build food object
Player.Food food = new Player.Food();
food.m_item = itemDrop.m_itemData.Clone(); // Clone to be safe
// Try parse remaining time
if (player.m_customData.TryGetValue("TrolFood_Time", out string timeStr) && float.TryParse(timeStr, System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out float time))
float time = 0f;
if (player.m_customData.TryGetValue(timeKey, out string timeStr))
{
food.m_time = time;
float.TryParse(timeStr, NumberStyles.Float, CultureInfo.InvariantCulture, out time);
}
food.m_health = itemDrop.m_itemData.m_shared.m_food;
food.m_stamina = itemDrop.m_itemData.m_shared.m_foodStamina;
food.m_eitr = itemDrop.m_itemData.m_shared.m_foodEitr;
ExtraFoods[player] = food;
if (player.m_customData.ContainsKey("TrolFood5_Prefab"))
ItemDrop.ItemData.SharedData shared = itemDrop.m_itemData.m_shared;
// A meal that finished digesting is not restored, and its keys go with it - otherwise
// a stale pair could sit in the save forever, since UpdateFood only prunes what it can
// already see in the dictionaries.
if (shared.m_foodBurnTime > 0f && time >= shared.m_foodBurnTime)
{
string prefabName5 = player.m_customData["TrolFood5_Prefab"];
GameObject prefab5 = ObjectDB.instance.GetItemPrefab(prefabName5);
if (prefab5 != null)
{
ItemDrop itemDrop5 = prefab5.GetComponent<ItemDrop>();
if (itemDrop5 != null)
{
Player.Food food5 = new Player.Food();
food5.m_item = itemDrop5.m_itemData.Clone();
if (player.m_customData.TryGetValue("TrolFood5_Time", out string timeStr5) && float.TryParse(timeStr5, System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out float time5))
{
food5.m_time = time5;
}
food5.m_health = itemDrop5.m_itemData.m_shared.m_food;
food5.m_stamina = itemDrop5.m_itemData.m_shared.m_foodStamina;
food5.m_eitr = itemDrop5.m_itemData.m_shared.m_foodEitr;
ExtraFoods5[player] = food5;
}
}
player.m_customData.Remove(prefabKey);
player.m_customData.Remove(timeKey);
return;
}
Player.Food food = new Player.Food();
food.m_item = itemDrop.m_itemData.Clone();
food.m_item.m_stack = 1;
food.m_time = time;
// Restore the values the stomach actually had, not a fresh meal's. Same lerp
// Trol_PlayerUpdateFood_Patch runs every frame; without it a reload handed back full
// nourishment until the next tick corrected it.
float factor = shared.m_foodBurnTime > 0f ? Mathf.Clamp01(time / shared.m_foodBurnTime) : 0f;
food.m_health = Mathf.Lerp(shared.m_food, shared.m_food * 0.2f, factor);
food.m_stamina = Mathf.Lerp(shared.m_foodStamina, shared.m_foodStamina * 0.2f, factor);
food.m_eitr = Mathf.Lerp(shared.m_foodEitr, shared.m_foodEitr * 0.2f, factor);
dict[player] = food;
}
// Called to save the current runtime 4th food to custom data for persistence
// Saves the current runtime state of both extra stomachs. Authoritative: it is called from
// SetExtraFood/SetExtraFood5, where the dictionaries are known to be current, and it
// removes the keys of an empty slot on purpose. Do NOT call it from anywhere that could
// run before LoadFood has populated the dictionaries - use SaveFoodTimes there.
public static void SaveFood(Player player)
{
if (player == null) return;
if (ExtraFoods.TryGetValue(player, out Player.Food food) && food != null && food.m_item != null)
{
player.m_customData["TrolFood_Prefab"] = food.m_item.m_dropPrefab.name;
player.m_customData["TrolFood_Time"] = food.m_time.ToString(System.Globalization.CultureInfo.InvariantCulture);
player.m_customData[Slot4Prefab] = food.m_item.m_dropPrefab.name;
player.m_customData[Slot4Time] = food.m_time.ToString(CultureInfo.InvariantCulture);
}
else
{
player.m_customData.Remove("TrolFood_Prefab");
player.m_customData.Remove("TrolFood_Time");
player.m_customData.Remove(Slot4Prefab);
player.m_customData.Remove(Slot4Time);
}
if (ExtraFoods5.TryGetValue(player, out Player.Food food5) && food5 != null && food5.m_item != null)
{
player.m_customData["TrolFood5_Prefab"] = food5.m_item.m_dropPrefab.name;
player.m_customData["TrolFood5_Time"] = food5.m_time.ToString(System.Globalization.CultureInfo.InvariantCulture);
player.m_customData[Slot5Prefab] = food5.m_item.m_dropPrefab.name;
player.m_customData[Slot5Time] = food5.m_time.ToString(CultureInfo.InvariantCulture);
}
else
{
player.m_customData.Remove("TrolFood5_Prefab");
player.m_customData.Remove("TrolFood5_Time");
player.m_customData.Remove(Slot5Prefab);
player.m_customData.Remove(Slot5Time);
}
}
/// <summary>
/// Writes how far each stomach has digested, and nothing else. Called from a Player.Save
/// prefix, because the time was previously only ever written at the moment of eating -
/// always as 0 - so both extra stomachs came back from a reload at full duration while the
/// three vanilla slots kept their remaining time.
///
/// This updates existing entries and never removes a key. Player.Save can run at any
/// moment, including before OnSpawned has restored the dictionaries, and a save hook able
/// to empty the save file is the exact bug this file is recovering from.
/// </summary>
public static void SaveFoodTimes(Player player)
{
if (player == null) return;
WriteTime(player, ExtraFoods, Slot4Time);
WriteTime(player, ExtraFoods5, Slot5Time);
}
private static void WriteTime(Player player, Dictionary<Player, Player.Food> dict, string timeKey)
{
if (dict.TryGetValue(player, out Player.Food food) && food != null && food.m_item != null)
{
player.m_customData[timeKey] = food.m_time.ToString(CultureInfo.InvariantCulture);
}
}
@ -131,10 +194,10 @@ namespace RacesOfValheim
if (player == null) return;
ExtraFoods.Remove(player);
ExtraFoods5.Remove(player);
player.m_customData.Remove("TrolFood_Prefab");
player.m_customData.Remove("TrolFood_Time");
player.m_customData.Remove("TrolFood5_Prefab");
player.m_customData.Remove("TrolFood5_Time");
player.m_customData.Remove(Slot4Prefab);
player.m_customData.Remove(Slot4Time);
player.m_customData.Remove(Slot5Prefab);
player.m_customData.Remove(Slot5Time);
}
}
}

View file

@ -252,4 +252,22 @@ namespace RacesOfValheim
return true;
}
}
// m_customData only reaches the disk through Player.Save, and TrolFood_Time / TrolFood5_Time
// were only ever written at the moment of eating - always as 0. Both extra stomachs therefore
// came back from every reload with a full burn time ahead of them, digesting from scratch,
// while the three vanilla slots kept whatever they had left. Refreshing the two timestamps
// just before the package is packed puts all five on the same footing.
//
// A prefix, so the two keys are already in m_customData when Save packs it. SaveFoodTimes only
// updates keys that already exist and never removes one - see its comment for why that
// distinction matters here.
[HarmonyPatch(typeof(Player), nameof(Player.Save))]
public static class Trol_PlayerSave_Patch
{
public static void Prefix(Player __instance)
{
TrolFoodManager.SaveFoodTimes(__instance);
}
}
}

View file

@ -24,12 +24,26 @@ namespace RacesOfValheim
}
}
// The ZDO copy is authoritative once it has been written - but it is written by a
// Player.OnSpawned postfix in ZdoVisualSync that Harmony registers AFTER this race's own
// OnSpawned postfix (type 363 against type 319 in the built assembly), and the player's
// ZDO is a brand new empty one every session. So on every single load there is a window
// where m_customData is the only place the race exists, and returning out of the ZDO
// branch unconditionally made that window answer "not a Trol" - which is what had
// TrolFoodManager.LoadFood wiping the 4th and 5th stomach out of the save file on reload.
//
// Same fix, same reason, as FactionHostilityPatch.GetPlayerRace: only trust the ZDO
// string when it is non-empty. An explicit "Human" written by resetrace IS non-empty and
// still wins over a stale m_customData, which is the behaviour that fix was added for.
public static bool IsTrol()
{
if (Player.m_localPlayer == null) return false;
ZNetView nview = Player.m_localPlayer.GetComponent<ZNetView>();
if (nview != null && nview.IsValid())
return nview.GetZDO().GetString("RacesOfValheim_Race", "") == "Trol";
{
string zdoRace = nview.GetZDO().GetString("RacesOfValheim_Race", "");
if (!string.IsNullOrEmpty(zdoRace)) return zdoRace == "Trol";
}
return Player.m_localPlayer.m_customData.TryGetValue("Race", out string r) && r == "Trol";
}