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