Merge branch 'war-vulture' into main

Brings in the Sverm race, the War Vulture flying mount, and Skadi's
Crystal Golem (replacing the Hidden Hollow). Resolved conflicts:
AswidVisuals.cs took war-vulture's skeleton-eye-light rewrite with
main's attach/attack/sleep timing guard re-applied on top, and
RaceCompendium.cs kept main's rewritten race entries while folding in
war-vulture's Sverm/War Vulture pages and the new Claws paragraphs for
Aswid and Fenrir.
This commit is contained in:
kanym 2026-08-11 20:35:48 +02:00
commit 58f70f1a4c
57 changed files with 11362 additions and 1102 deletions

View file

@ -0,0 +1,69 @@
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The Claws of the Beast: the Bjorn claw, burned down to almost black.
///
/// Everything about how they behave - issued once, never dropped, back in hand the moment the
/// hands are free, tier damage as slash - lives in RaceClawSet. This file is only the Aswid's
/// half of the answer: which model, what colour, and when the race is wearing another body.
///
/// The tint is config rather than a constant because "almost black" is a look, not a number,
/// and it needs one pass in front of a mirror. It is applied to the item's own copies of the
/// model's materials, so the vanilla weapon is untouched for everyone else.
/// </summary>
public class AswidClaws : RaceClawSet
{
public static readonly AswidClaws Instance = new AswidClaws();
public override string RaceId => "Aswid";
public override string ItemName => "AswidBeastClaws";
public override string DisplayName => "Claws of the Beast";
public override string Description => "Grown in the dark, and darker for it. They do not come off.";
// The Bjorn claw first, by name, because that is the one this race is meant to wear. The
// rest are the near-identical ids the manifest also carries - see SvermConfig's own
// fallback list for why a single name is not trusted here.
public override string[] ModelPrefabs => new[]
{
"FistBjornClaw",
"FistBjornUndeadClaw",
"FistBjornClawUndead",
"FistUnbjornClaw",
};
/// <summary>Published by AswidRace.UpdateAswidState, so a remote Aswid claws at its own tier.</summary>
public override string StateZdoKey => "RacesOfValheim_AswidState";
public override Color? Tint => new Color(
AswidConfig.ClawTintRed.Value,
AswidConfig.ClawTintGreen.Value,
AswidConfig.ClawTintBlue.Value,
1f);
/// <summary>
/// A bat and a bank of mist have no hands. IsTransformed is the local player's own flag;
/// the two ZDO booleans are how AswidPatches already publishes the same thing for everyone
/// else, which is what makes this answer correctly for a remote attacker.
/// </summary>
public override bool IsTransformed(Player player)
{
if (player == null) return false;
if (player == Player.m_localPlayer && AswidRace.Instance != null && AswidRace.Instance.IsTransformed)
{
return true;
}
ZNetView nview = player.GetComponent<ZNetView>();
if (nview != null && nview.IsValid())
{
return nview.GetZDO().GetBool("Aswid_IsBatForm", false) ||
nview.GetZDO().GetBool("Aswid_IsMistForm", false);
}
return false;
}
}
}

View file

@ -60,6 +60,41 @@ namespace RacesOfValheim
public static ConfigEntry<float> EnslaveCooldown;
public static ConfigEntry<float> ThrallLifetime;
// ─── Eyes ──────────────────────────────────────────────────────────────
// The Aswid wears the vanilla skeleton's eye lights (AswidVisuals), and where a borrowed
// object sits on a borrowed rig is not something to get right by reasoning about it. All
// of these read live, so they can be dragged in Configuration Manager while looking at the
// face. Once the pose settles they could collapse back into constants, the same way the
// mandible's did - but unlike the mandible these are worth keeping, because the source
// creature and the colour are genuine preferences.
public static ConfigEntry<string> EyeSourceModel;
public static ConfigEntry<int> EyeFinalStage;
public static ConfigEntry<float> EarlyEyeColorRed;
public static ConfigEntry<float> EarlyEyeColorGreen;
public static ConfigEntry<float> EarlyEyeColorBlue;
public static ConfigEntry<float> EarlyEyeGlowStrength;
public static ConfigEntry<float> EyeColorRed;
public static ConfigEntry<float> EyeColorGreen;
public static ConfigEntry<float> EyeColorBlue;
public static ConfigEntry<float> EyeGlowStrength;
public static ConfigEntry<float> EyeSizeMultiplier;
public static ConfigEntry<float> EyeForwardOffset;
public static ConfigEntry<float> EyeHeightOffset;
public static ConfigEntry<float> EyeSeparationOffset;
public static ConfigEntry<float> EyeRotationX;
public static ConfigEntry<float> EyeRotationY;
public static ConfigEntry<float> EyeRotationZ;
public static ConfigEntry<bool> EyeSmoke;
public static ConfigEntry<bool> EyeFlatColorShader;
// ─── Claws of the Beast ────────────────────────────────────────────────
// The tint the Bjorn claw is worn at (AswidClaws). Config rather than a constant because
// "almost black" is a look and not a number, and it multiplies the model's own texture, so
// what a given value looks like depends on the model. Reads live.
public static ConfigEntry<float> ClawTintRed;
public static ConfigEntry<float> ClawTintGreen;
public static ConfigEntry<float> ClawTintBlue;
public static void Bind(ConfigFile config)
{
const string keybinds = "Aswid - Keybinds";
@ -134,6 +169,109 @@ namespace RacesOfValheim
new ConfigDescription("Seconds between dominating a creature, tier 6+.", new AcceptableValueRange<float>(0f, 3600f)));
ThrallLifetime = config.Bind(domination, "Thrall Lifetime", 60f,
new ConfigDescription("Seconds a dominated thrall survives before it dies on its own.", new AcceptableValueRange<float>(10f, 600f)));
BindEyes(config);
BindClaws(config);
}
/// <summary>
/// The Claws of the Beast. Only their colour is tunable: everything about how they behave
/// is shared with the Fenrir's and the Sverm's, and a race that could quietly retune its
/// own claw damage would defeat the point of balancing the three against one yardstick.
/// </summary>
private static void BindClaws(ConfigFile config)
{
const string claws = "Aswid - Claws";
ClawTintRed = config.Bind(claws, "Claw Tint Red", 0.12f,
new ConfigDescription("Multiplied into the claw model's own colours. All three near zero is what makes them read as almost black.",
new AcceptableValueRange<float>(0f, 1f), new ConfigurationManagerAttributes { Order = 30 }));
ClawTintGreen = config.Bind(claws, "Claw Tint Green", 0.11f,
new ConfigDescription("As above, green channel.",
new AcceptableValueRange<float>(0f, 1f), new ConfigurationManagerAttributes { Order = 29 }));
ClawTintBlue = config.Bind(claws, "Claw Tint Blue", 0.13f,
new ConfigDescription("As above, blue channel. A shade above the other two keeps the black cold rather than muddy.",
new AcceptableValueRange<float>(0f, 1f), new ConfigurationManagerAttributes { Order = 28 }));
}
/// <summary>
/// The eye lights. Everything here is read every frame by AswidVisuals, so a slider moves
/// the eyes while you are looking at them - no relog, no equipment change.
///
/// The offsets are deltas on the pose the source creature authored its own eyes at, which
/// is why they all default to zero: zero means "exactly where the game's skeleton wears
/// them", and that is already the right place for a face on this rig.
/// </summary>
private static void BindEyes(ConfigFile config)
{
const string eyes = "Aswid - Eyes";
EyeSourceModel = config.Bind(eyes, "Eye Source Model", "Skeleton",
new ConfigDescription(
"Which creature's eye lights to wear. The plain skeleton's are smaller and dimmer than the poison one's; Hildir's are its own. Changing this rebuilds the pair.",
new AcceptableValueList<string>("Skeleton", "Skeleton_Poison", "Skeleton_Hildir"),
new ConfigurationManagerAttributes { Order = 100 }));
EyeFinalStage = config.Bind(eyes, "Eye Final Stage", 8,
new ConfigDescription("The progression state at which the eyes turn red. Below it they burn the spectral green set out just under here; 8 is Fader, the last one.",
new AcceptableValueRange<int>(1, 8), new ConfigurationManagerAttributes { Order = 95 }));
EarlyEyeColorRed = config.Bind(eyes, "Early Eye Colour Red", 0.08f,
new ConfigDescription("Red channel of the pre-final tint. Near zero: what little there is only keeps the green from reading as pure cyan.",
new AcceptableValueRange<float>(0f, 8f), new ConfigurationManagerAttributes { Order = 94 }));
EarlyEyeColorGreen = config.Bind(eyes, "Early Eye Colour Green", 1.4f,
new ConfigDescription("Green channel of the pre-final tint - the one doing the work.",
new AcceptableValueRange<float>(0f, 8f), new ConfigurationManagerAttributes { Order = 93 }));
EarlyEyeColorBlue = config.Bind(eyes, "Early Eye Colour Blue", 0.5f,
new ConfigDescription("Blue channel of the pre-final tint. A third of the green is what makes it read as cold and spectral rather than as a leaf.",
new AcceptableValueRange<float>(0f, 8f), new ConfigurationManagerAttributes { Order = 92 }));
EarlyEyeGlowStrength = config.Bind(eyes, "Early Eye Glow Strength", 0.8f,
new ConfigDescription("How bright the green burns. Deliberately below the red's, so arriving at the last stage is a visible change and not just a hue swap.",
new AcceptableValueRange<float>(0f, 3f), new ConfigurationManagerAttributes { Order = 91 }));
EyeColorRed = config.Bind(eyes, "Eye Colour Red", 2f,
new ConfigDescription("Red channel of the final-stage tint. Past 1 is HDR, which is what the bloom pass needs to make it glow rather than merely be red.",
new AcceptableValueRange<float>(0f, 8f), new ConfigurationManagerAttributes { Order = 90 }));
EyeColorGreen = config.Bind(eyes, "Eye Colour Green", 0.05f,
new ConfigDescription("Green channel of the final-stage tint. Near zero is what keeps a bright red from washing out to pink.",
new AcceptableValueRange<float>(0f, 8f), new ConfigurationManagerAttributes { Order = 89 }));
EyeColorBlue = config.Bind(eyes, "Eye Colour Blue", 0.02f,
new ConfigDescription("Blue channel of the final-stage tint. Near zero, same reason as green.",
new AcceptableValueRange<float>(0f, 8f), new ConfigurationManagerAttributes { Order = 88 }));
EyeGlowStrength = config.Bind(eyes, "Eye Glow Strength", 1f,
new ConfigDescription("How bright the final-stage red burns - the single knob for it, since the hue is already pure. Expect a floor: below the bloom threshold the eyes stop glowing and become flat dots.",
new AcceptableValueRange<float>(0f, 3f), new ConfigurationManagerAttributes { Order = 87 }));
EyeSizeMultiplier = config.Bind(eyes, "Eye Size Multiplier", 1f,
new ConfigDescription("Scales both sockets. 1 is the size the source creature wears them at.",
new AcceptableValueRange<float>(0.1f, 5f), new ConfigurationManagerAttributes { Order = 80 }));
EyeForwardOffset = config.Bind(eyes, "Eye Forward Offset", 0f,
new ConfigDescription("Moves both eyes out of (or into) the face. 0 leaves them where the source creature wears them.",
new AcceptableValueRange<float>(-0.1f, 0.1f), new ConfigurationManagerAttributes { Order = 70 }));
EyeHeightOffset = config.Bind(eyes, "Eye Height Offset", 0f,
new ConfigDescription("Moves both eyes up or down the face.",
new AcceptableValueRange<float>(-0.1f, 0.1f), new ConfigurationManagerAttributes { Order = 69 }));
EyeSeparationOffset = config.Bind(eyes, "Eye Separation Offset", 0f,
new ConfigDescription("Pushes the two eyes apart (or together). Each moves away from the centre of the face, so this is half the change in the gap.",
new AcceptableValueRange<float>(-0.1f, 0.1f), new ConfigurationManagerAttributes { Order = 68 }));
EyeRotationX = config.Bind(eyes, "Eye Rotation X", 0f,
new ConfigDescription("Turns both eyes on the spot. Only matters if the borrowed socket is flat enough to be seen edge-on.",
new AcceptableValueRange<float>(-180f, 180f), new ConfigurationManagerAttributes { Order = 60 }));
EyeRotationY = config.Bind(eyes, "Eye Rotation Y", 0f,
new ConfigDescription("As above, around the second axis.",
new AcceptableValueRange<float>(-180f, 180f), new ConfigurationManagerAttributes { Order = 59 }));
EyeRotationZ = config.Bind(eyes, "Eye Rotation Z", 0f,
new ConfigDescription("As above, around the third axis.",
new AcceptableValueRange<float>(-180f, 180f), new ConfigurationManagerAttributes { Order = 58 }));
EyeSmoke = config.Bind(eyes, "Eye Smoke", true,
new ConfigDescription("Lights the smoke the creature carries inside its own sockets and leaves switched off. Tinted to match the eyes, so it turns with them at the last stage.",
null, new ConfigurationManagerAttributes { Order = 50 }));
EyeFlatColorShader = config.Bind(eyes, "Eye Flat Colour Shader", false,
new ConfigDescription("Escape hatch: if the borrowed material refuses the red tint, this repaints the sockets with a plain colour shader instead - guaranteed red, but the socket loses its own texture. Changing this rebuilds the pair.",
null, new ConfigurationManagerAttributes { Order = 49 }));
}
}
}

View file

@ -90,6 +90,13 @@ namespace RacesOfValheim
CreateFoodItems();
AswidBloodRefinery.Register();
// Registered HERE and not lazily from the maintain tick: this method runs on
// PrefabManager.OnVanillaPrefabsAvailable, which is the one moment Jotunn will take a
// new item into ObjectDB. Registered later, the prefab is built and logged and looks
// entirely healthy - and then nobody can spawn it, which is exactly how the first
// version of the claws failed: two empty hands and a log full of success.
AswidClaws.Instance.EnsureRegistered();
GameObject geirrhafa = Jotunn.Managers.PrefabManager.Cache.GetPrefab<GameObject>("Fenring_Cultist_Hildir");
if (geirrhafa != null)
{

View file

@ -1,16 +1,28 @@
using System.Collections.Generic;
using Jotunn.Managers;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The Aswid's glowing eyes: two small emissive spheres burned into the face, evil red.
/// The Aswid's burning eyes: the vanilla skeleton's own eye lights, worn spectral green until
/// the last tier and red once it arrives.
///
/// Built the same way the Dvergar's eyes are (see DvergarVisuals.ApplyEyes) and for the same
/// reason - a player's eyes are painted into the skin texture, and Custom/Player has no
/// emission channel to light them with. The geometry is shared work: both races render on the
/// plain human rig (Aswid tints it, same as Dvergar), so the head bone, its axes, and the
/// spherical-cap placement trick all carry over unchanged. Only the numbers differ, because an
/// Aswid stands at normal human scale most of the time instead of the Dvergar's 0.78.
/// They used to be two spheres built from scratch on an Unlit/Color shader, the same trick the
/// Dvergar and the Sverm still use, because a player's eyes are painted into the skin texture
/// and Custom/Player has no emission channel to light them with. Those spheres were fine and
/// they were also obviously spheres. What the game already has is better: the creature named
/// 'Skeleton' carries two objects, eye_l and eye_r, parented to its Head bone and drawn with a
/// material built for exactly this - a lit socket seen from any angle.
///
/// Borrowing them is cheap because the skeleton is skinned to the player's own rig: its Head
/// bone is our Head bone, so the local pose those two objects were authored at lands on a
/// player's face without a single measurement. The placement config below is deltas on top of
/// that pose, not a placement of its own, and 0 means "wherever the game put them".
///
/// Only the Aswid is changed by this file. The Dvergar (DvergarVisuals) and the Sverm
/// (SvermVisuals) keep their own spheres - they each own a copy of the sphere code, so nothing
/// here reaches them.
///
/// Runs for local and remote players alike, which is why it takes a Player rather than reading
/// Player.m_localPlayer.
@ -19,65 +31,19 @@ namespace RacesOfValheim
{
private const string EyesName = "AswidEyes";
// ─── Glow colour ────────────────────────────────────────────────────
// HDR on purpose - past 1 is what makes the bloom pass pick these up at all - but only
// just past it. The first attempt used (6, 0.08, 0.03) at full strength and came out as a
// white headlamp with a red halo: bloom spreads the excess outward and saturates the core,
// so beyond a point more brightness buys nothing but a bigger white disc and *less* red.
// The Dvergar hit this exact wall and answered it by dimming, which is the same answer
// here.
//
// The near-zero green and blue are what keep it red rather than pink as it brightens.
// Not tied to star tier: unlike the Dvergar, whose colour borrows a real creature's
// progression, the Aswid has no such reference to read from.
public static readonly Color EvilEyeColor = new Color(4f, 0.06f, 0.02f, 1f);
// Darker than the Dvergar's 0.3, which put the red at an effective 1.2 - above 1, so the
// core clipped to a flat saturated red and the shade was decided by the clip rather than
// by the colour. 0.2 lands it at 0.8: under the clip, so the red keeps its depth and reads
// as blood rather than as a warning light.
//
// This is the one knob for how dark the eyes are - the hue is already pure red, so with
// green and blue at zero there is nothing left to darken *except* the intensity. Lower it
// further for deeper, but expect a floor: bloom only picks up what is bright enough to
// pass its threshold, so far enough down the eyes stop glowing and become flat dots.
public static readonly float EyeGlowStrength = 0.2f;
// ─── Placement ──────────────────────────────────────────────────────
// The Dvergar's numbers, carried over unchanged. That is not laziness - it is the only
// correct conversion, and the arithmetic says so:
//
// local offset = config x scale x (1 / headBone.lossyScale)
// lossyScale = 100 (the armature's authored scale) x scale
// => config x scale / (100 x scale) = config / 100
//
// The scale cancels. These constants live in the *unscaled* rig's units, and the face they
// have to land on shrinks and grows by exactly the same factor, so the same config value
// lands on the same part of the face at any size. Both races render on the plain human
// rig, so the Dvergar's tuning transfers verbatim.
//
// The first version of this file rescaled them by 0.78 on the theory that the Dvergar's
// values were "pre-shrink" and needed converting up to human size. They are not, and it
// put the eyes 18mm deeper and 40mm lower in rig units - on a human skull, the drop from
// the eye line to the mouth.
//
// What this also means: the Fader-tier +10% (Aswid_PlayerUpdate_Patch in AswidPatches.cs)
// needs no special case. It is not that the multiply handles it - the multiply cancels
// out. It is that the offsets are expressed in the head bone's own local space, and a
// child transform rides its parent's scale for free.
public static readonly float EyeSeparation = 0.032f; // half the distance between them
public static readonly float EyeForward = 0.081f; // centre out from the head bone
public static readonly float EyeHeight = 0.181f; // up from the head bone
public static readonly float EyeSize = 0.0558f; // 0.062 x 0.9 - across, so a 24mm radius at 0.78
// Carried over from the Dvergar's own tuning on this same rig: the face is not flat, so
// two eyes placed symmetrically do not come out looking symmetrical. May need a pass in
// game to confirm it holds at Aswid's own scale - flip to index 1 in PlaceEyes if it turns
// out to be the wrong eye.
public static readonly float LeftEyeSizeMultiplier = 0.85f;
// The two objects to look for inside whichever creature the config points at. Both vanilla
// skeletons carry this pair; the material differs (skeleton_eye vs skeleton_eye_big) and
// that difference is the whole reason the source is a config and not a constant.
private static readonly string[] SourceEyeNames = { "eye_l", "eye_r" };
public const string PlayerHeadBoneName = "Head";
// ─── Placement, and why the numbers are unitless ─────────────────────
// The offsets below are applied as: local offset = config x scale x (1 / headBone.lossyScale)
// and lossyScale is the armature's authored 100x times the player's own scale, so the
// scale cancels and a given config value lands on the same part of the face at any size -
// Fader-tier growth included. Kept in the arithmetic because it is honest about intent.
// ─── Race check ─────────────────────────────────────────────────────
/// <summary>
@ -104,21 +70,59 @@ namespace RacesOfValheim
/// <summary>
/// The skull's own idea of forward, up and right, measured once while the head is still
/// looking where the body is. Kept on the eye holder so it survives as long as the eyes
/// do, and so nothing is tempted to work it out again from a rig that has since moved.
/// looking where the body is, plus what the eyes currently in place were built from. Kept
/// on the eye holder so it survives as long as the eyes do, and so nothing is tempted to
/// work it out again from a rig that has since moved.
/// </summary>
private class EyeFrame : MonoBehaviour
{
public Vector3 LocalForward = Vector3.forward;
public Vector3 LocalUp = Vector3.up;
public Vector3 LocalRight = Vector3.right;
// What these eyes were cloned from, and whether they were flattened onto a plain
// colour shader. Either one changing in Configuration Manager means the pair has to be
// built again rather than merely moved.
public string SourceModel = "";
public bool FlatShader;
}
private static Shader cachedGlowShader;
private static bool glowShaderResolved;
/// <summary>The pose an eye was authored at on the creature. Everything else is a delta on this.</summary>
private class EyeBase : MonoBehaviour
{
public Vector3 Position;
public Quaternion Rotation = Quaternion.identity;
public Vector3 Scale = Vector3.one;
}
/// <summary>
/// Keeps two small emissive spheres burning over the player's painted-on eyes. Safe to call
/// Reapplies the eyes every frame, which is what makes the Configuration Manager sliders
/// move them while you watch. Added to a player once they turn out to be an Aswid and
/// destroyed when they stop being one; VisEquipment's own refresh is what puts it back.
/// </summary>
public class EyeTicker : MonoBehaviour
{
private Player m_player;
private void Awake()
{
m_player = GetComponent<Player>();
}
private void LateUpdate()
{
if (m_player == null)
{
Destroy(this);
return;
}
ApplyEyes(m_player);
}
}
/// <summary>
/// Keeps the pair of lit sockets burning over the player's painted-on eyes. Safe to call
/// for anyone: it removes them again from whoever is not a living Aswid.
///
/// Parented straight onto the head bone rather than Character.m_eye - the Dvergar tried
@ -144,38 +148,51 @@ namespace RacesOfValheim
eyes.name = EyesName + "_Removed";
Object.Destroy(eyes.gameObject);
}
EyeTicker ticker = player.GetComponent<EyeTicker>();
if (ticker != null) Object.Destroy(ticker);
return;
}
if (player.GetComponent<EyeTicker>() == null)
{
player.gameObject.AddComponent<EyeTicker>();
}
// A different source creature, or the shader override being flipped, changes what the
// eyes are rather than where they sit - so the pair is thrown away and built again.
if (eyes != null)
{
EyeFrame existing = eyes.GetComponent<EyeFrame>();
if (existing == null ||
existing.SourceModel != AswidConfig.EyeSourceModel.Value ||
existing.FlatShader != AswidConfig.EyeFlatColorShader.Value)
{
eyes.name = EyesName + "_Removed";
Object.Destroy(eyes.gameObject);
eyes = null;
}
}
if (eyes == null)
{
// BuildEyes measures which way the skull faces from the head bone's pose at this
// exact instant (see the frame comment above it) - a one-time reading, cached for
// as long as the eyes exist. Taken while sitting, attached to something, mid-attack
// or asleep, the head can be tilted or turned away from the body's own forward, and
// the snap-to-axis picks whichever axis is closest to THAT pose - which is how eyes
// ended up behind the skull instead of on the face. Waiting for a plain standing
// pose costs nothing (ApplyEyes runs again on the next UpdateColors either way) and
// this is the only place in the whole flow where the timing actually matters.
// BuildEyes takes a one-time reading of the head bone's pose to work out which way
// the skull faces, and caches it for as long as the eyes exist. Sitting, attached,
// mid-attack or asleep, the head can be turned away from the body's own forward at
// that instant, which is how the snap-to-axis has picked the wrong side and left
// the eyes behind the skull before (see DvergarVisuals.ApplyEyes). Waiting for a
// plain standing pose costs nothing - ApplyEyes runs again on the next tick either
// way.
if (player.IsAttached() || player.IsAttachedToShip() || player.InAttack() || player.IsSleeping())
{
return;
}
eyes = BuildEyes(headBone);
eyes = BuildEyes(player, headBone);
}
if (eyes == null) return; // already logged once by the resolver
if (eyes == null) return; // already logged once by the builder
PlaceEyes(player, headBone, eyes);
Color glow = GetEyeColor();
foreach (Renderer renderer in eyes.GetComponentsInChildren<Renderer>(true))
{
Material material = renderer.material;
if (material == null) continue;
material.color = glow;
if (material.HasProperty("_EmissionColor")) material.SetColor("_EmissionColor", glow);
}
PaintEyes(eyes, GetEyeColor(player));
}
/// <summary>
@ -183,21 +200,29 @@ namespace RacesOfValheim
/// DvergarVisuals.FindHeadBone for why: the avatar's HumanBodyBones.Head moves with the
/// player but ignores the head's own idle animation, and only VisEquipment.m_bodyModel's
/// own bone array is the one the skinned mesh - and every animation - actually drives.
///
/// THE ANIMATOR'S HEAD IS NOT AN ACCEPTABLE ANSWER, and this used to fall back to it
/// "so that something renders if the body model is not up yet". That fallback is what put
/// the eyes at the wrong height: the avatar's HumanBodyBones.Head is a DIFFERENT transform,
/// sitting at a different place in the hierarchy, so a holder parented to it hangs at the
/// wrong height for as long as it lives - and it lives until the player changes race. It
/// only ever bit once the claws landed, because equipping an item on spawn moved the first
/// build a few frames earlier, into the window where the body model is not up yet.
///
/// Returning null costs nothing: the ticker calls this again next frame, and a frame with
/// no eyes is invisible next to a session with them on the jaw.
/// </summary>
private static Transform FindHeadBone(Player player)
{
VisEquipment visEq = player.GetComponent<VisEquipment>();
if (visEq != null && visEq.m_bodyModel != null && visEq.m_bodyModel.bones != null)
if (visEq == null || visEq.m_bodyModel == null || visEq.m_bodyModel.bones == null) return null;
foreach (Transform bone in visEq.m_bodyModel.bones)
{
foreach (Transform bone in visEq.m_bodyModel.bones)
{
if (bone != null && bone.name == PlayerHeadBoneName) return bone;
}
if (bone != null && bone.name == PlayerHeadBoneName) return bone;
}
// Last resort, and only so that something renders if the body model is not up yet.
Animator animator = player.GetComponentInChildren<Animator>();
return animator != null ? animator.GetBoneTransform(HumanBodyBones.Head) : null;
return null;
}
/// <summary>
@ -208,25 +233,55 @@ namespace RacesOfValheim
/// </summary>
private static float GetPlayerScale(Player player) => player.transform.localScale.x;
private static Color GetEyeColor()
/// <summary>
/// The tier this particular Aswid is rendering at. Off the ZDO, so a remote player's eyes
/// burn at their own standing rather than at ours; without one - the main-menu preview -
/// fall back to what this client can work out, the same fallback the Skeleton's visuals
/// make (SkeletonVisuals.GetProgressionState).
/// </summary>
private static int GetProgressionState(Player player)
{
float strength = EyeGlowStrength;
return new Color(
EvilEyeColor.r * strength,
EvilEyeColor.g * strength,
EvilEyeColor.b * strength,
EvilEyeColor.a);
ZNetView nview = player != null ? player.GetComponent<ZNetView>() : null;
if (nview != null && nview.IsValid())
{
return nview.GetZDO().GetInt("RacesOfValheim_AswidState", 0);
}
return BossProgressionManager.GetCurrentProgressionState();
}
/// <summary>
/// Puts the two eyes where the face is, in the head bone's own coordinates, every frame.
/// See DvergarVisuals.PlaceEyes for the full derivation of the axes.
/// Spectral green for as long as the Aswid is still becoming one, and red only at the end.
///
/// The scale term is kept for the Dvergar's sake and because it is honest about intent,
/// but it does not do the work it looks like it does: lossyScale already contains the
/// player's scale, so the multiply and the divide cancel and the local offset is simply
/// config/100 at every size. Growth is handled by the parenting, not by this arithmetic -
/// see the note on the placement constants above.
/// The red was the colour from the start and it reads as arrival, so it is worth not
/// spending it early: every tier below the last burns a cold green instead, dimmer on
/// purpose - the green is the eyes of something dead, the red is the eyes of something
/// that has finished feeding. Each has its own brightness rather than sharing one, because
/// "not too bright" is exactly the difference between them.
/// </summary>
private static Color GetEyeColor(Player player)
{
bool final = GetProgressionState(player) >= AswidConfig.EyeFinalStage.Value;
float strength = final
? AswidConfig.EyeGlowStrength.Value
: AswidConfig.EarlyEyeGlowStrength.Value;
Color hue = final
? new Color(AswidConfig.EyeColorRed.Value, AswidConfig.EyeColorGreen.Value, AswidConfig.EyeColorBlue.Value)
: new Color(AswidConfig.EarlyEyeColorRed.Value, AswidConfig.EarlyEyeColorGreen.Value, AswidConfig.EarlyEyeColorBlue.Value);
return new Color(hue.r * strength, hue.g * strength, hue.b * strength, 1f);
}
/// <summary>
/// Moves each eye off the pose it was authored at, by the config's deltas, in the head
/// bone's own coordinates. Every value at 0 (and size at 1) leaves them exactly where the
/// game's own skeleton wears them, which is the intended starting point.
///
/// See DvergarVisuals.PlaceEyes for the full derivation of the axes: they are measured
/// once at build time and snapped to the skull's square axes, because the raw measurement
/// is taken at whatever pose the head happens to hold that frame and arrives tilted.
/// </summary>
private static void PlaceEyes(Player player, Transform headBone, Transform holder)
{
@ -238,27 +293,69 @@ namespace RacesOfValheim
EyeFrame frame = holder.GetComponent<EyeFrame>();
if (frame == null) return;
Vector3 localForward = frame.LocalForward;
Vector3 localUp = frame.LocalUp;
Vector3 localRight = frame.LocalRight;
float scale = GetPlayerScale(player) * toLocal;
float scale = GetPlayerScale(player);
Vector3 baseLocal = localForward * (EyeForward * scale * toLocal)
+ localUp * (EyeHeight * scale * toLocal);
Vector3 shift = frame.LocalForward * (AswidConfig.EyeForwardOffset.Value * scale)
+ frame.LocalUp * (AswidConfig.EyeHeightOffset.Value * scale);
float eyeLocalSize = EyeSize * scale * toLocal;
Quaternion twist = Quaternion.Euler(
AswidConfig.EyeRotationX.Value,
AswidConfig.EyeRotationY.Value,
AswidConfig.EyeRotationZ.Value);
for (int i = 0; i < holder.childCount; i++)
{
Transform eye = holder.GetChild(i);
EyeBase authored = eye.GetComponent<EyeBase>();
if (authored == null) continue;
// Index 0 is offset against the right axis, so it is the model's left eye - the
// one on your right as you face it.
float side = i == 0 ? -1f : 1f;
float size = i == 0 ? eyeLocalSize * LeftEyeSizeMultiplier : eyeLocalSize;
// Which way "outwards" is for this particular eye, read from where the creature
// put it rather than from the order the children happen to be in. Widening then
// pushes both eyes apart whichever one this is.
float side = Mathf.Sign(Vector3.Dot(authored.Position, frame.LocalRight));
if (side == 0f) side = i == 0 ? -1f : 1f;
eye.localPosition = baseLocal + localRight * (side * EyeSeparation * scale * toLocal);
eye.localScale = Vector3.one * size;
eye.localPosition = authored.Position + shift +
frame.LocalRight * (side * AswidConfig.EyeSeparationOffset.Value * scale);
eye.localRotation = twist * authored.Rotation;
eye.localScale = authored.Scale * AswidConfig.EyeSizeMultiplier.Value;
}
}
/// <summary>
/// Tints the borrowed material red - the one thing about these eyes that is not the
/// skeleton's.
///
/// Every colour property the shader turns out to have is written, rather than guessing
/// which one it uses: a Valheim VFX material can carry _Color, _TintColor, _EmissionColor
/// or none of them, and writing a property a shader does not have is an error while
/// writing all of the ones it does is free.
/// </summary>
private static void PaintEyes(Transform holder, Color glow)
{
bool smoke = AswidConfig.EyeSmoke.Value;
foreach (Renderer renderer in holder.GetComponentsInChildren<Renderer>(true))
{
Material material = renderer.material;
if (material == null) continue;
if (material.HasProperty("_Color")) material.SetColor("_Color", glow);
if (material.HasProperty("_TintColor")) material.SetColor("_TintColor", glow);
if (material.HasProperty("_BaseColor")) material.SetColor("_BaseColor", glow);
if (material.HasProperty("_EmissionColor")) material.SetColor("_EmissionColor", glow);
}
// The smoke curling out of the sockets is authored on the creature but left switched
// off there, waiting for a script that this clone does not have. Off by default here
// too: it is a much louder effect than the glow itself.
foreach (ParticleSystem ps in holder.GetComponentsInChildren<ParticleSystem>(true))
{
if (ps.gameObject.activeSelf != smoke) ps.gameObject.SetActive(smoke);
if (!smoke) continue;
ParticleSystem.MainModule main = ps.main;
main.startColor = new ParticleSystem.MinMaxGradient(glow);
}
}
@ -277,10 +374,18 @@ namespace RacesOfValheim
return new Vector3(0f, 0f, Mathf.Sign(direction.z));
}
private static Transform BuildEyes(Transform headBone)
private static Transform BuildEyes(Player player, Transform headBone)
{
Shader glow = ResolveGlowShader();
if (glow == null) return null;
string modelName = AswidConfig.EyeSourceModel.Value;
List<Transform> sources = FindSourceEyes(modelName);
if (sources.Count == 0) return null; // already logged once by the finder
// Anything of ours left anywhere else on this player goes first. ApplyEyes only ever
// looks under the head bone, so a holder that ended up on some other transform is
// invisible to it - it would build a second pair beside the wrong one rather than
// replace it. That is exactly the state the animator fallback used to leave behind.
SweepStrayHolders(player, headBone);
GameObject holder = new GameObject(EyesName);
holder.transform.SetParent(headBone, false);
@ -296,35 +401,164 @@ namespace RacesOfValheim
frame.LocalForward = SnapToAxis(headBone.InverseTransformDirection(root.forward));
frame.LocalUp = SnapToAxis(headBone.InverseTransformDirection(root.up));
frame.LocalRight = Vector3.Cross(frame.LocalUp, frame.LocalForward).normalized;
frame.SourceModel = modelName;
frame.FlatShader = AswidConfig.EyeFlatColorShader.Value;
for (int i = 0; i < 2; i++)
foreach (Transform source in sources)
{
// Spheres, not quads: a quad seen edge-on is a line and vanishes, which is why an
// earlier attempt on the Dvergar came and went with the camera angle. A sphere
// reads the same from every direction and is properly hidden by the skull when the
// head is between it and the camera.
GameObject eye = GameObject.CreatePrimitive(PrimitiveType.Sphere);
eye.name = "Eye" + i;
GameObject eye = Object.Instantiate(source.gameObject, holder.transform);
eye.name = source.name;
foreach (Collider collider in eye.GetComponents<Collider>())
// Remembered before anything moves it, because everything the config does is
// expressed as a delta on this.
EyeBase authored = eye.AddComponent<EyeBase>();
authored.Position = source.localPosition;
authored.Rotation = source.localRotation;
authored.Scale = source.localScale;
eye.transform.localPosition = source.localPosition;
eye.transform.localRotation = source.localRotation;
eye.transform.localScale = source.localScale;
// Allowlist, not a blocklist - the same rule the skeleton's own glow and the head
// flame are cloned under. Whatever rode along goes, whatever type it turns out to
// be; EyeBase is added back afterwards because it is ours.
foreach (Component comp in eye.GetComponentsInChildren<Component>(true))
{
Object.Destroy(collider);
if (comp is Transform || comp is MeshRenderer || comp is MeshFilter ||
comp is ParticleSystem || comp is ParticleSystemRenderer || comp is EyeBase)
{
continue;
}
Object.Destroy(comp);
}
eye.transform.SetParent(holder.transform, false);
eye.transform.localPosition = Vector3.zero;
eye.transform.localRotation = Quaternion.identity;
eye.transform.localScale = Vector3.zero; // PlaceEyes runs immediately after this
foreach (Renderer renderer in eye.GetComponentsInChildren<Renderer>(true))
{
renderer.enabled = true;
renderer.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off;
renderer.receiveShadows = false;
Renderer renderer = eye.GetComponent<Renderer>();
renderer.material = new Material(glow);
renderer.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off;
renderer.receiveShadows = false;
// The escape hatch, for if the borrowed material turns out not to take a tint:
// a plain colour shader renders past 1 so the bloom pass picks it up, at the
// cost of the socket's own texture.
if (!AswidConfig.EyeFlatColorShader.Value) continue;
Shader flat = ResolveGlowShader();
if (flat != null) renderer.material = new Material(flat);
}
eye.SetActive(true);
}
LogMaterialsOnce(modelName, holder.transform);
// What the pair was actually anchored to. If the height is ever wrong again, this line
// is the answer rather than the start of another guess: it names the bone, its parent,
// and the axes the offsets are measured along.
Jotunn.Logger.LogInfo(
$"[Aswid] Eyes built on bone '{headBone.name}' (parent '{(headBone.parent != null ? headBone.parent.name : "-")}') " +
$"at world y={headBone.position.y:F2}, lossyScale={headBone.lossyScale.x:F1}, " +
$"localUp={frame.LocalUp}, localForward={frame.LocalForward}.");
return holder.transform;
}
/// <summary>
/// Destroys every eye holder on this player that is not parented to the bone we are about
/// to build on. Runs only when a pair is being built, which is on a race change or a config
/// change - never on a hot path.
/// </summary>
private static void SweepStrayHolders(Player player, Transform keepParent)
{
if (player == null) return;
foreach (Transform t in player.GetComponentsInChildren<Transform>(true))
{
if (t == null || t.name != EyesName) continue;
if (t.parent == keepParent) continue;
Jotunn.Logger.LogInfo(
$"[Aswid] Removing a stray eye holder parented to '{(t.parent != null ? t.parent.name : "-")}'.");
// Renamed first: Destroy is deferred to the end of the frame, and this sweep would
// otherwise find it again on the next build.
t.name = EyesName + "_Removed";
Object.Destroy(t.gameObject);
}
}
private static readonly HashSet<string> warnedSources = new HashSet<string>();
private static readonly HashSet<string> loggedMaterials = new HashSet<string>();
/// <summary>
/// The creature's own eye objects, by name. Not cached: this runs when the pair is built,
/// which is on a race change or a config change and not on any hot path.
/// </summary>
private static List<Transform> FindSourceEyes(string modelName)
{
List<Transform> found = new List<Transform>();
GameObject prefab = PrefabManager.Cache.GetPrefab<GameObject>(modelName);
if (prefab == null)
{
if (warnedSources.Add(modelName))
{
Jotunn.Logger.LogWarning(
$"[Aswid] Eye source prefab '{modelName}' not found - the eyes stay dark. " +
"Check the model name in Configuration Manager.");
}
return found;
}
foreach (Transform t in prefab.GetComponentsInChildren<Transform>(true))
{
string lower = t.name.ToLower();
foreach (string wanted in SourceEyeNames)
{
if (lower == wanted) { found.Add(t); break; }
}
}
if (found.Count == 0 && warnedSources.Add(modelName + ":eyes"))
{
Jotunn.Logger.LogWarning(
$"[Aswid] '{modelName}' carries no {string.Join("/", SourceEyeNames)} objects - the eyes stay dark.");
}
return found;
}
/// <summary>
/// Says what the borrowed material actually is, once per source. If red does not take,
/// this line is the answer: it names the shader and every colour property it exposes.
/// </summary>
private static void LogMaterialsOnce(string modelName, Transform holder)
{
if (!loggedMaterials.Add(modelName)) return;
foreach (Renderer renderer in holder.GetComponentsInChildren<Renderer>(true))
{
Material material = renderer.sharedMaterial;
if (material == null) continue;
List<string> properties = new List<string>();
foreach (string name in new[] { "_Color", "_TintColor", "_BaseColor", "_EmissionColor" })
{
if (material.HasProperty(name)) properties.Add(name);
}
Jotunn.Logger.LogInfo(
$"[Aswid] Eye '{renderer.name}' from '{modelName}': material '{material.name}' " +
$"shader '{(material.shader != null ? material.shader.name : "none")}' " +
$"colour properties: {(properties.Count > 0 ? string.Join(", ", properties.ToArray()) : "none")}");
}
}
private static Shader cachedGlowShader;
private static bool glowShaderResolved;
/// <summary>
/// Finds a shader that will render a flat colour past 1 so the bloom pass picks it up.
/// Opaque first, deliberately - see DvergarVisuals.ResolveGlowShader: a transparent shader

View file

@ -194,7 +194,7 @@ namespace RacesOfValheim
Items = new List<CatalogEntry>
{
new CatalogEntry("JuteRed", 2),
new CatalogEntry("GreaterFrostHeart", 1500), // gates the Skadi's hidden hollow
new CatalogEntry("GreaterFrostHeart", 1500), // the Skadi's bought reagent
new CatalogEntry("TrophyCultist", 1500),
}
};

View file

@ -0,0 +1,56 @@
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The Cursed Claws: the flesh rippers, worn exactly as the game authored them.
///
/// Everything about how they behave - issued once, never dropped, back in hand the moment the
/// hands are free, tier damage as slash - lives in RaceClawSet. This file is only the Fenrir's
/// half: which model, and when the race is currently a wolf.
///
/// No tint. The fenrir claw already looks like something a Fenrir would grow, which is the
/// whole reason it is the one being borrowed.
/// </summary>
public class FenrirClaws : RaceClawSet
{
public static readonly FenrirClaws Instance = new FenrirClaws();
public override string RaceId => "Fenrir";
public override string ItemName => "FenrirCursedClaws";
public override string DisplayName => "Cursed Claws";
public override string Description => "The wolf's hands, kept on in the man's shape. They do not come off.";
public override string[] ModelPrefabs => new[]
{
"FistFenrirClaw",
"FistFenrirClaw_Undead",
"FenrirClaw",
};
// The Fenrir publishes no per-tier state of its own, so the damage falls back to the local
// player's progression. That is right for the player at the keyboard and approximate for
// somebody else's claws on a shared world - the same compromise the Sverm makes, and the
// fix if it ever matters is a state key in FenrirRace, not a change here.
/// <summary>
/// A wolf swings its own jaws, and FenrirFormBehavior does that damage itself. The ZDO
/// carries the form for everyone; the status effect is the local player's own copy of the
/// same fact, checked second so a form that has begun but not yet replicated still counts.
/// </summary>
public override bool IsTransformed(Player player)
{
if (player == null) return false;
ZNetView nview = player.GetComponent<ZNetView>();
if (nview != null && nview.IsValid())
{
if (!string.IsNullOrEmpty(nview.GetZDO().GetString("RacesOfValheim_FenrirForm", ""))) return true;
}
return player == Player.m_localPlayer &&
player.GetSEMan() != null &&
player.GetSEMan().HaveStatusEffect("SE_FenrirForm".GetStableHashCode());
}
}
}

View file

@ -35,6 +35,11 @@ namespace RacesOfValheim {
// Fenring is ever set up as a bench.
FenrirMangiatoia.Register();
// Same window, same reason: this method runs on PrefabManager.OnVanillaPrefabsAvailable,
// which is the one moment Jotunn will take a new item into ObjectDB. Registered later
// the prefab exists, logs its success, and cannot be spawned by anyone.
FenrirClaws.Instance.EnsureRegistered();
curseSE = ScriptableObject.CreateInstance<SE_FenrirCurse>();
curseSE.name = "SE_FenrirCurse";
curseSE.m_name = "Fenrir's Blood";

View file

@ -40,6 +40,33 @@ namespace RacesOfValheim
public static GameObject Attach(Transform parent, string holderName, string sourcePrefab,
Vector3 localPosition, Quaternion localRotation, float targetSize,
string label)
{
GameObject source = Jotunn.Managers.PrefabManager.Cache.GetPrefab<GameObject>(sourcePrefab);
if (source == null)
{
Jotunn.Logger.LogWarning($"[{label}] No '{sourcePrefab}' to borrow a model from; nothing was attached.");
GameObject empty = new GameObject(holderName);
empty.transform.SetParent(parent, false);
empty.transform.localPosition = localPosition;
return empty;
}
return Attach(parent, holderName, source, localPosition, localRotation, targetSize, label);
}
/// <summary>
/// The same, for a source that has already been found by hand.
///
/// Not every borrowable model is a top-level prefab. The Seeker's wing, for one, is a
/// child of the creature's death effect rather than a prefab of its own, so no name lookup
/// can reach it and the caller has to walk to it first. Everything past the lookup - the
/// inactive holder, the component strip, the measure-and-ground - is identical, which is
/// exactly why this is an overload and not a second copy.
/// </summary>
public static GameObject Attach(Transform parent, string holderName, GameObject source,
Vector3 localPosition, Quaternion localRotation, float targetSize,
string label)
{
GameObject holder = new GameObject(holderName);
holder.transform.SetParent(parent, false);
@ -48,14 +75,14 @@ namespace RacesOfValheim
// BEFORE the Instantiate below. This single line is the whole point of the class.
holder.SetActive(false);
GameObject source = Jotunn.Managers.PrefabManager.Cache.GetPrefab<GameObject>(sourcePrefab);
if (source == null)
{
Jotunn.Logger.LogWarning($"[{label}] No '{sourcePrefab}' to borrow a model from; nothing was attached.");
Jotunn.Logger.LogWarning($"[{label}] No source model handed to '{holderName}'; nothing was attached.");
holder.SetActive(true);
return holder;
}
string sourcePrefab = source.name;
GameObject copy = Object.Instantiate(source, holder.transform);
copy.name = "model";
copy.transform.localPosition = Vector3.zero;

View file

@ -35,6 +35,20 @@ namespace RacesOfValheim
private static readonly Dictionary<string, Limit> Limits = new Dictionary<string, Limit>();
/// <summary>
/// Extra placement rules, one per piece, for the chains whose cap cannot be expressed as
/// "how many of THIS piece stand nearby".
///
/// The Skadi's golem is the case that forced this: the piece it builds removes itself a frame
/// later and leaves a creature behind, so counting the piece counts nothing, and one of its two
/// caps is per-stonecutter rather than per-area. A gate is handed the same player and the same
/// placement point the simple limit gets, says yes or no, and is responsible for its own
/// refusal message - which is the whole extension: the counting is the chain's business, being
/// the ONE Player.PlacePiece prefix in the mod is still this class's.
/// </summary>
private static readonly Dictionary<string, System.Func<Player, Vector3, bool>> Gates =
new Dictionary<string, System.Func<Player, Vector3, bool>>();
/// <summary>
/// The radius of a circle with the given area, so a limit can be written the way it is
/// actually discussed - "five per 1.6 square kilometres" - instead of as a magic distance.
@ -61,6 +75,45 @@ namespace RacesOfValheim
Jotunn.Logger.LogInfo($"[Density] {piecePrefabName}: at most {max} within {radius:0} m.");
}
/// <summary>
/// Adds a rule of the chain's own to a piece. Same call-once-from-Register() contract as
/// <see cref="Register"/>, and a second call replaces the first rather than stacking.
/// </summary>
public static void RegisterGate(string piecePrefabName, System.Func<Player, Vector3, bool> gate)
{
if (string.IsNullOrEmpty(piecePrefabName) || gate == null)
{
Jotunn.Logger.LogWarning($"[Density] Refusing a nonsense gate for '{piecePrefabName}'.");
return;
}
Gates[piecePrefabName] = gate;
Jotunn.Logger.LogInfo($"[Density] {piecePrefabName}: a rule of its own runs at placement.");
}
/// <summary>
/// Every ZDO in the world carrying that prefab. False when the world cannot be asked right
/// now, which callers must read as "no information" rather than as "none".
///
/// ZDOs and not loaded GameObjects, for the reason at the top of this file, and public
/// because the Skadi's golem counts by an anchor written INTO each ZDO rather than by
/// distance - so it needs the ZDOs themselves and not a tally of them.
/// </summary>
public static bool Gather(string prefabName, List<ZDO> into)
{
if (ZDOMan.instance == null || into == null) return false;
int index = 0;
// The iterative sweep hands back a chunk per call and reports true when it is done. The
// guard is so a pathological world cannot spin here forever.
for (int guard = 0; guard < 1000; guard++)
{
if (ZDOMan.instance.GetAllZDOsWithPrefabIterative(prefabName, into, ref index)) break;
}
return true;
}
/// <summary>
/// How many of that piece already stand within the radius of a point, or -1 if the world
/// cannot be asked right now - in which case callers must let the placement through rather
@ -68,16 +121,8 @@ namespace RacesOfValheim
/// </summary>
public static int Count(string piecePrefabName, Vector3 position, float radius)
{
if (ZDOMan.instance == null) return -1;
List<ZDO> zdos = new List<ZDO>();
int index = 0;
// The iterative sweep hands back a chunk per call and reports true when it is done. The
// guard is so a pathological world cannot spin here forever.
for (int guard = 0; guard < 1000; guard++)
{
if (ZDOMan.instance.GetAllZDOsWithPrefabIterative(piecePrefabName, zdos, ref index)) break;
}
if (!Gather(piecePrefabName, zdos)) return -1;
float rangeSq = radius * radius;
int count = 0;
@ -96,6 +141,14 @@ namespace RacesOfValheim
/// </summary>
public static bool Allow(Player player, string piecePrefabName, Vector3 position)
{
// The chain's own rule first: it is the more specific of the two, so it should be the one
// that gets to explain itself when both would refuse.
if (Gates.TryGetValue(piecePrefabName, out System.Func<Player, Vector3, bool> gate) &&
!gate(player, position))
{
return false;
}
if (!Limits.TryGetValue(piecePrefabName, out Limit limit)) return true;
int nearby = Count(piecePrefabName, position, limit.Radius);
@ -141,28 +194,7 @@ namespace RacesOfValheim
{
if (__instance != Player.m_localPlayer || __0 == null) return true;
if (!HollowAllowsPiece(__instance, __0)) return false;
return PieceDensityLimit.Allow(__instance, Utils.GetPrefabName(__0.gameObject), __1);
}
/// <summary>
/// "You may build in your hollow, but nothing takes root there." Rides along on this prefix
/// rather than adding a second one, which is the whole reason this class exists.
///
/// Worth knowing that the refusal is about the MESSAGE, not about making the impossible
/// impossible: a Plant needs cultivated ground and a matching biome (Plant.m_needCultivated-
/// Ground, Plant.m_biome), and five kilometres above the sea there is no terrain to cultivate
/// and no biome to match, so a seed would have failed anyway - with a vanilla error that says
/// nothing useful about why.
/// </summary>
private static bool HollowAllowsPiece(Player player, Piece piece)
{
if (!SkadiHollow.IsInside(player)) return true;
if (piece.GetComponentInChildren<Plant>(true) == null) return true;
player.Message(MessageHud.MessageType.Center, "Nothing takes root here.");
return false;
}
}
}

600
JotunnModStub/RaceClaws.cs Normal file
View file

@ -0,0 +1,600 @@
using System.Collections.Generic;
using HarmonyLib;
using Jotunn.Managers;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// Claws that are part of the body, for the races that grow a pair.
///
/// This is SvermClawSlot generalised, not reinvented: the Sverm's Vilebone Maulclaws worked out
/// the whole shape of the problem, and the Aswid and the Fenrir are asking for the same object
/// with a different face. So the machinery moved here and each race supplies only what is
/// genuinely its own - the item name, the model to wear, and whether it is currently a wolf.
/// The Sverm still runs its own copy, untouched, because it also carries a carapace, a stinger
/// form and a fire term at Fader that none of this knows about.
///
/// WHY A REAL ITEM AND NOT A COSMETIC. Bolting a model to the hand bones works right up until
/// the game rebuilds equipment visuals - which it does on every equip - and wipes it. A real
/// item in a real slot has nothing to put back. The trade is that a real weapon occupies the
/// right hand, so three rules keep that reading as intended rather than as a bug: sheathe
/// anything else and the claws come back, the holster key cannot put them away, and they
/// cannot be dragged, moved or dropped.
///
/// BALANCE IS SHARED ON PURPOSE. The damage is not read from the model each race wears - the
/// Fenrir's flesh rippers and the Bjorn claw are not worth the same, and a race should not be
/// stronger because its claws are prettier. Every set reads the Sverm's own reference weapon at
/// quality 4 and the Sverm's own per-tier percentages, so all three races hit for identical
/// numbers at identical tiers. What differs here is the shape of the damage: these two land it
/// entirely as slash, where the Sverm splits it three ways and lights it on fire at Fader.
/// </summary>
public abstract class RaceClawSet
{
// ─── What a race has to say about its own claws ──────────────────────
/// <summary>The race string in the ZDO, e.g. "Aswid".</summary>
public abstract string RaceId { get; }
/// <summary>Prefab id of the cloned item. Never seen by a player.</summary>
public abstract string ItemName { get; }
/// <summary>What the item is called in the inventory.</summary>
public abstract string DisplayName { get; }
public abstract string Description { get; }
/// <summary>
/// Models to clone, in order of preference. A list rather than a name because the install's
/// manifest carries several near-identical claw ids and only some of them resolve - see
/// SvermConfig.ClawPrefabFallbacks, which is where that lesson was learned. The winner is
/// logged; a miss is a warning rather than two empty hands and silence.
/// </summary>
public abstract string[] ModelPrefabs { get; }
/// <summary>ZDO key carrying this race's progression state, or null if it publishes none.</summary>
public virtual string StateZdoKey => null;
/// <summary>Multiplied into the model's own colours. Null leaves the model as authored.</summary>
public virtual Color? Tint => null;
/// <summary>
/// True while the player is wearing another body entirely - a bat, mist, a wolf. Claws are
/// neither issued nor counted while that is the case: the form does its own damage and has
/// its own hands, and a weapon equipped underneath it is at best invisible and at worst the
/// thing the game decides to swing.
/// </summary>
public abstract bool IsTransformed(Player player);
// ─── Registry ────────────────────────────────────────────────────────
private static readonly List<RaceClawSet> sets = new List<RaceClawSet>();
/// <summary>
/// The roster. Kept here rather than in RacesOfValheim.Awake so the whole feature is this
/// file plus one short file per race, and adding a third clawed race is one line - not one
/// line here and another one three hundred lines away in the plugin's startup.
/// </summary>
static RaceClawSet()
{
Register(AswidClaws.Instance);
Register(FenrirClaws.Instance);
}
public static void Register(RaceClawSet set)
{
if (set == null || sets.Contains(set)) return;
sets.Add(set);
}
/// <summary>The set that belongs to this player's race, or null for everyone else.</summary>
public static RaceClawSet For(Player player)
{
if (player == null) return null;
string race = GetRace(player);
foreach (RaceClawSet set in sets)
{
if (set.RaceId == race) return set;
}
return null;
}
/// <summary>True if the item is any registered race's claws.</summary>
public static RaceClawSet SetOwning(ItemDrop.ItemData item)
{
if (item == null || item.m_shared == null) return null;
foreach (RaceClawSet set in sets)
{
if (set.IsClaws(item)) return set;
}
return null;
}
/// <summary>
/// Reads the race off the ZDO, falling back to m_customData - the same order every visual
/// in this mod reads it in, so a remote player and the menu preview both answer correctly.
/// </summary>
private static string GetRace(Player player)
{
ZNetView nview = player.GetComponent<ZNetView>();
if (nview != null && nview.IsValid())
{
string race = nview.GetZDO().GetString("RacesOfValheim_Race", "");
if (!string.IsNullOrEmpty(race)) return race;
}
if (player.m_customData != null && player.m_customData.TryGetValue("Race", out string custom))
{
return custom;
}
return "Human";
}
// ─── Registration of the item ────────────────────────────────────────
private bool registered;
private bool warnedModel;
private bool loggedMaterials;
private readonly List<Material> ownedMaterials = new List<Material>();
/// <summary>
/// Clones whichever of the candidate models this build actually has. Deferred until ObjectDB
/// is up, so it is driven from the maintain tick rather than from Awake.
/// </summary>
public void EnsureRegistered()
{
if (registered) return;
if (ObjectDB.instance != null && ObjectDB.instance.GetItemPrefab(ItemName) != null)
{
registered = true;
return;
}
GameObject source = ResolveModel();
if (source == null) return; // already warned once by the resolver
GameObject clone = PrefabManager.Instance.CreateClonedPrefab(ItemName, source);
if (clone == null)
{
Jotunn.Logger.LogWarning($"[{RaceId}] Could not clone '{source.name}'; the claws stay unregistered.");
return;
}
ItemDrop drop = clone.GetComponent<ItemDrop>();
if (drop != null && drop.m_itemData != null && drop.m_itemData.m_shared != null)
{
ItemDrop.ItemData.SharedData shared = drop.m_itemData.m_shared;
shared.m_name = DisplayName;
shared.m_description = Description;
// Quest item: Valheim refuses to drop, trade or stack these. It is the cheapest
// honest way to say "this is part of your body" without a patch per verb.
shared.m_questItem = true;
shared.m_teleportable = true;
shared.m_weight = 0f;
shared.m_maxQuality = 1;
// No recipe and no station: this item is never crafted, only issued.
}
TakeOwnershipOfMaterials(clone);
ItemManager.Instance.AddItem(new Jotunn.Entities.CustomItem(clone, fixReference: false));
registered = true;
Jotunn.Logger.LogInfo($"[{RaceId}] Registered '{ItemName}' from '{source.name}'.");
RefreshTint();
}
private GameObject ResolveModel()
{
foreach (string name in ModelPrefabs)
{
// PrefabManager's cache first, ObjectDB second: the cache answers earlier in the
// load, and ObjectDB is still empty when the plugin wakes.
GameObject candidate = PrefabManager.Cache.GetPrefab<GameObject>(name);
if (candidate == null && ObjectDB.instance != null)
{
candidate = ObjectDB.instance.GetItemPrefab(name);
}
if (candidate != null)
{
Jotunn.Logger.LogInfo($"[{RaceId}] Claw model resolved to '{name}'.");
return candidate;
}
}
// Warned once, but NOT latched: a later call may run when more of the game is loaded,
// and a race with no hands is worth retrying for.
if (!warnedModel)
{
warnedModel = true;
Jotunn.Logger.LogWarning($"[{RaceId}] None of " + string.Join(", ", ModelPrefabs) +
" resolved yet; retrying as the game loads.");
}
return null;
}
/// <summary>
/// Gives the clone its own copies of every material it draws with.
///
/// A cloned prefab still points at the ORIGINAL material assets, so tinting them straight
/// would repaint the vanilla weapon in every hand in the world - a thing that would show up
/// as "why are the flesh rippers black now" and take an hour to trace back here. Copies
/// also make the tint live: an instantiated item shares these same material objects, so
/// writing a colour on them reaches the pair already in the player's hands.
/// </summary>
private void TakeOwnershipOfMaterials(GameObject clone)
{
ownedMaterials.Clear();
foreach (Renderer renderer in clone.GetComponentsInChildren<Renderer>(true))
{
Material[] materials = renderer.sharedMaterials;
if (materials == null) continue;
for (int i = 0; i < materials.Length; i++)
{
if (materials[i] == null) continue;
Material copy = new Material(materials[i]);
copy.name = materials[i].name + "_" + ItemName;
materials[i] = copy;
ownedMaterials.Add(copy);
}
renderer.sharedMaterials = materials;
}
}
/// <summary>
/// Repaints the claws. Called on the maintain tick as well as at registration, so a tint
/// driven by config moves while the game is running.
///
/// Every colour property the shader turns out to have is written rather than guessing which
/// one it uses: writing a property a shader does not have is an error, writing all the ones
/// it does is free.
/// </summary>
public void RefreshTint()
{
if (Tint == null || ownedMaterials.Count == 0) return;
Color tint = Tint.Value;
foreach (Material material in ownedMaterials)
{
if (material == null) continue;
if (material.HasProperty("_Color")) material.SetColor("_Color", tint);
if (material.HasProperty("_BaseColor")) material.SetColor("_BaseColor", tint);
if (material.HasProperty("_MainColor")) material.SetColor("_MainColor", tint);
// A claw is not a lamp. Whatever the source model glowed with goes out, or the
// tint fights a bloom it cannot win against.
if (material.HasProperty("_EmissionColor")) material.SetColor("_EmissionColor", Color.black);
}
if (loggedMaterials) return;
loggedMaterials = true;
foreach (Material material in ownedMaterials)
{
if (material == null) continue;
List<string> properties = new List<string>();
foreach (string name in new[] { "_Color", "_BaseColor", "_MainColor", "_EmissionColor" })
{
if (material.HasProperty(name)) properties.Add(name);
}
Jotunn.Logger.LogInfo(
$"[{RaceId}] Claw material '{material.name}' shader " +
$"'{(material.shader != null ? material.shader.name : "none")}' " +
$"colour properties: {(properties.Count > 0 ? string.Join(", ", properties.ToArray()) : "none")}");
}
}
// ─── Issue and re-equip ──────────────────────────────────────────────
/// <summary>
/// Guards against re-entry, and it is not belt-and-braces - it is the fix for a crash the
/// Sverm hit first. Maintain equips the claws; Humanoid.EquipItem unequips the right hand
/// first, which fires the UnequipItem postfix, which calls Maintain... Mono answers an
/// unbounded recursion by killing the process outright, with no exception and a log file
/// that ends mid-word.
/// </summary>
private static bool maintaining;
/// <summary>
/// Makes sure the player owns exactly one pair and is holding them whenever both hands are
/// free. Safe to call on a timer: every step checks first.
/// </summary>
public void Maintain(Player player)
{
if (maintaining) return;
if (player == null || player != Player.m_localPlayer) return;
if (For(player) != this) return;
if (player.IsDead() || IsTransformed(player)) return;
maintaining = true;
try { MaintainInner(player); }
finally { maintaining = false; }
}
private void MaintainInner(Player player)
{
EnsureRegistered();
RefreshTint();
Inventory inventory = player.GetInventory();
if (inventory == null) return;
ItemDrop.ItemData claws = Find(inventory);
if (claws == null)
{
GameObject prefab = ObjectDB.instance != null ? ObjectDB.instance.GetItemPrefab(ItemName) : null;
if (prefab == null)
{
// The failure that cost the first version of this feature an evening. The item
// registers, logs its success, tints its materials - and is not in ObjectDB,
// because Jotunn only takes new items at OnVanillaPrefabsAvailable and this ran
// afterwards. It looked from the log exactly like everything had worked.
WarnOnce("missing-from-objectdb",
$"'{ItemName}' is registered but not in ObjectDB, so it cannot be issued. " +
"It has to be registered from CreateModAssets (PrefabManager.OnVanillaPrefabsAvailable), not later.");
return;
}
// The GameObject overload, deliberately: it is the one that is public in the
// shipped assembly, and this project compiles against that rather than against the
// publicized copy - so anything else would build here and not on a clean machine.
if (!inventory.AddItem(prefab, 1))
{
WarnOnce("inventory-full", $"No room in the inventory for the {DisplayName}; retrying.");
return;
}
claws = Find(inventory);
if (claws == null) return;
// Tidied into the bottom-right corner IF that corner is free, and left wherever the
// inventory put them otherwise. Nothing of the player's is ever displaced: an item
// that cannot be moved has no business shoving one that can.
Vector2i corner = new Vector2i(inventory.GetWidth() - 1, inventory.GetHeight() - 1);
if (corner.x >= 0 && ItemAt(inventory, corner.x, corner.y) == null)
{
claws.m_gridPos = corner;
}
Jotunn.Logger.LogInfo($"[{RaceId}] Issued the {DisplayName}.");
}
// Empty-handed means clawed. Anything else in the right hand wins until it is put away,
// which is the whole compromise.
ItemDrop.ItemData held = Traverse.Create((Humanoid)player).Field<ItemDrop.ItemData>("m_rightItem").Value;
if (held == null && !player.InAttack())
{
player.EquipItem(claws, false);
}
}
private readonly HashSet<string> warned = new HashSet<string>();
/// <summary>
/// Says a thing once. The maintain tick runs twice a second, so a plain warning here is a
/// log file rather than a message - which is the other half of why this failure was silent.
/// </summary>
private void WarnOnce(string key, string message)
{
if (!warned.Add(key)) return;
Jotunn.Logger.LogWarning($"[{RaceId}] {message}");
}
/// <summary>
/// What is sitting at this grid position, read from the items themselves.
/// Inventory.GetItemAt is private in the shipped assembly, and every item already carries
/// its own m_gridPos, so a scan answers the same question with nothing but public members.
/// </summary>
private static ItemDrop.ItemData ItemAt(Inventory inventory, int x, int y)
{
foreach (ItemDrop.ItemData item in inventory.GetAllItems())
{
if (item != null && item.m_gridPos.x == x && item.m_gridPos.y == y) return item;
}
return null;
}
public ItemDrop.ItemData Find(Inventory inventory)
{
if (inventory == null) return null;
foreach (ItemDrop.ItemData item in inventory.GetAllItems())
{
if (IsClaws(item)) return item;
}
return null;
}
public bool IsClaws(ItemDrop.ItemData item)
{
if (item == null || item.m_shared == null) return false;
if (item.m_dropPrefab != null && item.m_dropPrefab.name == ItemName) return true;
return item.m_shared.m_name == DisplayName;
}
// ─── Damage ──────────────────────────────────────────────────────────
/// <summary>
/// The tier this player is fighting at. Remote players answer from their own ZDO where the
/// race publishes one; where it does not, this falls back to the local player's progression
/// - the same compromise SvermVisuals.GetRenderState makes, and it only ever matters for
/// somebody else's claws on a shared world.
/// </summary>
private int GetState(Player player)
{
if (player != null && player != Player.m_localPlayer && !string.IsNullOrEmpty(StateZdoKey))
{
ZNetView nview = player.GetComponent<ZNetView>();
if (nview != null && nview.IsValid())
{
int remote = nview.GetZDO().GetInt(StateZdoKey, 0);
if (remote > 0)
{
return Mathf.Clamp(remote, BossProgressionManager.MinState, BossProgressionManager.MaxState);
}
}
}
return BossProgressionManager.GetCurrentProgressionState();
}
/// <summary>
/// Rewrites a bare-handed blow into a claw blow, as slash and nothing else.
///
/// The figure is the Sverm's - its reference weapon at quality 4, times its percentage for
/// this tier - but where the Sverm keeps the weapon's own three-way split, this collapses
/// the whole physical total into slash. Claws cut. The total is preserved rather than the
/// slash component copied, so the three races stay worth the same and only the damage type
/// differs, which is the entire point of the exercise.
/// </summary>
public void ApplyToUnarmedHit(HitData hit, Player attacker)
{
if (hit == null || attacker == null) return;
if (IsTransformed(attacker)) return; // the form is doing its own damage
HitData.DamageTypes reference = SvermClaws.GetReferenceDamage();
float percent = SvermClaws.GetDamagePercent(GetState(attacker));
if (percent <= 0f) return;
float total = (reference.m_slash + reference.m_pierce + reference.m_blunt) * percent;
// Nothing to give: the reference item did not resolve. Leave vanilla's fist alone
// rather than zeroing the player's only attack.
if (total <= 0f) return;
hit.m_damage.m_slash = total;
hit.m_damage.m_pierce = 0f;
hit.m_damage.m_blunt = 0f;
}
}
// ─── Patches ─────────────────────────────────────────────────────────────
/// <summary>
/// Issues the claws and puts them back in hand. On a throttle rather than every frame: it is a
/// handful of checks that all short-circuit once the claws exist.
/// </summary>
[HarmonyPatch(typeof(Player), "Update")]
public static class RaceClaws_PlayerUpdate_Patch
{
private const float Interval = 0.5f;
private static float next;
public static void Postfix(Player __instance)
{
if (__instance != Player.m_localPlayer) return;
if (Time.time < next) return;
next = Time.time + Interval;
RaceClawSet set = RaceClawSet.For(__instance);
if (set != null) set.Maintain(__instance);
}
}
/// <summary>
/// Put anything else away and the claws come straight back. A postfix rather than a prefix: the
/// game is mid-way through tearing down the old item's visuals when a prefix would run, and
/// equipping there leaves the new item without a model.
/// </summary>
[HarmonyPatch(typeof(Humanoid), nameof(Humanoid.UnequipItem))]
public static class RaceClaws_UnequipItem_Patch
{
public static void Postfix(Humanoid __instance, ItemDrop.ItemData item)
{
// NULL IS THE IMPORTANT CASE. Humanoid.EquipItem calls UnequipItem(m_rightItem) before
// putting a weapon in the hand, and an empty hand means that argument is null. Without
// this line the postfix treats "nothing was unequipped" as "something was unequipped",
// and the recursion that follows kills the process silently.
if (item == null) return;
Player player = __instance as Player;
if (player == null || player != Player.m_localPlayer) return;
RaceClawSet set = RaceClawSet.For(player);
if (set == null) return;
if (set.IsClaws(item)) return; // do not re-equip what was just taken off
set.Maintain(player);
}
}
/// <summary>
/// The holster key cannot put the claws away. Refused only while the claws ARE the thing in
/// hand: holding a sword, R sheathes the sword normally and the unequip postfix hands the claws
/// back on the same action. So the key keeps working and simply never leaves the race
/// empty-handed.
/// </summary>
[HarmonyPatch(typeof(Humanoid), nameof(Humanoid.HideHandItems))]
public static class RaceClaws_HideHandItems_Patch
{
public static bool Prefix(Humanoid __instance)
{
Player player = __instance as Player;
if (player == null || player != Player.m_localPlayer) return true;
RaceClawSet set = RaceClawSet.For(player);
if (set == null) return true;
ItemDrop.ItemData held = Traverse.Create(__instance).Field<ItemDrop.ItemData>("m_rightItem").Value;
return !set.IsClaws(held);
}
}
/// <summary>
/// The claws cannot be picked up with the mouse. SetupDragItem is the single door every manual
/// move goes through - within the inventory, out to a chest, onto the ground, into a crafting
/// slot - so refusing here closes all of them with one prefix.
/// </summary>
[HarmonyPatch(typeof(InventoryGui), "SetupDragItem")]
public static class RaceClaws_SetupDragItem_Patch
{
public static bool Prefix(ItemDrop.ItemData item)
{
if (RaceClawSet.SetOwning(item) == null) return true;
if (Player.m_localPlayer != null)
{
Player.m_localPlayer.Message(MessageHud.MessageType.Center, "They are part of your hands.");
}
return false;
}
}
/// <summary>
/// The tier's damage, on any bare-handed blow. Fist weapons report Unarmed, so this covers both
/// the equipped claws and an actually empty hand - which is what keeps the two halves of the
/// feature agreeing with each other.
/// </summary>
[HarmonyPatch(typeof(Character), nameof(Character.Damage))]
public static class RaceClaws_Damage_Patch
{
public static void Prefix(HitData hit)
{
if (hit == null || hit.m_skill != Skills.SkillType.Unarmed) return;
Player attacker = hit.GetAttacker() as Player;
if (attacker == null) return;
RaceClawSet set = RaceClawSet.For(attacker);
if (set == null) return;
set.ApplyToUnarmedHit(hit, attacker);
}
}
}

View file

@ -17,7 +17,8 @@ namespace RacesOfValheim
"Trol Secrets",
"Draugh Secrets",
"Dvergar Secrets",
"Trenta Secrets"
"Trenta Secrets",
"Sverm Secrets"
};
public static void UpdateCompendiumText(Player player)
@ -77,6 +78,142 @@ namespace RacesOfValheim
{
GenerateTrentaText(knownTexts, state);
}
else if (currentRace == SvermConfig.RaceId)
{
GenerateSvermText(knownTexts, state);
}
// The War Vulture is not a racial power and does not belong inside any one race's
// generator: it is an item whose access list is a config entry. Appended here, once,
// to whichever page was just written - so adding a race to that list in Configuration
// Manager puts the paragraph on that race's page without a line of code changing.
AppendWarVulture(knownTexts, currentRace);
}
/// <summary>
/// The War Vulture's half-page, added to any race allowed to call the bird.
///
/// Asks WarVultureConfig instead of naming Furling and Dvergar, because the allowed list is
/// a config entry and a hard-coded pair would be wrong the moment anyone edits it. The
/// speeds are read the same way, so the page cannot promise a number the bird does not fly.
/// </summary>
private static void AppendWarVulture(Dictionary<string, string> knownTexts, string race)
{
// Before Bind runs there are no numbers to print. RaceAllowed already survives a null
// config; the speeds below would not.
if (WarVultureConfig.CruiseSpeed == null) return;
if (!WarVultureConfig.RaceAllowed(race)) return;
string key = race + " Secrets";
if (!knownTexts.TryGetValue(key, out string page)) return;
StringBuilder sb = new StringBuilder(page);
sb.AppendLine("\n-- THE WAR VULTURE --\n");
sb.AppendLine("A vulture's head kept on a stick, and the bird answers to it. Raise it and the vulture comes back under you. Raise it again and it carries you down, deaf to you until the ground arrives - and a third time lets go of it where you are.\n");
sb.AppendLine($"It goes where you look, and it goes as long as you care to stay up: {WarVultureConfig.CruiseSpeed.Value:0.#} meters a second costs it nothing at all. Hold your run key and it gives you {WarVultureConfig.SprintSpeed.Value:0.#} for {WarVultureConfig.SprintSeconds.Value:0} seconds and not a moment longer - there is only so much haste in a bird. Let go and the wind comes back into it in {WarVultureConfig.RechargeSeconds.Value:0} seconds, in the air. You never have to land for it.\n");
if (WarVultureConfig.ShowStaminaBar.Value)
sb.AppendLine("What the bird has left is the bar under your own.\n");
knownTexts[key] = sb.ToString();
}
/// <summary>
/// The Sverm's entry, in two halves because the race is two halves: a body that grows on its
/// own, and a colony that has to be built. Figures are read from the live rules and from the
/// colony's own tables rather than restated, so the page cannot drift from the code.
/// </summary>
private static void GenerateSvermText(Dictionary<string, string> knownTexts, int state)
{
SvermProgression.SvermRules rules = SvermProgression.GetRules(state);
StringBuilder sb = new StringBuilder();
sb.AppendLine("The Sverm's Colony\n");
sb.AppendLine("[Base Passive] Chitin Plating: You do not dress. Chest, legs and helm are carapace and never come off, and at every tier they are worth the full set of the biome ahead of you - at its best quality, weightless, and without the slowness that armour costs anyone else. Cloak and trinket are the only things you may still wear.\n");
sb.AppendLine($"[Base Passive] Toxin Immunity: Poison cannot touch you. What can is the club and the torch: you take {rules.BluntWeakness * 100f:0}% more from blunt blows{(rules.FireWeakness > 0f ? $" and {rules.FireWeakness * 100f:0}% more from fire" : ", and fire has stopped being a weakness")}.\n");
sb.AppendLine("[Base Passive] Hive Pheromones: No invertebrate will attack you - not leeches, not ticks, not deathsquitos, not seekers, not the bees. Bonemass is not an insect and does not care.\n");
sb.AppendLine("[Base Passive] Insect Metabolism: You eat everything anyone else eats, and honey is worth double to you. Alchemical blood is the one thing you will not swallow.\n");
sb.AppendLine($"[Base Passive] Vilebone Maulclaws: Your hands are the weapon. Bare-handed blows land at {rules.ClawDamagePercent * 100f:0}% of the claws' full weight, and they cannot be taken from you - draw a sword and they wait, sheathe it and they are back.\n");
if (rules.MetabolicSurge)
sb.AppendLine("[Eikthyr Unlock] Metabolic Surge: Running and jumping cost you less, and you jump higher.\n");
if (rules.CarryWeightBonus > 0f)
sb.AppendLine($"[Eikthyr Unlock] Ventral Pouches: You carry {rules.CarryWeightBonus:0} more.\n");
if (rules.SeedsEdible)
sb.AppendLine("[Elder Unlock] Grinding Mandibles: Seeds are food. Raw nourishment and nothing more - the garden's blessings belong to somebody else.\n");
if (rules.SensoryAntennae)
sb.AppendLine("[Elder Unlock] Sensory Antennae: You feel what lives around you, through stone and through soil.\n");
if (rules.VenomOnHit > 0f)
sb.AppendLine($"[Bonemass Unlock] Venom Glands: Every blow you land carries +{rules.VenomOnHit:0.#} poison.\n");
if (rules.AcidHemolymph > 0f)
sb.AppendLine($"[Bonemass Unlock] Acid Hemolymph: Whoever strikes you in melee takes {rules.AcidHemolymph:0.#} poison back for the trouble.\n");
if (rules.FallDamageModifier <= 0f)
sb.AppendLine("[Moder Unlock] Vestigial Wings: Small wings, and no ground hard enough to hurt you.\n");
if (rules.StingerMorph)
sb.AppendLine($"[Yagluth Unlock] Stinger Morph ('{SvermConfigManagement.StingerKey.Value}' Key): Become a deathsquito. Real flight and the creature's own sting - and a body made of paper. It is how you kill, not how you travel.\n");
if (rules.BodyScale > 1f)
sb.AppendLine("[Queen Unlock] Surrenal Glands: You stand a tenth larger, and the carapace takes its greatest leap.\n");
if (rules.CarapaceRegenPerSecond > 0f)
sb.AppendLine($"[Fader Unlock] Carapace Regeneration: You knit yourself back together, {rules.CarapaceRegenPerSecond:0.##} health a second, always.\n");
if (rules.Emberform)
sb.AppendLine("[Fader Unlock] Annealed Chitin and Emberform: Eight tiers of burning have turned the flaw into armour - fire no longer hurts you, and the chitin goes black with a red heat under it.\n");
// ── The colony
sb.AppendLine("\n-- THE COLONY --\n");
if (state < SvermConfig.HiveUnlockState)
{
sb.AppendLine("The colony will not wake until the Elder falls. Until then you are a body, and the body is enough.\n");
}
else
{
sb.AppendLine($"Brood Mound (Hammer): Your nest, and no more than two of them may stand within {SvermConfig.HiveDensityRadius:0} meters of each other. Press it, or the hive at its foot, to feed it a whole stack out of your pack: any food, any wood, any resin. Honey and royal jelly are medicine now and it will not take them.\n");
sb.AppendLine($"Digestion: what you feed it is not yours to spend yet. It seeps into the nest's bank at {SvermConfigManagement.DigestRate:0.#} a second, and only what has arrived can be spent.\n");
sb.AppendLine($"Brood Eggs: the nest lays one every {SvermConfig.EggInterval:0} seconds and holds {SvermConfig.EggCapBase + 1} of them at its first stage, one more at each stage after. Every troop costs an egg as well as biomass - the egg grows back, the biomass does not.\n");
sb.AppendLine("Hive Market (Hammer): a counter raised within ten meters of a nest. Everything the colony buys is bought here, out of that nest's bank.\n");
sb.AppendLine($"Growth: {SvermHiveStage.NameOf(2)} {SvermHiveStage.PriceToLeave(1):0}, {SvermHiveStage.NameOf(3)} {SvermHiveStage.PriceToLeave(2):0}, {SvermHiveStage.NameOf(4)} {SvermHiveStage.PriceToLeave(3):0}. Each one costs that stage's whole tankful and opens the next rung of the roster.\n");
StringBuilder roster = new StringBuilder();
foreach (SvermBrood.Kind kind in SvermBrood.Roster)
{
roster.Append($"{kind.Display} {kind.Price:0} (from {SvermHiveStage.NameOf(kind.Stage)}, at most {kind.Cap}). ");
}
sb.AppendLine($"Troops: {roster}They follow when you ask, walk home when you let them go, and mend themselves.\n");
string haulers = state >= SvermConfig.HaulerUnlockState
? $", and up to {SvermConfigManagement.Haulers} haulers come out of the nest to carry food back into it"
: ", and the haulers who carry food back into it will not hatch until Bonemass falls";
sb.AppendLine($"Seeker Workers: free, and always free - no biomass, no egg, and a new one when an old one dies. Two trades that never share hands: up to {SvermConfigManagement.Farmers} farmers come out of the infected beehives to work the ground{haulers}. They are half a Seeker in size, in health and in reach, they take no orders and they never follow - they stay where they were born and defend what stands there.\n");
sb.AppendLine($"Blister Tick {SvermConfig.TickPrice:0}: buys a slot forever. It runs at what you are fighting and bursts, and the nest grows another one {SvermConfig.TickRespawnSeconds:0} seconds later, free.\n");
sb.AppendLine("Surrenal Glands 800 and Hyperplasia 1600: everything hatched after them is born with one star, then two.\n");
sb.AppendLine($"The beehives: raise vanilla hives inside the nest's ten meters and the colony takes them over after a minute - twice the speed, three times the honey, and royal jelly instead once Yagluth is down. Press honey or royal jelly on one of your own insects to heal it: {SvermConfig.HoneyHealing:0} and {SvermConfig.RoyalJellyHealing:0}.\n");
}
knownTexts["Sverm Secrets"] = sb.ToString();
}
/// <summary>
@ -255,6 +392,10 @@ namespace RacesOfValheim
sb.AppendLine("Vampiric Aura (Passive, toggle with 'I'):");
sb.AppendLine($"Always active, in every form, with no key to hold - only the on/off toggle. Drains a {auraRadiusDay}m radius by day, {auraRadiusNight}m by night, for magic damage that scales with your Blood Magic skill, healing you for the damage dealt. Enemies at or below {auraExecute}% health are executed outright. The aura hits for half in human form, full as a Bat, and double as Mist.\n");
// The live figure, so the entry cannot drift from the code: it is the same yardstick
// the Sverm's own claws are measured against, which is what keeps the three races even.
sb.AppendLine($"[Base Passive] Claws of the Beast: Blackened claws you did not forge and cannot put down. Bare-handed blows land at {SvermClaws.GetDamagePercent(state) * 100f:0}% of a full-grown pair's weight, all of it as slash, and they grow with every boss that falls. Draw a sword and they wait; sheathe it and they are back. They cannot be dropped, traded or stolen - and in bat or mist form you have no hands to hold them with.\n");
if (state >= 2)
sb.AppendLine("[Eikthyr Unlock] Bat Form ('G' Key, night only): Take the shape of a bat.\n");
@ -318,6 +459,10 @@ namespace RacesOfValheim
sb.AppendLine($"[Base Passive] The Beast Within: Physical kills automatically consume edible enemies. Your physical stats scale with every boss you defeat: +{arm} Armor, +{dmg} Damage, +{spd}% Speed, +{jmp}% Jump, and -{fall}% Fall Damage.\n");
// The live figure, so the entry cannot drift from the code: the same yardstick the
// Sverm's own claws are measured against, which is what keeps the three races even.
sb.AppendLine($"[Base Passive] Cursed Claws: The wolf's hands, kept on in the man's shape. Bare-handed blows land at {SvermClaws.GetDamagePercent(state) * 100f:0}% of a full-grown pair's weight, all of it as slash, and they grow with every boss that falls. Draw a sword and they wait; sheathe it and they are back. They cannot be dropped, traded or stolen - and in beast form the jaws do the work instead.\n");
if (state >= 3)
sb.AppendLine("[The Elder Unlock] Wolf Form ('G' Key, night only): Take the shape of a wolf. Faster and lighter on your feet, with three claw attacks of growing weight on Left, Right, and Middle Mouse.\n");
@ -411,6 +556,23 @@ namespace RacesOfValheim
sb.AppendLine("The bones of a dragon rise at your call, wreathed in frost. It rends with bite and claw, sweeps all around it with a spinning tail (Right Mouse), and its breath carries thrice the fury of Moder's.\n");
}
// ── The station. Figures come from SkadiGolem's own constants, which are also what
// MayRaise enforces, so the page and the refusal message can never disagree.
sb.AppendLine("\n-- THE CRYSTAL GOLEM --\n");
if (state < SkadiGolem.ModerProgressionState)
{
sb.AppendLine("The tear is cold. Nothing wakes in the stone until the mountain's queen has fallen.\n");
}
else
{
sb.AppendLine($"Cut one at a stonecutter for a stone golem's trophy, {SkadiGolem.CrystalCost} crystal and a dragon tear. The stone answers to no one who is not Skadi, so what you raise is yours and stays yours.\n");
sb.AppendLine($"It is bound to the stonecutter that shaped it and may never leave the {SkadiGolem.LeashRange:0} meters around it - the same circle the station itself builds in. It cannot be named, cannot be ordered and will not follow you. It guards the stone that cut it, and that is the whole of what it does.\n");
sb.AppendLine($"One stonecutter holds {SkadiGolem.MaxPerStation} of them, and no more than {SkadiGolem.MaxInArea} may stand within a day's walk of each other. Break the stonecutter and what it cut goes still {SkadiGolem.WitherSeconds:0} seconds later.\n");
}
knownTexts["Skadi Secrets"] = sb.ToString();
}

View file

@ -93,6 +93,38 @@ namespace RacesOfValheim
__result = false;
}
}
// Sverm Race Logic - Hive Pheromones. No progression gate at all, unlike
// Aswid's escalating list: an invertebrate is kin from the first minute.
//
// That absence of a gate is doing real work rather than saving a few lines.
// Every invertebrate in the game lives from the Swamp onward, so a gated
// version would have handed the race nothing until Bonemass; ungated, a
// newborn Sverm walks through leeches and deathsquitoes, which is the whole
// of its early game.
//
// Bonemass is deliberately NOT here. It is a mass of ooze and it would
// qualify, but a boss that ignores the player is not a boss.
if (p.m_customData.ContainsKey("Race") && p.m_customData["Race"] == SvermConfig.RaceId)
{
string prefabName = monster.gameObject.name.ToLower();
// "blob" covers Blob, BlobElite, BlobTar and the Ashlands lava blob
// whatever it turns out to be called - which is why the one prefab name
// still unconfirmed in the design doc costs nothing here.
// "seeker" covers Seeker, SeekerBrood, SeekerBrute and SeekerQueen.
bool isKin = prefabName.Contains("blob")
|| prefabName.Contains("leech")
|| prefabName.Contains("tick")
|| prefabName.Contains("deathsquito")
|| prefabName.Contains("gjall")
|| prefabName.Contains("seeker");
if (isKin && !prefabName.Contains("bonemass"))
{
__result = false;
}
}
}
}
}

View file

@ -20,7 +20,12 @@ namespace RacesOfValheim
"Trol",
"Furling",
DvergarConfig.RaceId,
TrentaConfig.RaceId
TrentaConfig.RaceId,
// Sverm sizes itself only from the Queen on (Surrenal Glands, +10%). It is listed here
// for every tier all the same: below that tier its own ApplyScale asks for 1, which is
// the same answer another race's reset would give, and being on the list is what stops
// those resets from fighting it once the +10% does arrive.
SvermConfig.RaceId
};
public static bool ManagesOwnScale(string race)

View file

@ -34,8 +34,12 @@ namespace RacesOfValheim
FurlingConfig.Bind(Config);
SkadiConfig.Bind(Config);
SkeletonConfig.Bind(Config);
SvermConfigManagement.Bind(Config);
TrentaConfigManagement.Bind(Config);
TrolConfig.Bind(Config);
// Not a race: a summoned mount two races share, so it binds after the races rather
// than inside the alphabetical run above.
WarVultureConfig.Bind(Config);
harmony.PatchAll();
gameObject.AddComponent<FenrirRace>();
gameObject.AddComponent<SkadiRace>();
@ -46,6 +50,7 @@ namespace RacesOfValheim
gameObject.AddComponent<DraughRace>();
gameObject.AddComponent<DvergarRace>();
gameObject.AddComponent<TrentaRace>();
gameObject.AddComponent<SvermRace>();
// Not a race: a perk two races share (Skadi and Trol build inside troll caves), so it
// gets its own component rather than living inside either one's Update.
gameObject.AddComponent<RaceCaveBuilding>();
@ -119,6 +124,8 @@ namespace RacesOfValheim
DraughRace.Instance.CreateModAssets();
DvergarRace.Instance.CreateModAssets();
TrentaRace.Instance.CreateModAssets();
SvermRace.Instance.CreateModAssets();
WarVultureItem.Register();
}
// --- RACE SELECTION UI ---
public void ShowRaceSelectionMenu()
@ -262,6 +269,7 @@ namespace RacesOfValheim
// Row 3 (y = -140)
CreateRaceButtonWithConfirm("Dvergar", new Vector2(-450, -140), GetDvergarIcon(), "Small, stubborn smiths of the deep. Frail of frame, but masters of metal, mine and market.", SelectDvergar);
CreateRaceButtonWithConfirm("Trenta", new Vector2(-150, -140), GetTrentaIcon(), "Tree-born folk, kin to root and leaf. Patient and hard to fell.", SelectTrenta);
CreateRaceButtonWithConfirm("Sverm", new Vector2(150, -140), GetSvermIcon(), "Chitin-born swarm kin. Armoured from birth and never slowed, venomous, at peace with every crawling thing - but blunt trauma and fire find the seams.", SelectSverm);
GUIManager.BlockInput(true);
}
@ -628,6 +636,58 @@ namespace RacesOfValheim
}
}
private void SelectSverm()
{
if (Player.m_localPlayer != null)
{
Player.m_localPlayer.m_customData["Race"] = SvermConfig.RaceId;
ZNetView nview = Player.m_localPlayer.GetComponent<ZNetView>();
if (nview != null && nview.IsValid()) nview.GetZDO().Set("RacesOfValheim_Race", SvermConfig.RaceId);
Player.m_localPlayer.GetSEMan().AddStatusEffect(SvermConfig.StatsSE.GetStableHashCode(), true);
// The carapace seals chest, legs and helmet, so whatever the player was wearing in
// those slots has to come off before the visual rebuild - otherwise the old chest
// stays on screen underneath a carapace that the equip patch will refuse to remove
// later, because the refusal is on EQUIPPING, not on unequipping.
Humanoid humanoid = Player.m_localPlayer;
foreach (ItemDrop.ItemData.ItemType slot in SvermConfig.SealedSlots)
{
ItemDrop.ItemData worn = null;
foreach (ItemDrop.ItemData item in humanoid.GetInventory().GetEquippedItems())
{
if (item != null && item.m_shared != null && item.m_shared.m_itemType == slot) { worn = item; break; }
}
if (worn != null) humanoid.UnequipItem(worn, false);
}
VisEquipment visEq = Player.m_localPlayer.GetComponent<VisEquipment>();
if (visEq != null)
{
visEq.GetType().GetMethod("UpdateVisuals", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Public)?.Invoke(visEq, null);
}
Player.m_localPlayer.Message(MessageHud.MessageType.Center, "You chose the path of the Sverm.");
CloseRaceSelectionMenu();
}
}
private Sprite GetSvermIcon()
{
GameObject prefab = PrefabManager.Cache.GetPrefab<ItemDrop>("TrophySeekerBrute")?.gameObject;
if (prefab == null) prefab = PrefabManager.Cache.GetPrefab<ItemDrop>("TrophySeeker")?.gameObject;
if (prefab == null) prefab = PrefabManager.Cache.GetPrefab<ItemDrop>("Chitin")?.gameObject;
if (prefab != null)
{
ItemDrop drop = prefab.GetComponent<ItemDrop>();
if (drop != null && drop.m_itemData.m_shared.m_icons.Length > 0)
{
return drop.m_itemData.m_shared.m_icons[0];
}
}
return null;
}
private Sprite GetDvergarIcon()
{
GameObject prefab = PrefabManager.Cache.GetPrefab<ItemDrop>("HelmetDverger")?.gameObject;

View file

@ -34,9 +34,10 @@
<Reference Include="assembly_valheim">
<HintPath>..\..\..\..\..\..\Program Files (x86)\Steam\steamapps\common\Valheim\valheim_Data\Managed\assembly_valheim.dll</HintPath>
</Reference>
<!-- Needed by SkadiHollow: ZoneSystem.ZoneLocation.m_prefab is a SoftReference<GameObject>,
and touching any member of it (Load/Asset/IsLoaded) does not compile unless the assembly
that declares SoftReference<T> is referenced. Nothing else in the mod uses it yet. -->
<!-- ZoneSystem.ZoneLocation.m_prefab is a SoftReference<GameObject>, and touching any member of
it (Load/Asset/IsLoaded) does not compile unless the assembly that declares SoftReference<T>
is referenced. Nothing in the mod uses it right now - the hidden hollow that needed it is
gone - but the build's Copy step below still ships the dll, so the reference stays. -->
<Reference Include="SoftReferenceableAssets">
<HintPath>..\..\..\..\..\..\Program Files (x86)\Steam\steamapps\common\Valheim\valheim_Data\Managed\SoftReferenceableAssets.dll</HintPath>
</Reference>

View file

@ -48,12 +48,6 @@ namespace RacesOfValheim
// ─── Passive combat ──────────────────────────────────────────────────
public static ConfigEntry<float> BonusFrostDamagePerState;
// ─── Skadis Nokkel / the hidden hollow ───────────────────────────────
public static ConfigEntry<float> HollowCooldown;
public static ConfigEntry<float> HollowPortalCloseDelay;
public static ConfigEntry<float> HollowPortalSpawnDistance;
public static ConfigEntry<float> HollowEntryHeight;
// ─── Dragon forms: scale ─────────────────────────────────────────────
public static ConfigEntry<float> DrakeScale;
public static ConfigEntry<float> ModerScale;
@ -108,16 +102,6 @@ namespace RacesOfValheim
BonusFrostDamagePerState = config.Bind(combat, "Bonus Frost Damage Per State", 2f,
new ConfigDescription("Flat frost damage added to every hit the player lands, multiplied by the current progression state.", new AcceptableValueRange<float>(0f, 10f)));
const string hollow = "Skadi - Hidden Hollow";
HollowCooldown = config.Bind(hollow, "Cooldown", 120f,
new ConfigDescription("Seconds between openings of the hollow. This is the only brake on Skadis Nokkel - it costs no stamina, eitr or health - and it never applies to LEAVING: stepping in and changing your mind must not lock you in.", new AcceptableValueRange<float>(0f, 600f)));
HollowPortalCloseDelay = config.Bind(hollow, "Portal Close Delay", 5f,
new ConfigDescription("Seconds the portal pair lingers after the player comes back out. Until then both ends simply stand there - unlike the Trenta portal, this one has no lifetime of its own.", new AcceptableValueRange<float>(0f, 60f)));
HollowPortalSpawnDistance = config.Bind(hollow, "Portal Spawn Distance", 2f,
new ConfigDescription("Metres in front of the player the outside end of the portal appears.", new AcceptableValueRange<float>(0.5f, 10f)));
HollowEntryHeight = config.Bind(hollow, "Entry Height", 1f,
new ConfigDescription("Height above the claimed troll cave's own origin that the inner portal stands at. Raise it if arriving ever puts the player inside the ground.", new AcceptableValueRange<float>(0f, 20f)));
const string spell = "Skadi - Cold Spell";
SpellStaminaCost = config.Bind(spell, "Stamina Cost", 20f,
new ConfigDescription("Stamina spent per cast.", new AcceptableValueRange<float>(0f, 100f)));

View file

@ -0,0 +1,460 @@
using System.Collections.Generic;
using HarmonyLib;
using Jotunn.Configs;
using Jotunn.Entities;
using Jotunn.Managers;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The Skadi station: crystal golems, cut at a stonecutter and bound to it.
///
/// Eighth of the per-race item-progression chains, and the odd one out in two ways that decide
/// everything else in this file.
///
/// FIRST, the station is not ours. Every other chain builds its own bench - a trough, a bone pile,
/// a composter - and can therefore hang a MonoBehaviour on it, count its own garrison from it, and
/// mark its thralls when it falls. The stonecutter is vanilla's, and nothing here modifies it: the
/// golem carries the stonecutter's position in its own ZDO and asks the world whether one still
/// stands there. That is why this chain does not use RaisedThrall, which is otherwise exactly the
/// right component - RaisedThrall's wither depends on the station registering itself, and a vanilla
/// piece never will.
///
/// SECOND, a golem is not a follower. RaisedThrall's whole vocabulary - follow me, stand down, call
/// to arms - is wrong for something that may not leave a twenty metre circle. There is deliberately
/// no Tameable on it either: it is tame, so it will never turn on anyone, but it cannot be named,
/// ordered, or walked away with. It guards the stone that shaped it, and that is all it does.
///
/// The three limits are the design, not decoration:
/// never further than 20 m from its stonecutter (the vanilla station build range)
/// two per stonecutter
/// ten per square mile
/// The first is enforced on the golem (SkadiGolemGuard), the other two at the moment of building,
/// through PieceDensityLimit's single Player.PlacePiece prefix - refusing later would spend a
/// dragon tear before telling anyone no.
/// </summary>
public static class SkadiGolem
{
// ─── Names ───────────────────────────────────────────────────────────
public const string GolemName = "SkadiCrystalGolem";
public const string SeedPieceName = "SkadiCrystalGolemSeed";
public const string DisplayName = "Crystal Golem";
private const string SourceGolem = "StoneGolem";
/// <summary>
/// The seed piece's model, and it is chosen for its BUILD GHOST: the golem itself only exists
/// a frame later, so a standing stone is what the player actually aims with. Everything the
/// ward DOES - the private area above all - is stripped off the clone below; a chain that
/// quietly planted a ward every time you cut a golem would be a much worse bug than a wrong
/// silhouette.
/// </summary>
private const string SourcePiece = "guard_stone";
public const string StationPrefab = "piece_stonecutter";
// ─── The price ───────────────────────────────────────────────────────
// Moder needs no state check of her own to BUILD one - her drop is in the recipe - but the
// gate asks anyway, because the recipe is not the only way an item reaches an inventory.
public const string GolemTrophy = "TrophySGolem";
public const string CrystalItem = "Crystal";
public const int CrystalCost = 10;
public const string ModerDrop = "DragonTear";
public const int ModerProgressionState = 5;
// ─── The limits ──────────────────────────────────────────────────────
/// <summary>
/// How far a golem may get from its stonecutter. Twenty metres because that is the
/// stonecutter's own build range in vanilla, so the circle a golem defends is exactly the
/// circle it could have been built in - one number, visible in game, not two that nearly
/// agree.
/// </summary>
public const float LeashRange = 20f;
/// <summary>
/// Past this it has stopped walking home and started failing to. A golem that has been pushed
/// into water, or that stands on the wrong side of something it cannot path around, would
/// otherwise sit outside its leash forever - so at half again the leash it is simply put back.
/// It is a failsafe for a stuck pathfinder, not a movement mechanic.
/// </summary>
public const float HardLeashRange = 30f;
public const int MaxPerStation = 2;
// Ten per square mile. 2.59 km2, the same area the Fenrir's trough is measured in, so the two
// stations are spaced by the same yardstick even though the numbers differ.
public const int MaxInArea = 10;
public const float DensityAreaKm2 = 2.59f;
/// <summary>
/// How long a golem outlives the stonecutter that cut it. Shorter than the Fenrir trough's
/// five minutes because there is nothing to rebuild: a stonecutter costs ten stone and two
/// wood, so "put it back" is a moment's work, and a longer grace would just mean a garrison
/// that survives being moved.
/// </summary>
public const float WitherSeconds = 60f;
/// <summary>Slack when asking "is my stonecutter still there" - a station never moves.</summary>
public const float StationCheckRange = 2f;
/// <summary>
/// Only asked this close to home, for the reason RaisedThrall's wither carries the same guard:
/// further out the station's zone is probably not loaded, so "nothing stands there" would be a
/// lie. A golem is leashed to 20 m anyway, so this is never the reason one survives.
/// </summary>
public const float HomeCheckRange = 40f;
// ─── Behaviour ───────────────────────────────────────────────────────
/// <summary>Idle wander around the stonecutter. Half the leash, so it never idles onto it.</summary>
private const float WanderRange = 10f;
/// <summary>
/// The station's m_name, read off the stonecutter prefab once at registration.
///
/// It is NOT the prefab name: CraftingStation.HaveBuildStationInRange compares against
/// m_name, which is a localisation token, while Jotunn's PieceConfig.CraftingStation wants the
/// prefab name. Both spellings are needed and they are not the same string, which is exactly
/// the kind of thing worth reading off the game once instead of guessing at twice.
/// </summary>
private static string StationName = "$piece_stonecutter";
public static void Register()
{
CacheStationName();
if (!RegisterGolem()) return;
RegisterSeedPiece();
PieceDensityLimit.RegisterGate(SeedPieceName, MayRaise);
}
private static void CacheStationName()
{
GameObject station = PrefabManager.Cache.GetPrefab<GameObject>(StationPrefab);
CraftingStation component = station != null ? station.GetComponent<CraftingStation>() : null;
if (component == null || string.IsNullOrEmpty(component.m_name))
{
Jotunn.Logger.LogWarning($"[Skadi] Could not read the stonecutter's station name off " +
$"'{StationPrefab}'; falling back to '{StationName}'.");
return;
}
StationName = component.m_name;
}
// ---------------------------------------------------------------- the golem
/// <summary>
/// A vanilla stone golem, tamed, frozen over, and made incapable of the three things it must
/// never do.
///
/// Health, damage and resistances stay exactly as vanilla has them. A mountain golem is a slow
/// wall with a great deal of health, which is precisely what a defender that cannot leave its
/// circle should be - there is nothing to retune, and nothing here does.
///
/// What IS written over:
/// - it does not sleep. Vanilla golems start as rocks and wake when something comes near;
/// a guard that has to be woken up is not a guard.
/// - it does not target player-built anything (m_attackPlayerObjects). That is the first
/// half of "never attacks structures"; the second half is the WearNTear guard below,
/// because an area attack aimed at a greydwarf can still land on a wall.
/// - it does not flee. A golem holds its ground or it dies on it.
/// - it gives up a chase past its leash, measured from its own spawn point, which
/// SkadiGolemGuard pins to the stonecutter. That is vanilla's own leash, used as intended
/// rather than reimplemented.
/// - it drops nothing. Two golems per stonecutter that could be farmed for crystals and
/// trophies would be a mint, and the trophy is this chain's own gate item.
/// It never attacks tamed creatures or players for free: Attack.DoMeleeAttack only lets a
/// tamed attacker through to targets its own AI counts as enemies, which is checked in the
/// game's code rather than assumed here.
/// </summary>
private static bool RegisterGolem()
{
GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(GolemName, SourceGolem);
if (prefab == null)
{
Jotunn.Logger.LogWarning($"[Skadi] Could not clone {SourceGolem}; {DisplayName} not registered.");
return false;
}
Character character = prefab.GetComponent<Character>();
if (character != null) character.m_name = DisplayName;
SkadiIce.Apply(prefab);
BaseAI ai = prefab.GetComponent<BaseAI>();
if (ai != null)
{
ai.m_randomMoveRange = WanderRange;
ai.m_avoidWater = true;
}
MonsterAI monster = prefab.GetComponent<MonsterAI>();
if (monster != null)
{
monster.m_sleeping = false;
monster.m_attackPlayerObjects = false;
// It notices what comes into the circle it defends, and nothing outside it. Being
// hit still turns it around - OnDamaged sets a target whatever the alert range says -
// which is the difference between a defender and a statue.
monster.m_alertRange = LeashRange;
monster.m_maxChaseDistance = LeashRange;
monster.m_fleeIfLowHealth = 0f;
monster.m_fleeIfNotAlerted = false;
monster.m_fleeIfHurtWhenTargetCantBeReached = false;
}
foreach (CharacterDrop drops in prefab.GetComponentsInChildren<CharacterDrop>(true))
{
if (drops != null) Object.DestroyImmediate(drops);
}
foreach (Procreation breeding in prefab.GetComponentsInChildren<Procreation>(true))
{
if (breeding != null) Object.DestroyImmediate(breeding);
}
// "Ten seconds unhurt, then 2% a second" - the Skeleton's sentry regeneration, which three
// chains now share. A guard that cannot heal between raids is a guard you rebuild.
prefab.AddComponent<SkeletonSentryBehaviour>();
prefab.AddComponent<SkadiGolemGuard>();
PrefabManager.Instance.AddPrefab(prefab);
Jotunn.Logger.LogInfo($"[Skadi] {GolemName} from '{SourceGolem}': awake, tame, leashed, " +
"blind to structures, drops nothing.");
return true;
}
// ---------------------------------------------------------------- the seed piece
/// <summary>
/// The hammer entry, and the same trick SkeletonSentry uses for the same reason: the hammer
/// builds Piece, a golem is a Character, so a piece is placed and swaps itself for one.
/// </summary>
private static void RegisterSeedPiece()
{
GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(SeedPieceName, SourcePiece);
if (prefab == null)
{
Jotunn.Logger.LogWarning($"[Skadi] Could not clone {SourcePiece}; {DisplayName} cannot be built.");
return;
}
// Everything the ward does goes - PrivateArea and its effect areas above all. What is
// wanted is a placeable shell with the right outline, alive for one frame.
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);
}
AswidBloodRefinery.StripOffensive(prefab, SeedPieceName);
SkadiIce.Apply(prefab);
prefab.AddComponent<SkadiGolemSeed>();
Piece piece = prefab.GetComponent<Piece>() ?? prefab.AddComponent<Piece>();
piece.m_resources = new Piece.Requirement[0];
piece.m_name = DisplayName;
piece.m_canBeRemoved = true;
piece.m_groundPiece = true;
piece.m_groundOnly = true;
piece.m_icon = BorrowIcon(CrystalItem);
PieceManager.Instance.AddPiece(new CustomPiece(prefab, fixReference: false, new PieceConfig
{
Name = DisplayName,
Description = "Cut at the stone and woken with a tear. It will not follow you, and it " +
"will not leave the stonecutter that shaped it.",
PieceTable = PieceTables.Hammer,
Category = PieceCategories.Crafting,
// The stonecutter is the station, so vanilla itself refuses to place one anywhere its
// golem could not then be bound - the gate below never has to be the first to say no.
CraftingStation = CraftingStations.Stonecutter,
Icon = BorrowIcon(CrystalItem),
Requirements = new[]
{
new RequirementConfig(GolemTrophy, 1, 0, true),
new RequirementConfig(CrystalItem, CrystalCost, 0, true),
new RequirementConfig(ModerDrop, 1, 0, true),
}
}));
}
// ---------------------------------------------------------------- the gate
/// <summary>
/// The two caps that cannot live on the golem, asked at the moment of building.
///
/// Order matters: race, then boss, then the stonecutter, then its own two, so the first thing
/// a player is told is the thing they can actually do something about.
///
/// HONEST LIMIT, inherited from PieceDensityLimit and worth repeating: the counts are over
/// ZDOs, which on a remote client are only the ZDOs the server has sent. On the host they are
/// exact. Where a count cannot be taken at all the placement is allowed - refusing on no
/// information is worse than a cap that occasionally misses.
/// </summary>
public static bool MayRaise(Player player, Vector3 position)
{
if (player == null) return true;
if (!SkadiRace.IsLocalSkadi())
{
player.Message(MessageHud.MessageType.Center, "The stone does not answer to you.");
return false;
}
if (BossProgressionManager.GetCurrentProgressionState() < ModerProgressionState)
{
player.Message(MessageHud.MessageType.Center,
"The tear is cold. Nothing wakes in the stone until the mountain's queen has fallen.");
return false;
}
CraftingStation station = FindStonecutter(position);
if (station == null)
{
player.Message(MessageHud.MessageType.Center, "It needs a stonecutter to be cut at.");
return false;
}
int bound = CountBoundTo(station.transform.position);
if (bound >= MaxPerStation)
{
player.Message(MessageHud.MessageType.Center,
$"That stonecutter already holds {bound}. It will not hold more.");
return false;
}
int nearby = PieceDensityLimit.Count(GolemName, position, PieceDensityLimit.RadiusForArea(DensityAreaKm2));
if (nearby >= MaxInArea)
{
player.Message(MessageHud.MessageType.Center,
$"There are already {nearby} of these within a day's walk. The stone is spent.");
return false;
}
return true;
}
/// <summary>
/// The stonecutter that owns a point, by the station's OWN build range rather than by a number
/// of ours - so the circle a golem may be cut in and the circle it may stand in are the same
/// circle, and stay the same if a game update retunes the station.
/// </summary>
public static CraftingStation FindStonecutter(Vector3 position)
{
return CraftingStation.HaveBuildStationInRange(StationName, position);
}
/// <summary>True if a stonecutter still stands at that exact point.</summary>
public static bool StonecutterStandsAt(Vector3 position)
{
return CraftingStation.FindClosestStationInRange(StationName, position, StationCheckRange) != null;
}
/// <summary>
/// How many golems already answer to the stonecutter at that point, counted over ZDOs and not
/// over loaded creatures.
///
/// That distinction is the whole cap: a golem in an unloaded zone is still a golem, and
/// counting only what is loaded would make walking away and coming back the way to hold six.
/// Dead ones are gone from the world entirely, so a slot frees itself with no bookkeeping.
/// </summary>
public static int CountBoundTo(Vector3 station)
{
List<ZDO> zdos = new List<ZDO>();
if (!PieceDensityLimit.Gather(GolemName, zdos)) return 0;
int count = 0;
foreach (ZDO zdo in zdos)
{
if (zdo == null) continue;
// A generous epsilon: a station never moves, so this only has to survive float
// round-tripping through the ZDO.
Vector3 anchor = zdo.GetVec3(SkadiGolemGuard.KeyAnchor, Vector3.zero);
if (anchor != Vector3.zero && Vector3.SqrMagnitude(anchor - station) < 0.25f) count++;
}
return count;
}
// ---------------------------------------------------------------- known pieces
/// <summary>
/// Learnt by being Skadi, and not by having killed Moder.
///
/// Deliberate: the entry shows up greyed out with its price on it, which is how every vanilla
/// recipe tells you what to go and get. Gating the entry itself on the boss would hide it
/// until a relog anyway - OnSpawned is the only moment this is asked - so the boss check lives
/// where it can be asked every time instead, in MayRaise.
/// </summary>
public static void EnsureKnown(Player player)
{
if (player == null || !SkadiRace.IsLocalSkadi()) return;
GameObject prefab = PrefabManager.Instance.GetPrefab(SeedPieceName);
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();
}
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;
if (icons != null && icons.Length > 0 && icons[0] != null) return icons[0];
Jotunn.Logger.LogWarning($"[Skadi] Could not borrow the icon from '{prefabName}'.");
return null;
}
}
[HarmonyPatch(typeof(Player), "OnSpawned")]
public static class SkadiGolemKnownPatch
{
public static void Postfix(Player __instance)
{
if (__instance != Player.m_localPlayer) return;
SkadiGolem.EnsureKnown(__instance);
}
}
/// <summary>
/// The second half of "it never attacks structures".
///
/// m_attackPlayerObjects stops a golem CHOOSING a wall as a target; it does not stop one landing a
/// swing on the wall behind a greydwarf, because Attack.DoMeleeAttack has no tamed check on the
/// destructible path at all - only on the character one. Read off the game's own code rather than
/// assumed, and it is why this patch exists instead of one field being trusted to do both jobs.
///
/// The signature is spelled out and bound positionally for the reason PieceDensityLimitPatch
/// carries in its own comment: Damage returns VOID, so a prefix returning false is the whole
/// mechanism, and asking for a __result on a void method throws at patch time and takes the rest
/// of the mod's patches down with it.
/// </summary>
[HarmonyPatch(typeof(WearNTear), "Damage", new[] { typeof(HitData) })]
public static class SkadiGolemStructureGuardPatch
{
public static bool Prefix(HitData __0)
{
if (__0 == null) return true;
Character attacker = __0.GetAttacker();
return attacker == null || attacker.GetComponent<SkadiGolemGuard>() == null;
}
}
}

View file

@ -0,0 +1,302 @@
using System;
using HarmonyLib;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// One crystal golem: tame, bound to a stonecutter, and unable to get more than its leash away
/// from it.
///
/// Same shape as RaisedThrall - an anchor in the creature's own ZDO, a leash pinned to it, a
/// wither clock that starts when the station is gone - and deliberately NOT that class. Two
/// differences make it a copy rather than a reuse, and both are in SkadiGolem's own comment: the
/// station is vanilla's and cannot register itself, and a golem takes no orders, so the follow,
/// stand-down and call-to-arms half of RaisedThrall is not merely unused here but wrong.
///
/// The leash is three layers, weakest first, because each one covers the case the one before it
/// cannot:
/// - vanilla's own chase limit (m_maxChaseDistance, measured from m_spawnPoint, which is pinned
/// to the stonecutter below) makes it GIVE UP on anything it would have to leave home for;
/// - the patrol point, re-pinned every tick, is what brings it back and what keeps it wandering
/// around the station rather than drifting after it has been pushed or knocked back;
/// - and past half again the leash it is simply put back, because at that distance it is not
/// walking home slowly, it is failing to walk home at all.
/// </summary>
public class SkadiGolemGuard : MonoBehaviour
{
public const string KeyAnchor = "RoV_golemAnchor";
public const string KeyOrphanAt = "RoV_golemOrphanAt";
/// <summary>
/// One second, and not the two RaisedThrall uses. Vanilla will not drop a target it can still
/// SEE, whatever m_maxChaseDistance says - read off MonsterAI.UpdateTarget, where the give-up
/// test also wants a second of having lost sight of it - so this tick is what actually holds
/// the leash, and how far past twenty metres a golem gets is how far it walks between two of
/// them. A stone golem is slow; at one second that is a stride.
/// </summary>
private const float TickSeconds = 1f;
// SetPatrolPoint(Vector3) is private - only the parameterless overload, which uses the
// creature's current position, is public. Resolved once here rather than per call, exactly as
// RaisedThrall does it.
private static readonly System.Reflection.MethodInfo SetPatrolPointMethod =
AccessTools.Method(typeof(BaseAI), "SetPatrolPoint", new[] { typeof(Vector3) });
// m_spawnPoint is protected, and it is the point vanilla measures m_maxChaseDistance from -
// read off MonsterAI.UpdateTarget rather than assumed, because "chase distance" could just as
// easily have meant distance from the target.
private static readonly System.Reflection.FieldInfo SpawnPointField =
AccessTools.Field(typeof(BaseAI), "m_spawnPoint");
private Character m_character;
private BaseAI m_ai;
private MonsterAI m_monsterAI;
private ZNetView m_nview;
private Rigidbody m_body;
private void Awake()
{
m_character = GetComponent<Character>();
m_ai = GetComponent<BaseAI>();
m_monsterAI = GetComponent<MonsterAI>();
m_nview = GetComponent<ZNetView>();
m_body = GetComponent<Rigidbody>();
InvokeRepeating("Tick", TickSeconds, TickSeconds);
}
/// <summary>Where the stonecutter that cut this one stands, or null if it was cut by none.</summary>
public Vector3? Anchor
{
get
{
if (m_nview == null || !m_nview.IsValid()) return null;
Vector3 anchor = m_nview.GetZDO().GetVec3(KeyAnchor, Vector3.zero);
return anchor == Vector3.zero ? (Vector3?)null : anchor;
}
}
/// <summary>
/// Called once, by the seed piece that placed it. Tames it, marks whose stonecutter it is, and
/// sends it home - all three, so nothing else has to remember to do any of them.
/// </summary>
public void Bind(Vector3 anchor)
{
if (m_nview == null || !m_nview.IsValid()) return;
m_nview.GetZDO().Set(KeyAnchor, anchor);
if (m_monsterAI != null) m_monsterAI.MakeTame();
if (m_character != null) m_character.SetTamed(true);
GoHome();
}
// ---------------------------------------------------------------- the tick
private void Tick()
{
if (m_nview == null || !m_nview.IsValid() || !m_nview.IsOwner()) return;
if (m_character == null || m_character.IsDead()) return;
if (TickWither()) return;
Vector3? anchor = Anchor;
if (anchor == null) return;
float distance = Vector3.Distance(transform.position, anchor.Value);
if (distance > SkadiGolem.LeashRange)
{
// Whatever it was going after is outside the circle it defends, so it stops going
// after it. Vanilla would drop the target itself a second or so later through
// m_maxChaseDistance; doing it here as well means the leash does not depend on that
// one field surviving a game update.
ClearTarget();
}
if (distance > SkadiGolem.HardLeashRange) SnapHome(anchor.Value);
// Every tick, and not only when it has strayed: this is also what pins m_spawnPoint after
// a zone reload, where Bind is never called again.
GoHome();
}
/// <summary>
/// Starts the clock when the stonecutter is gone, and stops the golem when it runs out.
/// Returns true once it has done so, so the caller stops bothering with it.
///
/// Without some form of this a stonecutter is a duplication exploit: cut two golems, take the
/// stonecutter down, put it up somewhere else, and keep both from every round.
/// </summary>
private bool TickWither()
{
Vector3? anchor = Anchor;
if (anchor == null || ZNet.instance == null) return false;
long stamp = m_nview.GetZDO().GetLong(KeyOrphanAt, 0L);
if (stamp == 0L)
{
// Only asked from close to home - see SkadiGolem.HomeCheckRange. Being leashed to
// twenty metres, a golem is essentially always close enough, so this guard is about
// the moment after a zone loads rather than about distance.
if (Vector3.SqrMagnitude(transform.position - anchor.Value) >
SkadiGolem.HomeCheckRange * SkadiGolem.HomeCheckRange) return false;
if (SkadiGolem.StonecutterStandsAt(anchor.Value)) return false;
MarkOrphaned();
return false;
}
// Put back in time, on the same spot: the clock is cleared and the golem lives. It opens
// no exploit - a stonecutter on the same spot owns these golems by anchor anyway.
if (SkadiGolem.StonecutterStandsAt(anchor.Value))
{
m_nview.GetZDO().Set(KeyOrphanAt, 0L);
return false;
}
double elapsed = (ZNet.instance.GetTime() - new DateTime(stamp)).TotalSeconds;
if (elapsed < SkadiGolem.WitherSeconds) return false;
Crumble();
return true;
}
/// <summary>Starts the wither clock, once. Idempotent, so it cannot be restarted and keep an
/// orphan alive forever.</summary>
private void MarkOrphaned()
{
if (m_nview == null || !m_nview.IsValid() || ZNet.instance == null) return;
if (m_nview.GetZDO().GetLong(KeyOrphanAt, 0L) != 0L) return;
m_nview.ClaimOwnership();
m_nview.GetZDO().Set(KeyOrphanAt, ZNet.instance.GetTime().Ticks);
if (Player.m_localPlayer != null &&
Vector3.Distance(Player.m_localPlayer.transform.position, transform.position) < 30f)
{
Player.m_localPlayer.Message(MessageHud.MessageType.Center,
"The stonecutter is gone. What it cut will not outlast it by long.");
}
}
/// <summary>
/// Pins the patrol point - and the spawn point vanilla measures its own chase limit from -
/// back onto the stonecutter. Cheap enough to call on a timer, and calling it repeatedly is
/// what stops a golem drifting after it has been pushed or knocked back.
/// </summary>
private void GoHome()
{
Vector3? anchor = Anchor;
if (anchor == null || m_ai == null) return;
if (SpawnPointField != null) SpawnPointField.SetValue(m_ai, anchor.Value);
if (SetPatrolPointMethod != null)
{
SetPatrolPointMethod.Invoke(m_ai, new object[] { anchor.Value });
}
else
{
// Fall back to writing the two fields the private method writes.
Traverse traverse = Traverse.Create(m_ai);
traverse.Field("m_patrolPoint").SetValue(anchor.Value);
traverse.Field("m_patrol").SetValue(true);
}
}
/// <summary>Forgets whatever it was going after, creature or otherwise.</summary>
private void ClearTarget()
{
if (m_monsterAI == null) return;
Traverse traverse = Traverse.Create(m_monsterAI);
traverse.Field("m_targetCreature").SetValue(null);
traverse.Field("m_targetStatic").SetValue(null);
}
/// <summary>
/// The failsafe, and only that. A golem that is this far out has not wandered - it has been
/// pushed somewhere it cannot path back from, and the alternative to putting it back is one
/// that stands in a lake until its stonecutter falls.
/// </summary>
private void SnapHome(Vector3 anchor)
{
Vector2 offset = UnityEngine.Random.insideUnitCircle * 3f;
Vector3 destination = anchor + new Vector3(offset.x, 0.5f, offset.y);
transform.position = destination;
if (m_body != null) m_body.linearVelocity = Vector3.zero;
ClearTarget();
Jotunn.Logger.LogWarning($"[Skadi] A golem was {SkadiGolem.HardLeashRange:0} m or more from its " +
"stonecutter and could not walk back; it was put back.");
}
private void Crumble()
{
if (m_character == null || m_character.IsDead()) return;
HitData hit = new HitData();
hit.m_damage.m_damage = 1E+10f;
hit.m_hitType = HitData.HitType.Undefined;
m_character.ApplyDamage(hit, true, false);
}
}
/// <summary>
/// Lives for one frame: swaps itself for the golem and goes. Owner only, so in multiplayer exactly
/// one golem stands up rather than one per client.
///
/// The stonecutter is looked up again here rather than handed over by the placement gate, and that
/// is deliberate: both call SkadiGolem.FindStonecutter with the same point, so both get the same
/// answer, and there is no piece of state between them that can go stale or arrive out of order.
///
/// If the lookup comes back empty the materials are lost, and that is the honest outcome rather
/// than an oversight: it can only happen if the stonecutter was taken down between the gate saying
/// yes and this frame, and the alternative - a golem anchored to nothing - would wither in a
/// minute anyway while looking like a bug.
/// </summary>
public class SkadiGolemSeed : MonoBehaviour
{
private void Start()
{
ZNetView nview = GetComponent<ZNetView>();
if (nview == null || !nview.IsValid() || !nview.IsOwner()) return;
GameObject prefab = ZNetScene.instance != null
? ZNetScene.instance.GetPrefab(SkadiGolem.GolemName)
: null;
if (prefab == null)
{
Jotunn.Logger.LogWarning($"[Skadi] No '{SkadiGolem.GolemName}' in ZNetScene; nothing was cut.");
ZNetScene.instance.Destroy(gameObject);
return;
}
CraftingStation station = SkadiGolem.FindStonecutter(transform.position);
if (station == null)
{
Jotunn.Logger.LogWarning("[Skadi] No stonecutter in range at the moment of cutting; " +
"nothing was raised.");
ZNetScene.instance.Destroy(gameObject);
return;
}
GameObject spawned = Instantiate(prefab, transform.position, transform.rotation);
// Bind tames it, marks whose stonecutter it is, and sends it home - all three.
SkadiGolemGuard guard = spawned.GetComponent<SkadiGolemGuard>();
if (guard != null) guard.Bind(station.transform.position);
ZNetScene.instance.Destroy(gameObject);
}
}
}

View file

@ -1,256 +0,0 @@
using System.Collections.Generic;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// Where Skadis Nokkel takes you: a troll cave that already exists in the world, the same one
/// every time, claimed the first time the staff is used.
///
/// THIRD AND FINAL SHAPE, and it is by far the smallest. What used to be here - instantiating a
/// cave shell, learning where its interior was, emptying it of trolls, standing three benches up
/// in it - is all gone. Four things that could each fail, and between them always did.
///
/// What makes the cave usable now is not here at all: RaceCaveBuilding lets a Skadi (and a Trol)
/// build inside ANY troll cave, by lifting the one restriction that mattered. So this file has
/// nothing left to arrange. It picks a cave, it remembers which, and it opens a door to it.
///
/// The three failed designs are on the record in Skadi_PortaleGhiaccio.txt sections 0c to 0g, in
/// particular the two facts that killed them: DestroyImmediate is forbidden inside an animation
/// event callback (and the cast runs in one), and a location's m_position is its MOUTH rather
/// than its inside - which is why the portal kept putting the player out on the hillside.
/// </summary>
public static class SkadiHollow
{
/// <summary>
/// Confirmed present in a live world, along with TrollCave (interior radius 0, so no use to
/// us), MountainCave01, MountainCave02 and Hildir_cave.
/// </summary>
public const string SourceLocation = "TrollCave02";
// ─── Which cave ───────────────────────────────────────────────────────
//
// "Half way out, and away from the north." Half of the world's ~10 km radius is 5000, and the
// band is generous because a Black Forest troll cave has to actually exist in it.
private const float ClaimRadiusMin = 3500f;
private const float ClaimRadiusMax = 6500f;
/// <summary>
/// Everything with a positive Z is thrown out, which is the whole northern half of the map.
/// Cruder than a bearing test and that is deliberate: it cannot accidentally admit the Deep
/// North, which is where the first design landed.
/// </summary>
private const float MaxNorthing = 0f;
/// <summary>
/// How far from the cave counts as "at my hollow" - used only by the no-planting rule now.
/// Wide, because the cave's origin is its mouth and the inside is some way past it.
/// </summary>
public const float Radius = 72f;
// The claim is written down rather than recomputed. It depends on where this world's troll
// caves are and on the order the candidates come back in, so recomputing it after any change
// to either would hand the player a different cave and orphan everything built in the old one.
private const string CaveKey = "Skadi_HollowCave";
private const string ReturnPointKey = "Skadi_HollowReturn";
private static float lastCastTime = -100000f;
// ─── Claiming ─────────────────────────────────────────────────────────
/// <summary>
/// This player's cave, if they have claimed one. Does not allocate: it is called from the
/// build prefix, which runs on every attempted placement.
/// </summary>
public static bool TryGetCave(Player player, out Vector3 cave)
{
cave = Vector3.zero;
if (player == null || player.m_customData == null) return false;
return TryReadVector(player, CaveKey, out cave);
}
public static bool IsInside(Player player)
{
if (player == null) return false;
if (!TryGetCave(player, out Vector3 cave)) return false;
return (player.transform.position - cave).sqrMagnitude <= Radius * Radius;
}
private static bool TryClaimCave(Player player, out Vector3 cave)
{
if (TryGetCave(player, out cave)) return true;
List<Vector3> candidates = FindCandidateCaves();
if (candidates.Count == 0)
{
Jotunn.Logger.LogWarning($"[Skadi] No '{SourceLocation}' found in the Black Forest between " +
$"{ClaimRadiusMin:0} m and {ClaimRadiusMax:0} m of the centre, south of the equator. " +
"The hollow cannot be claimed in this world.");
return false;
}
// Sorted before indexing, because GetLocationList() makes no promise about order and an
// unstable order would mean an unstable claim on the very first cast.
candidates.Sort((a, b) => a.x != b.x ? a.x.CompareTo(b.x) : a.z.CompareTo(b.z));
cave = candidates[(int)(HashOf(player) % (uint)candidates.Count)];
player.m_customData[CaveKey] = FormatVector(cave);
Jotunn.Logger.LogInfo($"[Skadi] Hollow claimed for '{player.GetPlayerName()}': {SourceLocation} at {cave} " +
$"({BiomeAt(cave)}, {new Vector2(cave.x, cave.z).magnitude:0} m from the centre) " +
$"- chosen from {candidates.Count} candidates.");
return true;
}
private static List<Vector3> FindCandidateCaves()
{
List<Vector3> found = new List<Vector3>();
if (ZoneSystem.instance == null) return found;
foreach (ZoneSystem.LocationInstance instance in ZoneSystem.instance.GetLocationList())
{
if (instance.m_location == null) continue;
if (instance.m_location.m_prefabName != SourceLocation) continue;
Vector3 position = instance.m_position;
if (position.z > MaxNorthing) continue;
float distance = new Vector2(position.x, position.z).magnitude;
if (distance < ClaimRadiusMin || distance > ClaimRadiusMax) continue;
if (BiomeAt(position) != Heightmap.Biome.BlackForest) continue;
found.Add(position);
}
return found;
}
private static Heightmap.Biome BiomeAt(Vector3 point)
{
if (WorldGenerator.instance == null) return Heightmap.Biome.None;
return WorldGenerator.instance.GetBiome(new Vector3(point.x, 0f, point.z));
}
private static uint HashOf(Player player)
{
long id = player != null ? player.GetPlayerID() : 0L;
if (id == 0L)
{
string name = player != null ? player.GetPlayerName() : null;
id = string.IsNullOrEmpty(name) ? 1L : name.GetStableHashCode();
}
// Knuth's multiplicative hash, so two ids one apart do not pick neighbouring caves.
return (uint)(id ^ (id >> 32)) * 2654435761u;
}
// ─── The cast ─────────────────────────────────────────────────────────
/// <summary>
/// What Skadis Nokkel does. Outside, it opens the pair; inside, it takes the player straight
/// back out. The cooldown applies to going IN only - stepping in and changing your mind must
/// not lock you in a cave for two minutes.
///
/// The far end stands at the cave's mouth, and the player walks in from there. That is not a
/// compromise any more: since building works in the cave itself, there is nothing waiting
/// inside that has to be lined up with, so the one point we can name honestly is the right
/// one to use.
/// </summary>
public static void Cast(Player player)
{
if (player == null || player != Player.m_localPlayer) return;
if (IsInside(player))
{
Leave(player);
return;
}
float cooldown = SkadiConfig.HollowCooldown.Value;
float waited = Time.time - lastCastTime;
if (waited < cooldown)
{
int remaining = Mathf.CeilToInt(cooldown - waited);
player.Message(MessageHud.MessageType.Center, $"The frost has not gathered again ({remaining}s).");
return;
}
if (!TryClaimCave(player, out Vector3 cave))
{
player.Message(MessageHud.MessageType.Center, "No hollow answers you.");
return;
}
lastCastTime = Time.time;
SkadiRace.ApplyCooldownIcon(SkadiRace.HOLLOW_COOLDOWN_SE, SkadiConfig.HollowCooldown.Value);
// Remembered across a logout, so casting from inside always has somewhere to put them.
player.m_customData[ReturnPointKey] = FormatVector(player.transform.position);
Vector3 castPoint = player.transform.position
+ player.transform.forward * SkadiConfig.HollowPortalSpawnDistance.Value;
SkadiHollowPortal.Open(castPoint, player.transform.rotation,
cave + Vector3.up * SkadiConfig.HollowEntryHeight.Value);
}
private static void Leave(Player player)
{
player.TeleportTo(ReturnPointFor(player), player.transform.rotation, true);
SkadiHollowPortal.CloseSoon();
}
/// <summary>
/// Called by the portal when the player walks through. Going in changes nothing - the pair
/// stands as long as they are inside. Coming out starts the collapse.
/// </summary>
public static void OnTraversed(bool intoHollow)
{
if (!intoHollow) SkadiHollowPortal.CloseSoon();
}
private static Vector3 ReturnPointFor(Player player)
{
if (TryReadVector(player, ReturnPointKey, out Vector3 stored)
&& TryGetCave(player, out Vector3 cave)
&& (stored - cave).sqrMagnitude > Radius * Radius) // a point inside would strand them
{
return stored;
}
// Same fallback the Trenta portal uses for its home end, and for the same reason: the
// respawn point is the one place the game itself considers always valid.
PlayerProfile profile = Game.instance != null ? Game.instance.GetPlayerProfile() : null;
if (profile != null)
{
return profile.HaveCustomSpawnPoint() ? profile.GetCustomSpawnPoint() : PlayerProfile.m_originalSpawnPoint;
}
return PlayerProfile.m_originalSpawnPoint;
}
// ─── customData helpers ───────────────────────────────────────────────
private static string FormatVector(Vector3 v)
{
return $"{v.x:R};{v.y:R};{v.z:R}";
}
private static bool TryReadVector(Player player, string key, out Vector3 value)
{
value = Vector3.zero;
if (player == null || player.m_customData == null) return false;
if (!player.m_customData.TryGetValue(key, out string stored) || string.IsNullOrEmpty(stored)) return false;
string[] parts = stored.Split(';');
if (parts.Length != 3) return false;
System.Globalization.CultureInfo invariant = System.Globalization.CultureInfo.InvariantCulture;
const System.Globalization.NumberStyles style = System.Globalization.NumberStyles.Float;
if (!float.TryParse(parts[0], style, invariant, out float x)) return false;
if (!float.TryParse(parts[1], style, invariant, out float y)) return false;
if (!float.TryParse(parts[2], style, invariant, out float z)) return false;
value = new Vector3(x, y, z);
return true;
}
}
}

View file

@ -1,234 +0,0 @@
using System.Collections;
using Jotunn.Managers;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// One end of the pair of portals Skadis Nokkel opens. Deliberately a copy of
/// TrentaPortalLink rather than a shared abstraction: the two diverge on colour, on who is
/// allowed through, and above all on when they close (the Trenta pair dies on a timer, this
/// one waits for the player to come back out), and three differences in a forty-line class is
/// cheaper duplicated than parameterised.
///
/// Everything the Trenta version earned is kept: a plain GameObject with no ZNetView, so it is
/// unregistered and purely local - which is most of "only the player can go in", since remote
/// clients never learn the thing exists - plus its own trigger, its own teleport call, and the
/// same guard against the same-frame ping-pong.
/// </summary>
public class SkadiHollowPortalLink : MonoBehaviour
{
public SkadiHollowPortalLink Other;
/// <summary>True on the end that stands inside the hollow.</summary>
public bool IsHollowSide;
// Without this, a player who arrives is still standing in the destination's own trigger and
// gets bounced straight back the way they came, forever.
private float reentryBlockedUntil = -1f;
private void OnTriggerEnter(Collider other)
{
if (Other == null || Time.time < reentryBlockedUntil) return;
Player player = other.GetComponentInParent<Player>();
if (player == null) return;
// The requirement spelled out, even though the portal being local already means no
// other player can reach this line: only the owner walks through.
if (player != Player.m_localPlayer) return;
Vector3 destination = Other.transform.position + Other.transform.forward * 1.5f;
player.TeleportTo(destination, Other.transform.rotation, true);
Other.reentryBlockedUntil = Time.time + 1.5f;
// Going in leaves the pair standing; coming out starts the collapse.
SkadiHollow.OnTraversed(intoHollow: !IsHollowSide);
}
}
public static class SkadiHollowPortal
{
private static Material cachedVfxMaterial;
private static bool vfxMaterialResolved;
private static GameObject outsideEnd;
private static GameObject hollowEnd;
private static Coroutine closing;
public static bool IsOpen => outsideEnd != null || hollowEnd != null;
/// <summary>
/// Spawns the pair: one where the Skadi is standing, one inside their hollow. Neither end
/// has a lifetime - they stand until CloseSoon is called.
/// </summary>
public static void Open(Vector3 outsidePoint, Quaternion outsideRotation, Vector3 hollowPoint)
{
CloseNow();
outsideEnd = SpawnEnd(outsidePoint, outsideRotation, isHollowSide: false);
hollowEnd = SpawnEnd(hollowPoint, Quaternion.identity, isHollowSide: true);
SkadiHollowPortalLink outsideLink = outsideEnd.GetComponent<SkadiHollowPortalLink>();
SkadiHollowPortalLink hollowLink = hollowEnd.GetComponent<SkadiHollowPortalLink>();
outsideLink.Other = hollowLink;
hollowLink.Other = outsideLink;
}
/// <summary>
/// Takes both ends down after the configured grace period. Called when the player leaves the
/// hollow - by walking out or by casting from inside - which is the only thing that closes
/// this pair.
/// </summary>
public static void CloseSoon()
{
if (!IsOpen || closing != null) return;
if (SkadiRace.Instance == null) { CloseNow(); return; }
closing = SkadiRace.Instance.StartCoroutine(
CloseAfter(SkadiConfig.HollowPortalCloseDelay.Value));
}
/// <summary>No grace period, no animation. For reopening, and for shutting down.</summary>
public static void CloseNow()
{
if (closing != null && SkadiRace.Instance != null)
{
SkadiRace.Instance.StopCoroutine(closing);
}
closing = null;
if (outsideEnd != null) Object.Destroy(outsideEnd);
if (hollowEnd != null) Object.Destroy(hollowEnd);
outsideEnd = null;
hollowEnd = null;
}
private static GameObject SpawnEnd(Vector3 position, Quaternion rotation, bool isHollowSide)
{
GameObject portal = new GameObject(isHollowSide ? "SkadiHollowPortal_In" : "SkadiHollowPortal_Out");
portal.transform.position = position;
portal.transform.rotation = rotation;
CapsuleCollider trigger = portal.AddComponent<CapsuleCollider>();
trigger.isTrigger = true;
trigger.height = 3f;
trigger.radius = 1.2f;
trigger.center = new Vector3(0, 1.5f, 0);
SkadiHollowPortalLink link = portal.AddComponent<SkadiHollowPortalLink>();
link.IsHollowSide = isHollowSide;
BuildSwirlVfx(portal.transform);
return portal;
}
/// <summary>
/// The swirl only, no wooden frame - same shape and same reasoning as the Trenta portal's:
/// borrow a particle material off the real portal prefab by READING it (never instantiating
/// it, so none of the real portal's gameplay components ever get a chance to run), then
/// drive shape, emission and colour from here. The one change is the colour, which is
/// Skadi's ice instead of the Trenta's toxic purple.
/// </summary>
private static void BuildSwirlVfx(Transform parent)
{
if (!vfxMaterialResolved)
{
vfxMaterialResolved = true;
GameObject source = PrefabManager.Cache.GetPrefab<GameObject>("portal_wood");
if (source != null)
{
ParticleSystemRenderer sourceRenderer = source.GetComponentInChildren<ParticleSystemRenderer>(true);
if (sourceRenderer != null) cachedVfxMaterial = sourceRenderer.material;
}
if (cachedVfxMaterial == null)
{
Jotunn.Logger.LogWarning("[Skadi] Hollow portal: no particle material on 'portal_wood'; using the default particle material.");
}
}
GameObject vfx = new GameObject("Swirl");
vfx.transform.SetParent(parent, false);
vfx.transform.localPosition = new Vector3(0, 1.2f, 0);
ParticleSystem ps = vfx.AddComponent<ParticleSystem>();
var main = ps.main;
main.loop = true;
main.startLifetime = 1.5f;
main.startSpeed = 0f;
main.startSize = new ParticleSystem.MinMaxCurve(0.15f, 0.3f);
main.maxParticles = 200;
main.simulationSpace = ParticleSystemSimulationSpace.Local;
var emission = ps.emission;
emission.rateOverTime = 80f;
var shape = ps.shape;
shape.shapeType = ParticleSystemShapeType.Circle;
shape.radius = 1f;
shape.radiusThickness = 0.1f; // hollow ring, not a filled disc
var rotationOverLifetime = ps.rotationOverLifetime;
rotationOverLifetime.enabled = true;
rotationOverLifetime.z = new ParticleSystem.MinMaxCurve(90f);
ParticleSystemRenderer renderer = ps.GetComponent<ParticleSystemRenderer>();
if (cachedVfxMaterial != null) renderer.material = cachedVfxMaterial;
var colorOverLifetime = ps.colorOverLifetime;
colorOverLifetime.enabled = true;
Gradient grad = new Gradient();
grad.SetKeys(
new GradientColorKey[] { new GradientColorKey(SkadiIce.PortalSwirl, 0f), new GradientColorKey(SkadiIce.PortalSwirl, 1f) },
new GradientAlphaKey[] { new GradientAlphaKey(0f, 0f), new GradientAlphaKey(0.9f, 0.3f), new GradientAlphaKey(0.9f, 0.7f), new GradientAlphaKey(0f, 1f) }
);
colorOverLifetime.color = grad;
ps.Play();
}
private static IEnumerator CloseAfter(float seconds)
{
yield return new WaitForSeconds(seconds);
GameObject a = outsideEnd;
GameObject b = hollowEnd;
outsideEnd = null;
hollowEnd = null;
closing = null;
yield return Collapse(a);
yield return Collapse(b);
}
/// <summary>
/// Link and trigger die first, so nothing can walk through mid-collapse, then a one-second
/// shrink stands in for a closing animation - vanilla portals are simply present or absent,
/// so there is no real one to borrow.
/// </summary>
private static IEnumerator Collapse(GameObject portal)
{
if (portal == null) yield break;
SkadiHollowPortalLink link = portal.GetComponent<SkadiHollowPortalLink>();
if (link != null) Object.Destroy(link);
CapsuleCollider trigger = portal.GetComponent<CapsuleCollider>();
if (trigger != null) Object.Destroy(trigger);
float t = 0f;
Vector3 startScale = portal.transform.localScale;
while (t < 1f)
{
if (portal == null) yield break;
t += Time.deltaTime;
portal.transform.localScale = Vector3.Lerp(startScale, Vector3.zero, t);
yield return null;
}
if (portal != null) Object.Destroy(portal);
}
}
}

View file

@ -0,0 +1,55 @@
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The one ice palette the whole Skadi chain shares. Taken from the Fader recolour in
/// SkadiRace.ExecuteTransformation rather than picked fresh, so the reagent and the crystal golem
/// are the same ice as the Skeleton Dragon the race turns into at tier 8.
///
/// It lived in SkadiNokkel.cs until that staff was removed; it is its own file now because the
/// two things still using it have nothing else to do with each other.
/// </summary>
public static class SkadiIce
{
public static readonly Color Albedo = new Color(0.6f, 0.8f, 1f, 1f);
public static readonly Color Emission = new Color(0f, 0.5f, 1f, 1f);
/// <summary>
/// Multiplies the ice tint over whatever the base texture already carries instead of
/// overwriting it, so the model keeps its detail and reads as frozen bone rather than as a
/// flat blue silhouette. Same approach as AswidSpectralClaw.ApplySpectralVisual, and like
/// that one it copies each material first so the vanilla asset is never touched.
/// </summary>
public static void Apply(GameObject root)
{
if (root == null) return;
foreach (Renderer renderer in root.GetComponentsInChildren<Renderer>(true))
{
if (renderer == null || renderer is ParticleSystemRenderer) continue;
Material[] source = renderer.sharedMaterials;
Material[] tinted = new Material[source.Length];
for (int i = 0; i < source.Length; i++)
{
if (source[i] == null) continue;
Material material = new Material(source[i]);
if (material.HasProperty("_Color"))
{
Color baseColor = material.GetColor("_Color");
material.SetColor("_Color", new Color(baseColor.r * Albedo.r,
baseColor.g * Albedo.g,
baseColor.b * Albedo.b,
baseColor.a));
}
if (material.HasProperty("_EmissionColor")) material.SetColor("_EmissionColor", Emission);
tinted[i] = material;
}
renderer.sharedMaterials = tinted;
}
}
}
}

View file

@ -1,396 +0,0 @@
using HarmonyLib;
using Jotunn.Configs;
using Jotunn.Entities;
using Jotunn.Managers;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The one ice palette the whole Skadi chain shares. Taken from the Fader recolour in
/// SkadiRace.ExecuteTransformation rather than picked fresh, so the staff, the reagent and the
/// portal are all the same ice as the Skeleton Dragon the race turns into at tier 8.
/// </summary>
public static class SkadiIce
{
public static readonly Color Albedo = new Color(0.6f, 0.8f, 1f, 1f);
public static readonly Color Emission = new Color(0f, 0.5f, 1f, 1f);
public static readonly Color PortalSwirl = new Color(0.55f, 0.85f, 1f, 1f);
/// <summary>
/// Multiplies the ice tint over whatever the base texture already carries instead of
/// overwriting it, so the model keeps its detail and reads as frozen bone rather than as a
/// flat blue silhouette. Same approach as AswidSpectralClaw.ApplySpectralVisual, and like
/// that one it copies each material first so the vanilla asset is never touched.
/// </summary>
public static void Apply(GameObject root)
{
if (root == null) return;
foreach (Renderer renderer in root.GetComponentsInChildren<Renderer>(true))
{
if (renderer == null || renderer is ParticleSystemRenderer) continue;
Material[] source = renderer.sharedMaterials;
Material[] tinted = new Material[source.Length];
for (int i = 0; i < source.Length; i++)
{
if (source[i] == null) continue;
Material material = new Material(source[i]);
if (material.HasProperty("_Color"))
{
Color baseColor = material.GetColor("_Color");
material.SetColor("_Color", new Color(baseColor.r * Albedo.r,
baseColor.g * Albedo.g,
baseColor.b * Albedo.b,
baseColor.a));
}
if (material.HasProperty("_EmissionColor")) material.SetColor("_EmissionColor", Emission);
tinted[i] = material;
}
renderer.sharedMaterials = tinted;
}
}
}
/// <summary>
/// Skadis Nokkel - "Skadi's key". A StaffSkeleton with the skeleton taken out of it: it costs no
/// eitr, no health and no stamina, it summons nothing, and what it does instead is open a portal
/// into the player's own hidden hollow (SkadiHollow).
///
/// The name is the point. It is not a weapon that happens to open a door, it is a key - and a
/// reproducible one: losing it costs a trip to the forge, not the hollow.
///
/// Two layers keep the vanilla staff's behaviour from leaking through, deliberately overlapping:
/// - every field that could carry a cost or a summon is zeroed on the clone (Strip below);
/// - the attack trigger itself is intercepted and vanilla's never runs for this staff
/// (SkadiNokkelCastPatch). Nulling a projectile field would leave vanilla walking into it;
/// taking over the method means that code path is not merely defused, it is unreachable.
/// </summary>
public static class SkadiNokkel
{
public const string PrefabName = "SkadiNokkel";
public const string DisplayName = "Skadis Nokkel";
private const string SourcePrefab = "StaffSkeleton";
private const string ModerDrop = "DragonTear";
private const string SkullTrophy = "TrophySkeleton";
public static void Register()
{
GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(PrefabName, SourcePrefab);
if (prefab == null)
{
Jotunn.Logger.LogWarning($"[Skadi] Could not clone {SourcePrefab}; {DisplayName} not registered.");
return;
}
ItemDrop drop = prefab.GetComponent<ItemDrop>();
if (drop == null || drop.m_itemData == null || drop.m_itemData.m_shared == null)
{
Jotunn.Logger.LogWarning($"[Skadi] {SourcePrefab} clone has no usable ItemDrop; {DisplayName} not registered.");
return;
}
ItemDrop.ItemData.SharedData shared = drop.m_itemData.m_shared;
shared.m_name = DisplayName;
shared.m_description = "A staff of frozen bone. It raises nothing. Used, it opens the way to a hollow " +
"that is yours and no one else's - and used again, it lets you out.";
shared.m_useDurability = false;
// ItemType is left exactly as the vanilla staff has it, on purpose: it decides the
// equip slot and which animation set the character uses, and the cast gesture is the
// whole reason this is a staff and not a trinket.
Strip(shared);
SkadiIce.Apply(prefab);
ItemManager.Instance.AddItem(new CustomItem(prefab, fixReference: false));
LogCosts("straight after registering", shared);
ItemManager.Instance.AddRecipe(new CustomRecipe(new RecipeConfig
{
Item = PrefabName,
Amount = 1,
CraftingStation = CraftingStations.Forge,
Requirements = new[]
{
new RequirementConfig(SkadiFrostHeart.PrefabName, 1, 0, true),
new RequirementConfig(ModerDrop, 1, 0, true),
new RequirementConfig(SkullTrophy, 1, 0, true),
},
}));
Jotunn.Logger.LogInfo($"[Skadi] {DisplayName} registered: no eitr, no health, no summon.");
}
/// <summary>
/// Takes the skeleton staff apart. Every field is zeroed on BOTH attacks, because the
/// secondary is a separate Attack with its own copy of every cost.
///
/// The summon is the interesting one: it comes from a SpawnAbility component (verified class,
/// field GameObject[] m_spawnPrefab) which does not live on the item but on a prefab hung off
/// the attack. WHICH field hangs it - m_attackProjectile or m_spawnOnTrigger - is not
/// knowable from the game files, so all of them go. Nulling three fields that might each be
/// the culprit costs nothing; guessing wrong costs a skeleton every cast.
///
/// m_attackStamina goes to zero too, and that is a decision, not thoroughness: the moment
/// someone wants to flee into their hollow is exactly the moment they have no stamina left.
/// The only brake on this staff is its cooldown.
/// </summary>
private static void Strip(ItemDrop.ItemData.SharedData shared)
{
StripAttack(shared.m_attack);
StripAttack(shared.m_secondaryAttack);
}
private static void StripAttack(Attack attack)
{
if (attack == null) return;
attack.m_attackEitr = 0f;
attack.m_drawEitrDrain = 0f;
attack.m_reloadEitrDrain = 0f;
attack.m_attackHealth = 0f;
attack.m_attackHealthPercentage = 0f;
attack.m_attackHealthLowBlockUse = false;
attack.m_attackHealthReturnHit = 0f;
attack.m_attackStamina = 0f;
attack.m_drawStaminaDrain = 0f;
attack.m_reloadStaminaDrain = 0f;
attack.m_attackProjectile = null;
attack.m_spawnOnTrigger = null;
attack.m_spawnOnHit = null;
attack.m_spawnOnHitChance = 0f;
// The animation stays. It is the summoning gesture, which is the right gesture for
// opening a way, and it is the same one TrentaAbilities plays by hand for its portal.
}
/// <summary>
/// Runs on the cast. Race-gated: the hollow belongs to the Skadi, so in anyone else's hands
/// this is an inert stick - the same shape as Aswid_SpectralClawDamage_Patch, which asks
/// AswidRace.IsAswid() before doing anything at all.
/// </summary>
public static void OnCast(Player player)
{
if (player == null || player != Player.m_localPlayer) return;
if (!SkadiRace.IsLocalSkadi())
{
player.Message(MessageHud.MessageType.Center, "The staff is cold and answers to someone else.");
return;
}
SkadiHollow.Cast(player);
}
public static bool IsNokkel(ItemDrop.ItemData item)
{
return item != null && item.m_dropPrefab != null && item.m_dropPrefab.name == PrefabName;
}
/// <summary>
/// True when a cost being asked about belongs to this staff.
///
/// The fallback on the equipped weapon is not belt-and-braces, it is necessary: the cost
/// getters are called from Attack.Start, and m_weapon is not guaranteed to have been assigned
/// by the time the cost is checked. It is deliberately only consulted when m_weapon is null,
/// so a creature's own attack cannot be zeroed just because the player happens to be holding
/// the staff at the time.
/// </summary>
public static bool IsNokkelContext(ItemDrop.ItemData weapon)
{
if (weapon != null) return IsNokkel(weapon);
Player local = Player.m_localPlayer;
return local != null && IsNokkel(local.GetCurrentWeapon());
}
/// <summary>
/// Prints what the clone's attack actually costs, so "the eitr cost came back" stops being a
/// mystery and becomes a number with a timestamp. Called once at registration and again from
/// the F8 dump, which between them say whether the zeroes were never written or were written
/// and then overwritten by something else.
/// </summary>
public static void LogCosts(string when, ItemDrop.ItemData.SharedData shared)
{
if (shared == null) { Jotunn.Logger.LogWarning($"[Skadi] Nokkel costs {when}: no shared data."); return; }
Attack primary = shared.m_attack;
Attack secondary = shared.m_secondaryAttack;
Jotunn.Logger.LogInfo($"[Skadi] Nokkel costs {when}: " +
$"primary eitr={Describe(primary, a => a.m_attackEitr)} " +
$"health={Describe(primary, a => a.m_attackHealth)} " +
$"health%={Describe(primary, a => a.m_attackHealthPercentage)} " +
$"stamina={Describe(primary, a => a.m_attackStamina)} | " +
$"secondary eitr={Describe(secondary, a => a.m_attackEitr)} " +
$"stamina={Describe(secondary, a => a.m_attackStamina)}");
}
private static string Describe(Attack attack, System.Func<Attack, float> read)
{
return attack == null ? "<no attack>" : read(attack).ToString("0.##");
}
/// <summary>
/// What the F8 dump prints for this chain. Two unknowns, both settled by reading them once
/// off a running game: which field of the vanilla staff carries the summon, and what the
/// troll cave location is really called in this build.
/// </summary>
public static void DumpSource()
{
Jotunn.Logger.LogInfo("=== SKADI NOKKEL SOURCE DUMP ===");
GameObject staff = PrefabManager.Cache.GetPrefab<GameObject>(SourcePrefab);
ItemDrop staffDrop = staff != null ? staff.GetComponent<ItemDrop>() : null;
if (staffDrop == null)
{
Jotunn.Logger.LogWarning($"{SourcePrefab} not found.");
}
else
{
Attack attack = staffDrop.m_itemData.m_shared.m_attack;
Jotunn.Logger.LogInfo($" m_attackType : {attack.m_attackType}");
Jotunn.Logger.LogInfo($" m_attackAnimation : {attack.m_attackAnimation}");
Jotunn.Logger.LogInfo($" m_attackProjectile : {(attack.m_attackProjectile != null ? attack.m_attackProjectile.name : "<null>")}");
Jotunn.Logger.LogInfo($" m_spawnOnTrigger : {(attack.m_spawnOnTrigger != null ? attack.m_spawnOnTrigger.name : "<null>")}");
Jotunn.Logger.LogInfo($" m_attackEitr : {attack.m_attackEitr}");
Jotunn.Logger.LogInfo($" m_attackHealth : {attack.m_attackHealth} / {attack.m_attackHealthPercentage}%");
foreach (GameObject candidate in new[] { attack.m_attackProjectile, attack.m_spawnOnTrigger })
{
if (candidate == null) continue;
foreach (SpawnAbility ability in candidate.GetComponentsInChildren<SpawnAbility>(true))
{
string spawns = "<none>";
if (ability.m_spawnPrefab != null && ability.m_spawnPrefab.Length > 0)
{
string[] names = new string[ability.m_spawnPrefab.Length];
for (int i = 0; i < names.Length; i++)
{
names[i] = ability.m_spawnPrefab[i] != null ? ability.m_spawnPrefab[i].name : "<null>";
}
spawns = string.Join(", ", names);
}
Jotunn.Logger.LogInfo($" SpawnAbility on '{candidate.name}' spawns: {spawns}");
}
}
}
// The clone as the game currently holds it, not as Register() left it. If these are not
// zero, the write in Strip() did not survive - which is the whole reason
// SkadiNokkelFreeCastPatch exists, and this line is how we find out whether it is still
// needed or whether the fields hold after all.
GameObject clone = PrefabManager.Cache.GetPrefab<GameObject>(PrefabName);
ItemDrop cloneDrop = clone != null ? clone.GetComponent<ItemDrop>() : null;
if (cloneDrop == null)
{
Jotunn.Logger.LogWarning($" {PrefabName} is not in the prefab cache.");
}
else
{
LogCosts("as the game holds it now", cloneDrop.m_itemData.m_shared);
Jotunn.Logger.LogInfo($" shared data instance is {(ReferenceEquals(cloneDrop.m_itemData.m_shared, staffDrop != null ? staffDrop.m_itemData.m_shared : null) ? "THE SAME OBJECT as the vanilla staff's - that is the bug" : "its own copy, as expected")}");
}
// The other half: is 'TrollCave02' actually what it is called here?
Jotunn.Logger.LogInfo($"--- locations matching 'cave' (looking for {SkadiHollow.SourceLocation}) ---");
if (ZoneSystem.instance == null || ZoneSystem.instance.m_locations == null)
{
Jotunn.Logger.LogWarning(" ZoneSystem not up yet; load a world first.");
}
else
{
// m_locations, not GetLocationList(): the latter is public but returns the locations
// PLACED in this world, and the hollow needs the definition, not an instance.
foreach (ZoneSystem.ZoneLocation location in ZoneSystem.instance.m_locations)
{
if (location == null || string.IsNullOrEmpty(location.m_prefabName)) continue;
if (location.m_prefabName.IndexOf("cave", System.StringComparison.OrdinalIgnoreCase) < 0) continue;
Jotunn.Logger.LogInfo($" {location.m_prefabName} (biome {location.m_biome}, " +
$"interior r{location.m_interiorRadius}, clearArea {location.m_clearArea})");
}
}
Jotunn.Logger.LogInfo("=== END SKADI NOKKEL SOURCE DUMP ===");
}
}
/// <summary>
/// The cast hook, and the second half of "remove the unwanted components".
///
/// Attack.OnAttackTrigger() is used rather than Attack.Start because it takes NO parameters -
/// its signature cannot drift and cannot be got wrong, which matters here because Attack.Start's
/// parameter types could not even be loaded for inspection outside the game. It also fires at
/// the moment the animation reaches its release point, which is exactly when a cast should land.
///
/// It is a Prefix returning FALSE, not a postfix, and that is the whole trick: for this staff
/// vanilla's attack-trigger code never executes at all. The summon and the projectile are not
/// just defused by the zeroed fields, they are unreachable - and vanilla cannot trip over the
/// nulls we left behind either, which a postfix would have been at the mercy of.
///
/// m_weapon and m_character are both PRIVATE on Attack, so they arrive through Harmony's triple
/// underscore field injection rather than off __instance - which is also why they are spelled
/// out here instead of being read with Traverse: the injection is checked at patch time, so a
/// rename shows up as a startup error instead of a silent null every cast.
/// </summary>
[HarmonyPatch(typeof(Attack), "OnAttackTrigger")]
public static class SkadiNokkelCastPatch
{
public static bool Prefix(ItemDrop.ItemData ___m_weapon, Humanoid ___m_character)
{
if (!SkadiNokkel.IsNokkel(___m_weapon)) return true;
SkadiNokkel.OnCast(___m_character as Player);
return false;
}
}
/// <summary>
/// The staff costs nothing, guaranteed - and this is what guarantees it.
///
/// Zeroing m_attackEitr, m_attackHealth and m_attackStamina on the clone is still done in
/// Strip(), and by every reading of the game's own code it ought to be enough: those three, plus
/// the two drain fields, are the ONLY eitr costs that exist anywhere on Attack, and SharedData
/// carries none at all (checked field by field). In game the cost came back anyway, which means
/// the write to the clone's own SharedData does not survive something - so relying on that write
/// is relying on a mechanism that has already been observed to fail.
///
/// These three getters are the single funnel every cost check flows through: Attack.Start asks
/// them before it will start, and the tooltip asks them for what to print. Forcing them to zero
/// makes the staff free no matter what any field says, which is the same reasoning as the prefix
/// above - do not defuse the code path, remove it.
///
/// All three are PRIVATE and take no parameters, so they are addressed by name through
/// AccessTools and share one postfix.
/// </summary>
[HarmonyPatch]
public static class SkadiNokkelFreeCastPatch
{
[HarmonyTargetMethods]
private static System.Collections.Generic.IEnumerable<System.Reflection.MethodBase> TargetMethods()
{
yield return AccessTools.Method(typeof(Attack), "GetAttackEitr");
yield return AccessTools.Method(typeof(Attack), "GetAttackHealth");
yield return AccessTools.Method(typeof(Attack), "GetAttackStamina");
}
[HarmonyPostfix]
private static void Postfix(ItemDrop.ItemData ___m_weapon, ref float __result)
{
if (__result == 0f) return;
if (!SkadiNokkel.IsNokkelContext(___m_weapon)) return;
__result = 0f;
}
}
}

View file

@ -33,7 +33,6 @@ namespace RacesOfValheim
// rebuild - see CONFIGURATION-MANAGER-HOWTO.md.
public const string SPELL_COOLDOWN_SE = "SE_SkadiSpellCooldown";
public const string ATTACK_COOLDOWN_SE = "SE_SkadiAttackCooldown";
public const string HOLLOW_COOLDOWN_SE = "SE_SkadiHollowCooldown";
private static float SPELL_STAMINA_COST => SkadiConfig.SpellStaminaCost.Value;
private static float SPELL_COOLDOWN => SkadiConfig.SpellCooldown.Value;
@ -53,9 +52,9 @@ namespace RacesOfValheim
{
// The reagent goes first: the faction merchant catalogue resolves its entries by prefab
// name, so Greater Frost Heart has to exist before a Fenring_Cultist is ever set up as a
// bench - and the staff's recipe references it by name too.
// bench.
SkadiFrostHeart.Register();
SkadiNokkel.Register();
SkadiGolem.Register();
var se = ScriptableObject.CreateInstance<SE_SkadiStats>();
se.name = "SE_SkadiStats";
@ -108,13 +107,6 @@ namespace RacesOfValheim
attackCd.m_tooltip = "Your dragon shape must ready itself to strike again.";
attackCd.m_icon = GetItemIcon("TrophyHatchling") ?? dragonIcon;
ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(attackCd, fixReference: false));
var hollowCd = ScriptableObject.CreateInstance<SE_SkadiAbilityCooldown>();
hollowCd.name = HOLLOW_COOLDOWN_SE;
hollowCd.m_name = "Skadis Nokkel";
hollowCd.m_tooltip = "The way to your hollow must freeze over again before it will open.";
hollowCd.m_icon = GetItemIcon("StaffIceShards") ?? dragonIcon;
ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(hollowCd, fixReference: false));
}
// Drives the HUD countdown: Valheim prints the remaining time on any status effect whose
@ -151,8 +143,8 @@ namespace RacesOfValheim
}
/// <summary>
/// The same check, reachable without an Instance - which the Nokkel's Harmony patch and the
/// hollow both need, since they run from static context.
/// The same check, reachable without an Instance - which the golem and the cave-building
/// watcher both need, since they run from static context.
/// </summary>
public static bool IsLocalSkadi()
{
@ -254,8 +246,7 @@ namespace RacesOfValheim
DumpPrefabDebugInfo("Dragon");
DumpPrefabDebugInfo("Hatchling");
DumpPrefabDebugInfo("Fader");
SkadiNokkel.DumpSource();
if (Player.m_localPlayer != null) Player.m_localPlayer.Message(MessageHud.MessageType.Center, "Dumped Dragon/Drake/Fader + Nokkel debug info to console!");
if (Player.m_localPlayer != null) Player.m_localPlayer.Message(MessageHud.MessageType.Center, "Dumped Dragon/Drake/Fader debug info to console!");
}
}

View file

@ -0,0 +1,264 @@
using System.Collections.Generic;
using Jotunn.Managers;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The lights in the eye sockets, taken from the creature the tier's body is borrowed from.
///
/// The body swap copies SkinnedMeshRenderers and nothing else, which is the whole of the mesh
/// but none of the effects hung off the creature's rig - so the race wore a skull with two
/// empty holes where the mob it is wearing has a lit pair. Every part of that lighting is
/// authored per creature, and the tiers wear three different creatures (Skeleton,
/// Skeleton_Poison, Skeleton_Hildir) with three different colours, so nothing here names a
/// colour: each tier's glow is cloned out of that tier's own prefab and arrives already the
/// right one.
///
/// What counts as "the eye lights" is deliberately broad - any Light, any ParticleSystem, and
/// any mesh whose object is named for an eye - because which of the three a given creature
/// uses is the creature's business, not ours. Everything cloned is logged once per model, so
/// if a tier turns out to carry something this misses, the log says exactly what it carries.
///
/// Each clone is parented to the player bone its own parent maps onto - the same by-name
/// mapping the body itself is skinned through - and keeps the local pose it had on the
/// creature, so it sits where the creature wore it and rides the head animation for free.
/// </summary>
public static class SkeletonEyeGlow
{
// Every clone carries this, followed by the model it came from: the sweep below uses the
// name alone to tell its own work from a previous tier's and from everyone else's.
private const string Prefix = "SkeletonEyeFX_";
private static readonly HashSet<string> loggedModels = new HashSet<string>();
/// <summary>
/// Makes sure the player wears the eye lights of <paramref name="modelName"/> and of no
/// other tier. Cheap to call on every visual refresh: once the right ones are on, it does
/// nothing but the sweep.
/// </summary>
public static void Apply(VisEquipment vis, string modelName)
{
Transform[] bones = GetBones(vis);
if (bones == null || string.IsNullOrEmpty(modelName)) return;
string wanted = Prefix + modelName + "_";
if (Sweep(bones, wanted)) return; // already wearing this tier's
GameObject source = PrefabManager.Cache.GetPrefab<GameObject>(modelName);
if (source == null) return; // the body swap already warns about a missing model
LogSourceEffectsOnce(modelName, source);
foreach (GameObject effect in CollectEffects(source))
{
Transform parentBone = ResolveParentBone(bones, effect.transform);
if (parentBone == null) continue;
Clone(effect, parentBone, wanted);
}
}
/// <summary>Takes every cloned light back off, for a player who is no longer a Skeleton.</summary>
public static void Clear(VisEquipment vis)
{
Transform[] bones = GetBones(vis);
if (bones == null) return;
Sweep(bones, null);
}
private static Transform[] GetBones(VisEquipment vis)
{
if (vis == null || vis.m_bodyModel == null) return null;
return vis.m_bodyModel.bones;
}
/// <summary>
/// Destroys clones that do not belong to <paramref name="keepPrefix"/> and reports whether
/// any that do are already in place. Pass null to clear the lot.
/// </summary>
private static bool Sweep(Transform[] bones, string keepPrefix)
{
bool present = false;
foreach (Transform bone in bones)
{
if (bone == null) continue;
for (int i = bone.childCount - 1; i >= 0; i--)
{
Transform child = bone.GetChild(i);
if (!child.name.StartsWith(Prefix)) continue;
if (keepPrefix != null && child.name.StartsWith(keepPrefix))
{
present = true;
continue;
}
// Renamed before it goes: Destroy only takes effect at the end of the frame,
// and until then this sweep would keep finding it and counting it as present.
child.name = child.name + "_Removed";
Object.Destroy(child.gameObject);
}
}
return present;
}
/// <summary>
/// The objects on a creature worth bringing across. Depth first, and a match swallows its
/// own subtree - a light with a particle system under it is one clone, not two.
/// </summary>
private static List<GameObject> CollectEffects(GameObject source)
{
List<GameObject> found = new List<GameObject>();
HashSet<Transform> taken = new HashSet<Transform>();
foreach (Transform t in source.GetComponentsInChildren<Transform>(true))
{
if (!IsEffect(t)) continue;
bool insideOne = false;
for (Transform parent = t.parent; parent != null; parent = parent.parent)
{
if (taken.Contains(parent)) { insideOne = true; break; }
}
if (insideOne) continue;
taken.Add(t);
found.Add(t.gameObject);
}
return found;
}
private static bool IsEffect(Transform t)
{
if (t.GetComponent<Light>() != null) return true;
if (t.GetComponent<ParticleSystem>() != null) return true;
// Meshes are taken by name only. A creature's non-skinned meshes are mostly the
// weapons in its hands, and a player who sprouts a second sword out of their wrist is
// a worse bug than a missing glow.
return t.name.ToLower().Contains("eye") && t.GetComponent<MeshRenderer>() != null;
}
/// <summary>
/// The player bone a creature's effect should hang from: whatever its own parent chain
/// first matches by name. No root fallback - an effect nobody can place is better left
/// off than dropped on the pelvis.
/// </summary>
private static Transform ResolveParentBone(Transform[] bones, Transform effect)
{
for (Transform parent = effect.parent; parent != null; parent = parent.parent)
{
Transform match = SkeletonPatches.VisEquipment_UpdateVisuals_Patch.FindBoneByName(bones, parent.name);
if (match != null) return match;
}
return null;
}
private static void Clone(GameObject source, Transform parentBone, string namePrefix)
{
GameObject copy = Object.Instantiate(source, parentBone);
copy.name = namePrefix + source.name;
// The pose it was authored at on the creature. Instantiate keeps the world transform,
// which for a prefab means nothing useful.
copy.transform.localPosition = source.transform.localPosition;
copy.transform.localRotation = source.transform.localRotation;
copy.transform.localScale = source.transform.localScale;
// Allowlist, not a blocklist - the same rule the head flame is built under. Whatever
// else rode along (an AnimEvent, a collider, a script that expects a Character above
// it) goes, whatever type it turns out to be; what is left is a light and the things
// that draw it.
foreach (Component comp in copy.GetComponentsInChildren<Component>(true))
{
if (comp is Transform || comp is Light || comp is ParticleSystem ||
comp is ParticleSystemRenderer || comp is MeshRenderer || comp is MeshFilter)
{
continue;
}
Object.Destroy(comp);
}
// A creature can leave its own effects switched off for a script to turn on later, and
// that script is exactly what was just destroyed.
copy.SetActive(true);
foreach (Light light in copy.GetComponentsInChildren<Light>(true)) light.enabled = true;
foreach (Renderer renderer in copy.GetComponentsInChildren<Renderer>(true)) renderer.enabled = true;
}
/// <summary>
/// Says what a creature actually carries, once per model per session.
///
/// Which of the three shapes a glow is authored as is not something to guess at, and if a
/// tier arrives here with none of them, the emission on its skinned materials - printed
/// below - is the remaining answer to where its eyes get their colour.
/// </summary>
private static void LogSourceEffectsOnce(string modelName, GameObject source)
{
if (!loggedModels.Add(modelName)) return;
Jotunn.Logger.LogInfo($"[Skeleton] Eye glow: reading '{modelName}'.");
int count = 0;
foreach (Transform t in source.GetComponentsInChildren<Transform>(true))
{
Light light = t.GetComponent<Light>();
if (light != null)
{
count++;
Jotunn.Logger.LogInfo(
$"[Skeleton] Light '{t.name}' under '{(t.parent != null ? t.parent.name : "-")}' " +
$"color={light.color} intensity={light.intensity:F2} range={light.range:F2} " +
$"active={t.gameObject.activeSelf}");
}
ParticleSystem ps = t.GetComponent<ParticleSystem>();
if (ps != null)
{
count++;
Jotunn.Logger.LogInfo(
$"[Skeleton] ParticleSystem '{t.name}' under '{(t.parent != null ? t.parent.name : "-")}' " +
$"startColor={ps.main.startColor.color} active={t.gameObject.activeSelf}");
}
MeshRenderer mesh = t.GetComponent<MeshRenderer>();
if (mesh != null)
{
count++;
Jotunn.Logger.LogInfo(
$"[Skeleton] MeshRenderer '{t.name}' under '{(t.parent != null ? t.parent.name : "-")}' " +
$"material='{(mesh.sharedMaterial != null ? mesh.sharedMaterial.name : "none")}' " +
$"active={t.gameObject.activeSelf}");
}
}
if (count == 0)
{
Jotunn.Logger.LogInfo("[Skeleton] no lights, particles or loose meshes at all.");
}
foreach (SkinnedMeshRenderer smr in source.GetComponentsInChildren<SkinnedMeshRenderer>(true))
{
foreach (Material material in smr.sharedMaterials)
{
if (material == null) continue;
string emission = material.HasProperty("_EmissionColor")
? material.GetColor("_EmissionColor").ToString()
: "no _EmissionColor";
Jotunn.Logger.LogInfo(
$"[Skeleton] skin '{smr.name}' material '{material.name}' shader '{material.shader?.name}' " +
$"emission={emission} keyword={material.IsKeywordEnabled("_EMISSION")}");
}
}
}
}
}

View file

@ -0,0 +1,114 @@
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// Poses the Skeleton's mandible, which the player rig alone puts in the wrong place.
///
/// The three skeleton models are skinned to the player rig by bone name, and the rig owns a
/// real 'Jaw' bone, so the mandible lands on the right bone - just at the rest pose that bone
/// happens to hold, which sits a little low and a little far back for a skull. Nothing here
/// remaps anything: it moves that one bone, and only that one.
///
/// THE POSE IS WRITTEN ABSOLUTELY, NEVER ACCUMULATED. That distinction is the whole reason
/// this file reads the way it does. No Valheim animation touches the Jaw bone, so nothing
/// resets it between frames: an earlier version added its offset to whatever the bone already
/// held, on the usual assumption that the Animator rewrites the rig every frame. It does not,
/// so the jaw drifted a few centimetres further away every frame - it left the skull entirely
/// within a fifth of a second, snapped back when a visual refresh happened to rebind the rig,
/// and started over, which is what showed up in game as a head flickering five times a second.
/// With the game paused nothing rebound anything and the mandible simply kept going, dragging
/// the vertices weighted to it into a metres-long spike. Writing the base pose back before
/// applying the correction makes the whole thing idempotent: applied once, five times or not
/// at all in a given frame, the jaw ends up in exactly the same place.
///
/// Runs in LateUpdate, after the animation phase, so the correction cannot be undone by an
/// animation that does move the head around the jaw.
///
/// Attached to every player VisEquipment rebuilds visuals for - local, remote and the
/// main-menu preview - so the jaw is right for everyone looking, not just for the client
/// wearing it.
/// </summary>
public class SkeletonJawFix : MonoBehaviour
{
// Found in game with a temporary set of Configuration Manager sliders, on the tier-3
// Skeleton_Poison model; the plain and the fire models share the rig and the same jaw rest
// pose bone for bone (confirmed in the bone-mapping dump), so one correction covers all
// three. Metres along the skull's own axes, so the mandible keeps following the head
// however it turns.
private static readonly Vector3 Offset = new Vector3(0.0338f, 0.0394f, 0f);
// The rig's jaw is a touch large for these skulls.
private const float Scale = 0.9437f;
private Player m_player;
private VisEquipment m_vis;
private Transform m_jaw;
private Vector3 m_baseLocalPosition;
private Vector3 m_baseLocalScale;
private bool m_applied;
private void Awake()
{
m_player = GetComponent<Player>();
m_vis = GetComponent<VisEquipment>();
}
private void LateUpdate()
{
if (m_player == null || m_vis == null) return;
Transform jaw = ResolveJaw();
if (jaw == null || jaw.parent == null) return;
if (!SkeletonVisuals.IsSkeletonPlayer(m_player))
{
// Nothing rewrites this bone on its own, so a player who stops being a Skeleton
// would otherwise keep wearing the correction on their human face.
if (m_applied)
{
jaw.localPosition = m_baseLocalPosition;
jaw.localScale = m_baseLocalScale;
m_applied = false;
}
return;
}
// Back to the rest pose first: this is what makes the block below absolute rather than
// a nudge on top of last frame's nudge. See the note in the class summary.
jaw.localPosition = m_baseLocalPosition;
jaw.localScale = m_baseLocalScale * Scale;
// In world space rather than localPosition, so the offset stays in metres whatever the
// rig's authored scale is, and rotated by the skull so it tracks the head.
jaw.position += jaw.parent.rotation * Offset;
m_applied = true;
}
/// <summary>
/// The player rig's own jaw bone, with the rest pose it holds before anything here has
/// touched it. Captured once per bone: re-reading it later would sample a pose this
/// component had already moved and bake the correction in twice.
/// </summary>
private Transform ResolveJaw()
{
if (m_jaw != null) return m_jaw;
if (m_vis.m_bodyModel == null || m_vis.m_bodyModel.bones == null) return null;
foreach (Transform bone in m_vis.m_bodyModel.bones)
{
if (bone == null || !bone.name.ToLower().Contains("jaw")) continue;
m_jaw = bone;
m_baseLocalPosition = bone.localPosition;
m_baseLocalScale = bone.localScale;
m_applied = false;
break;
}
return m_jaw;
}
}
}

View file

@ -338,6 +338,21 @@ namespace RacesOfValheim
HideItemInstances(__instance, "m_hairItemInstance");
HideItemInstances(__instance, "m_beardItemInstance");
SetHelmetVisible(__instance, false);
// Poses the mandible, once per frame, after the animation. Attached from
// here rather than from SkeletonRace because this postfix is the one path
// every skeleton reaches - local, remote and the menu preview - and the
// jaw is a rig bone, so whoever is looking sees the same face.
if (p.GetComponent<SkeletonJawFix>() == null)
{
p.gameObject.AddComponent<SkeletonJawFix>();
}
// The lights in the eye sockets, cloned out of this tier's own creature so
// that each one arrives its own colour. Outside the build block above on
// purpose: they hang off the player's rig bones rather than off the body
// container, so they outlive it and have to be checked every refresh.
SkeletonEyeGlow.Apply(__instance, rules.ModelPrefab);
}
}
else
@ -362,6 +377,10 @@ namespace RacesOfValheim
ShowItemInstances(__instance, "m_hairItemInstance");
ShowItemInstances(__instance, "m_beardItemInstance");
SetHelmetVisible(__instance, true);
// Parented to rig bones, not to the body container that was just switched
// off above - so without this a human keeps the skeleton's lit sockets.
SkeletonEyeGlow.Clear(__instance);
}
}
}
@ -514,7 +533,12 @@ namespace RacesOfValheim
}
}
private static Transform FindBoneByName(Transform[] bones, string skelBoneName)
/// <summary>
/// The player bone a creature's bone maps onto. Internal because the eye glow hangs
/// its clones off the same mapping the body is skinned through - one answer to
/// "which bone is this", not two that can drift apart.
/// </summary>
internal static Transform FindBoneByName(Transform[] bones, string skelBoneName)
{
// Exact match first
foreach (Transform b in bones)

View file

@ -0,0 +1,170 @@
using System.Collections.Generic;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// Sensory Antennae: from The Elder on, a Sverm feels every living thing around it and reads
/// what each one is by colour.
///
/// This is the Aswid's Auspex (AswidRace, the sensesCheckTimer loop) with one thing added: the
/// Aswid marks everything green because it only wants to know that something is THERE. An
/// insect's antennae are a chemical sense, and a chemical sense tells kin from prey from
/// threat - so the light is the same trick and the colour carries the information.
///
/// red - hostile
/// yellow - invertebrate: kin, and by Hive Pheromones already harmless to you
/// azure - yours: tamed, and in due course the colony's own brood
/// green - alive and indifferent
///
/// NOTHING HERE IS REPLICATED. A Light created on this client and parented to a creature costs
/// other players nothing and never touches the ZDO - the same reason the Aswid and the Dvergar
/// both mark with lights rather than with anything the server would have to carry.
///
/// The cost that IS real is local: this is a passive with no cooldown, so in a busy forest it
/// can hold a dozen or more point lights at once, and Valheim renders few per pixel. If it
/// ever misbehaves the lever is the radius, not the mechanism.
/// </summary>
public static class SvermAntennae
{
private const string LightName = "SvermAntennaeLight";
private static readonly Dictionary<Character, GameObject> lights = new Dictionary<Character, GameObject>();
private static readonly List<Character> stale = new List<Character>();
private static float nextSweep;
public static void Tick(Player player)
{
bool active = player != null
&& player == Player.m_localPlayer
&& SvermVisuals.IsSvermPlayer(player)
&& !player.IsDead()
&& SvermProgression.Current.SensoryAntennae;
if (!active)
{
ClearAll();
return;
}
if (Time.time < nextSweep) return;
nextSweep = Time.time + SvermConfig.AntennaeInterval;
Sweep(player);
}
private static void Sweep(Player player)
{
Vector3 centre = player.transform.position;
float radius = SvermConfig.AntennaeRadius;
HashSet<Character> inRange = new HashSet<Character>();
foreach (Character c in Character.GetAllCharacters())
{
if (c == null || c == player || c.IsDead()) continue;
if (Vector3.Distance(c.transform.position, centre) > radius) continue;
inRange.Add(c);
Color colour = ColourFor(player, c);
if (lights.TryGetValue(c, out GameObject existing) && existing != null)
{
// Already lit. Only the colour can have changed - a boar that turns hostile,
// a creature that gets tamed - and re-colouring is cheaper than rebuilding.
Light live = existing.GetComponent<Light>();
if (live != null && live.color != colour) live.color = colour;
continue;
}
lights[c] = BuildLight(c, colour);
}
// Anything no longer in range, or dead, or gone. Collected first and removed after:
// deleting from a dictionary while enumerating it throws.
stale.Clear();
foreach (KeyValuePair<Character, GameObject> pair in lights)
{
if (pair.Key == null || !inRange.Contains(pair.Key)) stale.Add(pair.Key);
}
foreach (Character gone in stale)
{
if (lights.TryGetValue(gone, out GameObject go) && go != null) Object.Destroy(go);
lights.Remove(gone);
}
}
/// <summary>
/// Order matters more than the colours do.
///
/// Tamed is checked FIRST because a tamed wolf is still an enemy of nothing and a friend of
/// yours, and asking IsEnemy first would paint your own animals as threats. Invertebrates
/// come next because Hive Pheromones has already made them harmless, so calling them
/// hostile would contradict the rest of the race. Only then does the hostile test run, and
/// everything left over is simply alive.
/// </summary>
private static Color ColourFor(Player player, Character c)
{
if (c.IsTamed()) return SvermConfig.AntennaeKinColor;
if (IsInvertebrate(c)) return SvermConfig.AntennaeInvertebrateColor;
if (BaseAI.IsEnemy(player, c)) return SvermConfig.AntennaeHostileColor;
return SvermConfig.AntennaePassiveColor;
}
/// <summary>
/// The same substring test RaceHostilityManager uses for Hive Pheromones, and deliberately
/// so: whatever counts as kin for the truce has to count as kin for the antennae, or the
/// player is told one thing and shown another.
/// </summary>
private static bool IsInvertebrate(Character c)
{
string prefabName = c.gameObject.name.ToLowerInvariant();
if (prefabName.Contains("bonemass")) return false;
return prefabName.Contains("blob")
|| prefabName.Contains("leech")
|| prefabName.Contains("tick")
|| prefabName.Contains("deathsquito")
|| prefabName.Contains("gjall")
|| prefabName.Contains("seeker");
}
private static GameObject BuildLight(Character c, Color colour)
{
GameObject go = new GameObject(LightName);
go.transform.SetParent(c.transform);
go.transform.position = c.GetCenterPoint();
Light light = go.AddComponent<Light>();
light.type = LightType.Point;
light.color = colour;
light.range = SvermConfig.AntennaeLightRange;
light.intensity = SvermConfig.AntennaeLightIntensity;
// No shadows, ever. A dozen shadow-casting point lights in a forest is a slideshow,
// and none of these lights is meant to light the world - only to say "here".
light.shadows = LightShadows.None;
return go;
}
/// <summary>Puts out every light. Called when the perk stops applying, and on death.</summary>
public static void ClearAll()
{
if (lights.Count == 0) return;
foreach (KeyValuePair<Character, GameObject> pair in lights)
{
if (pair.Value != null) Object.Destroy(pair.Value);
}
lights.Clear();
}
}
}

View file

@ -0,0 +1,197 @@
using System.Collections.Generic;
using Jotunn.Managers;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The takeover of the ordinary beehives standing inside a nest's aura.
///
/// A minute inside the aura and a hive stops being the player's and becomes the colony's: an
/// egg pushes out through the roof, and from then on it fills twice as fast and holds three
/// times as much. After Yagluth what comes out is royal jelly instead of honey.
///
/// NOTHING IS CLONED AND NOTHING IS REPLACED. The vanilla Beehive component is retuned in
/// place on that one instance, and the state lives on that instance's ZDO - so an infected
/// hive stays infected across a reload, other players see the same thing, and a hive outside
/// any aura is never touched. The egg is a borrowed model parented to the hive, exactly the
/// way the crest is worn on a bone.
///
/// Retuning a COMPONENT is safe where retuning m_shared would not be: m_secPerUnit lives on
/// the instance, not on shared item data, so one hive changing does not change every hive in
/// the world.
/// </summary>
public static class SvermBeehive
{
/// <summary>Written on the hive's own ZDO, so the takeover survives a reload.</summary>
private const string InfectedKey = "RacesOfValheim_SvermInfected";
/// <summary>When this hive first came under an aura, so the minute can be counted.</summary>
private const string ClaimedAtKey = "RacesOfValheim_SvermClaimedAt";
private const string EggName = "SvermHiveEgg";
/// <summary>Values captured before we touched them, so a hive can be handed back intact.</summary>
private static readonly Dictionary<Beehive, float> originalSecPerUnit = new Dictionary<Beehive, float>();
// ─── The sweep ───────────────────────────────────────────────────────
/// <summary>
/// Called by the nest, on a timer. Claims what is in range and ripens what has waited.
/// </summary>
public static void SweepAura(Vector3 nest)
{
foreach (Beehive hive in Find(nest))
{
ZNetView nview = hive.GetComponent<ZNetView>();
if (nview == null || !nview.IsValid()) continue;
if (nview.GetZDO().GetBool(InfectedKey, false))
{
Apply(hive, nview);
continue;
}
// First sighting starts the clock. Stored as world time rather than counted in a
// field, because a nest that unloads and comes back must not restart the minute.
double claimedAt = nview.GetZDO().GetFloat(ClaimedAtKey, 0f);
if (claimedAt <= 0.0)
{
nview.GetZDO().Set(ClaimedAtKey, (float)ZNet.instance.GetTimeSeconds());
continue;
}
if (ZNet.instance.GetTimeSeconds() - claimedAt < SvermConfig.BeehiveInfectionSeconds) continue;
nview.GetZDO().Set(InfectedKey, true);
Apply(hive, nview);
Jotunn.Logger.LogInfo("[Sverm] A beehive has been taken over by the colony.");
}
}
/// <summary>
/// Retunes one infected hive and makes sure it is wearing its egg.
///
/// Re-applied on every sweep rather than once at infection: Valheim rebuilds these
/// components when the zone reloads, and a hive that came back at vanilla speed would
/// quietly undo the whole feature with nothing in the log to say so.
/// </summary>
private static void Apply(Beehive hive, ZNetView nview)
{
if (!originalSecPerUnit.ContainsKey(hive)) originalSecPerUnit[hive] = hive.m_secPerUnit;
float wanted = originalSecPerUnit[hive] / SvermConfig.BeehiveSpeedMultiplier;
if (!Mathf.Approximately(hive.m_secPerUnit, wanted)) hive.m_secPerUnit = wanted;
int wantedMax = Mathf.RoundToInt(SvermConfig.BeehiveBaseMaxHoney * SvermConfig.BeehiveCapacityMultiplier);
if (hive.m_maxHoney != wantedMax) hive.m_maxHoney = wantedMax;
// After Yagluth the colony stops making honey and starts making royal jelly. Read from
// ObjectDB rather than held as a reference, because the item has to exist first.
string wantedItem = BossProgressionManager.GetCurrentProgressionState() >= SvermConfig.RoyalJellyHiveState
? SvermConfig.RoyalJellyPrefab
: "Honey";
if (hive.m_honeyItem == null || hive.m_honeyItem.gameObject.name != wantedItem)
{
ItemDrop replacement = PrefabManager.Cache.GetPrefab<ItemDrop>(wantedItem);
if (replacement != null) hive.m_honeyItem = replacement;
}
EnsureEgg(hive.transform);
}
/// <summary>
/// The egg on the roof: a permanent mark, and the only way to tell an infected hive from an
/// ordinary one at a glance.
///
/// Borrowed through ModelBorrow, so it arrives stripped of its ItemDrop and its networking
/// and cannot be picked up, walked into, or dropped on the floor.
/// </summary>
private static void EnsureEgg(Transform hive)
{
if (hive.Find(EggName) != null) return;
ModelBorrow.Attach(
hive,
EggName,
SvermConfig.HiveEggPrefab,
Vector3.up * SvermConfigManagement.EggHeight,
Quaternion.identity,
SvermConfigManagement.EggSize,
"Sverm");
}
// ─── Lookups ─────────────────────────────────────────────────────────
/// <summary>Every beehive standing inside a nest's aura.</summary>
public static List<Beehive> Find(Vector3 nest)
{
List<Beehive> found = new List<Beehive>();
foreach (Collider collider in Physics.OverlapSphere(nest, SvermConfig.HiveAuraRadius))
{
if (collider == null) continue;
Beehive hive = collider.GetComponentInParent<Beehive>();
if (hive != null && !found.Contains(hive)) found.Add(hive);
}
return found;
}
public static int CountInAura(Vector3 nest) => Find(nest).Count;
public static int CountInfectedInAura(Vector3 nest)
{
int count = 0;
foreach (Beehive hive in Find(nest))
{
if (IsInfected(hive)) count++;
}
return count;
}
/// <summary>
/// Puts the colony's marks on every taken hive in range: flies always, green gas only when
/// the hive is FULL and has nothing left to do but wait for someone to empty it.
///
/// Called by the nest on every client, not from the owner's sweep - particles are local, and
/// a hive that only smoked on the host's screen would be half a feature.
/// </summary>
public static void DressInfected(Vector3 nest)
{
float scale = SvermConfigManagement.BeehiveVfxScale;
foreach (Beehive hive in Find(nest))
{
if (!IsInfected(hive)) continue;
SvermHiveVfx.EnsureFlies(hive.transform, scale);
SvermHiveVfx.SetGas(hive.transform, IsFull(hive), scale);
}
}
/// <summary>
/// Whether the hive has no room left for honey.
///
/// GetHoneyLevel is private in the assembly this project compiles against - like
/// Container.Save and Inventory.FindEmptySlot - so it is read through Traverse rather than
/// called, and rather than second-guessed by reading the ZDO key by hand.
/// </summary>
private static bool IsFull(Beehive hive)
{
if (hive == null) return false;
int level = HarmonyLib.Traverse.Create(hive).Method("GetHoneyLevel").GetValue<int>();
return level >= hive.m_maxHoney;
}
public static bool IsInfected(Beehive hive)
{
ZNetView nview = hive != null ? hive.GetComponent<ZNetView>() : null;
return nview != null && nview.IsValid() && nview.GetZDO().GetBool(InfectedKey, false);
}
}
}

View file

@ -0,0 +1,243 @@
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The nest's tank, and the rule for what may go into it.
///
/// The number lives on the nest's own ZDO rather than in a field, so it survives a reload, a
/// zone unload, and a different player walking up to the same nest.
///
/// WHAT COUNTS AS FUEL is the part worth reading. Anything the Sverm could eat, at half its
/// nutritional sum, plus a flat rate for wood and resin - EXCEPT honey and royal jelly, which
/// stopped being fuel the moment they became medicine. Feeding the colony its own healing
/// supply would be the worst kind of bug: quiet, expensive, and entirely the mod's fault.
/// </summary>
public static class SvermBiomass
{
// ─── What burns ──────────────────────────────────────────────────────
public static bool IsFuel(ItemDrop.ItemData item)
{
if (item == null || item.m_shared == null) return false;
string prefabName = item.m_dropPrefab != null ? item.m_dropPrefab.name : "";
// The medicine. Explicitly first, so no later rule can accidentally readmit it.
if (prefabName == "Honey" || prefabName == SvermConfig.RoyalJellyPrefab) return false;
if (IsWood(prefabName)) return true;
return item.m_shared.m_food + item.m_shared.m_foodStamina + item.m_shared.m_foodEitr > 0f;
}
/// <summary>
/// Wood and resin, at a flat rate regardless of biome. Ashwood is out.
///
/// Flat because a per-biome table for firewood is a lot of bookkeeping for a resource whose
/// whole job is to be the bulk filler while food is the concentrate.
/// </summary>
private static bool IsWood(string prefabName)
{
if (string.IsNullOrEmpty(prefabName)) return false;
if (prefabName.ToLowerInvariant().Contains("ash")) return false; // ashwood excluded
return prefabName == "Wood"
|| prefabName == "RoundLog"
|| prefabName == "FineWood"
|| prefabName == "ElderBark"
|| prefabName == "YggdrasilWood"
|| prefabName == "Resin";
}
/// <summary>What one of this item is worth in the tank.</summary>
public static float ValueOf(ItemDrop.ItemData item)
{
if (!IsFuel(item)) return 0f;
string prefabName = item.m_dropPrefab != null ? item.m_dropPrefab.name : "";
if (IsWood(prefabName)) return SvermConfig.WoodBiomassValue;
return (item.m_shared.m_food + item.m_shared.m_foodStamina + item.m_shared.m_foodEitr) * 0.5f;
}
// ─── The tank ────────────────────────────────────────────────────────
//
// THREE NUMBERS, NOT ONE, and the middle one is the whole point of the shop. What the hive
// has just been handed is not what the hive can spend: everything it eats lands in
// DIGESTION and seeps into the BANK at a fixed rate, and only the bank ever pays for
// anything. CAPACITY is the stage's ceiling and it covers both together, because a stomach
// that is full is full whether or not the last meal has gone down yet.
// The bank keeps the key the tank has always had, so a hive standing in somebody's world
// reads back with its biomass intact rather than at zero.
private const string BankKey = "RacesOfValheim_SvermBiomass"; // spendable
private const string DigestKey = "RacesOfValheim_SvermDigesting"; // eaten, not yet spendable
private const string ClockKey = "RacesOfValheim_SvermDigestedAt"; // world second of the last digest
/// <summary>What the hive can actually spend.</summary>
public static float Bank(Transform nest)
{
ZDO zdo = Zdo(nest);
return zdo != null ? zdo.GetFloat(BankKey, 0f) : 0f;
}
/// <summary>Eaten but not yet spendable.</summary>
public static float Digesting(Transform nest)
{
ZDO zdo = Zdo(nest);
return zdo != null ? zdo.GetFloat(DigestKey, 0f) : 0f;
}
public static float Capacity(Transform nest)
{
return SvermHiveStage.Capacity(SvermHiveStage.Of(nest));
}
/// <summary>How much more the hive can hold, digested or not.</summary>
public static float Space(Transform nest)
{
return Mathf.Max(0f, Capacity(nest) - Bank(nest) - Digesting(nest));
}
/// <summary>Adds one item's worth. Returns what actually fitted.</summary>
public static float Deposit(Transform nest, ItemDrop.ItemData item)
{
return Swallow(nest, ValueOf(item));
}
/// <summary>
/// Puts raw biomass into digestion, clamped to what is left of the tank. Returns what fitted.
///
/// EVERYTHING the hive eats comes through here - the shop's one button and the haulers'
/// chest round alike. A meal that arrived by way of a chest is still a meal, and giving the
/// haulers a shortcut straight into the bank would make the wait the shop imposes
/// avoidable by anyone who owns a box.
/// </summary>
public static float Swallow(Transform nest, float amount)
{
if (amount <= 0f) return 0f;
ZNetView nview = Claim(nest);
if (nview == null) return 0f;
float accepted = Mathf.Min(amount, Space(nest));
if (accepted <= 0f) return 0f;
ZDO zdo = nview.GetZDO();
// The clock is started by the first mouthful and not before: an untouched hive has no
// "last digested" second, and reading a missing key as zero would hand it every second
// since the world began the moment it was finally fed.
//
// WHOLE SECONDS IN A LONG FIELD, deliberately and everywhere. ZDO.Set takes a long as
// readily as a float, and a clock written through one overload and read through the
// other is a key that always answers with its default - which here means an elapsed
// time of zero, forever, and a hive that digests nothing at all.
if (zdo.GetFloat(DigestKey, 0f) <= 0f) zdo.Set(ClockKey, WorldSecond());
zdo.Set(DigestKey, zdo.GetFloat(DigestKey, 0f) + accepted);
return accepted;
}
/// <summary>
/// Moves what time has earned from digestion into the bank.
///
/// Measured against the WORLD clock rather than frames, so a hive nobody is standing next
/// to still digests: come back to it in the morning and the meal has gone down. The owner
/// calls this on a timer - see SvermHiveBehaviour.
/// </summary>
public static void Digest(Transform nest)
{
ZNetView nview = nest != null ? nest.GetComponent<ZNetView>() : null;
if (nview == null || !nview.IsValid() || !nview.IsOwner()) return;
ZDO zdo = nview.GetZDO();
float digesting = zdo.GetFloat(DigestKey, 0f);
if (digesting <= 0f) return;
long now = WorldSecond();
long last = zdo.GetLong(ClockKey, now);
long elapsed = now - last;
// Whole seconds only, and the clock only moves by what was actually consumed, so the
// fraction left over is not quietly lost on every tick.
if (elapsed <= 0L) return;
float moved = Mathf.Min(digesting, SvermConfigManagement.DigestRate * elapsed);
zdo.Set(ClockKey, now);
if (moved <= 0f) return;
zdo.Set(DigestKey, digesting - moved);
zdo.Set(BankKey, zdo.GetFloat(BankKey, 0f) + moved);
}
/// <summary>
/// Puts spent biomass straight back in the bank, past the digestion.
///
/// Only ever for a purchase that was paid for and then could not be delivered. It skips the
/// digestion on purpose: the hive already digested this once, and making the player wait
/// again for a thing they did not get would be a second punishment for our own race.
/// </summary>
public static void Refund(Transform nest, float amount)
{
if (amount <= 0f) return;
ZNetView nview = Claim(nest);
if (nview == null) return;
ZDO zdo = nview.GetZDO();
zdo.Set(BankKey, Mathf.Min(zdo.GetFloat(BankKey, 0f) + amount, Capacity(nest)));
}
/// <summary>Takes from the bank if there is enough. All or nothing.</summary>
public static bool Spend(Transform nest, float amount)
{
ZNetView nview = Claim(nest);
if (nview == null) return false;
ZDO zdo = nview.GetZDO();
float bank = zdo.GetFloat(BankKey, 0f);
if (bank < amount) return false;
zdo.Set(BankKey, bank - amount);
return true;
}
// ─── Plumbing ────────────────────────────────────────────────────────
private static ZDO Zdo(Transform nest)
{
ZNetView nview = nest != null ? nest.GetComponent<ZNetView>() : null;
return nview != null && nview.IsValid() ? nview.GetZDO() : null;
}
/// <summary>
/// The nest's view, owned by us before we write to it.
///
/// A write to a ZDO somebody else owns survives until their copy comes back over the wire
/// and overwrites it - which reads, to the player who just sold half their larder, as the
/// hive having eaten it and forgotten.
/// </summary>
private static ZNetView Claim(Transform nest)
{
ZNetView nview = nest != null ? nest.GetComponent<ZNetView>() : null;
if (nview == null || !nview.IsValid()) return null;
if (!nview.IsOwner()) nview.ClaimOwnership();
return nview;
}
/// <summary>
/// The world clock in whole seconds.
///
/// The world's own time and not Time.time, so the answer means the same thing to a hive
/// that has just loaded as to one that has been standing there all evening. Zero when there
/// is no net yet, which only happens before a world is up - and Digest reads a missing
/// clock as "now", so nothing is ever handed a windfall.
/// </summary>
private static long WorldSecond()
{
return ZNet.instance != null ? (long)ZNet.instance.GetTimeSeconds() : 0L;
}
}
}

View file

@ -0,0 +1,289 @@
using Jotunn.Managers;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The Blister Tick: fifty biomass buys a SLOT, and the slot is forever.
///
/// SECTION 12, and it is the one troop that does not behave like the others. It runs at what the
/// colony is fighting and bursts. It leaves nothing behind, it heals nothing, and it does not
/// need to: thirty seconds after it dies the nest grows another one, free - no egg, no biomass.
/// The slot that was paid for is permanent, exactly like the Skeleton's chains, and ten of them
/// coming back every half minute is a continuous stream of explosions rather than a squad. That
/// is the whole point of the unit and the reason its damage is borrowed from two bombs the game
/// already balanced instead of from a number somebody invented.
///
/// THE DAMAGE IS READ, NOT COPIED: the poison blob's own projectile prefab is asked what it
/// hits for, once, at registration. Ooze up to the second stage of the nest, the elite blob
/// after that - section 12's "BombOoze then BombBile" expressed in the two projectiles this
/// build actually ships.
/// </summary>
public static class SvermBlisterTick
{
public const string PrefabName = "SvermBlisterTick";
public const string DisplayName = "Blister Tick";
private const string SourcePrefab = "Tick";
/// <summary>How many slots this nest has bought. Permanent, and the respawn reads it.</summary>
private const string SlotKey = "RacesOfValheim_SvermTickSlots";
/// <summary>The blast, in rising order of nastiness. Both are verified manifest names.</summary>
private const string EarlyBlast = "BombBlob_Poison_projectile";
private const string LateBlast = "BombBlob_PoisonElite_projectile";
private const string BlastEffect = "BombBlob_explode_poison";
private static HitData.DamageTypes earlyDamage;
private static HitData.DamageTypes lateDamage;
private static float blastRadius = 4f;
// ─── Registration ────────────────────────────────────────────────────
public static void Register()
{
GameObject source = PrefabManager.Cache.GetPrefab<GameObject>(SourcePrefab);
if (source == null)
{
Jotunn.Logger.LogWarning($"[Sverm] No '{SourcePrefab}' to build the Blister Tick from; no ticks.");
return;
}
GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(PrefabName, source);
if (prefab == null) return;
Character character = prefab.GetComponent<Character>();
if (character != null) character.m_name = DisplayName;
BaseAI ai = prefab.GetComponent<BaseAI>();
if (ai != null) ai.m_randomMoveRange = SvermConfig.TroopLeashRange;
// Nothing to farm off something that respawns for free forever. This one matters more
// than on the other troops for exactly that reason.
foreach (CharacterDrop drops in prefab.GetComponentsInChildren<CharacterDrop>(true))
{
if (drops != null) Object.DestroyImmediate(drops);
}
RaisedThrall thrall = prefab.AddComponent<RaisedThrall>();
thrall.m_kind = PrefabName;
thrall.m_commandingRace = SvermConfig.RaceId;
thrall.m_maxFollowers = -1;
thrall.m_witherSeconds = SvermConfig.TroopWitherSeconds;
thrall.m_homeCheckRange = SvermConfig.TroopHomeCheckRange;
thrall.m_refusalMessage = "It does not smell your colony on you.";
// No SkeletonSentryBehaviour. A tick that healed itself would be a tick that never gets
// round to exploding, which is its entire job.
prefab.AddComponent<SvermBlisterTickBehaviour>();
ReadBlastDamage();
PrefabManager.Instance.AddPrefab(prefab);
Jotunn.Logger.LogInfo($"[Sverm] Registered '{PrefabName}' from '{SourcePrefab}'.");
}
/// <summary>
/// Asks the two blob projectiles what they hit for, once. A missing one leaves its stage on
/// the fallback rather than on zero - a tick that exploded for nothing would look like it
/// was working.
/// </summary>
private static void ReadBlastDamage()
{
earlyDamage = DamageOf(EarlyBlast, SvermConfig.TickFallbackDamage);
lateDamage = DamageOf(LateBlast, SvermConfig.TickFallbackDamage * 2f);
}
private static HitData.DamageTypes DamageOf(string projectileName, float fallbackPoison)
{
GameObject prefab = PrefabManager.Cache.GetPrefab<GameObject>(projectileName);
Projectile projectile = prefab != null ? prefab.GetComponent<Projectile>() : null;
if (projectile == null)
{
Jotunn.Logger.LogWarning($"[Sverm] No '{projectileName}' to price the Blister Tick's blast; " +
$"it falls back to {fallbackPoison:0} poison.");
return new HitData.DamageTypes { m_poison = fallbackPoison };
}
if (projectile.m_aoe > 0f) blastRadius = projectile.m_aoe;
return projectile.m_damage;
}
/// <summary>What one blast does, at this nest's stage. Section 12's two tiers.</summary>
public static HitData.DamageTypes BlastFor(int stage)
{
return stage >= SvermConfig.TickLateBlastStage ? lateDamage : earlyDamage;
}
public static float BlastRadius => blastRadius;
public static GameObject BlastVfx()
{
return PrefabManager.Cache.GetPrefab<GameObject>(BlastEffect);
}
// ─── The slots ───────────────────────────────────────────────────────
public static int SlotsOf(Transform nest)
{
ZNetView nview = nest != null ? nest.GetComponent<ZNetView>() : null;
if (nview == null || !nview.IsValid()) return 0;
return Mathf.Clamp(nview.GetZDO().GetInt(SlotKey, 0), 0, SvermConfigManagement.BlisterTick);
}
public static void BuySlot(Transform nest)
{
ZNetView nview = nest != null ? nest.GetComponent<ZNetView>() : null;
if (nview == null || !nview.IsValid()) return;
if (!nview.IsOwner()) nview.ClaimOwnership();
nview.GetZDO().Set(SlotKey, SlotsOf(nest) + 1);
}
/// <summary>How many are alive right now, counted off the nest the way the roster is.</summary>
public static int CountAlive(SvermHiveBehaviour hive)
{
if (hive == null) return 0;
int count = 0;
foreach (RaisedThrall thrall in RaisedThrall.BoundTo(hive.transform.position))
{
if (thrall != null && thrall.Kind == PrefabName) count++;
}
return count;
}
/// <summary>
/// Fills the empty slots, free. Called by the nest on its own timer, owner only.
///
/// One per call rather than all at once: ten ticks arriving in the same frame after a fight
/// would be a wall of bodies, and a slot every half minute is what the design asks for.
/// </summary>
public static void Replace(SvermHiveBehaviour hive)
{
if (hive == null) return;
int slots = SlotsOf(hive.transform);
if (slots <= 0 || CountAlive(hive) >= slots) return;
Hatch(hive);
}
public static bool Hatch(SvermHiveBehaviour hive)
{
GameObject prefab = ZNetScene.instance != null ? ZNetScene.instance.GetPrefab(PrefabName) : null;
if (prefab == null) return false;
Vector3 offset = Random.insideUnitSphere * 2f;
offset.y = 0f;
GameObject spawned = Object.Instantiate(prefab, hive.transform.position + offset + Vector3.up * 0.5f,
Quaternion.Euler(0f, Random.Range(0, 360), 0f));
if (spawned == null) return false;
Character character = spawned.GetComponent<Character>();
if (character != null)
{
int stars = SvermBroodStars.Of(hive.transform);
if (stars > 0) character.SetLevel(1 + stars);
}
RaisedThrall thrall = spawned.GetComponent<RaisedThrall>();
if (thrall != null) thrall.Bind(hive.transform.position);
return true;
}
}
/// <summary>
/// One tick's short life: get close to something the colony is fighting, and burst.
///
/// It goes off on ITS OWN TARGET and not on anything that happens to be near. A tick that
/// exploded because a boar walked past would clear its own base of livestock, and one that went
/// off next to the player it was following would be a trap rather than a weapon - so the blast
/// spares everything tame, the player included.
/// </summary>
public class SvermBlisterTickBehaviour : MonoBehaviour
{
private Character m_character;
private MonsterAI m_ai;
private ZNetView m_nview;
private bool m_bursting;
private void Awake()
{
m_character = GetComponent<Character>();
m_ai = GetComponent<MonsterAI>();
m_nview = GetComponent<ZNetView>();
InvokeRepeating("TickCheck", 1f, 0.5f);
}
private void TickCheck()
{
if (m_bursting) return;
if (m_character == null || m_character.IsDead()) return;
if (m_nview == null || !m_nview.IsValid() || !m_nview.IsOwner()) return;
if (m_ai == null) return;
Character target = m_ai.GetTargetCreature();
if (target == null || target.IsDead()) return;
if (Vector3.Distance(transform.position, target.transform.position) > SvermConfig.TickBurstRange) return;
Burst();
}
private void Burst()
{
m_bursting = true;
Vector3 where = transform.position + Vector3.up * 0.3f;
GameObject vfx = SvermBlisterTick.BlastVfx();
if (vfx != null) Object.Instantiate(vfx, where, Quaternion.identity);
// The stage of whichever nest it belongs to. A tick whose nest has been torn down still
// bursts - at the early damage, which is the honest answer when there is nobody left to
// ask.
int stage = SvermHiveStage.First;
RaisedThrall thrall = GetComponent<RaisedThrall>();
Vector3? anchor = thrall != null ? thrall.Anchor : null;
if (anchor != null)
{
SvermHiveBehaviour nest = SvermHive.NearestNest(anchor.Value, 2f);
if (nest != null) stage = SvermHiveStage.Of(nest.transform);
}
HitData.DamageTypes damage = SvermBlisterTick.BlastFor(stage);
foreach (Collider collider in Physics.OverlapSphere(where, SvermBlisterTick.BlastRadius))
{
if (collider == null) continue;
Character victim = collider.GetComponentInParent<Character>();
if (victim == null || victim == m_character || victim.IsDead()) continue;
// Everything of ours walks away from this: the player, their tames, and every other
// thing the colony has hatched.
if (victim.IsPlayer() || victim.IsTamed()) continue;
HitData hit = new HitData();
hit.m_damage = damage;
hit.m_point = victim.GetCenterPoint();
hit.m_dir = (victim.transform.position - where).normalized;
hit.SetAttacker(m_character);
victim.Damage(hit);
}
// Its own death is the cost of the attack, and it is what the free respawn is measured
// from: the nest sees an empty slot and grows another.
//
// Killed through RaisedThrall.Kill rather than by writing health to zero, because that
// is the one path in this mod already proven to take a summoned creature all the way
// through the game's own death sequence.
if (thrall != null) thrall.Kill();
else m_character.SetHealth(0f);
}
}
}

View file

@ -0,0 +1,293 @@
using System.Collections.Generic;
using Jotunn.Managers;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The army: four creatures, hatched at the market, bound to the nest that paid for them.
///
/// TWO RESOURCES IN PARALLEL, which is section 10.2 and the whole shape of the colony. The EGG
/// is the slot and it grows back on its own; the BIOMASS is the price and it does not. A troop
/// needs both, so a hive with a full tank and no eggs waits, and a hive full of eggs and no
/// biomass waits differently.
///
/// Nothing here is new machinery. A troop is a RaisedThrall - the same component the Draugh's
/// spawner, the Dvergar's bank and the Fenrir's trough hang their rosters on - so the follow and
/// stay orders, the leash, the walk home and the withering when the station falls all come for
/// free and behave exactly like every other summoned thing in the mod. The self-healing is
/// SkeletonSentryBehaviour, reused whole, which is section 11.2 word for word.
/// </summary>
public static class SvermBrood
{
/// <summary>
/// What every troop prefab's name starts with. One place, because two things ask the
/// question "is this creature one of ours" - the roster and the medicine.
/// </summary>
public const string PrefabPrefix = "SvermTroop_";
/// <summary>One rung of the ladder, from section 11's table.</summary>
public class Kind
{
public string Id;
public string Display;
public string Source; // the vanilla creature it is cloned from
public string Icon;
public float Price;
public int Stage; // the nest stage it becomes available at
public float Cooldown; // seconds between two of these
public string PrefabName => PrefabPrefix + Source;
public int Cap => CapOf(Id);
}
/// <summary>
/// Section 11's table, prices and caps and stage gates unchanged.
///
/// The cooldowns are section 20.4's: ten minutes for a Gjall and "the others scaled
/// accordingly", which is read here as scaled BY PRICE - a Brood is a tenth of a Gjall in
/// biomass, so it is a tenth of a Gjall in patience too.
/// </summary>
public static readonly List<Kind> Roster = new List<Kind>
{
new Kind { Id = "brood", Display = "Brood", Source = "SeekerBrood", Icon = "TrophySeeker", Price = 100f, Stage = 1, Cooldown = 60f },
new Kind { Id = "seeker", Display = "Seeker", Source = "Seeker", Icon = "TrophySeeker", Price = 250f, Stage = 2, Cooldown = 150f },
new Kind { Id = "soldier", Display = "Soldier", Source = "SeekerBrute", Icon = "TrophySeekerBrute", Price = 500f, Stage = 3, Cooldown = 300f },
new Kind { Id = "gjall", Display = "Gjall", Source = "Gjall", Icon = "TrophyGjall", Price = 1000f, Stage = 4, Cooldown = 600f },
};
private static int CapOf(string id)
{
switch (id)
{
case "brood": return SvermConfigManagement.Brood;
case "seeker": return SvermConfigManagement.Seeker;
case "soldier": return SvermConfigManagement.Soldier;
case "gjall": return SvermConfigManagement.Gjall;
default: return 0;
}
}
// ─── Registration ────────────────────────────────────────────────────
public static void Register()
{
foreach (Kind kind in Roster) RegisterOne(kind);
}
/// <summary>
/// One troop prefab: the vanilla creature, tamed at spawn, leashed, healing, worth nothing dead.
///
/// The drop table goes for the reason it always goes here - a troop that dropped seeker parts
/// would turn the colony into a trophy farm, and the biomass would be paying for itself.
/// </summary>
private static void RegisterOne(Kind kind)
{
GameObject source = PrefabManager.Cache.GetPrefab<GameObject>(kind.Source);
if (source == null)
{
Jotunn.Logger.LogWarning($"[Sverm] No '{kind.Source}' to build the {kind.Display} from; " +
"that rung of the roster is missing.");
return;
}
GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(kind.PrefabName, source);
if (prefab == null) return;
BaseAI ai = prefab.GetComponent<BaseAI>();
if (ai != null) ai.m_randomMoveRange = SvermConfig.TroopLeashRange;
foreach (CharacterDrop drops in prefab.GetComponentsInChildren<CharacterDrop>(true))
{
if (drops != null) Object.DestroyImmediate(drops);
}
RaisedThrall thrall = prefab.AddComponent<RaisedThrall>();
thrall.m_kind = kind.PrefabName;
thrall.m_commandingRace = SvermConfig.RaceId;
thrall.m_maxFollowers = -1; // the cap is the colony's, counted at the nest, not per player
thrall.m_witherSeconds = SvermConfig.TroopWitherSeconds;
thrall.m_homeCheckRange = SvermConfig.TroopHomeCheckRange;
thrall.m_refusalMessage = "It does not smell your colony on you.";
// Section 11.2, reused whole: ten seconds untouched, then two percent a second. Healing
// and not respawning - a dead troop is dead, and the egg it cost is already back.
prefab.AddComponent<SkeletonSentryBehaviour>();
PrefabManager.Instance.AddPrefab(prefab);
Jotunn.Logger.LogInfo($"[Sverm] Registered '{kind.PrefabName}' for the {kind.Display}.");
}
// ─── Counting and hatching ───────────────────────────────────────────
/// <summary>
/// How many of this kind this nest has alive.
///
/// Counted off the thralls bound to the nest, which is the same answer every other station in
/// the mod gives - and carries the same honest limit: it can only see creatures that are
/// loaded. A troop in an unloaded zone is not counted, so a cap can be briefly exceeded by
/// hatching a replacement for something that is still alive far away.
/// </summary>
public static int CountAlive(SvermHiveBehaviour hive, Kind kind)
{
if (hive == null || kind == null) return 0;
int count = 0;
foreach (RaisedThrall thrall in RaisedThrall.BoundTo(hive.transform.position))
{
if (thrall != null && thrall.Kind == kind.PrefabName) count++;
}
return count;
}
/// <summary>
/// Puts one on the ground beside the nest, bound to it and born at whatever star the colony
/// has bought.
/// </summary>
public static bool Hatch(SvermHiveBehaviour hive, Kind kind)
{
if (hive == null || kind == null) return false;
GameObject prefab = ZNetScene.instance != null ? ZNetScene.instance.GetPrefab(kind.PrefabName) : null;
if (prefab == null)
{
Jotunn.Logger.LogWarning($"[Sverm] No '{kind.PrefabName}' in ZNetScene; the {kind.Display} " +
"could not be hatched.");
return false;
}
Vector3 offset = Random.insideUnitSphere * 2f;
offset.y = 0f;
Vector3 where = hive.transform.position + offset + Vector3.up * 0.5f;
GameObject spawned = Object.Instantiate(prefab, where, Quaternion.Euler(0f, Random.Range(0, 360), 0f));
if (spawned == null) return false;
// The stars, and this is the ONLY thing the two star upgrades do: they are read here, at
// birth, so everything bought before them stays as it was born. Section 14's "valgono su
// tutto quello che nasce DOPO l'acquisto", enforced by the fact that nothing goes back
// and re-levels anyone.
Character character = spawned.GetComponent<Character>();
if (character != null)
{
int stars = SvermBroodStars.Of(hive.transform);
if (stars > 0) character.SetLevel(1 + stars);
}
RaisedThrall thrall = spawned.GetComponent<RaisedThrall>();
if (thrall != null) thrall.Bind(hive.transform.position);
return true;
}
}
/// <summary>
/// The brood eggs: the slot half of the price, section 10.2.
///
/// One every twenty seconds up to five plus the stage, and it is worked out from the WORLD CLOCK
/// rather than ticked - the same trick the digestion uses. A nest nobody is standing next to
/// still fills its clutch, and there is no timer to lose when a zone unloads.
/// </summary>
public static class SvermBroodEggs
{
private const string EggKey = "RacesOfValheim_SvermEggs";
private const string ClockKey = "RacesOfValheim_SvermEggAt";
public static int Cap(Transform nest)
{
return SvermConfig.EggCapBase + SvermHiveStage.Of(nest);
}
/// <summary>What the clutch holds right now, without writing anything.</summary>
public static int Count(Transform nest)
{
ZNetView nview = View(nest);
if (nview == null) return 0;
ZDO zdo = nview.GetZDO();
int stored = zdo.GetInt(EggKey, 0);
long clock = zdo.GetLong(ClockKey, 0L);
// A clutch that has never been settled has no elapsed time to claim. Reading a missing
// clock as zero would hand a brand new nest every egg since the world began.
if (clock <= 0L) return Mathf.Clamp(stored, 0, Cap(nest));
long elapsed = WorldSecond() - clock;
int laid = elapsed > 0L ? (int)(elapsed / SvermConfig.EggInterval) : 0;
return Mathf.Clamp(stored + laid, 0, Cap(nest));
}
/// <summary>
/// Writes down what time has laid and restarts the clock. The owner calls this on a timer so
/// the number the other clients read is never far behind.
/// </summary>
public static void Settle(Transform nest)
{
ZNetView nview = View(nest);
if (nview == null || !nview.IsOwner()) return;
ZDO zdo = nview.GetZDO();
int now = Count(nest);
zdo.Set(EggKey, now);
zdo.Set(ClockKey, WorldSecond());
}
/// <summary>Takes eggs out of the clutch. All or nothing.</summary>
public static bool Take(Transform nest, int howMany)
{
ZNetView nview = View(nest);
if (nview == null) return false;
int have = Count(nest);
if (have < howMany) return false;
if (!nview.IsOwner()) nview.ClaimOwnership();
nview.GetZDO().Set(EggKey, have - howMany);
nview.GetZDO().Set(ClockKey, WorldSecond());
return true;
}
private static ZNetView View(Transform nest)
{
ZNetView nview = nest != null ? nest.GetComponent<ZNetView>() : null;
return nview != null && nview.IsValid() ? nview : null;
}
private static long WorldSecond()
{
return ZNet.instance != null ? (long)ZNet.instance.GetTimeSeconds() : 0L;
}
}
/// <summary>
/// Surrenal Glands and Hyperplasia: what star the colony's troops are born at.
///
/// One number on the nest, 0 to 2, and it is read at the moment a troop is hatched and never
/// again. Everything already walking around keeps the stars it was born with, which is the
/// document's own rule and also the only version that does not need to find and re-level a
/// garrison spread over half the map.
/// </summary>
public static class SvermBroodStars
{
private const string StarKey = "RacesOfValheim_SvermStars";
public static int Of(Transform nest)
{
ZNetView nview = nest != null ? nest.GetComponent<ZNetView>() : null;
if (nview == null || !nview.IsValid()) return 0;
return Mathf.Clamp(nview.GetZDO().GetInt(StarKey, 0), 0, 2);
}
public static void Set(Transform nest, int stars)
{
ZNetView nview = nest != null ? nest.GetComponent<ZNetView>() : null;
if (nview == null || !nview.IsValid()) return;
if (!nview.IsOwner()) nview.ClaimOwnership();
nview.GetZDO().Set(StarKey, Mathf.Clamp(stars, 0, 2));
}
}
}

View file

@ -0,0 +1,133 @@
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The carapace: chest, legs and helmet, permanently, at every tier.
///
/// WHAT IT IS WORTH IS NOT WRITTEN DOWN. Each tier names a vanilla set in SvermConfig, and the
/// armour value is that set's three pieces read off ObjectDB and priced at quality 4. The race
/// therefore tracks vanilla's own balance forever: if a game patch buffs iron, the Sverm's
/// third tier is buffed with it, and nobody has to remember this file exists.
///
/// The lookup is cached per state and not per frame on purpose - GetBodyArmor runs from the
/// HUD and from every damage calculation, and ObjectDB.GetItemPrefab is a dictionary hit plus
/// a GetComponent on each of three prefabs.
///
/// Resolution is deferred rather than done at startup: ObjectDB is not populated when the
/// plugin wakes, so the first caller inside a world is what fills the cache. A missing prefab
/// contributes zero and logs once, so a renamed vanilla item costs a warning and a soft tier
/// rather than a null-reference in the damage path.
/// </summary>
public static class SvermCarapace
{
private static readonly float[] armorCache = new float[BossProgressionManager.MaxState + 1];
private static readonly bool[] armorCached = new bool[BossProgressionManager.MaxState + 1];
private static float eitrRegenReference = -1f;
/// <summary>
/// Total armour the carapace is worth at this tier: the three reference pieces at quality
/// 4, plus the hand-picked Fader bonus, which is the one number in the race that is chosen
/// rather than derived - there is no biome after the Ashlands to read a set from.
/// </summary>
public static float GetArmor(int state)
{
state = Mathf.Clamp(state, BossProgressionManager.MinState, BossProgressionManager.MaxState);
if (armorCached[state]) return armorCache[state];
if (ObjectDB.instance == null) return 0f; // too early; do not poison the cache
float total = 0f;
string[] set = SvermConfig.ArmorReferenceSets[state];
if (set != null)
{
foreach (string prefabName in set)
{
total += ArmorOf(prefabName);
}
}
if (state >= SvermConfig.AnnealedChitinState) total += SvermConfig.FaderArmorBonus;
armorCache[state] = total;
armorCached[state] = true;
Jotunn.Logger.LogInfo($"[Sverm] Carapace tier {state} priced at {total:0.#} armour " +
$"from {(set == null ? "nothing" : string.Join(" + ", set))} at quality " +
$"{SvermConfig.ArmorReferenceQuality}.");
return total;
}
/// <summary>Armour of one vanilla piece at the reference quality, or 0 with a warning.</summary>
private static float ArmorOf(string prefabName)
{
GameObject prefab = ObjectDB.instance.GetItemPrefab(prefabName);
if (prefab == null)
{
Jotunn.Logger.LogWarning($"[Sverm] No item '{prefabName}' to price the carapace from; " +
"it contributes nothing to this tier.");
return 0f;
}
ItemDrop drop = prefab.GetComponent<ItemDrop>();
if (drop == null || drop.m_itemData == null || drop.m_itemData.m_shared == null) return 0f;
// Valheim's own formula: armour + (quality - 1) * armourPerLevel.
return drop.m_itemData.m_shared.m_armor +
(SvermConfig.ArmorReferenceQuality - 1) * drop.m_itemData.m_shared.m_armorPerLevel;
}
/// <summary>
/// Eitr regeneration the carapace hands back, from Eitr Sacs on.
///
/// The eitr-weave set gives REGENERATION, not maximum eitr - the maximum comes from food,
/// which the Sverm eats like anyone else. So sealing the armour slots never blocked magic;
/// it only slowed the recovery, and this gives back a fraction of it. Deliberately a
/// fraction: eitr-weave is light armour and pays for its regeneration in defence, and a
/// Sverm carrying a biome set at quality 4 AND the full regeneration would simply be a
/// better mage than a mage.
/// </summary>
public static float GetEitrRegenBonus(int state)
{
if (state < SvermConfig.EitrSacsState) return 0f;
if (ObjectDB.instance == null) return 0f;
if (eitrRegenReference < 0f)
{
float total = 0f;
foreach (string prefabName in SvermConfig.EitrReferenceSet)
{
GameObject prefab = ObjectDB.instance.GetItemPrefab(prefabName);
ItemDrop drop = prefab != null ? prefab.GetComponent<ItemDrop>() : null;
if (drop != null && drop.m_itemData != null && drop.m_itemData.m_shared != null)
{
total += drop.m_itemData.m_shared.m_eitrRegenModifier;
}
}
eitrRegenReference = total;
Jotunn.Logger.LogInfo($"[Sverm] Eitr Sacs reference: eitr-weave set regenerates {total:0.##}, " +
$"carapace returns {SvermConfig.EitrRegenFraction:P0} of it.");
}
return eitrRegenReference * SvermConfig.EitrRegenFraction;
}
/// <summary>True when this slot is taken by the carapace and cannot hold anything else.</summary>
public static bool IsSealedSlot(ItemDrop.ItemData.ItemType type)
{
foreach (ItemDrop.ItemData.ItemType sealedType in SvermConfig.SealedSlots)
{
if (sealedType == type) return true;
}
return false;
}
/// <summary>The tint the carapace, the helmet and the claws all share at this tier.</summary>
public static Color GetTint(int state)
{
state = Mathf.Clamp(state, BossProgressionManager.MinState, BossProgressionManager.MaxState);
return SvermConfig.CarapaceTintByState[state];
}
}
}

View file

@ -0,0 +1,283 @@
using System.Collections.Generic;
using HarmonyLib;
using Jotunn.Managers;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The Maulclaws as a REAL equipped weapon, sitting in the inventory in plain sight and
/// refusing to be moved.
///
/// WHY THIS REPLACED THE COSMETIC VERSION. Bolting a model to the hand bones worked, but the
/// carapace beside it did not: the game rebuilds equipment visuals from what is ACTUALLY in
/// the slots, so every unequip wiped the lot and something had to put it back, one frame late
/// and visibly. A real item in a real slot removes the whole class of problem - there is
/// nothing to put back, because nothing was ever faked.
///
/// The trade, accepted deliberately: a real weapon occupies the right hand, so drawing a sword
/// puts the claws away. Three rules make that read as intended rather than as a bug:
///
/// 1. sheathe anything else and the claws come straight back (UnequipItem postfix);
/// 2. the holster key cannot put the claws away - a Sverm is never empty-handed
/// (HideHandItems prefix);
/// 3. the claws cannot be dragged, moved or dropped (SetupDragItem prefix, quest-item flag).
///
/// VISIBLE, NOT HIDDEN, and that is the second design this file has had. The first reserved
/// the rightmost column and switched its slots off in the inventory window - which meant
/// patching InventoryGrid.UpdateGui, a method that runs for every chest and every grid in the
/// game, to hide something in exactly one of them. It also cost the player four slots.
/// Showing the claws and refusing to let them move is less code, touches no UI, and tells the
/// player something true: they are carrying them, and they always will be.
///
/// The last resort behind all three rules is that Maintain re-issues the claws whenever they
/// are missing. However they get lost - a tombstone, a mod, a bug in this file - they are back
/// within half a second.
/// </summary>
public static class SvermClawSlot
{
public const string ItemName = "SvermMaulclaws";
public const string ItemDisplayName = "Vilebone Maulclaws";
/// <summary>Row in the reserved column the claws sit on. The other three await the carapace.</summary>
private const int ClawRow = 0;
private static bool registered;
// ─── Registration ────────────────────────────────────────────────────
/// <summary>
/// Clones whichever of the four candidate prefabs this build actually has. Deferred until
/// ObjectDB is up, so it is driven from the first player spawn rather than from Awake.
/// </summary>
public static void EnsureRegistered()
{
if (registered) return;
if (ObjectDB.instance != null && ObjectDB.instance.GetItemPrefab(ItemName) != null)
{
registered = true;
return;
}
GameObject source = SvermClaws.GetPrefab();
if (source == null) return; // already logged once by the resolver
GameObject clone = PrefabManager.Instance.CreateClonedPrefab(ItemName, source);
if (clone == null)
{
Jotunn.Logger.LogWarning($"[Sverm] Could not clone '{source.name}'; the claws stay unregistered.");
return;
}
ItemDrop drop = clone.GetComponent<ItemDrop>();
if (drop != null && drop.m_itemData != null && drop.m_itemData.m_shared != null)
{
ItemDrop.ItemData.SharedData shared = drop.m_itemData.m_shared;
shared.m_name = ItemDisplayName;
shared.m_description = "Grown, not forged. They do not come off.";
// Quest item: Valheim refuses to drop, trade or stack these. It is the cheapest
// honest way to say "this is part of your body" without a patch per verb.
shared.m_questItem = true;
shared.m_teleportable = true;
shared.m_weight = 0f;
shared.m_maxQuality = 1;
// No recipe and no station: this item is never crafted, only issued.
}
ItemManager.Instance.AddItem(new Jotunn.Entities.CustomItem(clone, fixReference: false));
registered = true;
Jotunn.Logger.LogInfo($"[Sverm] Registered '{ItemName}' from '{source.name}'.");
}
// ─── Issue and re-equip ──────────────────────────────────────────────
/// <summary>
/// Makes sure the player owns exactly one pair and is holding them whenever both hands are
/// free. Safe to call on a timer: every step checks first.
/// </summary>
/// <summary>
/// Guards against re-entry, and it is not belt-and-braces - it is the fix for a crash.
///
/// Maintain equips the claws. Humanoid.EquipItem unequips the right hand first, which
/// fires the UnequipItem postfix, which calls Maintain, which equips the claws... Mono
/// answers an unbounded recursion by killing the process outright, with no exception and a
/// log file that ends mid-word. Switching race was enough to trigger it every time.
///
/// The null check in the postfix closes the specific door; this closes the corridor.
/// </summary>
private static bool maintaining;
public static void Maintain(Player player)
{
if (maintaining) return;
if (player == null || player != Player.m_localPlayer) return;
if (!SvermVisuals.IsSvermPlayer(player)) return;
maintaining = true;
try { MaintainInner(player); }
finally { maintaining = false; }
}
private static void MaintainInner(Player player)
{
EnsureRegistered();
Inventory inventory = player.GetInventory();
if (inventory == null) return;
ItemDrop.ItemData claws = Find(inventory);
if (claws == null)
{
GameObject prefab = ObjectDB.instance != null ? ObjectDB.instance.GetItemPrefab(ItemName) : null;
if (prefab == null) return;
// The GameObject overload, deliberately: it is the one that is public in the
// shipped assembly. The overloads that take a grid position are private there, and
// the project compiles against the shipped assembly rather than the publicized
// copy - so anything else would build on this machine and not on a clean one.
if (!inventory.AddItem(prefab, 1)) return;
claws = Find(inventory);
if (claws == null) return;
// Tidied into the bottom-right corner IF that corner is free, and left wherever
// the inventory put them otherwise. Nothing of the player's is ever displaced to
// make room: an item that cannot be moved has no business shoving one that can.
Vector2i corner = new Vector2i(inventory.GetWidth() - 1, inventory.GetHeight() - 1);
if (corner.x >= 0 && ItemAt(inventory, corner.x, corner.y) == null)
{
claws.m_gridPos = corner;
}
Jotunn.Logger.LogInfo("[Sverm] Issued the Maulclaws.");
}
// Empty-handed means clawed. Anything else in the right hand wins until it is put
// away, which is the whole compromise.
ItemDrop.ItemData held = Traverse.Create((Humanoid)player).Field<ItemDrop.ItemData>("m_rightItem").Value;
if (held == null && !player.InAttack() && !player.IsDead())
{
player.EquipItem(claws, false);
}
}
/// <summary>
/// What is sitting at this grid position, read from the items themselves.
///
/// Inventory.GetItemAt is private in the shipped assembly, and every item already carries
/// its own m_gridPos, so a scan over GetAllItems answers the same question with nothing
/// but public members. An inventory holds a few dozen items; this is not a hot path.
/// </summary>
private static ItemDrop.ItemData ItemAt(Inventory inventory, int x, int y)
{
foreach (ItemDrop.ItemData item in inventory.GetAllItems())
{
if (item != null && item.m_gridPos.x == x && item.m_gridPos.y == y) return item;
}
return null;
}
public static ItemDrop.ItemData Find(Inventory inventory)
{
if (inventory == null) return null;
foreach (ItemDrop.ItemData item in inventory.GetAllItems())
{
if (item != null && item.m_dropPrefab != null && item.m_dropPrefab.name == ItemName) return item;
if (item != null && item.m_shared != null && item.m_shared.m_name == ItemDisplayName) return item;
}
return null;
}
public static bool IsClaws(ItemDrop.ItemData item)
{
if (item == null || item.m_shared == null) return false;
if (item.m_dropPrefab != null && item.m_dropPrefab.name == ItemName) return true;
return item.m_shared.m_name == ItemDisplayName;
}
}
// ─── Patches ─────────────────────────────────────────────────────────────
/// <summary>
/// Put anything else away and the claws come straight back.
///
/// A postfix rather than doing it inside UnequipItem's own flow: the game is mid-way through
/// tearing down the old item's visuals when the prefix would run, and equipping there leaves
/// the new item without a model.
/// </summary>
[HarmonyPatch(typeof(Humanoid), nameof(Humanoid.UnequipItem))]
public static class Sverm_UnequipItem_Patch
{
public static void Postfix(Humanoid __instance, ItemDrop.ItemData item)
{
// NULL IS THE IMPORTANT CASE. Humanoid.EquipItem calls UnequipItem(m_rightItem) before
// putting a weapon in the hand, and an empty hand means that argument is null. Without
// this line the postfix treats "nothing was unequipped" as "something was unequipped",
// calls Maintain, which equips the claws, which unequips null again - and Mono kills
// the process on the recursion, instantly and silently.
if (item == null) return;
Player player = __instance as Player;
if (player == null || player != Player.m_localPlayer) return;
if (!SvermVisuals.IsSvermPlayer(player)) return;
if (SvermClawSlot.IsClaws(item)) return; // do not re-equip what was just taken off
SvermClawSlot.Maintain(player);
}
}
/// <summary>
/// The holster key cannot put the claws away.
///
/// HideHandItems is what R calls. Refused only while the claws ARE the thing in hand: holding
/// a sword, R sheathes the sword normally, and the unequip postfix above hands the claws back
/// on the same action. So the key keeps working and simply never leaves a Sverm empty-handed.
/// </summary>
[HarmonyPatch(typeof(Humanoid), nameof(Humanoid.HideHandItems))]
public static class Sverm_HideHandItems_Patch
{
public static bool Prefix(Humanoid __instance)
{
Player player = __instance as Player;
if (player == null || player != Player.m_localPlayer) return true;
if (!SvermVisuals.IsSvermPlayer(player)) return true;
ItemDrop.ItemData held = Traverse.Create(__instance).Field<ItemDrop.ItemData>("m_rightItem").Value;
return !SvermClawSlot.IsClaws(held);
}
}
/// <summary>
/// The claws cannot be picked up with the mouse.
///
/// SetupDragItem is the single door every manual move goes through - within the inventory, out
/// to a chest, onto the ground, into a crafting slot. Refusing here closes all of them with
/// one prefix, instead of one patch per destination, and leaves every OTHER item's handling
/// completely untouched.
///
/// It replaces an earlier design that hid the rightmost column outright. That one had to patch
/// InventoryGrid.UpdateGui - a method that runs for every chest and every grid in the game -
/// in order to change exactly one of them, and it cost the player four slots. The claws are
/// visible now, which is also more honest: they are part of the character, and the character
/// can see them.
/// </summary>
[HarmonyPatch(typeof(InventoryGui), "SetupDragItem")]
public static class Sverm_SetupDragItem_Patch
{
public static bool Prefix(ItemDrop.ItemData item)
{
if (!SvermClawSlot.IsClaws(item)) return true;
if (Player.m_localPlayer != null)
{
Player.m_localPlayer.Message(MessageHud.MessageType.Center, "They are part of your hands.");
}
return false;
}
}
}

View file

@ -0,0 +1,158 @@
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The Vilebone Maulclaws: attached to the hands for good, and never equipped.
///
/// WHY NOT A REAL WEAPON. Valheim has one weapon slot. A claw that is genuinely equipped locks
/// the Sverm out of every sword, bow and staff in the game for the whole run, which is not
/// what "permanent claws" is supposed to mean. So the feature is split:
///
/// the MODEL is cosmetic - two copies bolted to the hand bones, visible always, including
/// while holding a two-hander (SvermVisuals does the mounting);
/// the DAMAGE is unarmed - a bare-handed Sverm punches for the claws of its tier. Pick up a
/// sword and you swing the sword; the claws are still on your hands.
///
/// So the race is never disarmed and never restricted, and the two halves can be tuned apart.
///
/// THE PREFAB NAME IS NOT TRUSTED. The install's manifest carries four near-identical names -
/// FistBjornUndeadClaw, FistBjornClawUndead, FistUnbjornClaw, FistBjornClaw - and only some of
/// them have a recipe, which means the item and the mesh may not share a name. Guessing wrong
/// costs two empty hands and no error at all, so the resolve walks the list and logs the
/// winner. A warning beats a silent nothing.
/// </summary>
public static class SvermClaws
{
private static GameObject resolved;
private static bool resolveAttempted;
private static HitData.DamageTypes referenceDamage;
private static bool referenceRead;
/// <summary>
/// The claw prefab, or null. Resolution happens once, inside a world, because ObjectDB is
/// empty when the plugin wakes.
/// </summary>
public static GameObject GetPrefab()
{
if (resolved != null) return resolved;
foreach (string name in SvermConfig.ClawPrefabFallbacks)
{
// PrefabManager's cache first, ObjectDB second, and that order is what lets this
// run at OnVanillaPrefabsAvailable - which is the only moment Jotunn will accept a
// new item. ObjectDB is still empty then.
GameObject candidate = Jotunn.Managers.PrefabManager.Cache.GetPrefab<GameObject>(name);
if (candidate == null && ObjectDB.instance != null)
{
candidate = ObjectDB.instance.GetItemPrefab(name);
}
if (candidate != null)
{
resolved = candidate;
Jotunn.Logger.LogInfo($"[Sverm] Maulclaws resolved to '{name}'.");
return resolved;
}
}
// Warned once, but NOT latched: a later call may run when more of the game is loaded,
// and a race with no hands is worth retrying for.
if (!resolveAttempted)
{
resolveAttempted = true;
Jotunn.Logger.LogWarning("[Sverm] None of " + string.Join(", ", SvermConfig.ClawPrefabFallbacks) +
" resolved yet; retrying as the game loads.");
}
return null;
}
/// <summary>
/// The vanilla weapon's damage at quality 4, read once. This is the ceiling the tier
/// percentages are a fraction of, and state 7 is 100% of it - the real Maulclaws.
///
/// Public because it is the shared yardstick: the Aswid's and the Fenrir's claws
/// (RaceClawSet) are balanced against this same figure rather than against the models they
/// happen to wear, so all three races hit for the same numbers at the same tier.
/// </summary>
public static HitData.DamageTypes GetReferenceDamage()
{
if (referenceRead) return referenceDamage;
GameObject prefab = GetPrefab();
ItemDrop drop = prefab != null ? prefab.GetComponent<ItemDrop>() : null;
if (drop == null || drop.m_itemData == null || drop.m_itemData.m_shared == null)
{
return referenceDamage; // all zeroes; referenceRead stays false so a later world can retry
}
ItemDrop.ItemData.SharedData shared = drop.m_itemData.m_shared;
HitData.DamageTypes at1 = shared.m_damages;
HitData.DamageTypes perLevel = shared.m_damagesPerLevel;
int steps = SvermConfig.ArmorReferenceQuality - 1;
referenceDamage = new HitData.DamageTypes
{
m_blunt = at1.m_blunt + perLevel.m_blunt * steps,
m_slash = at1.m_slash + perLevel.m_slash * steps,
m_pierce = at1.m_pierce + perLevel.m_pierce * steps,
m_chop = at1.m_chop + perLevel.m_chop * steps,
m_pickaxe = at1.m_pickaxe + perLevel.m_pickaxe * steps,
m_fire = at1.m_fire + perLevel.m_fire * steps,
m_frost = at1.m_frost + perLevel.m_frost * steps,
m_lightning = at1.m_lightning + perLevel.m_lightning * steps,
m_poison = at1.m_poison + perLevel.m_poison * steps,
m_spirit = at1.m_spirit + perLevel.m_spirit * steps,
};
referenceRead = true;
Jotunn.Logger.LogInfo($"[Sverm] Maulclaws at quality {SvermConfig.ArmorReferenceQuality}: " +
$"slash {referenceDamage.m_slash:0.#}, pierce {referenceDamage.m_pierce:0.#}, " +
$"blunt {referenceDamage.m_blunt:0.#}.");
return referenceDamage;
}
/// <summary>Fraction of the reference damage the bare hands hit for at this tier.</summary>
public static float GetDamagePercent(int state)
{
state = Mathf.Clamp(state, BossProgressionManager.MinState, BossProgressionManager.MaxState);
return SvermConfig.ClawDamagePercentByState[state];
}
/// <summary>
/// Rewrites a bare-handed blow into a claw blow. Called from the Character.Damage prefix,
/// and only when the attacker really is punching: an unarmed hit in Valheim carries a tiny
/// blunt figure, which is REPLACED here rather than added to, so the tier percentage means
/// what it says.
/// </summary>
public static void ApplyToUnarmedHit(HitData hit, int state)
{
if (hit == null) return;
HitData.DamageTypes reference = GetReferenceDamage();
float percent = GetDamagePercent(state);
if (percent <= 0f) return;
float slash = reference.m_slash * percent;
float pierce = reference.m_pierce * percent;
float blunt = reference.m_blunt * percent;
// Nothing to give: the reference item did not resolve. Leave vanilla's fist alone
// rather than zeroing the player's only attack.
if (slash + pierce + blunt <= 0f) return;
hit.m_damage.m_slash = slash;
hit.m_damage.m_pierce = pierce;
hit.m_damage.m_blunt = blunt;
// Annealed Chitin lights the claws too. A fraction of the physical total rather than a
// flat number, so it scales with whatever the reference weapon turns out to be worth.
if (state >= SvermConfig.AnnealedChitinState)
{
hit.m_damage.m_fire += (slash + pierce + blunt) * SvermConfig.ClawFireFraction;
}
}
}
}

View file

@ -0,0 +1,535 @@
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// Every tunable number the Sverm uses, in one place.
///
/// Same contract as DvergarConfig: nothing here is baked into the logic. SvermProgression reads
/// these to build its per-tier rules and the patches read the rules, never a literal. Retuning
/// the race means editing this file only.
///
/// Two of these numbers are NOT numbers but prefab names, and that is deliberate. The carapace
/// is worth "whatever the vanilla set of that biome is worth", and the claws hit for "whatever
/// the vanilla weapon hits for" - both read off ObjectDB at runtime rather than transcribed
/// here. A game patch that rebalances iron armour rebalances the Sverm with it, and nobody has
/// to remember that this file existed.
/// </summary>
public static class SvermConfig
{
// ─── Identity ────────────────────────────────────────────────────────
// Stored in m_customData["Race"] and on the ZDO, so renaming it after players have chosen
// the race would orphan their characters. See DvergarRace.MigrateLegacyRaceId for what
// that costs to undo.
public const string RaceId = "Sverm";
public const string StatsSE = "SE_SvermStats";
public const string StingerSE = "SE_SvermStingerForm";
public const string StingerCdSE = "SE_SvermStingerCooldown";
// Mirrors the ZDO key layout the other races use, so remote clients can work out the tier
// without having the local player's progression state.
public const string StateZdoKey = "RacesOfValheim_SvermState";
// ─── Damage taken ────────────────────────────────────────────────────
// Chitin burns and chitin cracks. Expressed as a plain multiplier rather than
// HitData.DamageModifier.Weak because that enum is discrete - Weak is a flat +50% and
// there is no rung at +40%. Applied in a Character.Damage prefix, the way Aswid, Draugh
// and Dvergar already scale damage.
public static readonly float BluntWeakness = 0.40f;
public static readonly float FireWeakness = 0.40f;
// Annealed Chitin: at Fader the weakness inverts. 0.40 means fire lands at 60% of its
// value, i.e. roughly one rung of DamageModifier.Resistant, arrived at by the same knob
// that hurt for eight tiers.
public const int AnnealedChitinState = 8;
public static readonly float FireResistanceAtFader = 0.40f;
// ─── Chitin Plating: the carapace ────────────────────────────────────
// Reference sets, one per progression state. The carapace is worth the SUM of these three
// pieces AT QUALITY 4, read from ObjectDB. Every name here was verified against the
// install's own SoftRef manifest, so a null means the game changed, not that we guessed.
//
// Index 0 is unused: progression states run 1..8 and indexing by state is worth one wasted
// slot to avoid an off-by-one in every caller.
public static readonly string[][] ArmorReferenceSets =
{
null, // unused
new[] { "ArmorLeatherChest", "ArmorLeatherLegs", "HelmetLeather" }, // 1
new[] { "ArmorBronzeChest", "ArmorBronzeLegs", "HelmetBronze" }, // 2 Eikthyr
new[] { "ArmorIronChest", "ArmorIronLegs", "HelmetIron" }, // 3 Elder
new[] { "ArmorWolfChest", "ArmorWolfLegs", "HelmetDrake" }, // 4 Bonemass
new[] { "ArmorPaddedCuirass", "ArmorPaddedGreaves", "HelmetPadded" }, // 5 Moder
new[] { "ArmorCarapaceChest", "ArmorCarapaceLegs", "HelmetCarapace" }, // 6 Yagluth
new[] { "ArmorFlametalChest", "ArmorFlametalLegs", "HelmetFlametal" }, // 7 Queen
new[] { "ArmorFlametalChest", "ArmorFlametalLegs", "HelmetFlametal" }, // 8 Fader
};
/// <summary>Quality the reference set is priced at. Valheim: armor + (q-1) * armorPerLevel.</summary>
public const int ArmorReferenceQuality = 4;
/// <summary>
/// Added on top at Fader only. There is no biome after the Ashlands to read a set from, so
/// state 8 is the one tier whose number is chosen rather than derived - and it is a flat
/// bonus rather than a multiplier precisely so it reads as "chosen" in the log.
/// </summary>
public static readonly float FaderArmorBonus = 10f;
/// <summary>Slots the carapace occupies and therefore forbids.</summary>
public static readonly ItemDrop.ItemData.ItemType[] SealedSlots =
{
ItemDrop.ItemData.ItemType.Chest,
ItemDrop.ItemData.ItemType.Legs,
ItemDrop.ItemData.ItemType.Helmet,
};
/// <summary>What the carapace LOOKS like, at every tier. The value changes, the shape does not.</summary>
public const string CarapaceChestVisual = "ArmorCarapaceChest";
public const string CarapaceLegsVisual = "ArmorCarapaceLegs";
public const string CarapaceHelmetVisual = "HelmetCarapace";
// ─── Vilebone Maulclaws ──────────────────────────────────────────────
// FOUR near-identical names exist in the manifest and only some carry a recipe, so the
// prefab is resolved by trying them in order and logging which one answered. A wrong guess
// here fails soft and silently - two empty hands - which is exactly the failure this
// chain exists to make loud.
public static readonly string[] ClawPrefabFallbacks =
{
"FistBjornUndeadClaw",
"FistBjornClawUndead",
"FistUnbjornClaw",
"FistBjornClaw",
};
/// <summary>Length in METRES from the back of the hand to the tip. ModelBorrow sizes in metres.</summary>
public static readonly float ClawLength = 0.22f;
/// <summary>
/// Fraction of the vanilla weapon's quality-4 damage the bare hands hit for, per state.
/// State 7 is the ceiling - the real Maulclaws - and state 8 adds fire on top rather than
/// going past it. Index 0 unused, as above.
/// </summary>
public static readonly float[] ClawDamagePercentByState =
{
0f, 0.35f, 0.45f, 0.55f, 0.70f, 0.85f, 0.95f, 1.00f, 1.00f
};
/// <summary>Fire added at Fader, as a fraction of the claws' physical total.</summary>
public static readonly float ClawFireFraction = 0.30f;
// ─── Insect Metabolism ───────────────────────────────────────────────
/// <summary>Raw meat is worth this much of its cooked counterpart.</summary>
public static readonly float RawMeatFraction = 0.70f;
/// <summary>Honey and royal jelly: bonus and duration both multiplied by this.</summary>
public static readonly float HoneyMultiplier = 2f;
/// <summary>Seeds become food from this state on (The Elder).</summary>
public const int SeedsEdibleState = 3;
// Royal jelly, made edible from scratch. These are the FINAL values, already doubled -
// they are not multiplied again by HoneyMultiplier.
public const string RoyalJellyPrefab = "RoyalJelly";
public static readonly float RoyalJellyHealth = 90f;
public static readonly float RoyalJellyStamina = 90f;
public static readonly float RoyalJellyEitr = 90f;
public static readonly float RoyalJellyDuration = 2400f;
public static readonly float RoyalJellyRegen = 5f;
// ─── Perk unlock states ──────────────────────────────────────────────
public const int MetabolicSurgeState = 2;
public const int VentralPouchesState = 2;
public const int GrindingMandiblesState = 3;
public const int SensoryAntennaeState = 3;
public const int VenomGlandsState = 4;
public const int AcidHemolymphState = 4;
public const int VestigialWingsState = 5;
public const int StingerMorphState = 6;
public const int EitrSacsState = 6;
public const int MajesticCarapaceState = 7;
public const int SurrenalGlandsState = 7;
public const int FullWingspanState = 7;
public const int CarapaceRegenState = 8;
// ─── Metabolic Surge (state 2) ───────────────────────────────────────
public static readonly float RunStaminaDiscount = 0.20f; // -20% on running
public static readonly float JumpStaminaDiscount = 0.20f;
public static readonly float JumpBonus = 0.15f; // +15% jump force
// ─── Ventral Pouches (state 2) ───────────────────────────────────────
public static readonly float CarryWeightBonus = 100f;
// ─── Sensory Antennae (state 3) ──────────────────────────────────────
// Passive and always on, so the radius is the only real brake on how many point lights can
// be alive at once. Raise it with that in mind.
public static readonly float AntennaeRadius = 30f;
public static readonly float AntennaeInterval = 2f;
public static readonly float AntennaeLightRange = 4f;
public static readonly float AntennaeLightIntensity = 1.4f;
// What each colour means, and the meaning is the whole feature: the Aswid's Auspex marks
// everything the same because it only asks "is something there". A chemical sense answers
// "what is it".
public static readonly Color AntennaeHostileColor = new Color(1f, 0.15f, 0.10f, 1f); // red
public static readonly Color AntennaePassiveColor = new Color(0.25f, 1f, 0.30f, 1f); // green
public static readonly Color AntennaeInvertebrateColor = new Color(1f, 0.90f, 0.20f, 1f); // yellow
public static readonly Color AntennaeKinColor = new Color(0.35f, 0.75f, 1f, 1f); // azure
// ─── Venom Glands (state 4) ──────────────────────────────────────────
/// <summary>Poison added to every blow, per state above the unlock.</summary>
public static readonly float VenomPerState = 6f;
// ─── Acid Hemolymph (state 4) ────────────────────────────────────────
/// <summary>Poison dealt back to whoever lands a melee blow, per state above the unlock.</summary>
public static readonly float HemolymphPerState = 5f;
public static readonly float HemolymphRange = 4f;
// ─── Dorsal Spines (state 5) / Full Crest (state 7) ──────────────────
// Wings were the first design and they lost on cost. Wing_gib turned out not to be a
// prefab at all - it is a child inside a death effect, reachable only by walking somebody
// else's hierarchy and hoping the parent list is right - and animated wings on a static
// mount never look like anything but a prop. A ribcage worn spine-up is STATIC by nature,
// it is a real prefab that resolves by name, and it reads as xenomorph spines rather than
// as a bird.
public const string SpinesPrefab = "UndeadBjornRibcage";
public static readonly float SpineSizeSmall = 0.45f; // metres, state 5-6
public static readonly float SpineSizeFull = 0.80f; // metres, state 7+
/// <summary>
/// Which bone they ride. Spine3 and ONLY Spine3 - no fallback chain.
///
/// The earlier version tried Spine2, then Spine1, then Spine, on the theory that a missing
/// bone should degrade rather than disappear. On this rig all three exist, so the fallback
/// never fired for the right reason and only ever meant "somewhere on the back, roughly" -
/// which is not good enough for a crest that was positioned by eye. One bone, or nothing.
/// </summary>
public const string SpineBoneName = "Spine3";
// Found in game with the crest on screen. A ribcage is authored lying around a body, so
// standing it up out of a back is a quarter turn on two axes - not something anybody was
// going to derive on paper.
public static readonly float SpineRotationX = 0f;
public static readonly float SpineRotationY = -90f;
public static readonly float SpineRotationZ = 90f;
/// <summary>
/// What holds a falling Sverm up: the Mistlands' own fireflies, swarming under the body.
///
/// Note the capital F in the middle. "Fireflies" resolves to nothing and fails silently,
/// which is the whole reason every prefab name in this race is checked against the game's
/// manifest before it is written down.
/// </summary>
public const string GlideMotesPrefab = "FireFlies";
// ─── Eitr Sacs (state 6) ─────────────────────────────────────────────
/// <summary>Fraction of the eitr-weave set's regeneration the carapace gives back.</summary>
public static readonly float EitrRegenFraction = 0.50f;
public static readonly string[] EitrReferenceSet = { "ArmorMageChest", "ArmorMageLegs", "HelmetMage" };
// ─── Surrenal Glands (state 7) ───────────────────────────────────────
public static readonly float BodyScaleAtQueen = 1.10f;
// ─── Carapace Regeneration (state 8) ─────────────────────────────────
public static readonly float CarapaceRegenPerSecond = 0.5f;
// ─── Stinger Morph (state 6) ─────────────────────────────────────────
public const string StingerCreature = "Deathsquito";
public static readonly float StingerDurationSeconds = 120f;
public static readonly float StingerCooldownSeconds = 480f;
/// <summary>
/// Multiplier on every point of damage taken while in form. 2.5 means a blow that the
/// carapace would shrug off very nearly ends you.
///
/// This is the entire cost of the ability and it has to be steep: in form you deal the
/// hardest single hit in the Plains and you can leave any fight by going straight up. The
/// balance is not the cooldown, it is that a single arrow answers you.
/// </summary>
public static readonly float StingerFragility = 2.5f;
// ─── The escort ──────────────────────────────────────────────────────
/// <summary>
/// Two deathsquitoes called up with the form, and they OUTLIVE it on purpose.
///
/// Three minutes against the form's two. The extra minute is the whole idea: the form ends
/// wherever it ends, usually in the air, and the Sverm comes back to being a slow armoured
/// thing halfway through a fall. The escort is what covers that minute. Then it dies too.
/// </summary>
public const int EscortCount = 2;
public static readonly float EscortLifetimeSeconds = 180f;
public static readonly float EscortSpawnSpread = 2.5f;
// ─── Transformation effects ──────────────────────────────────────────
// The Seeker's own spawn and death bursts, verified in the manifest. vfx_boar_death is the
// fallback because it is what the Aswid uses and is certain to exist.
public static readonly string[] MorphInEffects = { "fx_seeker_spawn", "vfx_boar_death" };
public static readonly string[] MorphOutEffects = { "fx_seeker_death", "vfx_boar_death" };
// ─── Palette ─────────────────────────────────────────────────────────
// Read off a Seeker Soldier. The exposed skin is almost black and matte: what makes the
// look is the CONTRAST against the amber plates, not the skin colour itself.
public static readonly Color SkinColor = Hex(0x24, 0x1B, 0x15);
public static readonly Color MembraneColor = Hex(0xB8, 0x5F, 0x5C);
/// <summary>
/// The tint ramp IS the visual progression. Same carapace silhouette at every tier, aged
/// by colour: pale washed sand, then full amber, then dark amber, then black with a red
/// burn at Fader. Zero new assets. Index 0 unused.
/// </summary>
/// <summary>
/// A YOUNG insect is not a small adult, and the ramp says so. The early tiers are violet -
/// the soft, pale, not-yet-hardened shell of something freshly moulted - and the amber of
/// the reference photograph is where the race ARRIVES rather than where it starts. The
/// last two tiers darken out of amber into near black, which is what gives Emberform's red
/// something to burn through.
///
/// Index 0 unused.
/// </summary>
public static readonly Color[] CarapaceTintByState =
{
Color.white,
Hex(0xB0, 0xA3, 0xC8), // 1 pale violet - newly moulted, soft
Hex(0x9B, 0x88, 0xB8), // 2
Hex(0x86, 0x70, 0x9F), // 3 violet, deepening
Hex(0x7C, 0x60, 0x79), // 4 mauve: the turn towards amber begins
Hex(0x8A, 0x62, 0x49), // 5
Hex(0x8B, 0x5E, 0x34), // 6 full amber - the colour of the photograph
Hex(0x4A, 0x32, 0x20), // 7 dark amber
Hex(0x14, 0x10, 0x0C), // 8 near black; Emberform adds the red
};
// ─── Emberform ───────────────────────────────────────────────────────
// The hue at full strength, dimmed by EmberGlowStrength below. Split in two for the same
// reason AswidVisuals splits its eye colour: the hue and the brightness are tuned against
// different things, and mixing them into one HDR value makes every adjustment a guess.
//
// The first version shipped this at (3.2, 0.30, 0.06) applied directly, and it came out
// blinding - which is the Aswid's lesson arriving late and at ten times the surface area.
// Two glowing spheres on a face can carry an HDR value past 3; a whole chest, both legs
// and a helmet cannot. Past the bloom threshold the extra brightness buys a bigger white
// area and LESS red, so the fix is downward, not sideways.
public static readonly Color EmberEmission = new Color(3.2f, 0.30f, 0.06f, 1f);
/// <summary>
/// How much of that hue actually reaches the material.
///
/// Tuned downward twice, in game, and the trend is the whole lesson: full HDR was blinding,
/// 0.25 was still too strong, and 0.0625 is where it stopped looking like a lamp. That puts
/// the red at 0.2 - well under the clip - which on a surface the size of a whole body is
/// plenty. Two glowing eyes and a glowing torso are not the same problem and do not take
/// the same number.
///
/// Live from the .cfg, because this is a number only an eye can settle.
/// </summary>
public static readonly float EmberGlowStrength = 0.0625f;
// Glowing eyes, same geometry as the Aswid's. Placement constants live in the head bone's
// own local space, which is why the state-7 +10% needs no special case: a child transform
// rides its parent's scale for free.
public static readonly Color EyeColor = new Color(3.4f, 0.12f, 0.08f, 1f);
public static readonly float EyeGlowStrength = 0.22f;
// ─── The colony (stub - see SvermHive when that half is written) ─────
/// <summary>Two nests per square mile. A square mile is 2.59 km2; the circle of equal area has r = 908 m.</summary>
public static readonly float HiveDensityRadius = 908f;
public const int HiveDensityMax = 2;
/// <summary>The Elder. Before that the Sverm is a body and nothing else.</summary>
public const int HiveUnlockState = 3;
// ─── Colony caps ─────────────────────────────────────────────────────
// The DEFAULTS. What is actually enforced comes from SvermConfigManagement, which binds
// these into the .cfg so a machine that cannot carry nineteen creatures can say so without
// a rebuild. Only the nest density stays out of reach - two per square mile is a rule
// about the world, not a comfort setting.
public const int CapBrood = 8;
public const int CapSeeker = 6;
public const int CapSoldier = 3;
public const int CapGjall = 2;
public const int CapBlisterTick = 10;
/// <summary>Two separate pools, nine workers alive at most. Farmers come from the infected
/// beehives, haulers from the nest after Bonemass, and neither can starve the other.</summary>
public const int CapFarmers = 6;
public const int CapHaulers = 3;
// ─── The aura and the beehives in it ─────────────────────────────────
public static readonly float HiveAuraRadius = 10f;
public const int HiveAuraBeehiveMax = 10;
/// <summary>Not every frame: it walks a sphere of colliders and nothing here is urgent.</summary>
public static readonly float HiveAuraSweepInterval = 5f;
/// <summary>How long a beehive must stand in the aura before the colony takes it.</summary>
public static readonly float BeehiveInfectionSeconds = 60f;
public static readonly float BeehiveSpeedMultiplier = 2f; // twice as fast
public static readonly float BeehiveCapacityMultiplier = 3f; // three times the honey
/// <summary>
/// Vanilla's own cap, written down because m_maxHoney is an instance field and by the time
/// we read it on a hive we may already have changed it. Multiplying what we find would
/// treble the trebled number on the next sweep.
/// </summary>
public const int BeehiveBaseMaxHoney = 4;
/// <summary>After Yagluth the colony makes royal jelly instead of honey.</summary>
public const int RoyalJellyHiveState = 6;
// The mark of a taken hive. SeekerEgg is a real prefab - unlike Wing_gib, which was not.
// The first pass shipped a 35 cm egg at 90 cm and nobody could see it: too small, and high
// enough above the hive's origin to float clear of the roof instead of sitting on it. Both
// numbers are in the .cfg now, because where a thing sits on another thing is decided by
// an eye and not by arithmetic.
public const string HiveEggPrefab = "SeekerEgg";
public static readonly float HiveEggSize = 0.55f; // metres
public static readonly float HiveEggHeight = 0.45f; // above the hive's own origin
/// <summary>The nest's own size. 0.75 is the quarter off that the first placement asked for.</summary>
public static readonly float HiveScale = 0.75f;
// ─── What the colony looks like from outside ─────────────────────────
// How big the swarm of flies and the green reek are on each thing that wears them. Metres,
// near enough - the holder is scaled by these and the particles ride it. Both are first
// guesses and both are in the .cfg, because nobody can settle a cloud of flies on paper.
public static readonly float NestVfxScale = 1.5f;
public static readonly float BeehiveVfxScale = 0.5f;
// The two hives bolted to the nest: the stomach at its foot, the market up top. Sizes are
// in metres and heights are metres up the trunk from the ground. Both sizes are also the
// width of the sphere you press, so a mouth that is too small is a mouth that is hard to
// point at as well as hard to see - the stomach is the bigger of the two because it is the
// one you use every time you come home.
public static readonly float StomachSize = 1.4f;
public static readonly float StomachHeight = 0f;
/// <summary>
/// The Hive Market bench's own scale. It is a BUILDING now, not a mouth on the nest.
///
/// Two heights were tried while it still hung on the trunk and neither could work: the
/// measured crown put it eight metres over the player's head, and the number that replaced
/// it lost to the zero already written in everyone's .cfg, which dropped it inside the
/// stomach's own sphere. A counter you raise where you like has no such argument to lose.
/// </summary>
public static readonly float MarketSize = 1.6f; // metres, the borrowed model's largest side
// ─── Seeker Worker ───────────────────────────────────────────────────
public const string WorkerDisplayName = "Seeker Worker";
public static readonly float WorkerScale = 0.5f;
public static readonly float WorkerHealthFraction = 0.5f;
public static readonly float WorkerDamageFraction = 0.5f;
/// <summary>One out of every infected beehive on this timer, until the pool is full.</summary>
public static readonly float WorkerSpawnInterval = 120f;
/// <summary>Haulers only start after Bonemass.</summary>
public const int HaulerUnlockState = 4;
/// <summary>Ten metres. Also the radius it keeps in repair.</summary>
public static readonly float WorkerLeashRange = 10f;
/// <summary>How far a worker reaches to mend, and how often it mends one thing.</summary>
public static readonly float WorkerRepairRange = 10f;
public static readonly float WorkerRepairInterval = 5f;
/// <summary>How far from its anchor a worker looks for chests.</summary>
public static readonly float WorkerChestRange = 3f;
/// <summary>How often a worker does a round of its trade.</summary>
public static readonly float WorkerRoundInterval = 4f;
/// <summary>Plants per infected beehive, once the farmer's job lands.</summary>
public const int PlantsPerBeehive = 15;
// ─── Biomass ─────────────────────────────────────────────────────────
public static readonly float BiomassTankBase = 1000f;
/// <summary>Section 10.1: 1000 / 1500 / 2000 / 2500 across the four stages.</summary>
public static readonly float BiomassTankPerStage = 500f;
/// <summary>
/// Headroom over the document's tank, on every stage: 1500 / 2000 / 2500 / 3000.
///
/// FOUND IN PLAY, and it is a real hole rather than a balance opinion. A stage costs exactly
/// the tankful of the stage below it, so with the tank and the price being the same number
/// the hive had to be full TO THE GRAM before it could grow - and it never was. Biomass
/// arrives in whole items: with three units of room left, a log worth five does not fit, so
/// the last few points can never be filled and the price is never reached.
///
/// The prices are untouched. This is the room above them.
/// </summary>
public static readonly float BiomassTankHeadroom = 500f;
public static readonly float WoodBiomassValue = 5f;
/// <summary>
/// How big the nest is at the last stage, as a multiple of how it was built.
///
/// SECTION 9 SAYS TRIPLE and triple was wrong on screen: the trunk measures about eight
/// metres as placed, so a Hive Citadel stood twenty-four metres tall and read as a bug
/// rather than as a building. 1.75 keeps the growth legible - each stage is visibly bigger
/// than the last - without the last one swallowing the base. In the .cfg because this is a
/// number only an eye can settle.
/// </summary>
public static readonly float HiveStageGrowth = 1.75f;
/// <summary>Section 20.4's day between purchases, in game days.</summary>
public static readonly float UpgradeCooldownDays = 1f;
// ─── Brood eggs and troops ───────────────────────────────────────────
/// <summary>Section 10.2: one egg every twenty seconds, five plus the stage in the clutch.</summary>
public static readonly float EggInterval = 20f;
public const int EggCapBase = 5;
/// <summary>How far a troop wanders from the nest when nobody is leading it.</summary>
public static readonly float TroopLeashRange = 12f;
/// <summary>How long a troop outlives the nest that hatched it, in seconds.</summary>
public static readonly float TroopWitherSeconds = 60f;
/// <summary>How close a troop has to be to see whether its nest is still standing.</summary>
public static readonly float TroopHomeCheckRange = 25f;
// ─── Blister Tick ────────────────────────────────────────────────────
/// <summary>Section 12: fifty a slot, and the slot is permanent.</summary>
public static readonly float TickPrice = 50f;
/// <summary>How close it gets before it bursts, in metres.</summary>
public static readonly float TickBurstRange = 2.5f;
/// <summary>How long the nest waits before growing a replacement, in seconds.</summary>
public static readonly float TickRespawnSeconds = 30f;
/// <summary>From this nest stage on, the blast is the elite blob's. Section 12's two tiers.</summary>
public const int TickLateBlastStage = 3;
/// <summary>Only used if the blob projectiles are not in this build - see SvermBlisterTick.</summary>
public static readonly float TickFallbackDamage = 30f;
// ─── Medicine ────────────────────────────────────────────────────────
/// <summary>
/// Section 19.4: what a jar heals when it is given to one of the colony's insects instead of
/// eaten. They stopped counting as biomass to become this.
/// </summary>
public static readonly float HoneyHealing = 40f;
public static readonly float RoyalJellyHealing = 90f;
// No Venom Coil numbers. Section 13's turret was built, seen and rejected, so its price, its
// Bonemass gate and its scale are gone with it rather than left here looking pending.
/// <summary>
/// How much biomass moves from digestion into the spendable bank each second.
///
/// NOT A NUMBER FROM THE DESIGN DOCUMENT - the digestion is described there, its speed is
/// not. Five a second empties a full stage-one tank in a little over three minutes, which
/// is long enough that a hive cannot be filled and spent in the same breath and short
/// enough that nobody stands there waiting. It is in the .cfg because it is the first thing
/// a play test will want to argue with.
/// </summary>
public static readonly float BiomassDigestRate = 5f;
// ─── Helpers ─────────────────────────────────────────────────────────
private static Color Hex(int r, int g, int b)
{
return new Color(r / 255f, g / 255f, b / 255f, 1f);
}
}
}

View file

@ -0,0 +1,271 @@
using BepInEx.Configuration;
namespace RacesOfValheim
{
/// <summary>
/// The BepInEx-configurable slice of the Sverm's numbers, bound as ConfigEntry so they can be
/// retuned without a rebuild - see CONFIGURATION-MANAGER-HOWTO.md. Bound once, from
/// RacesOfValheim.Awake().
///
/// Configuration Manager is a convenience, not a requirement: these land in
/// BepInEx/config/com.nandor.racesofvalheim.cfg as plain text and can be edited with a text
/// editor and picked up on the next launch.
///
/// WHAT IS IN HERE AND WHAT IS NOT, on the same boundary DvergarConfigManagement draws:
/// SvermConfig keeps the identity constants that must never change once a character exists
/// (RaceId, status effect names) and the per-tier tables. What lives here is the handful of
/// numbers that can only be judged by looking at them on screen - where the claws sit on the
/// hand, how wide the wings open - because those are guesses until someone sees them, and a
/// guess that needs a rebuild to correct is a guess that gets corrected slowly.
/// </summary>
public static class SvermConfigManagement
{
// No claw entries. They were here for one build, while the claws were a model bolted to
// the hand bones and their angle was a guess only an eye could settle. They are a real
// equipped item now (SvermClawSlot), so the game's own attach point decides where they sit
// and there is nothing left to tune.
// ─── Dorsal spines ───────────────────────────────────────────────────
public static ConfigEntry<float> SpineSizeSmall;
public static ConfigEntry<float> SpineSizeFull;
public static ConfigEntry<string> SpineBoneName;
public static ConfigEntry<float> SpineRotationX;
public static ConfigEntry<float> SpineRotationY;
public static ConfigEntry<float> SpineRotationZ;
// ─── Emberform ───────────────────────────────────────────────────────
public static ConfigEntry<float> EmberGlowStrength;
// ─── Keybinds ────────────────────────────────────────────────────────
public static ConfigEntry<KeyboardShortcut> StingerKey;
// ─── Stinger Morph, the model ────────────────────────────────────────
public static ConfigEntry<float> StingerScaleMultiplier;
public static ConfigEntry<float> StingerYawDegrees;
// ─── Colony caps ─────────────────────────────────────────────────────
// Every ceiling on how many things the colony can have alive at once, in one section, so
// the "is this too many creatures for my machine" question has exactly one place to be
// answered - and can be answered without a rebuild.
//
// The nest density limit is deliberately NOT here. Two per square mile is a rule about
// what the world may look like rather than a comfort setting, and PieceDensityLimit reads
// it once when the piece registers.
public static ConfigEntry<int> CapBrood;
public static ConfigEntry<int> CapSeeker;
public static ConfigEntry<int> CapSoldier;
public static ConfigEntry<int> CapGjall;
public static ConfigEntry<int> CapBlisterTick;
public static ConfigEntry<int> CapFarmers;
public static ConfigEntry<int> CapHaulers;
public static ConfigEntry<int> CapBeehives;
// ─── The nest and its mark ───────────────────────────────────────────
public static ConfigEntry<float> WorkerChestRangeValue;
public static ConfigEntry<bool> WorkerDebugValue;
public static ConfigEntry<float> HiveScaleValue;
public static ConfigEntry<float> EggSizeValue;
public static ConfigEntry<float> EggHeightValue;
public static ConfigEntry<float> DigestRateValue;
public static ConfigEntry<float> StomachSizeValue;
public static ConfigEntry<float> StomachHeightValue;
public static ConfigEntry<float> MarketSizeValue;
public static ConfigEntry<float> StageGrowthValue;
public static ConfigEntry<float> NestVfxScaleValue;
public static ConfigEntry<float> BeehiveVfxScaleValue;
public static void Bind(ConfigFile config)
{
const string spines = "Sverm - Dorsal Spines";
const string ember = "Sverm - Emberform";
const string keybinds = "Sverm - Keybinds";
// G, like every other first transformation in the mod - the Aswid's bat, the Fenrir's
// wolf, the Dvergar's ping. A character only ever has one race, so they never collide.
StingerKey = config.Bind(keybinds, "Stinger Morph", new KeyboardShortcut(UnityEngine.KeyCode.G),
"Turns into a Deathsquito, and back. Unlocked at Yagluth.");
const string stinger = "Sverm - Stinger Morph";
StingerScaleMultiplier = config.Bind(stinger, "Scale", 1f,
"Multiplies the deathsquito model's OWN authored scale. 1 means 'the size the " +
"game draws one'. Raise it if the insect reads as too small to be you.");
const string nest = "Sverm - Nest";
HiveScaleValue = config.Bind(nest, "Nest Scale", SvermConfig.HiveScale,
"How big the nest is. Only affects nests placed AFTER the change - the ones already " +
"standing keep the size they were built at, like every other building.");
EggSizeValue = config.Bind(nest, "Infection Egg Size", SvermConfig.HiveEggSize,
"How big the egg on a taken beehive is, in metres. The first pass used 0.35 and it " +
"was invisible in play.");
EggHeightValue = config.Bind(nest, "Infection Egg Height", SvermConfig.HiveEggHeight,
"How far above the beehive's own origin the egg sits, in metres. Too high and it " +
"floats clear of the roof; too low and it sinks into the mesh.");
// The two hives you press. Sizes are also how wide the sphere you point at is, so these
// decide how easy each mouth is to hit as much as how it looks. Read once, when the
// piece is registered: a change here shows up on the next launch, not on nests already
// standing.
StomachSizeValue = config.Bind(nest, "Stomach Size", SvermConfig.StomachSize,
"How big the hive at the foot of the nest is, in metres. It is the one you feed: " +
"press E on it and a whole stack goes in.");
StomachHeightValue = config.Bind(nest, "Stomach Height", SvermConfig.StomachHeight,
"How far up the trunk the stomach sits, in metres. Zero puts it on the ground.");
// NOT "Market Size" - that key already exists in everyone's .cfg holding the size of the
// mouth that used to hang on the trunk, and a key that is read back from a file laughs
// at a changed default. The market is a building of its own now and this is its scale,
// so it gets a name of its own too; the two old lines are orphans and are ignored.
StageGrowthValue = config.Bind(nest, "Growth At Last Stage", SvermConfig.HiveStageGrowth,
"How big a Hive Citadel is compared to the Brood Mound it started as, with the two " +
"middle stages spread evenly between. Applies to nests already standing, since it " +
"is worked out from the stage rather than baked in at placement.");
NestVfxScaleValue = config.Bind(nest, "Nest Swarm Scale", SvermConfig.NestVfxScale,
"How big the cloud of flies over the nest is, and the green reek it gives off while " +
"it is digesting. The reek only shows when there is something going down.");
BeehiveVfxScaleValue = config.Bind(nest, "Beehive Swarm Scale", SvermConfig.BeehiveVfxScale,
"The same two marks on a taken beehive, which wants a smaller cloud than the nest. " +
"Its gas shows when the hive is full of honey.");
MarketSizeValue = config.Bind(nest, "Market Bench Size", SvermConfig.MarketSize,
"How big the Hive Market bench is, in metres. It is a building you raise inside a " +
"hive's ten metres, not a part of the nest.");
DigestRateValue = config.Bind(nest, "Digestion Rate", SvermConfig.BiomassDigestRate,
"How much biomass moves from digestion into the hive's spendable bank each second. " +
"What you sell the hive is not spendable until it has gone down. At the default a " +
"full stage-one tank takes a little over three minutes. Measured against the world " +
"clock, so a hive nobody is watching digests at the same speed.");
const string workers = "Sverm - Workers";
WorkerChestRangeValue = config.Bind(workers, "Chest Range", SvermConfig.WorkerChestRange,
"How far from the nest or the beehive a worker will look for a chest, in metres. " +
"Three is the design figure; widen it if your storage will not fit that close.");
WorkerDebugValue = config.Bind(workers, "Log Rounds", false,
"Writes a line to the log when a worker finishes a round and found nothing to do. " +
"Off by default because a worker works every few seconds and would bury the log.");
const string caps = "Sverm - Colony Caps";
CapBrood = config.Bind(caps, "Brood", SvermConfig.CapBrood,
"How many Seeker Brood the colony can keep alive at once.");
CapSeeker = config.Bind(caps, "Seeker", SvermConfig.CapSeeker,
"How many Seekers the colony can keep alive at once.");
CapSoldier = config.Bind(caps, "Soldier", SvermConfig.CapSoldier,
"How many Seeker Soldiers the colony can keep alive at once.");
CapGjall = config.Bind(caps, "Gjall", SvermConfig.CapGjall,
"How many Gjall the colony can keep alive at once.");
CapBlisterTick = config.Bind(caps, "Blister Ticks", SvermConfig.CapBlisterTick,
"How many bomb ticks the colony can keep alive at once. They respawn for free, so " +
"this number is also how many explosions are in the air at any moment.");
CapFarmers = config.Bind(caps, "Worker - Farmers", SvermConfig.CapFarmers,
"Seeker Workers produced by infected beehives, the ones that plant and harvest. " +
"Separate pool from the haulers.");
CapHaulers = config.Bind(caps, "Worker - Haulers", SvermConfig.CapHaulers,
"Seeker Workers produced by the nest after Bonemass, the ones that carry food from " +
"nearby chests into the hive. Separate pool from the farmers.");
CapBeehives = config.Bind(caps, "Beehives per Aura", SvermConfig.HiveAuraBeehiveMax,
"How many beehives may stand in one nest's ten metres. Every one of them ends up " +
"infected and producing a worker, so this is the number that really decides how " +
"busy a base gets.");
StingerYawDegrees = config.Bind(stinger, "Yaw", 180f,
"Turns the model on the vertical axis, in degrees. The creature's forward is not " +
"the player's, so without this it flies looking back at you. 180 is the usual " +
"answer; try 90 or -90 if it comes out sideways.");
EmberGlowStrength = config.Bind(ember, "Glow Strength", SvermConfig.EmberGlowStrength,
"How hot the chitin burns at Fader. This multiplies an HDR colour and it is applied " +
"to the chest, the legs and the helmet at once, so it goes a very long way. Settled " +
"in game at 0.0625 after 1.0 blinded and 0.25 was still too bright. Above the bloom " +
"threshold more brightness buys a bigger white area and less red, so tune downward.");
SpineSizeSmall = config.Bind(spines, "Size Vestigial", SvermConfig.SpineSizeSmall,
"How tall the dorsal spines stand, in metres, from Moder to the Queen.");
SpineSizeFull = config.Bind(spines, "Size Full", SvermConfig.SpineSizeFull,
"How tall they stand from the Queen on.");
SpineBoneName = config.Bind(spines, "Bone", SvermConfig.SpineBoneName,
"Which bone the spines ride. This bone and no other - there is no fallback, so a " +
"name that is not in the rig means no crest at all. Leave it blank to use " +
"Spine3.");
// Defaults are the values found in game with the crest on screen, not zeroes: changing
// nothing here now reproduces the placement that was actually approved.
SpineRotationX = config.Bind(spines, "Rotation X", SvermConfig.SpineRotationX, "Pitch of the spines, in degrees.");
SpineRotationY = config.Bind(spines, "Rotation Y", SvermConfig.SpineRotationY, "Yaw of the spines, in degrees.");
SpineRotationZ = config.Bind(spines, "Rotation Z", SvermConfig.SpineRotationZ, "Roll of the spines, in degrees.");
}
// ─── Live reads ──────────────────────────────────────────────────────
// Null-guarded so the placement code works whether or not Bind has run - the main-menu
// character preview can build a body before Awake has finished on a slow load.
public static UnityEngine.Quaternion SpineRotation()
{
return UnityEngine.Quaternion.Euler(
SpineRotationX?.Value ?? SvermConfig.SpineRotationX,
SpineRotationY?.Value ?? SvermConfig.SpineRotationY,
SpineRotationZ?.Value ?? SvermConfig.SpineRotationZ);
}
public static float EmberStrength => EmberGlowStrength?.Value ?? SvermConfig.EmberGlowStrength;
public static int Brood => CapBrood?.Value ?? SvermConfig.CapBrood;
public static int Seeker => CapSeeker?.Value ?? SvermConfig.CapSeeker;
public static int Soldier => CapSoldier?.Value ?? SvermConfig.CapSoldier;
public static int Gjall => CapGjall?.Value ?? SvermConfig.CapGjall;
public static int BlisterTick => CapBlisterTick?.Value ?? SvermConfig.CapBlisterTick;
public static int Farmers => CapFarmers?.Value ?? SvermConfig.CapFarmers;
public static int Haulers => CapHaulers?.Value ?? SvermConfig.CapHaulers;
public static int Beehives => CapBeehives?.Value ?? SvermConfig.HiveAuraBeehiveMax;
public static float ChestRange => WorkerChestRangeValue?.Value ?? SvermConfig.WorkerChestRange;
public static bool WorkerDebug => WorkerDebugValue?.Value ?? false;
public static float HiveScale => HiveScaleValue?.Value ?? SvermConfig.HiveScale;
public static float EggSize => EggSizeValue?.Value ?? SvermConfig.HiveEggSize;
public static float EggHeight => EggHeightValue?.Value ?? SvermConfig.HiveEggHeight;
public static float DigestRate => DigestRateValue?.Value ?? SvermConfig.BiomassDigestRate;
public static float StomachSize => StomachSizeValue?.Value ?? SvermConfig.StomachSize;
public static float StomachHeight => StomachHeightValue?.Value ?? SvermConfig.StomachHeight;
public static float MarketSize => MarketSizeValue?.Value ?? SvermConfig.MarketSize;
public static float StageGrowth => StageGrowthValue?.Value ?? SvermConfig.HiveStageGrowth;
public static float NestVfxScale => NestVfxScaleValue?.Value ?? SvermConfig.NestVfxScale;
public static float BeehiveVfxScale => BeehiveVfxScaleValue?.Value ?? SvermConfig.BeehiveVfxScale;
public static float StingerScale => StingerScaleMultiplier?.Value ?? 1f;
public static float StingerYaw => StingerYawDegrees?.Value ?? 180f;
public static float SizeSmall => SpineSizeSmall?.Value ?? SvermConfig.SpineSizeSmall;
public static float SizeFull => SpineSizeFull?.Value ?? SvermConfig.SpineSizeFull;
/// <summary>
/// The bone name, never blank.
///
/// An empty string is not "no preference": FindBone's loose match asks whether a bone's
/// name CONTAINS the wanted string, and every string contains the empty one - so a blank
/// entry silently mounted the crest on the first bone of the armature. Clearing the field
/// while experimenting is an obvious thing to do, so it has to mean "the default".
/// </summary>
public static string Bone
{
get
{
string configured = SpineBoneName?.Value;
return string.IsNullOrWhiteSpace(configured) ? SvermConfig.SpineBoneName : configured;
}
}
}
}

View file

@ -0,0 +1,273 @@
using System.Collections.Generic;
using HarmonyLib;
using Jotunn.Entities;
using Jotunn.Managers;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// Insect Metabolism: raw meat is nearly as good as cooked, seeds are food, and honey and royal
/// jelly are worth twice what anyone else gets out of them.
///
/// THE ONE RULE THAT SHAPES THIS FILE: never write to a vanilla item's m_shared. That object is
/// shared by every instance of the item in the game, for every player and every race - setting
/// RoyalJelly.m_food would make royal jelly edible for a Skeleton too, permanently, and a
/// Sverm's 70% raw meat would be everyone's 70% raw meat.
///
/// So each edible gets a HIDDEN CLONE carrying the Sverm's numbers. When a Sverm right-clicks
/// the real item, the clone is what gets eaten and one of the real item is removed. The player
/// never sees the clone and the vanilla item is never touched. This is DraughFoodPatches'
/// EdibleUncooked_ trick, and it is here for the same reason it is there.
/// </summary>
public static class SvermFood
{
private const string ClonePrefix = "SvermMeal_";
/// <summary>Every real prefab we intercept, mapped to the clone that carries our numbers.</summary>
private static readonly Dictionary<string, string> meals = new Dictionary<string, string>();
/// <summary>Seeds are gated behind The Elder, everything else is live from tier 1.</summary>
private static readonly HashSet<string> gatedSeeds = new HashSet<string>();
private static bool registered;
// ─── The tables ──────────────────────────────────────────────────────
/// <summary>
/// Seeds by biome, and the numbers are deliberately modest.
///
/// This is grinding, not cooking: raw bulk with no buff attached. The buff on a seed is
/// Trenta's whole feature (TrentaConfig.AwakenedSeedFood), and two races eating the same
/// ingredient for the same reward would cost one of them its identity.
///
/// AncientSeed is deliberately absent. It is the offering that summons The Elder, not a
/// seed, and eating one would be an expensive accident.
/// </summary>
private struct SeedFood
{
public string Prefab;
public float Health, Stamina, Eitr, Duration, Regen;
public SeedFood(string prefab, float health, float stamina, float eitr, float duration, float regen)
{
Prefab = prefab; Health = health; Stamina = stamina; Eitr = eitr; Duration = duration; Regen = regen;
}
}
private static readonly SeedFood[] Seeds =
{
// Meadows - the weakest thing that still counts as a meal
new SeedFood("CarrotSeeds", 8f, 12f, 0f, 900f, 1f),
new SeedFood("TurnipSeeds", 8f, 12f, 0f, 900f, 1f),
new SeedFood("BeechSeeds", 8f, 10f, 0f, 900f, 1f),
new SeedFood("BirchSeeds", 8f, 10f, 0f, 900f, 1f),
// Black Forest - nuts and cones, denser
new SeedFood("Acorn", 12f, 16f, 0f, 1000f, 1f),
new SeedFood("FirCone", 12f, 16f, 0f, 1000f, 1f),
new SeedFood("PineCone", 12f, 16f, 0f, 1000f, 1f),
// Plains
new SeedFood("OnionSeeds", 16f, 20f, 0f, 1200f, 1f),
// Mistlands - the only seeds with eitr in them, which is what makes going that far pay
new SeedFood("VineberrySeeds",20f, 24f, 8f, 1200f, 2f),
new SeedFood("VineGreenSeeds",20f, 24f, 8f, 1200f, 2f),
};
// ─── Registration ────────────────────────────────────────────────────
/// <summary>
/// Builds every clone. Driven from SvermRace.CreateModAssets, which runs on
/// PrefabManager.OnVanillaPrefabsAvailable - the one moment Jotunn accepts new items.
/// </summary>
public static void Register()
{
if (registered) return;
registered = true;
// RAW MEAT. The raw-to-cooked table is Draugh's, borrowed on purpose rather than
// copied: which raw item becomes which cooked one is a fact about Valheim, not an
// opinion of either race, and a second copy would only drift out of step with the
// first the next time the game adds a meat.
foreach (KeyValuePair<string, string> pair in DraughFoodPatches.rawToCookedMapping)
{
ItemDrop.ItemData.SharedData cooked = SharedOf(pair.Value);
if (cooked == null) continue;
BuildMeal(pair.Key,
cooked.m_food * SvermConfig.RawMeatFraction,
cooked.m_foodStamina * SvermConfig.RawMeatFraction,
cooked.m_foodEitr * SvermConfig.RawMeatFraction,
cooked.m_foodBurnTime,
cooked.m_foodRegen,
"raw meat");
}
// SEEDS. Gated behind The Elder in the UseItem hook, not here: the clone can exist all
// along, it simply is not reachable before tier 3.
foreach (SeedFood seed in Seeds)
{
if (BuildMeal(seed.Prefab, seed.Health, seed.Stamina, seed.Eitr, seed.Duration, seed.Regen, "seed"))
{
gatedSeeds.Add(seed.Prefab);
}
}
// HONEY, doubled. Read at runtime and multiplied rather than transcribed, so a patch
// that rebalances honey rebalances the Sverm with it.
ItemDrop.ItemData.SharedData honey = SharedOf("Honey");
if (honey != null)
{
BuildMeal("Honey",
honey.m_food * SvermConfig.HoneyMultiplier,
honey.m_foodStamina * SvermConfig.HoneyMultiplier,
honey.m_foodEitr * SvermConfig.HoneyMultiplier,
honey.m_foodBurnTime * SvermConfig.HoneyMultiplier,
honey.m_foodRegen,
"honey");
}
// ROYAL JELLY. Not a food in vanilla at all - it is crafting material - so there is
// nothing to double and the numbers are the ones the design settled on. They are
// already the doubled figures; they are not multiplied again.
BuildMeal(SvermConfig.RoyalJellyPrefab,
SvermConfig.RoyalJellyHealth,
SvermConfig.RoyalJellyStamina,
SvermConfig.RoyalJellyEitr,
SvermConfig.RoyalJellyDuration,
SvermConfig.RoyalJellyRegen,
"royal jelly");
Jotunn.Logger.LogInfo($"[Sverm] Insect Metabolism: {meals.Count} edibles registered.");
}
private static ItemDrop.ItemData.SharedData SharedOf(string prefabName)
{
ItemDrop drop = PrefabManager.Cache.GetPrefab<ItemDrop>(prefabName);
return drop != null && drop.m_itemData != null ? drop.m_itemData.m_shared : null;
}
/// <summary>
/// One hidden clone of one real item, carrying the Sverm's numbers.
///
/// The clone is made a Consumable whatever the original was - a seed is Material in vanilla
/// and would otherwise be refused by EatFood before it got to look at the numbers.
/// </summary>
private static bool BuildMeal(string sourcePrefab, float health, float stamina, float eitr,
float duration, float regen, string label)
{
GameObject source = PrefabManager.Cache.GetPrefab<GameObject>(sourcePrefab);
if (source == null)
{
Jotunn.Logger.LogWarning($"[Sverm] No '{sourcePrefab}' to build a {label} from; skipped.");
return false;
}
string cloneName = ClonePrefix + sourcePrefab;
GameObject clone = PrefabManager.Instance.CreateClonedPrefab(cloneName, source);
if (clone == null) return false;
ItemDrop drop = clone.GetComponent<ItemDrop>();
if (drop == null || drop.m_itemData == null || drop.m_itemData.m_shared == null) return false;
ItemDrop.ItemData.SharedData shared = drop.m_itemData.m_shared;
shared.m_itemType = ItemDrop.ItemData.ItemType.Consumable;
shared.m_food = health;
shared.m_foodStamina = stamina;
shared.m_foodEitr = eitr;
shared.m_foodBurnTime = duration;
shared.m_foodRegen = regen;
// The name is what Player.Food compares on when it decides whether you are eating the
// same thing twice, so it must stay the ORIGINAL's name - otherwise raw meat and its
// clone would occupy two food slots at once.
// m_maxStackSize left alone; nothing ever holds one of these.
ItemManager.Instance.AddItem(new CustomItem(clone, fixReference: false));
meals[sourcePrefab] = cloneName;
return true;
}
// ─── Eating ──────────────────────────────────────────────────────────
/// <summary>Which clone answers for this item, or null when we do not cover it.</summary>
private static string MealFor(ItemDrop.ItemData item, int state)
{
if (item == null || item.m_shared == null) return null;
string prefabName = item.m_dropPrefab != null ? item.m_dropPrefab.name : null;
if (string.IsNullOrEmpty(prefabName)) return null;
if (gatedSeeds.Contains(prefabName) && state < SvermConfig.SeedsEdibleState) return null;
return meals.TryGetValue(prefabName, out string clone) ? clone : null;
}
public static bool IsGatedSeed(string prefabName) => gatedSeeds.Contains(prefabName);
/// <summary>
/// Swaps the real item for its clone at the moment of eating.
///
/// A prefix on UseItem rather than on EatFood, and that is what lets seeds and royal jelly
/// work at all: they are Material in vanilla, so by the time EatFood is reached the game
/// has already decided they are not food. UseItem runs before that judgement.
/// </summary>
[HarmonyPatch(typeof(Humanoid), "UseItem")]
public static class Sverm_UseItem_Patch
{
public static bool Prefix(Humanoid __instance, Inventory inventory, ItemDrop.ItemData item)
{
Player player = __instance as Player;
if (player == null || player != Player.m_localPlayer) return true;
if (!SvermVisuals.IsSvermPlayer(player)) return true;
if (item == null || item.m_shared == null) return true;
// MEDICINE BEFORE FOOD, and called from here rather than from a prefix of its own:
// honey and royal jelly are both a meal and the colony's medicine, and which one a
// press means is decided by whether the player is looking at one of our insects.
// Two prefixes both wanting to answer that first would be a coin toss.
if (SvermMedicine.TryAdminister(player, item)) return false;
// The one thing a Sverm may not eat. Blocked here rather than left to fail
// silently, so the refusal says why.
if (item.m_dropPrefab != null && item.m_dropPrefab.name.StartsWith("SvermMeal_") == false
&& IsAswidBlood(item))
{
player.Message(MessageHud.MessageType.Center, "Alchemical blood is not food.");
return false;
}
string cloneName = MealFor(item, BossProgressionManager.GetCurrentProgressionState());
if (cloneName == null) return true;
GameObject clonePrefab = ObjectDB.instance != null ? ObjectDB.instance.GetItemPrefab(cloneName) : null;
ItemDrop cloneDrop = clonePrefab != null ? clonePrefab.GetComponent<ItemDrop>() : null;
if (cloneDrop == null) return true; // registration failed; let vanilla decide
if (!player.EatFood(cloneDrop.m_itemData)) return false; // full, or too soon - vanilla already said so
if (inventory != null) inventory.RemoveItem(item, 1);
EffectList consume = Traverse.Create(player).Field<EffectList>("m_consumeItemEffects").Value;
if (consume != null) consume.Create(player.transform.position, Quaternion.identity, player.transform, 1f, -1);
ZSyncAnimation anim = Traverse.Create(player).Field<ZSyncAnimation>("m_zanim").Value;
if (anim != null) anim.SetTrigger("eat");
return false; // handled
}
/// <summary>
/// The Aswid's alchemical blood, recognised without a hard dependency on that race's
/// tables: everything it makes carries its own prefix.
/// </summary>
private static bool IsAswidBlood(ItemDrop.ItemData item)
{
string name = item.m_dropPrefab != null ? item.m_dropPrefab.name : "";
return name.StartsWith("Aswid") || name == "BloodEssence" || name.Contains("BloodPotion");
}
}
}
}

View file

@ -0,0 +1,621 @@
using System.Collections.Generic;
using Jotunn.Configs;
using Jotunn.Entities;
using Jotunn.Managers;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The nest itself: the piece, its gate, and the ten metres of ground it claims.
///
/// GATED ON THE ELDER, and that gate is the whole point of the revision. The colony used to
/// open at tier 1 and arrive all at once; now the early game is spent as a body, and the first
/// nest is a thing you earn. What the boss decides is WHEN you may plant one - how fast it
/// grows after that is still bought with biomass, four stages at the shop, exactly as before.
///
/// THE AURA is what makes it read as a colony rather than as a machine. Inside ten metres the
/// Sverm may raise up to ten vanilla beehives, and they cost only wood - no queen bee, because
/// a colony that has to go hunting for someone else's queen is telling the wrong story. Left
/// alone for a minute, each hive is taken over: an egg pushes out through the roof, and from
/// then on it works twice as fast and holds three times as much.
///
/// This file owns the piece and the aura. Biomass, eggs, troops and the shop are
/// SvermHiveBehaviour's; the workers are SvermWorker's.
/// </summary>
public static class SvermHive
{
public const string PieceName = SvermHiveNames.PieceName;
public const string DisplayName = SvermHiveNames.PieceDisplayName;
/// <summary>
/// What the nest borrows its body from, best first.
///
/// "Hive" WAS the first entry and it was a disaster. The name is in the game's manifest and
/// it sounds exactly right, so it went in unchecked - and it turned out to carry a
/// Character. Building it did not place a nest, it SPAWNED A CREATURE, and because a Piece
/// and a WearNTear had been bolted on top without removing anything, the health the console
/// tried to take off was not the health holding it up. A giant immortal Bonemass, from a
/// name that read as scenery.
///
/// Everything in this list now is a CreepProp - the game's own word for "this is a prop" -
/// and IsSafeScenery below refuses anything alive whatever the list says.
/// </summary>
private static readonly string[] SourceCandidates =
{
"CreepProp_pillar01",
"CreepProp_egg_hanging01",
"Creeppillar",
"CreepProp_hanging01",
};
public static void Register()
{
GameObject prefab = null;
string sourcePrefab = null;
foreach (string candidate in SourceCandidates)
{
GameObject source = PrefabManager.Cache.GetPrefab<GameObject>(candidate);
if (source == null) continue;
if (!IsSafeScenery(source, candidate)) continue;
prefab = PrefabManager.Instance.CreateClonedPrefab(PieceName, source);
if (prefab == null) continue;
sourcePrefab = candidate;
break;
}
if (prefab == null)
{
Jotunn.Logger.LogWarning("[Sverm] No safe scenery to build the nest from (" +
string.Join(", ", SourceCandidates) + "); the nest is not registered. " +
"Not registering is the correct outcome: a nest nobody can build beats " +
"a nest that turns out to be alive.");
return;
}
// Belt as well as braces: anything that could still make this act like a creature comes
// off the COPY. The guard above should mean there is nothing to find, and this is what
// makes that true rather than hoped for.
StripLife(prefab);
// Set on the PREFAB, so every nest ever placed comes out this size and the value is
// baked into the piece rather than chased at runtime. It follows that changing it in
// the .cfg only affects nests placed afterwards - the ones already standing keep the
// size they were built at, which is how every other building in the game behaves.
float scale = SvermConfigManagement.HiveScale;
prefab.transform.localScale = new Vector3(scale, scale, scale);
// A hive in the world is scenery, not a building: it arrives with no Piece and no
// WearNTear, and the hammer needs both. Added rather than assumed - the clone is
// whatever the game shipped, and asking for a component that is not there is how a
// station ends up unplaceable with no error.
Piece piece = prefab.GetComponent<Piece>() ?? prefab.AddComponent<Piece>();
piece.m_name = DisplayName;
piece.m_description = "The colony begins here. Everything else grows out of it.";
piece.m_groundPiece = true;
piece.m_groundOnly = true;
piece.m_cultivatedGroundOnly = false;
piece.m_canBeRemoved = true;
if (prefab.GetComponent<WearNTear>() == null)
{
WearNTear wear = prefab.AddComponent<WearNTear>();
wear.m_health = 1500f;
wear.m_noRoofWear = true;
wear.m_noSupportWear = true;
wear.m_destroyedEffect = new EffectList();
wear.m_hitEffect = new EffectList();
}
if (prefab.GetComponent<ZNetView>() == null) prefab.AddComponent<ZNetView>();
prefab.AddComponent<SvermHiveBehaviour>();
MountMouths(prefab);
PieceManager.Instance.AddPiece(new CustomPiece(prefab, fixReference: false, new PieceConfig
{
Name = DisplayName,
Description = piece.m_description,
PieceTable = PieceTables.Hammer,
Category = "Crafting",
// NOT OPTIONAL. Jotunn refuses a piece with no icon outright - "CustomPiece has no
// icon" followed by "is not valid" - and the piece simply never reaches the
// hammer. Borrowed off a trophy, the way SkeletonBonePile does.
Icon = BorrowIcon("TrophySeekerBrute") ?? BorrowIcon("TrophySeeker") ?? BorrowIcon("Honey"),
Requirements = new[]
{
new RequirementConfig { Item = "Wood", Amount = 40, Recover = true },
new RequirementConfig { Item = "Resin", Amount = 20, Recover = true },
},
}));
// Two per square mile, as before. The radius is 908 m because that is the circle of
// equal area, and PieceDensityLimit counts over ZDOs rather than loaded objects.
PieceDensityLimit.Register(PieceName, SvermConfig.HiveDensityRadius, SvermConfig.HiveDensityMax,
"There is already a hive holding this ground.");
// The gate. Race first, then the boss - two separate refusals, because "you are not a
// Sverm" and "you have not killed The Elder" are different problems and a player who
// gets the wrong message goes looking in the wrong place.
PieceDensityLimit.RegisterGate(PieceName, (player, position) =>
{
if (player == null) return false;
if (!SvermVisuals.IsSvermPlayer(player))
{
player.Message(MessageHud.MessageType.Center, "Only the Sverm can raise a hive.");
return false;
}
if (BossProgressionManager.GetCurrentProgressionState() < SvermConfig.HiveUnlockState)
{
player.Message(MessageHud.MessageType.Center, "The colony will not wake until the Elder falls.");
return false;
}
return true;
});
Jotunn.Logger.LogInfo($"[Sverm] Registered '{PieceName}' from '{sourcePrefab}'.");
}
/// <summary>
/// What the two mouths borrow their look from, best first. SCENERY ONLY.
///
/// "Hive" WAS ON THIS LIST for one build, on the reasoning that ModelBorrow strips a copy
/// down to its renderers so borrowing a living prefab is safe. IT IS NOT, and the game said
/// so in one line nobody had asked it for:
///
/// Can't remove Humanoid (Script) because CharacterDrop (Script) depends on it
///
/// ModelBorrow's strip is a single pass in component order. Unity REFUSES to destroy a
/// component another one still requires, so Humanoid survived on both mouths - and from then
/// on every placement ghost woke a Humanoid, registered it in Character.s_characters and
/// tore it down again, until Character.GetCharactersInRange threw on the wreckage inside
/// Player.UpdatePlacementGhost. The hammer stopped working. FOR EVERY PIECE IN THE GAME, not
/// just this one.
///
/// Which is house rule one, twice over: ask the prefab whether it has a Character, and do
/// not trust a helper to have asked for you. IsSafeScenery below now runs on the source
/// BEFORE anything is borrowed from it.
/// </summary>
private static readonly string[] MouthCandidates =
{
"TheHive",
"CreepProp_egg_hanging01",
"CreepProp_egg_hanging02",
"SeekerEgg",
"CreepProp_hanging01",
};
/// <summary>
/// The stomach: the hive at the nest's foot that a press feeds.
///
/// A MOUTH AND NOT A MENU, at the player's call, after a sell panel inside the vanilla store
/// came up empty and unclickable in game. Feeding is a press on a thing you can see, which
/// needs no UI to be right.
///
/// THERE WAS A SECOND MOUTH UP THE TRUNK, the shop, and it is gone: it never had a height
/// that worked. On the measured crown it was eight metres over the player's head; at the
/// number that replaced it the .cfg still held the old zero, so it sat inside the stomach's
/// own sphere and the ray always found the stomach first. The shop is its own building now -
/// SvermHiveMarketPiece - which is how the Dvergar bench and the Trol totem already do it.
///
/// The mouth gets a SPHERE OF ITS OWN because Player.FindHoverObject picks what you are
/// pointing at from the first collider the ray meets and reads the Hoverable off THAT
/// collider's own GameObject. A mouth sharing the trunk's collider would not be a mouth. The
/// sphere is as wide as the model, so it stands clear of the trunk rather than hiding inside
/// it - the one thing that would make it unreachable.
/// </summary>
private static void MountMouths(GameObject prefab)
{
// Measured BEFORE the mouths are hung, or it would be measuring them too. This is the
// trunk's own height, in the piece's local space, and it is what "up top" means when
// nobody has typed a number into the .cfg.
float trunk = ModelBorrow.HeightOf(prefab);
GameObject source = null;
string sourceName = null;
foreach (string candidate in MouthCandidates)
{
GameObject found = PrefabManager.Cache.GetPrefab<GameObject>(candidate);
if (found == null) continue;
// The same question the piece itself has to answer, asked again here: a model is
// borrowed from this, and a borrowed model that turns out to be alive is what broke
// the hammer.
if (!IsSafeScenery(found, candidate)) continue;
source = found;
sourceName = candidate;
break;
}
if (source == null)
{
Jotunn.Logger.LogWarning("[Sverm] No safe scenery to borrow the nest's mouths from (" +
string.Join(", ", MouthCandidates) + "); they are mounted " +
"anyway, invisible but pressable, rather than leaving the " +
"nest with no way to be fed.");
}
// The trunk is REPORTED and not used as a height: it measured 10.59 m, which is the
// number that made the old market unreachable. Kept in the log because it is the only
// way anyone can tell where there is room to put something on this piece.
Jotunn.Logger.LogInfo($"[Sverm] Nest stomach borrowed from '{sourceName ?? "nothing"}'; the trunk " +
$"measures {trunk:0.##} m and the stomach sits at " +
$"{SvermConfigManagement.StomachHeight:0.##} m.");
MountMouth<SvermHiveStomach>(prefab, source, "SvermHiveStomach",
SvermConfigManagement.StomachSize, SvermConfigManagement.StomachHeight);
}
private static void MountMouth<T>(GameObject prefab, GameObject source, string holderName,
float size, float height) where T : SvermHiveMouth
{
GameObject holder = ModelBorrow.Attach(prefab.transform, holderName, source,
new Vector3(0f, height, 0f), Quaternion.identity, size, "Sverm");
// The piece's own layer, because that is the layer the player's interact raycast looks
// at. A GameObject built from scratch comes up on Default, and Default is not it.
holder.layer = prefab.layer;
// Centred half a size up: ModelBorrow grounds a borrowed model on the holder's origin,
// so the holder's origin is the model's FOOT and not its middle.
SphereCollider ball = holder.AddComponent<SphereCollider>();
ball.center = new Vector3(0f, size * 0.5f, 0f);
ball.radius = size * 0.5f;
holder.AddComponent<T>();
}
/// <summary>
/// Refuses to build a building out of anything that is alive.
///
/// This is the check that was missing, and its absence cost a giant immortal Bonemass in
/// somebody's base. A name in the asset manifest says nothing about what a prefab DOES -
/// "Hive" carried a Character - and the only way to know is to ask the prefab itself.
///
/// It logs what it found rather than failing quietly, because the next person to add a
/// station from a borrowed prefab needs to be told which one to stop trusting.
/// </summary>
internal static bool IsSafeScenery(GameObject source, string name)
{
if (source.GetComponentInChildren<Character>(true) != null)
{
Jotunn.Logger.LogWarning($"[Sverm] '{name}' carries a Character - it is a CREATURE, not scenery. " +
"Refusing to make a building out of it.");
return false;
}
if (source.GetComponentInChildren<BaseAI>(true) != null)
{
Jotunn.Logger.LogWarning($"[Sverm] '{name}' carries a BaseAI; refusing to make a building out of it.");
return false;
}
if (source.GetComponentInChildren<SpawnArea>(true) != null)
{
Jotunn.Logger.LogWarning($"[Sverm] '{name}' is a spawner; refusing to make a building out of it.");
return false;
}
return true;
}
/// <summary>
/// Takes everything that could still behave like a creature off the copy.
///
/// Order matters for the same reason it does in ModelBorrow: behaviours first, then the
/// things they hold references to.
/// </summary>
internal static void StripLife(GameObject copy)
{
foreach (BaseAI ai in copy.GetComponentsInChildren<BaseAI>(true))
{
if (ai != null) Object.DestroyImmediate(ai);
}
foreach (Character character in copy.GetComponentsInChildren<Character>(true))
{
if (character != null) Object.DestroyImmediate(character);
}
foreach (CharacterDrop drop in copy.GetComponentsInChildren<CharacterDrop>(true))
{
if (drop != null) Object.DestroyImmediate(drop);
}
foreach (SpawnArea spawner in copy.GetComponentsInChildren<SpawnArea>(true))
{
if (spawner != null) Object.DestroyImmediate(spawner);
}
foreach (Rigidbody body in copy.GetComponentsInChildren<Rigidbody>(true))
{
if (body != null) Object.DestroyImmediate(body);
}
}
/// <summary>
/// The nest this point belongs to, or null.
///
/// Loaded objects and not ZDOs, deliberately: the only caller is the market bench, which is
/// standing inside the nest's ten metres or it would not have been allowed to exist. A nest
/// that close is loaded by definition, and the cheap answer is the right one.
/// </summary>
internal static SvermHiveBehaviour NearestNest(Vector3 position, float radius)
{
SvermHiveBehaviour closest = null;
float best = radius;
foreach (SvermHiveBehaviour nest in Object.FindObjectsOfType<SvermHiveBehaviour>())
{
if (nest == null) continue;
float distance = Vector3.Distance(nest.transform.position, position);
if (distance > best) continue;
best = distance;
closest = nest;
}
return closest;
}
/// <summary>An item's inventory icon, or null. Same helper shape as SkeletonBonePile's.</summary>
internal static Sprite BorrowIcon(string prefabName)
{
ItemDrop drop = PrefabManager.Cache.GetPrefab<ItemDrop>(prefabName);
if (drop == null || drop.m_itemData == null || drop.m_itemData.m_shared == null) return null;
if (drop.m_itemData.m_shared.m_icons == null || drop.m_itemData.m_shared.m_icons.Length == 0) return null;
return drop.m_itemData.m_shared.m_icons[0];
}
}
/// <summary>
/// The nest's own upkeep. Today that is the aura and the beehives inside it; biomass, eggs,
/// troops and the shop land here next.
/// </summary>
public class SvermHiveBehaviour : MonoBehaviour, Hoverable, Interactable
{
/// <summary>
/// The trunk feeds, exactly like the stomach at its foot.
///
/// IT USED TO TAKE WHAT WAS IN YOUR HAND, which could not be made to work: food is a
/// consumable, it never reaches the weapon slot, and the meat the player thought they were
/// offering was simply eaten by the player. It reads the inventory now.
///
/// The trunk is the widest thing to point at, so it does the thing you do most rather than
/// being a dead spot between the two mouths. The store has one way in and it is the hive up
/// top - see SvermHiveMarket.
/// </summary>
public bool Interact(Humanoid user, bool hold, bool alt)
{
if (hold) return false;
Player player = user as Player;
if (player == null || player != Player.m_localPlayer) return false;
if (!SvermVisuals.IsSvermPlayer(player))
{
player.Message(MessageHud.MessageType.Center, "The hive does not know you.");
return true;
}
return SvermHiveStore.FeedOneStack(this, player);
}
public bool UseItem(Humanoid user, ItemDrop.ItemData item) => false;
/// <summary>
/// What the nest says when you look at it.
///
/// The tank had no readout at all in the first pass, which made every other part of the
/// colony unfalsifiable: a hauler that was not working and a hauler that was working
/// looked exactly the same. A number on the hive is the cheapest possible test of the
/// whole chain.
/// </summary>
public string GetHoverText()
{
int beehives = SvermBeehive.CountInAura(transform.position);
int infected = SvermBeehive.CountInfectedInAura(transform.position);
// Both numbers, always, even when nothing is going down. A line that appears and
// disappears is one the player has to notice twice before they believe it.
return $"{SvermHiveStage.NameOf(SvermHiveStage.Of(transform))}\n" +
SvermHiveReadout.Tank(transform) +
$"Beehives {infected} taken of {beehives} in range\n" +
"[<color=yellow><b>$KEY_Use</b></color>] Feed it a stack";
}
public string GetHoverName() => SvermHiveStage.NameOf(SvermHiveStage.Of(transform));
private ZNetView nview;
private float nextSweep;
private float nextHauler;
private float nextDigest;
private float nextTick;
private float nextVfx;
/// <summary>
/// The size this nest was built at, before any growth is applied on top.
///
/// Read at Awake and kept, rather than taken from the config each time: the piece is
/// registered at the configured scale, so what the transform holds when it loads IS the size
/// this particular nest was placed at - which is the promise the config makes, that changing
/// it never resizes nests already standing.
/// </summary>
private Vector3 builtScale = Vector3.one;
private float shownScale = -1f;
private void Awake()
{
nview = GetComponent<ZNetView>();
builtScale = transform.localScale;
// A station, in the same sense the Draugh spawner and the Dvergar bank are: this is what
// the troops bound to it look for to decide they are not orphans. Without it the whole
// garrison would wither a minute after it hatched.
RaisedThrall.RegisterStation(transform);
// Before the first frame is drawn, or a grown nest pops from small to large in front of
// whoever is standing there when it loads.
ApplyStageScale();
}
private void OnDestroy()
{
// StationStandsAt cleans destroyed transforms out of its own list, so this is belt as
// well as braces - but a nest that is torn down should stop being a home the same frame,
// not the next time somebody asks.
RaisedThrall.UnregisterStation(transform);
}
/// <summary>
/// Puts the stage on screen. Every client does this off the ZDO, so nobody has to own the
/// nest to see it the right size - section 9.1's "la scala va sul ZDO", by derivation rather
/// than by a second synced field.
/// </summary>
private void ApplyStageScale()
{
if (nview == null || !nview.IsValid()) return;
// The SCALE and not the stage is what is remembered, so that retuning the growth in the
// .cfg moves the nests already standing instead of waiting for a stage they may never
// buy again.
float wanted = SvermHiveStage.ScaleOf(SvermHiveStage.Of(transform));
if (Mathf.Approximately(wanted, shownScale)) return;
shownScale = wanted;
transform.localScale = builtScale * wanted;
}
private void Update()
{
// ABOVE the owner check, and that is the point of it: the client who bought the stage is
// not necessarily the client who owns the nest, and everyone has to see it grow.
ApplyStageScale();
// Same reason, same place. The flies hang over the nest always; the green reek only
// while there is something going down, which makes the digestion a thing you can see
// from across the field instead of a number on a hover text.
if (Time.time >= nextVfx)
{
nextVfx = Time.time + 2f;
float scale = SvermConfigManagement.NestVfxScale;
SvermHiveVfx.EnsureFlies(transform, scale);
SvermHiveVfx.SetGas(transform, SvermBiomass.Digesting(transform) > 0f, scale);
// The taken beehives wear the same two marks, smaller. Driven from here rather than
// from the sweep because the sweep is the OWNER's round and these have to show up on
// every client.
SvermBeehive.DressInfected(transform.position);
}
// Only the owner runs the colony. Every client seeing this nest would otherwise infect
// the same beehives over and over, each writing its own answer to the same ZDO.
if (nview == null || !nview.IsValid() || !nview.IsOwner()) return;
// Ahead of the sweep gate and on a clock of its own: the sweep walks a sphere of
// colliders and can afford to wait five seconds, while a number the player is standing
// there watching should move about as often as they can see it move. What is actually
// digested comes from the world clock, so this interval only decides how smooth the
// readout is, never how fast the hive works.
if (Time.time >= nextDigest)
{
nextDigest = Time.time + 1f;
SvermBiomass.Digest(transform);
// Eggs work themselves out from the world clock, so this only writes down what has
// already happened - which is what keeps the number the other clients read close to
// the truth.
SvermBroodEggs.Settle(transform);
}
// The ticks' free respawn, on its own half-minute clock: an empty paid slot grows a new
// one, one per pass, so a wiped-out swarm trickles back rather than arriving all at once.
if (Time.time >= nextTick)
{
nextTick = Time.time + SvermConfig.TickRespawnSeconds;
SvermBlisterTick.Replace(this);
}
if (Time.time < nextSweep) return;
nextSweep = Time.time + SvermConfig.HiveAuraSweepInterval;
SvermBeehive.SweepAura(transform.position);
Haul();
// Haulers come out of the NEST, and only after Bonemass. The farmers are the beehives'
// business, not the nest's - see SvermBeehive.
if (BossProgressionManager.GetCurrentProgressionState() >= SvermConfig.HaulerUnlockState &&
Time.time >= nextHauler &&
SvermWorker.HasRoom(SvermWorker.Job.Hauler))
{
nextHauler = Time.time + SvermConfig.WorkerSpawnInterval;
SvermWorker.Spawn(SvermWorker.Job.Hauler, transform);
}
}
/// <summary>
/// The nest eats out of the chests around it, once per living hauler per sweep.
///
/// THE WORK MOVED HERE FROM THE WORKERS, and that is the fix rather than a shortcut. A
/// hauler is a creature: it wanders, it picks fights, it dies, and every one of those took
/// the whole supply chain with it - chests stayed full and the tank stayed at zero with
/// nothing to point at. The nest never moves and is always exactly where the chests are.
///
/// The haulers still matter: no hauler, no hauling. They are the reason the nest can do
/// it, and they defend the chests they feed from - which is what they were always meant to
/// be doing. What they are no longer is a single point of failure for the economy.
/// </summary>
private void Haul()
{
int hands = SvermWorker.Count(SvermWorker.Job.Hauler);
if (hands <= 0) return;
float range = SvermConfigManagement.ChestRange;
foreach (Container container in Object.FindObjectsOfType<Container>())
{
if (container == null) continue;
if (Vector3.Distance(container.transform.position, transform.position) > range) continue;
Inventory inventory = container.GetInventory();
if (inventory == null) continue;
foreach (ItemDrop.ItemData item in new List<ItemDrop.ItemData>(inventory.GetAllItems()))
{
if (item == null || item.m_shared == null) continue;
if (!SvermBiomass.IsFuel(item)) continue;
float taken = SvermBiomass.Deposit(transform, item);
if (taken <= 0f) return; // tank full: leave everything where it is
inventory.RemoveItem(item, 1);
// Container.Save is private in the shipped assembly, so the write is pushed
// through reflection. Without it the chest empties on this client and refills
// from the server's copy, which reads as nothing having happened.
ZNetView cview = container.GetComponent<ZNetView>();
if (cview != null && cview.IsValid())
{
HarmonyLib.Traverse.Create(container).Method("Save").GetValue();
}
if (--hands <= 0) return;
}
}
}
/// <summary>How many beehives are already claimed by this nest. Used by the build gate.</summary>
public int CountBeehives()
{
return SvermBeehive.CountInAura(transform.position);
}
}
}

View file

@ -0,0 +1,499 @@
using System;
using System.Collections.Generic;
using HarmonyLib;
using TMPro;
using UnityEngine;
using UnityEngine.UI;
namespace RacesOfValheim
{
/// <summary>
/// What the Hive Market sells, and the column it is sold from.
///
/// THE VANILLA BUY LIST CANNOT CARRY THIS. StoreGui's own column is a list of
/// Trader.TradeItem, every one of which is an ItemDrop that lands in your inventory when you pay
/// coin for it. The hive sells no items: it sells a stage of growth, which is a number on its
/// own ZDO. So the goods hang in a column of our own, cloned from the store's list element -
/// exactly what TrolTotemStore does for its warbands, down to sitting at m_listRoot's own
/// position and switching itself off when the window belongs to somebody else.
///
/// That position matters and it is the correction of a failed attempt: the first version of the
/// hive's panel put its column at m_listRoot's position PLUS 260 px, which is outside the panel
/// that clips it. It drew perfectly and nobody could see or click a single row of it.
///
/// PRICES ARE THE DOCUMENT'S, unchanged: 1000, 1500, 2000, each one the full tank of the stage
/// it buys you out of, so growing always empties the hive.
/// </summary>
public static class SvermHiveGoods
{
/// <summary>One thing the market sells.</summary>
public class Good
{
public string Id;
public string Name;
public float Price;
public string Icon;
public string Description;
/// <summary>Why this cannot be bought right now, or null when it can.</summary>
public Func<SvermHiveBehaviour, string> Refusal;
/// <summary>Hands over the goods. Only ever called after the price has been taken.</summary>
public Action<SvermHiveBehaviour> Deliver;
/// <summary>
/// How long before another of these, in seconds. A function and not a number because the
/// upgrades wait a GAME DAY, and how long a game day is belongs to the world rather than
/// to this table.
/// </summary>
public Func<float> Cooldown;
}
/// <summary>
/// The shelf: three stages, two stars, four troops.
///
/// NO VENOM COIL. Section 13's serpent turret was built and then taken out again at the
/// player's call - it is not on this shelf, there is no prefab for it, and it is not a thing
/// waiting to be finished. If it ever comes back it comes back as a new decision.
///
/// Stages first, because they are what unlocks the rest of the list.
/// </summary>
public static readonly List<Good> Shelf = BuildShelf();
private static List<Good> BuildShelf()
{
List<Good> shelf = new List<Good>
{
StageUpgrade(2, "TrophySeeker"),
StageUpgrade(3, "TrophySeekerBrute"),
StageUpgrade(4, "TrophySeekerQueen"),
Star(1, "Surrenal Glands", 800f, "TrophySeeker",
"Every troop hatched from now on is born with one star.\n\n" +
"It does nothing for the ones already walking around: what is born is born."),
Star(2, "Hyperplasia", 1600f, "TrophySeekerQueen",
"Every troop hatched from now on is born with two stars.\n\n" +
"The colony has to have grown the glands first."),
};
foreach (SvermBrood.Kind kind in SvermBrood.Roster) shelf.Add(Troop(kind));
shelf.Add(BlisterTick());
return shelf;
}
/// <summary>
/// The bomb tick, which is the only thing on this shelf you buy ONCE and keep having.
/// Section 12: fifty biomass and an egg buy a slot, the slot is permanent, and whatever
/// stands in it comes back for free half a minute after it bursts.
/// </summary>
private static Good BlisterTick()
{
return new Good
{
Id = "blistertick",
Name = SvermBlisterTick.DisplayName,
Price = SvermConfig.TickPrice,
Icon = "TrophyTick",
Description = "Buys a PERMANENT slot in the colony. What stands in it runs at whatever " +
"the colony is fighting and bursts, and thirty seconds later the nest " +
"grows another one - no egg, no biomass, forever.\n\n" +
"The blast spares you, your tames and the rest of the colony.",
Refusal = hive =>
{
int slots = SvermBlisterTick.SlotsOf(hive.transform);
if (slots >= SvermConfigManagement.BlisterTick)
{
return $"The colony already keeps {slots} of them.";
}
if (SvermBroodEggs.Count(hive.transform) < 1) return "No brood egg ready.";
return null;
},
Deliver = hive =>
{
if (!SvermBroodEggs.Take(hive.transform, 1))
{
SvermBiomass.Refund(hive.transform, SvermConfig.TickPrice);
return;
}
SvermBlisterTick.BuySlot(hive.transform);
SvermBlisterTick.Hatch(hive);
},
// The tick has no queue of its own: the wait is the thirty seconds it takes to come
// back, and that is enforced at the nest rather than at the counter.
Cooldown = () => 0f,
};
}
/// <summary>
/// One step up the four stages. The price is the tank it empties, from section 10.1.
/// </summary>
private static Good StageUpgrade(int target, string icon)
{
int from = target - 1;
return new Good
{
Id = "stage" + target,
Name = SvermHiveStage.NameOf(target),
Price = SvermHiveStage.PriceToLeave(from),
Icon = icon,
Description = $"Grows the nest into a {SvermHiveStage.NameOf(target)}: it holds " +
$"{SvermHiveStage.Capacity(target):0} biomass instead of " +
$"{SvermHiveStage.Capacity(from):0}, and stands half again as tall.\n\n" +
"It costs this stage's whole tankful, so it leaves the hive all but " +
"empty. Grow or field an army - never both in the same breath.",
Refusal = hive =>
{
int stage = SvermHiveStage.Of(hive.transform);
if (stage > from) return "Already grown past this.";
if (stage < from) return $"The nest has to be a {SvermHiveStage.NameOf(from)} first.";
return null;
},
Deliver = hive => SvermHiveStage.Advance(hive.transform),
Cooldown = () => DayLength() * SvermConfig.UpgradeCooldownDays,
};
}
/// <summary>
/// One of the two permanent star upgrades. They are a ladder: the glands before the
/// hyperplasia.
///
/// THE LADDER IS AN INVENTION. The document prices them separately and says nothing about
/// needing one for the other - but without it the cheap path to two stars is to skip the
/// eight hundred entirely, which makes the first upgrade a thing only a mistake buys.
/// </summary>
private static Good Star(int stars, string name, float price, string icon, string description)
{
return new Good
{
Id = "stars" + stars,
Name = name,
Price = price,
Icon = icon,
Description = description,
Refusal = hive =>
{
int have = SvermBroodStars.Of(hive.transform);
if (have >= stars) return "The colony already breeds like this.";
if (have < stars - 1) return "One star at a time.";
return null;
},
Deliver = hive => SvermBroodStars.Set(hive.transform, stars),
Cooldown = () => DayLength() * SvermConfig.UpgradeCooldownDays,
};
}
/// <summary>
/// One rung of the roster on sale. Costs biomass AND a brood egg, which is section 10.2's
/// two resources in parallel: the egg is the slot and grows back, the biomass is the price
/// and does not.
/// </summary>
private static Good Troop(SvermBrood.Kind kind)
{
return new Good
{
Id = "troop_" + kind.Id,
Name = kind.Display,
Price = kind.Price,
Icon = kind.Icon,
Description = $"Hatches a {kind.Display}, bound to this nest: it follows when you ask, " +
$"walks home when you let it go, and mends itself.\n\n" +
$"Costs one brood egg as well as the biomass. At most {kind.Cap} of them alive at once.",
Refusal = hive =>
{
int stage = SvermHiveStage.Of(hive.transform);
if (stage < kind.Stage)
{
return $"The nest has to be a {SvermHiveStage.NameOf(kind.Stage)} first.";
}
int alive = SvermBrood.CountAlive(hive, kind);
if (alive >= kind.Cap) return $"The colony is already keeping {alive} of them.";
if (SvermBroodEggs.Count(hive.transform) < 1) return "No brood egg ready.";
return null;
},
Deliver = hive =>
{
// The egg is taken here rather than in Buy, because it is this good's price and
// not every good's: an upgrade costs biomass and nothing else.
//
// And if the egg is gone between the refusal check and this line - which only two
// players at one nest can manage - the biomass goes back. A purchase that took
// the price and handed over nothing is the one outcome worth writing code for.
if (!SvermBroodEggs.Take(hive.transform, 1))
{
SvermBiomass.Refund(hive.transform, kind.Price);
return;
}
if (!SvermBrood.Hatch(hive, kind))
{
SvermBiomass.Refund(hive.transform, kind.Price);
}
},
Cooldown = () => kind.Cooldown,
};
}
// ─── Buying ──────────────────────────────────────────────────────────
/// <summary>
/// Why this good is greyed out, or null when it can be bought.
///
/// The order of the questions is the order the player would ask them: can I have it at all,
/// is it too soon, can I afford it.
/// </summary>
public static string RefusalFor(Good good, SvermHiveBehaviour hive)
{
if (good == null || hive == null) return "No hive.";
string ownRefusal = good.Refusal != null ? good.Refusal(hive) : null;
if (ownRefusal != null) return ownRefusal;
long waitingSeconds = CooldownLeft(hive.transform, good);
if (waitingSeconds > 0L)
{
return waitingSeconds >= 60L
? $"The hive is still working on the last one ({waitingSeconds / 60}m)."
: $"The hive is still working on the last one ({waitingSeconds}s).";
}
if (SvermBiomass.Bank(hive.transform) < good.Price) return "Not enough biomass in the bank.";
return null;
}
public static bool Buy(Good good, SvermHiveBehaviour hive, Player player)
{
string refusal = RefusalFor(good, hive);
if (refusal != null)
{
player?.Message(MessageHud.MessageType.Center, refusal);
return false;
}
// Paid first and delivered second, and never the other way round: Spend is the only
// thing here that can fail on a race with another client, and a hive that hands over a
// stage it was not paid for cannot be undone.
if (!SvermBiomass.Spend(hive.transform, good.Price))
{
player?.Message(MessageHud.MessageType.Center, "Not enough biomass in the bank.");
return false;
}
good.Deliver?.Invoke(hive);
StampCooldown(hive.transform, good.Id);
player?.Message(MessageHud.MessageType.Center, good.Name);
return true;
}
// ─── The day between purchases ───────────────────────────────────────
/// <summary>
/// How long this good still has to wait, on the world clock.
///
/// Section 20.4 asks for two different clocks and this is both of them: a GAME DAY between
/// upgrades, and a wait of its own for every troop - ten minutes for a Gjall, the rest
/// scaled by price. On the three stage upgrades nobody will ever see it, since each of them
/// can only be bought once; on the troops it is the pacing.
/// </summary>
private static long CooldownLeft(Transform nest, Good good)
{
ZNetView nview = nest != null ? nest.GetComponent<ZNetView>() : null;
if (nview == null || !nview.IsValid()) return 0L;
long stamped = nview.GetZDO().GetLong(CooldownKey(good.Id), 0L);
if (stamped <= 0L) return 0L;
float wait = good.Cooldown != null ? good.Cooldown() : 0f;
if (wait <= 0f) return 0L;
long ready = stamped + (long)wait;
long now = WorldSecond();
return now >= ready ? 0L : ready - now;
}
private static void StampCooldown(Transform nest, string id)
{
ZNetView nview = nest != null ? nest.GetComponent<ZNetView>() : null;
if (nview == null || !nview.IsValid()) return;
if (!nview.IsOwner()) nview.ClaimOwnership();
nview.GetZDO().Set(CooldownKey(id), WorldSecond());
}
private static string CooldownKey(string id) => "RacesOfValheim_SvermBought_" + id;
/// <summary>A day of game time in seconds. The world's own setting, not a hardcoded 1800.</summary>
private static float DayLength()
{
return EnvMan.instance != null ? EnvMan.instance.m_dayLengthSec : 1800f;
}
private static long WorldSecond()
{
return ZNet.instance != null ? (long)ZNet.instance.GetTimeSeconds() : 0L;
}
}
// ─── The column ──────────────────────────────────────────────────────────
[HarmonyPatch(typeof(StoreGui), "Awake")]
public static class SvermHiveGoodsSetupPatch
{
public static void Postfix(StoreGui __instance) => SvermHiveGoodsPanel.Create(__instance);
}
[HarmonyPatch(typeof(StoreGui), "FillList")]
public static class SvermHiveGoodsFillPatch
{
public static void Postfix(StoreGui __instance) => SvermHiveGoodsPanel.Refresh(__instance);
}
[HarmonyPatch(typeof(StoreGui), "Hide")]
public static class SvermHiveGoodsHidePatch
{
public static void Postfix() => SvermHiveGoodsPanel.Clear();
}
/// <summary>
/// The market's shelf on screen. Built the way TrolTotemStore builds the war totem's, which is
/// the one column in this mod that is known to draw where a player can see it.
/// </summary>
public static class SvermHiveGoodsPanel
{
private static RectTransform _root;
private static readonly List<GameObject> _rows = new List<GameObject>();
public static void Create(StoreGui gui)
{
if (gui == null || gui.m_listRoot == null)
{
Jotunn.Logger.LogWarning("[Sverm] StoreGui has no m_listRoot; the market's shelf cannot be built.");
return;
}
if (_root != null) return;
GameObject clone = UnityEngine.Object.Instantiate(gui.m_listRoot.gameObject, gui.m_listRoot.parent);
clone.name = "SvermHiveGoodsList";
_root = clone.GetComponent<RectTransform>();
// The vanilla list's OWN position. An offset from it - 260 px was the first guess - puts
// the column outside the panel that clips it, where it draws perfectly and invisibly.
_root.anchoredPosition = gui.m_listRoot.anchoredPosition;
foreach (Transform child in _root) UnityEngine.Object.Destroy(child.gameObject);
_root.gameObject.SetActive(false);
}
public static void Clear()
{
foreach (GameObject row in _rows) if (row != null) UnityEngine.Object.Destroy(row);
_rows.Clear();
if (_root != null) _root.gameObject.SetActive(false);
}
public static void Refresh(StoreGui gui)
{
Clear();
SvermHiveBehaviour hive = SvermHiveStore.ActiveHive(gui);
if (hive == null) return; // an ordinary merchant, or the war totem. Not ours.
if (_root == null)
{
Jotunn.Logger.LogWarning("[Sverm] The market's shelf was never built (did the patch on " +
"StoreGui.Awake fail?), so nothing can be drawn into it.");
return;
}
_root.gameObject.SetActive(true);
int row = 0;
foreach (SvermHiveGoods.Good good in SvermHiveGoods.Shelf)
{
BuildRow(gui, hive, good, row++);
}
float baseSize = Traverse.Create(gui).Field("m_itemlistBaseSize").GetValue<float>();
_root.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, Mathf.Max(baseSize, row * gui.m_itemSpacing));
}
private static void BuildRow(StoreGui gui, SvermHiveBehaviour hive, SvermHiveGoods.Good good, int rowIndex)
{
GameObject element = UnityEngine.Object.Instantiate(gui.m_listElement, _root);
element.SetActive(true);
RectTransform rt = (RectTransform)element.transform;
float offset = (_root.rect.width - rt.rect.width) / 2f;
rt.anchoredPosition = new Vector2(offset, rowIndex * -gui.m_itemSpacing - offset);
string refusal = SvermHiveGoods.RefusalFor(good, hive);
bool available = refusal == null;
Sprite icon = SvermHive.BorrowIcon(good.Icon) ?? SvermHive.BorrowIcon("Honey");
Image iconImage = element.transform.Find("icon").GetComponent<Image>();
if (icon != null) iconImage.sprite = icon;
iconImage.color = available ? Color.white : Color.grey;
TMP_Text nameLabel = element.transform.Find("name").GetComponent<TMP_Text>();
nameLabel.text = good.Name;
nameLabel.color = available ? Color.white : Color.grey;
TMP_Text price = FindDescendant<TMP_Text>(element.transform, "price");
if (price != null)
{
price.text = good.Price.ToString("0");
price.color = available ? Color.white : Color.grey;
}
UITooltip tooltip = element.GetComponent<UITooltip>();
if (tooltip != null)
{
string body = available ? good.Description : refusal + "\n\n" + good.Description;
tooltip.Set(good.Name, body, gui.m_tooltipAnchor, default(Vector2));
}
Button button = element.GetComponent<Button>();
button.interactable = available;
button.onClick.AddListener(() =>
{
SvermHiveGoods.Buy(good, hive, Player.m_localPlayer);
Traverse.Create(gui).Method("FillList").GetValue(); // repaints the shelf
});
_rows.Add(element);
}
private static T FindDescendant<T>(Transform root, string childName) where T : Component
{
foreach (T candidate in root.GetComponentsInChildren<T>(true))
{
if (candidate.gameObject.name == childName) return candidate;
}
return null;
}
}
}

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -0,0 +1,109 @@
using BepInEx.Configuration;
namespace RacesOfValheim
{
/// <summary>
/// Every tunable number behind the War Vulture, bound as BepInEx ConfigEntry so it shows up in
/// Configuration Manager - same shape as TrolConfig, which is the house model for this.
///
/// The three numbers most likely to need a pass in game are deliberately here rather than in
/// code: MountSize, MountOffsetY and MountOffsetZ. Where a bird sits under a rider is the one
/// thing the last attempt lost three rounds to (section 16.6 of the design doc: measure a
/// relation, never pick a number in metres from the armchair), and a value that can be dragged
/// in the menu while standing in the world beats another compile.
///
/// No keybind is bound here on purpose. The mount answers to LEFT CLICK on the item and to the
/// vanilla run key, so there is nothing new to learn and nothing new to rebind.
/// </summary>
public static class WarVultureConfig
{
// ─── Access ────────────────────────────────────────────────────────────
public static ConfigEntry<string> AllowedRaces;
// ─── Flight ────────────────────────────────────────────────────────────
public static ConfigEntry<float> CruiseSpeed;
public static ConfigEntry<float> SprintSpeed;
public static ConfigEntry<float> SprintSeconds;
public static ConfigEntry<float> RechargeSeconds;
public static ConfigEntry<float> LandingSpeed;
// ─── Model ─────────────────────────────────────────────────────────────
public static ConfigEntry<float> HandModelScale;
public static ConfigEntry<float> MountSize;
public static ConfigEntry<string> SeatBone;
public static ConfigEntry<float> SeatNudgeY;
public static ConfigEntry<float> SeatNudgeZ;
// ─── Interface ─────────────────────────────────────────────────────────
public static ConfigEntry<bool> ShowStaminaBar;
public static void Bind(ConfigFile config)
{
const string access = "War Vulture - Access";
AllowedRaces = config.Bind(access, "Allowed races", "Furling,Dvergar",
new ConfigDescription("Comma separated list of race ids that can call the vulture. " +
"In anyone else's hands the item is an inert trophy on a stick. " +
"Leave empty to let every race ride."));
const string flight = "War Vulture - Flight";
// 7 and 13 are not proposals: they are m_flySlowSpeed and m_flyFastSpeed read off the
// vanilla Volture at runtime (design doc 15.13). A number read from the game survives a
// Valheim patch; a number invented here does not.
CruiseSpeed = config.Bind(flight, "Cruise speed", 7f,
new ConfigDescription("Metres per second with the run key up. This one is unlimited - " +
"vultures stay up for hours."));
SprintSpeed = config.Bind(flight, "Sprint speed", 13f,
new ConfigDescription("Metres per second while the run key is held and the bird still " +
"has wind in it."));
SprintSeconds = config.Bind(flight, "Sprint seconds", 10f,
new ConfigDescription("How long full speed lasts before the bird drops back to cruise."));
RechargeSeconds = config.Bind(flight, "Recharge seconds", 10f,
new ConfigDescription("How long a spent bird takes to fill up again. It recharges in the " +
"air as soon as the run key is released - landing is not required."));
LandingSpeed = config.Bind(flight, "Landing speed", 12f,
new ConfigDescription("Metres per second of the automatic descent after the dismount " +
"click. The controls are ignored until the ground arrives."));
const string model = "War Vulture - Model";
HandModelScale = config.Bind(model, "Hand model scale", 0.6f,
new ConfigDescription("Size of the vulture trophy carried in hand, as a fraction of the " +
"real trophy. 0.6 is the 40% smaller that was asked for."));
MountSize = config.Bind(model, "Mount size", 7.75f,
new ConfigDescription("Largest dimension of the bird under the rider, in metres. 7.75 is " +
"the vanilla Volture's own mesh, wings included."));
// The rider is glued to a BONE, not to a height: the bird's back rises and falls with
// every wingbeat, and any offset in metres can only be right on one frame of that.
SeatBone = config.Bind(model, "Seat bone", "",
new ConfigDescription("Name (or part of a name) of the bone on the vulture's skeleton the " +
"rider sits on. Empty picks the last spine/chest bone automatically, " +
"which is what the bird actually flies with."));
SeatNudgeY = config.Bind(model, "Seat nudge Y", 0f,
new ConfigDescription("Fine adjustment up (+) or down (-) from the seat bone, in metres. " +
"Zero means exactly on the bone."));
SeatNudgeZ = config.Bind(model, "Seat nudge Z", 0f,
new ConfigDescription("Fine adjustment forward (+) or back (-) from the seat bone, in metres."));
const string ui = "War Vulture - Interface";
ShowStaminaBar = config.Bind(ui, "Show stamina bar", true,
new ConfigDescription("Draws the bird's own wind as a bar under the player's stamina, " +
"cloned from vanilla's mount stamina bar."));
}
/// <summary>
/// Whether a race id may call the bird. An empty list means everyone, which is the honest
/// reading of "no restriction" and is also what makes this testable on any character.
/// </summary>
public static bool RaceAllowed(string race)
{
string list = AllowedRaces != null ? AllowedRaces.Value : null;
if (string.IsNullOrEmpty(list)) return true;
if (string.IsNullOrEmpty(race)) return false;
foreach (string entry in list.Split(','))
{
if (entry.Trim().Equals(race.Trim(), System.StringComparison.OrdinalIgnoreCase)) return true;
}
return false;
}
}
}

View file

@ -0,0 +1,116 @@
using System.Reflection;
using HarmonyLib;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The bird's wind, as a bar under the player's stamina.
///
/// It is a CLONE of vanilla's own mount stamina bar, not a bar drawn from scratch, for two
/// reasons: it is already skinned, sized and animated like every other bar in the game, and it
/// is semantically the same thing - Hud.UpdateMount drives that bar from Sadle.GetStamina for
/// the asksvin. Ours is the same idea with a different animal underneath.
///
/// Vanilla's copy cannot simply be borrowed where it stands: Hud.UpdateMount switches the whole
/// mount panel off on every frame in which the player is not on a Sadle, and it would take the
/// bar with it. The clone is reparented out of that panel, so vanilla never touches it again.
///
/// Everything here is reflection because GuiBar lives in assembly_guiutils, which this project
/// does not reference - and adding a reference to the csproj is a bigger change than a bar is
/// worth. Every step is null-checked: a bar that fails to build costs the bar and nothing else,
/// which is the right trade for an ornament on a flying mount.
/// </summary>
public class WarVultureHud
{
private const float BelowStaminaPixels = 24f;
private readonly WarVultureMount mount;
private readonly GameObject barObject;
private readonly Component guiBar;
private readonly MethodInfo setValue;
private WarVultureHud(WarVultureMount mount, GameObject barObject, Component guiBar, MethodInfo setValue)
{
this.mount = mount;
this.barObject = barObject;
this.guiBar = guiBar;
this.setValue = setValue;
}
public static WarVultureHud Create(WarVultureMount mount)
{
Hud hud = Hud.instance;
if (hud == null) return null;
Component template = Traverse.Create(hud).Field("m_mountStaminaBar").GetValue<Component>();
RectTransform staminaRoot = hud.m_staminaBar2Root;
if (template == null || staminaRoot == null || staminaRoot.parent == null)
{
Jotunn.Logger.LogWarning("[WarVulture] The vanilla mount stamina bar or the stamina bar root " +
"could not be found, so the bird flies without a gauge.");
return null;
}
GameObject clone = Object.Instantiate(template.gameObject, staminaRoot.parent);
clone.name = "WarVultureWindBar";
// Anchored off the stamina bar rather than off the screen: the stamina bar moves with
// the player's HUD layout, and anything positioned against the screen would drift away
// from it the moment that layout changes.
RectTransform rect = clone.GetComponent<RectTransform>();
if (rect != null)
{
rect.anchorMin = staminaRoot.anchorMin;
rect.anchorMax = staminaRoot.anchorMax;
rect.pivot = staminaRoot.pivot;
rect.anchoredPosition = staminaRoot.anchoredPosition + new Vector2(0f, -BelowStaminaPixels);
rect.localScale = staminaRoot.localScale;
}
clone.SetActive(true);
Component bar = clone.GetComponent("GuiBar");
MethodInfo setter = bar != null
? bar.GetType().GetMethod("SetValue", new[] { typeof(float) })
: null;
if (setter == null)
{
Jotunn.Logger.LogWarning("[WarVulture] The cloned bar has no GuiBar.SetValue(float) to drive, " +
"so it would have sat there full forever; it was removed.");
Object.Destroy(clone);
return null;
}
TintBrown(bar);
return new WarVultureHud(mount, clone, bar, setter);
}
/// <summary>
/// Optional, and treated as such: if GuiBar ever loses SetColor the bar simply keeps
/// vanilla's colour instead of costing an exception every summon.
/// </summary>
private static void TintBrown(Component bar)
{
MethodInfo setColor = bar.GetType().GetMethod("SetColor", new[] { typeof(Color) });
if (setColor == null) return;
setColor.Invoke(bar, new object[] { new Color(0.72f, 0.55f, 0.32f, 1f) });
}
public void Refresh()
{
if (barObject == null || guiBar == null || setValue == null) return;
if (mount == null) return;
setValue.Invoke(guiBar, new object[] { mount.WindFraction });
}
public void Dispose()
{
if (barObject != null) Object.Destroy(barObject);
}
}
}

View file

@ -0,0 +1,309 @@
using HarmonyLib;
using Jotunn.Entities;
using Jotunn.Managers;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The War Vulture item: a Dead Raiser with the skeleton taken out of it and a vulture trophy
/// hung in its place. Clicked, it puts the player on a flying bird; clicked again, it brings
/// them down and takes the bird away.
///
/// Why a staff and not a trinket: the game lets a WEAPON be used without any trickery. Cloning
/// StaffSkeleton buys the click, the cast gesture and the effects for free - which is exactly
/// the reasoning that produced Skadis Nokkel, whose file this one was written as a twin of. The
/// Nokkel has since been removed - it opened a portal pair, which broke in multiplayer - so this
/// file is now the only copy of that pattern and there is no sibling to keep it in step with.
///
/// Three things are removed from the vanilla staff, and each is removed TWICE on purpose:
/// - the eitr, health and stamina costs are zeroed on the clone AND forced to zero in the
/// getters every cost check flows through (WarVultureFreeCastPatch). The eitr cost is not
/// cosmetic: it is checked BEFORE the attack starts, so a player without eitr would never
/// reach the code that summons;
/// - the summon is nulled on the clone AND the attack trigger itself is taken over, so
/// vanilla's spawn code is not merely defused but unreachable (WarVultureCastPatch);
/// - the staff's model is replaced by the trophy under the item's "attach" child, which is
/// the ONLY child VisEquipment draws - a model hung anywhere else is present, correct and
/// invisible (design doc 15.11, half an hour paid for once already).
/// </summary>
public static class WarVultureItem
{
public const string PrefabName = "WarVulture";
public const string DisplayName = "War Vulture";
private const string SourcePrefab = "StaffSkeleton";
private const string TrophyPrefab = "TrophyVolture";
private const string Label = "WarVulture";
public static void Register()
{
GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(PrefabName, SourcePrefab);
if (prefab == null)
{
Jotunn.Logger.LogWarning($"[{Label}] Could not clone {SourcePrefab}; {DisplayName} not registered.");
return;
}
ItemDrop drop = prefab.GetComponent<ItemDrop>();
if (drop == null || drop.m_itemData == null || drop.m_itemData.m_shared == null)
{
Jotunn.Logger.LogWarning($"[{Label}] {SourcePrefab} clone has no usable ItemDrop; {DisplayName} not registered.");
return;
}
ItemDrop.ItemData.SharedData shared = drop.m_itemData.m_shared;
shared.m_name = DisplayName;
shared.m_description = "A vulture's head, kept. Raise it and the bird comes back under you, " +
"and it will carry you as long as you care to stay up - though it only " +
"has so much haste in it before it settles into a glide.";
shared.m_useDurability = false;
// ItemType is left exactly as the vanilla staff has it: it decides the equip slot and
// which animation set the arms use, and the cast gesture is the whole reason this is a
// staff rather than a trinket.
Strip(shared);
SwapHandModel(prefab);
ItemManager.Instance.AddItem(new CustomItem(prefab, fixReference: false));
// Built HERE and not at the summon, and the comment on WarVultureVisual explains why in
// full: this is a context where components may be destroyed immediately, and the summon
// is not. Getting that wrong once put a live Ashlands predator in the player's world.
WarVultureVisual.BuildTemplate();
// No recipe, on purpose and for now: the item is spawned from the console
// ("spawn WarVulture") while the flight is being proven. A recipe costs nothing to add
// later and would only be materials invented before anyone knows what this is worth.
Jotunn.Logger.LogInfo($"[{Label}] {DisplayName} registered: no eitr, no health, no stamina, no skeleton.");
}
/// <summary>
/// Takes the skeleton staff apart. Every field is zeroed on BOTH attacks, because the
/// secondary is a separate Attack carrying its own copy of every cost.
///
/// The summon hangs off a SpawnAbility on a prefab referenced by the attack, and WHICH
/// field carries it is not knowable from the game files - so all three candidates go.
/// Nulling three fields that might each be the culprit costs nothing; guessing wrong costs
/// a skeleton on every click.
///
/// The animation is the one thing deliberately left alone. It is the whole point: the
/// player raises the trophy, and the bird answers.
/// </summary>
private static void Strip(ItemDrop.ItemData.SharedData shared)
{
StripAttack(shared.m_attack);
StripAttack(shared.m_secondaryAttack);
}
private static void StripAttack(Attack attack)
{
if (attack == null) return;
attack.m_attackEitr = 0f;
attack.m_drawEitrDrain = 0f;
attack.m_reloadEitrDrain = 0f;
attack.m_attackHealth = 0f;
attack.m_attackHealthPercentage = 0f;
attack.m_attackHealthLowBlockUse = false;
attack.m_attackHealthReturnHit = 0f;
attack.m_attackStamina = 0f;
attack.m_drawStaminaDrain = 0f;
attack.m_reloadStaminaDrain = 0f;
attack.m_attackProjectile = null;
attack.m_spawnOnTrigger = null;
attack.m_spawnOnHit = null;
attack.m_spawnOnHitChance = 0f;
}
/// <summary>
/// Puts the vulture trophy in the hand where the staff's model was.
///
/// "attach" is not a name picked for tidiness: VisEquipment instantiates that child and
/// nothing else, so this is the only place a held model can live.
///
/// The size is a MULTIPLIER rather than a measurement in metres, which is the opposite of
/// what ModelBorrow does and is right here for one reason: the brief was "the trophy, 40%
/// smaller". The trophy's own size is the measurement; 0.6 is the relation applied to it.
/// </summary>
private static void SwapHandModel(GameObject prefab)
{
Transform attach = FindChild(prefab.transform, "attach");
if (attach == null)
{
Jotunn.Logger.LogWarning($"[{Label}] The {SourcePrefab} clone has no 'attach' child, so the " +
"held model was left as the vanilla staff. VisEquipment draws " +
"nothing else, so there was nowhere else to put it.");
return;
}
GameObject trophy = PrefabManager.Cache.GetPrefab<GameObject>(TrophyPrefab);
if (trophy == null)
{
Jotunn.Logger.LogWarning($"[{Label}] No '{TrophyPrefab}' to borrow; the item keeps the " +
"skeleton staff's look.");
return;
}
// The old staff mesh goes first, or the hand holds both.
for (int i = attach.childCount - 1; i >= 0; i--)
{
Object.DestroyImmediate(attach.GetChild(i).gameObject);
}
foreach (Renderer renderer in attach.GetComponents<Renderer>())
{
if (renderer != null) Object.DestroyImmediate(renderer);
}
// Instantiate into a holder that is ALREADY INACTIVE - the one line ModelBorrow exists
// for. A trophy is an ItemDrop, and Instantiate runs Awake first: waking one for a
// single frame drops a real trophy on the floor.
GameObject holder = new GameObject("WarVultureTrophy");
holder.transform.SetParent(attach, false);
holder.SetActive(false);
GameObject copy = Object.Instantiate(trophy, holder.transform);
copy.name = "model";
copy.transform.localPosition = Vector3.zero;
copy.transform.localRotation = Quaternion.identity;
copy.transform.localScale = Vector3.one * WarVultureConfig.HandModelScale.Value;
StripToMeshesOnly(copy);
holder.SetActive(true);
}
/// <summary>
/// The trophy reduced to nothing but its shape.
///
/// This used to be a BLACKLIST - scripts, colliders, rigidbodies, ZNetView - and it let
/// through exactly what a blacklist always lets through: the things nobody thought to name.
/// A vanilla item prefab carries the sparkle that makes dropped loot findable in long grass,
/// and that lives in ParticleSystems, ParticleSystemRenderers and Lights. None of those is a
/// MonoBehaviour, so all of them survived, and the item glittered in the player's hand like
/// something they had just thrown away.
///
/// So it is a whitelist now, the same shape as WarVultureVisual's: MeshFilter,
/// MeshRenderer, SkinnedMeshRenderer, Transform. Note it is deliberately NARROWER than the
/// mount's whitelist - "Renderer" would be wrong here, because ParticleSystemRenderer IS a
/// Renderer and it is half of what we are trying to be rid of.
///
/// Passes, because Unity refuses to destroy a component another one still requires, and the
/// refusal only unblocks once the dependent is gone.
/// </summary>
private static void StripToMeshesOnly(GameObject copy)
{
for (int pass = 0; pass < 6; pass++)
{
bool destroyedSomething = false;
foreach (Component component in copy.GetComponentsInChildren<Component>(true))
{
if (component == null) continue;
if (component is Transform) continue;
if (component is MeshFilter) continue;
if (component is MeshRenderer) continue;
if (component is SkinnedMeshRenderer) continue;
Object.DestroyImmediate(component);
if (component == null) destroyedSomething = true;
}
if (!destroyedSomething) break;
}
}
private static Transform FindChild(Transform root, string name)
{
if (root.name == name) return root;
for (int i = 0; i < root.childCount; i++)
{
Transform found = FindChild(root.GetChild(i), name);
if (found != null) return found;
}
return null;
}
public static bool IsWarVulture(ItemDrop.ItemData item)
{
return item != null && item.m_dropPrefab != null && item.m_dropPrefab.name == PrefabName;
}
/// <summary>
/// True when a cost being asked about belongs to this item.
///
/// The fallback on the equipped weapon is necessary rather than belt-and-braces: the cost
/// getters are called from Attack.Start and m_weapon is not guaranteed to be assigned yet.
/// It is only consulted when m_weapon is null, so a creature's own attack cannot be zeroed
/// just because the player happens to be holding the trophy at the time.
/// </summary>
public static bool IsWarVultureContext(ItemDrop.ItemData weapon)
{
if (weapon != null) return IsWarVulture(weapon);
Player local = Player.m_localPlayer;
return local != null && IsWarVulture(local.GetCurrentWeapon());
}
}
/// <summary>
/// The click. Attack.OnAttackTrigger is used rather than Attack.Start because it takes NO
/// parameters - its signature cannot drift - and it fires when the animation reaches its
/// release point, which is when a summon should land.
///
/// A Prefix returning FALSE, so for this item vanilla's attack-trigger code never runs at all.
/// m_weapon and m_character are private on Attack and arrive through Harmony's triple
/// underscore injection, which is checked at patch time: a rename becomes a startup error
/// instead of a silent null on every click.
/// </summary>
[HarmonyPatch(typeof(Attack), "OnAttackTrigger")]
public static class WarVultureCastPatch
{
public static bool Prefix(ItemDrop.ItemData ___m_weapon, Humanoid ___m_character)
{
if (!WarVultureItem.IsWarVulture(___m_weapon)) return true;
// Still returns false while riding, so vanilla's trigger never runs - but the dismount
// is NOT taken from here. In the saddle this event is unreliable: the cast clip loses
// to the sitting pose before its event fires. WarVultureMount reads the button itself.
WarVultureMount.Toggle(___m_character as Player);
return false;
}
}
/// <summary>
/// The item costs nothing, guaranteed.
///
/// Zeroing the fields on the clone ought to be enough by every reading of the game's own code.
/// On the Skadi staff the cost came back in game anyway, which means the write to a clone's
/// SharedData does not survive something - so relying on it alone is relying on a mechanism
/// already observed to fail. These three getters are the single funnel every cost check flows
/// through: Attack.Start asks them before it will start, and the tooltip asks them for what to
/// print. All three are private and take no parameters, so they are addressed by name.
/// </summary>
[HarmonyPatch]
public static class WarVultureFreeCastPatch
{
[HarmonyTargetMethods]
private static System.Collections.Generic.IEnumerable<System.Reflection.MethodBase> TargetMethods()
{
yield return AccessTools.Method(typeof(Attack), "GetAttackEitr");
yield return AccessTools.Method(typeof(Attack), "GetAttackHealth");
yield return AccessTools.Method(typeof(Attack), "GetAttackStamina");
}
[HarmonyPostfix]
private static void Postfix(ItemDrop.ItemData ___m_weapon, ref float __result)
{
if (__result == 0f) return;
if (!WarVultureItem.IsWarVultureContext(___m_weapon)) return;
__result = 0f;
}
}
}

View file

@ -0,0 +1,389 @@
using HarmonyLib;
using Jotunn.Managers;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The ride itself. Lives on the local player while they are mounted, and nowhere else.
///
/// THE ONE IDEA THIS FILE IS BUILT ON: the PLAYER flies, the bird is how it looks from outside.
/// That inversion is what makes a flying mount a small feature instead of a large one - it
/// removes the ZDO owner problem, the AI, the taming, the passivity and the whole saddle, all
/// of which cost a session each the first time round. The flight itself is the Aswid's bat
/// form: Player.m_debugFly, and nothing else.
///
/// THE ONE TRAP: a real attach and a self-driven player are enemies in vanilla, and the game
/// says so twice.
/// - Player.SetControls: if the player is attached, has no doodad controller and presses ANY
/// movement key, vanilla calls AttachStop. That is how you stand up from a chair.
/// - Player.SetDoodadControlls: giving it a doodad controller instead is worse - it zeroes
/// moveDir, run and autoRun unconditionally after handing them to the controller, so the
/// rider could not move at all.
/// Both were read out of the assembly, not guessed. The way through is the third door: the
/// attach point is the PLAYER'S OWN TRANSFORM, so Player.UpdateAttach - which copies position
/// and rotation from the attach point every frame, and would otherwise nail the rider in place
/// - provably copies the player onto themselves and does nothing. The bird hangs off the
/// player, not the other way round. The one remaining conflict, the AttachStop above, is
/// switched off for the duration in WarVultureControlsPatch.
///
/// What the attach is still there FOR, after all that, is the pose: AttachStart ends with
/// m_zanim.SetBool(attachAnimation, true), and ZSyncAnimation replicates it - so every other
/// player sees the rider sitting, for free, with no code of ours involved.
/// </summary>
public class WarVultureMount : MonoBehaviour
{
/// <summary>The ZDO flag other clients watch to know they should draw a bird under this player.</summary>
public const string MountedKey = "WarVulture_Mounted";
private const string Label = "WarVulture";
private const string HolderName = "WarVultureMountModel";
/// <summary>How long after the summon a click is ignored, so one press cannot do both.</summary>
private const float ClickGuardSeconds = 0.6f;
/// <summary>The one live mount. There is at most one: this is the local player's own ride.</summary>
public static WarVultureMount Active { get; private set; }
private Player player;
private WarVultureRig rig;
private Transform seat;
private WarVultureHud hud;
private float wind; // seconds of full speed left in the bird
private bool landing; // dismount asked for; coming down before it takes effect
private float landingStartedAt;
private float summonedAt;
// ---------------------------------------------------------------- public surface
public static bool IsRiding(Player candidate)
{
return Active != null && candidate != null && Active.player == candidate;
}
/// <summary>Fraction of the bird's wind left, for the bar. 1 = fresh, 0 = spent.</summary>
public float WindFraction
{
get
{
float max = Mathf.Max(0.01f, WarVultureConfig.SprintSeconds.Value);
return Mathf.Clamp01(wind / max);
}
}
/// <summary>
/// The SUMMON, and only the summon. Called from WarVultureCastPatch, which has already
/// established that the thing being swung is ours and that the player is not already up.
///
/// The dismount used to come through here too, and it did not work: the click fires
/// Attack.OnAttackTrigger, which the game raises from an animation event partway through
/// the cast clip - and in the saddle that clip loses to the sitting pose before it ever
/// gets there. The rider was trapped in the air with a click that did nothing. The dismount
/// is now read straight off the button in Update, where no animation can swallow it.
/// </summary>
public static void Toggle(Player caster)
{
if (caster == null || caster != Player.m_localPlayer) return;
if (Active != null && Active.player == caster) return;
Summon(caster);
}
/// <summary>
/// The dismount button, read from the device rather than from the animation.
///
/// RaceInput.Allowed is the same gate every ability in this mod uses, and it is here for a
/// reason worth remembering: it reads Player.TakeInput, which is FALSE while the console is
/// open. A dismount that "does not work" during a test session is usually the console.
/// </summary>
private static bool DismountPressed()
{
if (!RaceInput.Allowed) return false;
return ZInput.GetButtonDown("Attack") || ZInput.GetButtonDown("JoyAttack");
}
// ---------------------------------------------------------------- summon
private static void Summon(Player rider)
{
string race = null;
if (rider.m_customData != null) rider.m_customData.TryGetValue("Race", out race);
if (!WarVultureConfig.RaceAllowed(race))
{
rider.Message(MessageHud.MessageType.Center, "The bird does not know you.");
return;
}
if (!WarVultureVisual.Ready)
{
rider.Message(MessageHud.MessageType.Center, "The vulture does not answer.");
Jotunn.Logger.LogWarning($"[{Label}] Call refused: the stripped model template was never built, " +
"so there is no bird to show. The reason is logged at startup - and " +
"refusing is deliberate, because the alternative is putting an unstripped " +
"creature prefab in the world.");
return;
}
ZNetView nview = rider.GetComponent<ZNetView>();
if (nview == null || !nview.IsValid())
{
Jotunn.Logger.LogWarning($"[{Label}] Call refused: the player has no valid ZNetView yet, so " +
"the flight state could not be published and no one else would see " +
"the bird.");
return;
}
WarVultureMount mount = rider.gameObject.AddComponent<WarVultureMount>();
mount.player = rider;
mount.Begin(nview);
}
private void Begin(ZNetView nview)
{
Active = this;
summonedAt = Time.time;
wind = WarVultureConfig.SprintSeconds.Value;
// No lift, and that is the point: the rider is not raised above anything. The bird is
// moved so that its BACK BONE arrives under the rider, every frame, in WarVultureRig.
rig = WarVultureVisual.Spawn(player.transform, HolderName);
Seat();
SetFlying(nview, true);
nview.GetZDO().Set(MountedKey, true);
if (WarVultureConfig.ShowStaminaBar.Value) hud = WarVultureHud.Create(this);
}
/// <summary>
/// The attach, and the reason it is harmless: the seat is a child of the player sitting
/// exactly on the player's own origin, so UpdateAttach's every-frame "put the rider on the
/// attach point" is the identity.
///
/// The pose string is READ from the lox's own Sadle rather than typed from memory - the
/// same rule as prefab names, applied to an animation.
///
/// hideWeapons is false on purpose: hiding the hand items unequips them, and the item in
/// that hand is the only way back down.
/// </summary>
private void Seat()
{
seat = new GameObject("WarVultureSeat").transform;
seat.SetParent(player.transform, false);
seat.localPosition = Vector3.zero;
seat.localRotation = Quaternion.identity;
player.AttachStart(seat, null, false, false, false, ReadSaddlePose(), Vector3.zero, null);
}
private static string ReadSaddlePose()
{
GameObject lox = PrefabManager.Cache.GetPrefab<GameObject>("Lox");
Sadle sadle = lox != null ? lox.GetComponentInChildren<Sadle>(true) : null;
if (sadle != null && !string.IsNullOrEmpty(sadle.m_attachAnimation)) return sadle.m_attachAnimation;
Jotunn.Logger.LogWarning($"[{Label}] Could not read the lox saddle's attach animation; " +
"falling back to 'attach_chair'. The rider may sit oddly.");
return "attach_chair";
}
// ---------------------------------------------------------------- per frame
private void Update()
{
if (player == null || player != Player.m_localPlayer) { Dismount(); return; }
if (player.IsDead()) { Dismount(); return; }
ZNetView nview = player.GetComponent<ZNetView>();
if (nview == null || !nview.IsValid())
{
// Not an ordinary way down: the rider's own networking went away mid-flight, so it
// is worth a line even though the dismount itself is silent.
Jotunn.Logger.LogWarning($"[{Label}] The rider's ZNetView went away mid-flight; dismounting.");
Dismount();
return;
}
// Held on every frame rather than set once: the same thing BatFormBehavior does, for
// the same reason - anything else in the game (or in this mod) that clears debug fly
// would otherwise drop the rider out of the sky without a word.
SetFlying(nview, true);
DriveAnimator();
// The guard is not superstition: the summoning click is still physically down on the
// frame the mount is created, and without it the bird would be called and dismissed by
// the same press.
if (Time.time - summonedAt > ClickGuardSeconds && DismountPressed())
{
// A second click during the descent lets go there and then.
if (landing) Dismount();
else BeginLanding();
return;
}
if (landing) UpdateLanding();
if (hud != null) hud.Refresh();
}
private void DriveAnimator()
{
if (rig == null) return;
Vector3 velocity = player.GetVelocity();
rig.Drive(new Vector3(velocity.x, 0f, velocity.z).magnitude);
}
/// <summary>
/// The descent. The rider's own controls are not disabled - they are simply overruled in
/// ApplyFlight, which writes the velocity last and therefore wins.
/// </summary>
private void BeginLanding()
{
landing = true;
landingStartedAt = Time.time;
player.Message(MessageHud.MessageType.Center, "The vulture spirals down.");
}
private void UpdateLanding()
{
Vector3 position = player.transform.position;
float floor = -10000f;
if (ZoneSystem.instance != null)
{
// Over open water the solid height is the seabed, which would mean a long swim
// down. The surface is the floor there.
floor = Mathf.Max(ZoneSystem.instance.GetSolidHeight(position), ZoneSystem.instance.m_waterLevel);
}
if (position.y - floor <= 0.6f) { Dismount(); return; }
// A descent that never ends is worse than a hard landing: if the ground cannot be
// found at all, let go anyway rather than trap the rider in a falling animation.
if (Time.time - landingStartedAt > 20f)
{
Jotunn.Logger.LogWarning($"[{Label}] The descent found no ground in 20s; letting go anyway.");
Dismount();
}
}
// ---------------------------------------------------------------- flight, called from the physics step
/// <summary>
/// Called from WarVultureFlightPatch, right after vanilla's UpdateDebugFly has written the
/// rider's velocity for this physics step.
///
/// Speed is applied as a FACTOR on what vanilla just computed rather than as a fresh
/// velocity, and that is deliberate: vanilla lerps towards its target, so scaling the
/// result keeps every bit of its smoothing - the ramp up, the ease off, the standstill at
/// zero input - and only changes how fast the whole thing runs. Writing a velocity of our
/// own would have thrown all of that away.
///
/// The wind is spent here, in the physics step, because this is the only place that knows
/// the rider is actually flying.
/// </summary>
public void ApplyFlight(bool runHeld, ref Vector3 currentVelocity, Rigidbody body)
{
float dt = Time.fixedDeltaTime;
if (landing)
{
currentVelocity = Vector3.down * WarVultureConfig.LandingSpeed.Value;
if (body != null) body.linearVelocity = currentVelocity;
return;
}
bool sprinting = runHeld && wind > 0f && currentVelocity.sqrMagnitude > 0.01f;
if (sprinting)
{
wind = Mathf.Max(0f, wind - dt);
if (wind <= 0f)
{
player.Message(MessageHud.MessageType.Center, "The vulture settles into a glide.");
}
}
else if (wind < WarVultureConfig.SprintSeconds.Value)
{
// Refills in the air the moment the run key is released. A vulture can stay up for
// hours; what it cannot do is keep stooping.
float perSecond = WarVultureConfig.SprintSeconds.Value /
Mathf.Max(0.01f, WarVultureConfig.RechargeSeconds.Value);
wind = Mathf.Min(WarVultureConfig.SprintSeconds.Value, wind + perSecond * dt);
}
float wanted = sprinting ? WarVultureConfig.SprintSpeed.Value : WarVultureConfig.CruiseSpeed.Value;
// What vanilla aimed for this step: m_debugFlySpeed, times 2.5 when the run key is
// down. Read from the game rather than assumed, so a Valheim retune cannot silently
// double our speeds.
float vanilla = WarVultureFlightPatch.DebugFlySpeed * (runHeld ? 2.5f : 1f);
if (vanilla <= 0.01f) return;
currentVelocity *= wanted / vanilla;
if (body != null) body.linearVelocity = currentVelocity;
}
// ---------------------------------------------------------------- dismount
private void Dismount()
{
Player rider = player;
if (rider != null)
{
ZNetView nview = rider.GetComponent<ZNetView>();
if (nview != null && nview.IsValid())
{
SetFlying(nview, false);
nview.GetZDO().Set(MountedKey, false);
}
else
{
// No ZDO to write to, but the local field still has to come off or the player
// keeps flying on foot.
Traverse.Create(rider).Field("m_debugFly").SetValue(false);
}
rider.AttachStop();
}
if (hud != null) { hud.Dispose(); hud = null; }
// Destroy, never DestroyImmediate: a dismount can be a click, which arrives from an
// animation event callback where immediate destruction is refused. The whole reason
// this feature had a live vulture in it once.
if (rig != null) { Destroy(rig.gameObject); rig = null; }
if (seat != null) { Destroy(seat.gameObject); seat = null; }
if (Active == this) Active = null;
Destroy(this);
}
private void OnDestroy()
{
// Belt and braces for a component torn off by something other than Dismount (a scene
// change, a reload). Leaving debug fly on would be the worst possible parting gift.
if (Active != this) return;
Active = null;
if (player == null) return;
Traverse.Create(player).Field("m_debugFly").SetValue(false);
}
/// <summary>
/// Both halves of debug fly. The field is what the local rider's own physics reads; the ZDO
/// var is what every OTHER client reads (Character.IsDebugFlying consults the ZDO when it
/// is not the owner). BatFormBehavior only ever wrote the field, which is why a bat looked
/// wrong to everyone else - this writes both.
/// </summary>
private void SetFlying(ZNetView nview, bool flying)
{
Traverse.Create(player).Field("m_debugFly").SetValue(flying);
nview.GetZDO().Set(ZDOVars.s_debugFly, flying);
}
}
}

View file

@ -0,0 +1,193 @@
using System.Reflection;
using HarmonyLib;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The one patch that makes a seated player able to fly.
///
/// Player.SetControls opens with: if the player is attached and presses any movement key, and
/// there is no doodad controller, call AttachStop. That is vanilla's "stand up from the chair",
/// read straight out of the assembly - and against a rider who drives themselves it fires on
/// the first tap of W.
///
/// Giving the game a doodad controller instead is not the way out: SetDoodadControlls zeroes
/// moveDir, run and autoRun unconditionally afterwards, so the rider would stay attached and
/// be unable to move. Both doors are shut, which is why this one is a patch.
///
/// So m_attached is lifted for the duration of SetControls and put straight back. Nothing else
/// in that method reads it (checked instruction by instruction), and everything else in the
/// game still sees an attached player - including ZSyncAnimation, which is what keeps the
/// sitting pose on everyone else's screen.
///
/// AND THE SECOND HALF, added after the first flight. Lifting m_attached hands the rider back
/// every action a standing player has, and three of them have no business happening in a
/// saddle: jump, dodge and crouch each played their own animation for half a second before the
/// sitting pose snapped back, which is what a rider trying to gain height actually saw.
///
/// They are suppressed here, at the source, and it costs nothing that was wanted: vanilla's
/// UpdateDebugFly does NOT read these arguments. It reads ZInput directly - GetButton("Jump")
/// to climb and KeyCode.LeftControl to descend - so taking them out of SetControls removes the
/// jump and keeps the climb. Same for the click: while riding, the dismount is read straight
/// off ZInput in WarVultureMount, so the attack is suppressed here rather than left to fight
/// the saddle pose for an animation it was never going to win.
///
/// It costs one boolean read per frame when nobody is riding.
/// </summary>
[HarmonyPatch(typeof(Player), "SetControls")]
public static class WarVultureControlsPatch
{
public static void Prefix(Player __instance, ref bool ___m_attached,
ref bool attack, ref bool attackHold,
ref bool secondaryAttack, ref bool secondaryAttackHold,
ref bool jump, ref bool crouch, ref bool dodge,
out bool __state)
{
__state = false;
if (!WarVultureMount.IsRiding(__instance)) return;
attack = false;
attackHold = false;
secondaryAttack = false;
secondaryAttackHold = false;
jump = false;
crouch = false;
dodge = false;
if (!___m_attached) return;
___m_attached = false;
__state = true;
}
public static void Postfix(ref bool ___m_attached, bool __state)
{
if (__state) ___m_attached = true;
}
}
/// <summary>
/// The speed of the ride, and the bird's wind.
///
/// Character.UpdateDebugFly has just written this physics step's velocity when this runs, so
/// this is the last word on it. The mount scales what vanilla computed rather than replacing
/// it - see WarVultureMount.ApplyFlight for why that keeps the flight feeling smooth.
///
/// m_currentVel, m_body and m_run are all private on Character and arrive through Harmony's
/// field injection, which is verified when the patch is applied: a Valheim rename becomes a
/// startup error instead of a mount that silently stops working.
/// </summary>
[HarmonyPatch(typeof(Character), "UpdateDebugFly")]
public static class WarVultureFlightPatch
{
private static readonly FieldInfo DebugFlySpeedField = AccessTools.Field(typeof(Character), "m_debugFlySpeed");
private static bool warnedAboutSpeedField;
/// <summary>
/// Vanilla's own debug fly speed, read live rather than cached: the game exposes it as a
/// static that can be retuned, and a stale copy here would quietly scale the whole ride.
/// </summary>
public static float DebugFlySpeed
{
get
{
if (DebugFlySpeedField != null) return System.Convert.ToSingle(DebugFlySpeedField.GetValue(null));
if (!warnedAboutSpeedField)
{
warnedAboutSpeedField = true;
Jotunn.Logger.LogWarning("[WarVulture] Character.m_debugFlySpeed could not be found, so the " +
"mount's speeds are being scaled against an assumed 10 m/s. If the " +
"bird flies wrong, this line is why.");
}
return 10f;
}
}
public static void Postfix(Character __instance, ref Vector3 ___m_currentVel, Rigidbody ___m_body, bool ___m_run)
{
WarVultureMount mount = WarVultureMount.Active;
if (mount == null) return;
Player player = __instance as Player;
if (player == null || !WarVultureMount.IsRiding(player)) return;
mount.ApplyFlight(___m_run, ref ___m_currentVel, ___m_body);
}
}
/// <summary>
/// Gives every player a watcher, so a rider on someone else's screen gets a bird under them.
///
/// A second Player.Awake postfix alongside the one in ZdoVisualSync rather than an edit to it:
/// that file belongs to the shared race visuals, this belongs to the vulture, and Harmony is
/// perfectly happy to hold both.
/// </summary>
[HarmonyPatch(typeof(Player), "Awake")]
public static class WarVulturePlayerAwakePatch
{
public static void Postfix(Player __instance)
{
if (__instance.GetComponent<WarVultureRemoteVisual>() == null)
{
__instance.gameObject.AddComponent<WarVultureRemoteVisual>();
}
}
}
/// <summary>
/// The bird as everyone ELSE sees it.
///
/// The rider's own client draws its bird from WarVultureMount; this draws one for every other
/// player who has the flag set on their ZDO. It never touches flight, attachment or input -
/// remote players are moved by their own owner and the pose replicates itself through
/// ZSyncAnimation, so there is nothing here but a model that appears and disappears.
/// </summary>
public class WarVultureRemoteVisual : MonoBehaviour
{
private const string HolderName = "WarVultureRemoteModel";
private Player player;
private WarVultureRig rig;
private void Awake()
{
player = GetComponent<Player>();
}
private void Update()
{
if (player == null) return;
// The local rider is drawn by their own mount; two birds is one too many.
if (player == Player.m_localPlayer) { Hide(); return; }
ZNetView nview = player.GetComponent<ZNetView>();
if (nview == null || !nview.IsValid()) { Hide(); return; }
bool mounted = nview.GetZDO().GetBool(WarVultureMount.MountedKey, false) && !player.IsDead();
if (mounted && rig == null) rig = WarVultureVisual.Spawn(player.transform, HolderName);
else if (!mounted && rig != null) Hide();
if (rig != null)
{
Vector3 velocity = player.GetVelocity();
rig.Drive(new Vector3(velocity.x, 0f, velocity.z).magnitude);
}
}
private void Hide()
{
if (rig == null) return;
Destroy(rig.gameObject);
rig = null;
}
private void OnDestroy()
{
Hide();
}
}
}

View file

@ -0,0 +1,376 @@
using UnityEngine;
using Jotunn.Managers;
namespace RacesOfValheim
{
/// <summary>
/// The bird's body: built dead once, then copied.
///
/// WHY IT IS BUILT AT REGISTRATION AND NOT AT THE SUMMON. The first version borrowed the model
/// the way ModelBorrow does it - instantiate into an inactive holder, then DestroyImmediate
/// everything that is not a renderer. That is correct at registration time and wrong at summon
/// time, and the game says so out loud:
///
/// Destroying components immediately is not permitted during physics trigger/contact,
/// animation event callbacks, rendering callbacks or OnValidate.
///
/// The summon runs from Attack.OnAttackTrigger, which the game calls from CharacterAnimEvent -
/// an animation event callback. Every DestroyImmediate was refused, the model kept its
/// Character, its MonsterAI and its ZNetView, and the moment the holder was switched on Awake
/// ran and a real Ashlands predator was born under the player. A live rigidbody ignores its
/// parent transform, so it flew off. Eleven refusal lines sat in the log directly above the
/// "Borrowed 'Volture'" line, which is exactly how it was found.
///
/// So: the stripping happens once, during CreateAllModAssets, where DestroyImmediate is legal.
/// What is kept is a TEMPLATE - an inactive, script-free carcass held in DontDestroyOnLoad -
/// and a summon is a plain Instantiate of it. Instantiate is allowed in any context.
///
/// And it is CHECKED, not assumed. If a single MonoBehaviour survives the strip, the template
/// is thrown away and the item refuses to summon. A bird that does not appear is a bug report;
/// a bird that appears with an AI is a predator in the player's world with a saved ZDO.
/// </summary>
public static class WarVultureVisual
{
private const string SourcePrefab = "Volture";
private const string Label = "WarVulture";
// The three parameters DrakeFormBehavior drives, which is the only animated borrowed
// creature in this mod known to look right.
private const string FlyingParam = "flying";
private const string GroundParam = "onGround";
private const string SpeedParam = "forward_speed";
private static GameObject template;
private static float templateSize = 1f;
public static bool Ready => template != null;
// ---------------------------------------------------------------- the template
/// <summary>
/// Called once from WarVultureItem.Register, i.e. from CreateAllModAssets, i.e. from a
/// context where components may be destroyed immediately.
/// </summary>
public static void BuildTemplate()
{
if (template != null) return;
GameObject source = PrefabManager.Cache.GetPrefab<GameObject>(SourcePrefab);
if (source == null)
{
Jotunn.Logger.LogWarning($"[{Label}] No '{SourcePrefab}' prefab to copy; the mount will refuse " +
"to summon rather than put an invisible rider in the sky.");
return;
}
// Inactive BEFORE the Instantiate - the one line that keeps Awake from running on a
// live predator. Everything else here depends on it.
GameObject root = new GameObject("WarVultureTemplate");
root.SetActive(false);
Object.DontDestroyOnLoad(root);
GameObject copy = Object.Instantiate(source, root.transform);
copy.name = "VoltureModel";
copy.transform.localPosition = Vector3.zero;
copy.transform.localRotation = Quaternion.identity;
copy.transform.localScale = Vector3.one;
int refused = StripToRenderers(copy);
int alive = CountBehaviours(copy);
if (alive > 0)
{
Jotunn.Logger.LogError($"[{Label}] {alive} script(s) survived the strip on '{SourcePrefab}' " +
$"({refused} destroy calls were refused). The template is being thrown " +
"away and the War Vulture will not summon - a half-stripped creature " +
"prefab is a live animal, not a model.");
Object.DestroyImmediate(root);
return;
}
PrepareAnimator(copy);
templateSize = Mathf.Max(0.01f, LargestDimension(copy));
template = copy;
}
/// <summary>
/// Everything that is not geometry or animation, removed in passes.
///
/// Passes rather than one sweep because Unity refuses to destroy a component another
/// component still requires, and the refusal is silent as far as the caller is concerned -
/// it logs and moves on. Repeating until a pass changes nothing lets a dependency chain
/// unwind in whatever order it needs to.
///
/// Returns how many destroy calls were refused on the last pass, purely so the failure
/// above can say something useful.
/// </summary>
private static int StripToRenderers(GameObject copy)
{
int stubborn = 0;
for (int pass = 0; pass < 6; pass++)
{
bool destroyedSomething = false;
stubborn = 0;
foreach (Component component in copy.GetComponentsInChildren<Component>(true))
{
if (component == null) continue;
if (IsKept(component)) continue;
Object.DestroyImmediate(component);
if (component == null) destroyedSomething = true;
else stubborn++;
}
if (!destroyedSomething) break;
}
return stubborn;
}
/// <summary>
/// The whitelist. Anything not on it goes - colliders, rigidbodies, ZNetView, Character,
/// MonsterAI, the lot. Keeping a list of what to KEEP rather than a list of what to remove
/// is the difference between a model and an animal: a new component in a future Valheim
/// patch is removed by default instead of surviving by omission.
///
/// The two MESH renderers by name rather than Renderer as a family, which looks like
/// pedantry and is not: ParticleSystemRenderer is a Renderer, and "keep every Renderer" is
/// how the trophy in the player's hand ended up carrying the sparkle vanilla puts on
/// dropped loot. Meshes and the animator that poses them - nothing else.
/// </summary>
private static bool IsKept(Component component)
{
return component is Transform
|| component is MeshFilter
|| component is MeshRenderer
|| component is SkinnedMeshRenderer
|| component is Animator
|| component is LODGroup;
}
private static int CountBehaviours(GameObject copy)
{
int alive = 0;
foreach (MonoBehaviour behaviour in copy.GetComponentsInChildren<MonoBehaviour>(true))
{
if (behaviour != null) alive++;
}
return alive;
}
/// <summary>
/// Three settings, each preventing one specific failure rather than tidying anything.
///
/// applyRootMotion: clips authored to walk a creature through the world would walk the
/// model out from under its rider.
///
/// cullingMode: the default stops animating when no renderer is on screen, and this bird
/// lives half off the bottom of the screen - a frozen mid-flap reads as a bug.
///
/// fireEvents: the flight clips carry animation events aimed at CharacterAnimEvent, which
/// has just been stripped off. Left on, every wingbeat would log "has no receiver".
/// </summary>
private static void PrepareAnimator(GameObject copy)
{
Animator animator = copy.GetComponentInChildren<Animator>(true);
if (animator == null)
{
Jotunn.Logger.LogWarning($"[{Label}] The stripped '{SourcePrefab}' has no Animator, so the bird " +
"will hang in its bind pose - wings out, legs straight.");
return;
}
animator.applyRootMotion = false;
animator.cullingMode = AnimatorCullingMode.AlwaysAnimate;
animator.fireEvents = false;
animator.enabled = true;
}
// ---------------------------------------------------------------- summoning a copy
/// <summary>
/// Hangs a copy of the template under a rider and returns the rig that keeps it there.
/// Null when the template could not be built, which the caller must treat as "do not
/// summon" rather than "summon an invisible bird".
/// </summary>
public static WarVultureRig Spawn(Transform rider, string holderName)
{
if (template == null || rider == null) return null;
GameObject holder = new GameObject(holderName);
holder.transform.SetParent(rider, false);
holder.transform.localPosition = Vector3.zero;
holder.transform.localRotation = Quaternion.identity;
GameObject model = Object.Instantiate(template, holder.transform);
model.name = "model";
model.transform.localPosition = Vector3.zero;
model.transform.localRotation = Quaternion.identity;
model.transform.localScale = Vector3.one * (WarVultureConfig.MountSize.Value / templateSize);
model.SetActive(true);
WarVultureRig rig = holder.AddComponent<WarVultureRig>();
rig.Bind(rider, model);
return rig;
}
// ---------------------------------------------------------------- animation
/// <summary>
/// One frame of flight, told to the animator. Any parameter this controller does not have
/// is skipped, so a Valheim animator rename costs a stiff-looking bird rather than a wall
/// of errors every frame.
/// </summary>
public static void Drive(Animator animator, float forwardSpeed)
{
if (animator == null || animator.runtimeAnimatorController == null) return;
if (Has(animator, FlyingParam, AnimatorControllerParameterType.Bool)) animator.SetBool(FlyingParam, true);
if (Has(animator, GroundParam, AnimatorControllerParameterType.Bool)) animator.SetBool(GroundParam, false);
if (Has(animator, SpeedParam, AnimatorControllerParameterType.Float)) animator.SetFloat(SpeedParam, forwardSpeed);
}
private static bool Has(Animator animator, string name, AnimatorControllerParameterType type)
{
foreach (AnimatorControllerParameter parameter in animator.parameters)
{
if (parameter.type == type && parameter.name == name) return true;
}
return false;
}
// ---------------------------------------------------------------- the seat bone
/// <summary>
/// The bone the rider sits on.
///
/// A bone rather than an offset in metres, because that is the difference between sitting
/// on the bird and hovering above it: the back moves with every wingbeat, and a fixed
/// offset can only ever be right on one frame of the animation.
///
/// The name is guessed from a priority list and can be overridden in config, because the
/// rig's bone names are not knowable from outside the game. The automatic pick was the right
/// one in play, so the startup dump that found it has been retired.
/// </summary>
public static Transform FindSeatBone(GameObject model)
{
if (model == null) return null;
Transform[] bones = model.GetComponentsInChildren<Transform>(true);
string wanted = WarVultureConfig.SeatBone.Value;
if (!string.IsNullOrEmpty(wanted))
{
Transform named = Match(bones, wanted);
if (named != null) return named;
Jotunn.Logger.LogWarning($"[{Label}] No bone matching '{wanted}' on the vulture; falling back " +
"to the automatic pick. The bone list is in the log from startup.");
}
// Deliberately in this order: the back of a bird is its spine and chest, and the hips
// and root are last-ditch so that SOMETHING is anchored rather than nothing.
foreach (string candidate in new[] { "spine", "chest", "back", "torso", "body", "pelvis", "hip", "root" })
{
Transform found = Match(bones, candidate);
if (found != null) return found;
}
return null;
}
/// <summary>
/// Last match rather than first, on purpose: rigs number their spines outward from the
/// hips, so the last "spine" is the one furthest along the back - which is where a saddle
/// goes, not where the tail joins.
/// </summary>
private static Transform Match(Transform[] bones, string needle)
{
Transform best = null;
foreach (Transform bone in bones)
{
if (bone.name.IndexOf(needle, System.StringComparison.OrdinalIgnoreCase) >= 0) best = bone;
}
return best;
}
// ---------------------------------------------------------------- measuring
private static float LargestDimension(GameObject model)
{
bool any = false;
Bounds bounds = new Bounds();
foreach (Renderer renderer in model.GetComponentsInChildren<Renderer>(true))
{
Mesh mesh = renderer is SkinnedMeshRenderer skinned
? skinned.sharedMesh
: renderer.GetComponent<MeshFilter>()?.sharedMesh;
if (mesh == null) continue;
Bounds local = mesh.bounds;
Matrix4x4 toModel = model.transform.worldToLocalMatrix * renderer.transform.localToWorldMatrix;
for (int corner = 0; corner < 8; corner++)
{
Vector3 point = toModel.MultiplyPoint3x4(local.center + new Vector3(
(corner & 1) == 0 ? -local.extents.x : local.extents.x,
(corner & 2) == 0 ? -local.extents.y : local.extents.y,
(corner & 4) == 0 ? -local.extents.z : local.extents.z));
if (!any) { bounds = new Bounds(point, Vector3.zero); any = true; }
else bounds.Encapsulate(point);
}
}
return any ? Mathf.Max(bounds.size.x, Mathf.Max(bounds.size.y, bounds.size.z)) : 1f;
}
}
/// <summary>
/// Keeps the bird under its rider, one bone at a time.
///
/// In LateUpdate, after the animator has posed the skeleton for this frame, the whole model is
/// slid so that the seat bone lands exactly on the rider's own origin. That is what "sitting on
/// the bird's back" means as a piece of code, and it is why there is no height offset anywhere
/// in this feature any more: the back tells us where it is, every frame, including while it
/// rises and falls with the wingbeat.
///
/// Shared by the rider's own copy and by the copy other players see, so the bird cannot sit in
/// two different places depending on who is looking.
/// </summary>
public class WarVultureRig : MonoBehaviour
{
private Transform rider;
private Transform model;
private Transform seatBone;
private Animator animator;
public void Bind(Transform rider, GameObject model)
{
this.rider = rider;
this.model = model.transform;
seatBone = WarVultureVisual.FindSeatBone(model);
animator = model.GetComponentInChildren<Animator>(true);
}
public void Drive(float forwardSpeed)
{
WarVultureVisual.Drive(animator, forwardSpeed);
}
private void LateUpdate()
{
if (rider == null || model == null) return;
Vector3 seat = rider.position + rider.rotation * new Vector3(
0f, WarVultureConfig.SeatNudgeY.Value, WarVultureConfig.SeatNudgeZ.Value);
if (seatBone != null) model.position += seat - seatBone.position;
else model.position = seat;
}
}
}