Merge pull request 'add-dvergar-color-and-skeleton-menu' (#14) from add-dvergar-color-and-skeleton-menu into main

Reviewed-on: #14
This commit is contained in:
kanym 2026-08-05 22:08:38 +02:00
commit 10e0485540
7 changed files with 661 additions and 8 deletions

View file

@ -51,6 +51,108 @@ namespace RacesOfValheim
// Dvergr are white-haired. The hood hides most of it, but the beard shows.
public static readonly Color HairColor = new Color(0.85f, 0.87f, 0.92f, 1f);
// ─── Star colours ────────────────────────────────────────────────────
// A starred dverger is not a different model: Valheim recolours the same one with a
// LevelEffects component, whose LevelSetup list carries a hue/saturation/value offset per
// star and an optional emissive colour for the eyes. Setup 0 is one star, setup 1 is two.
//
// Nothing here hardcodes a colour. The offsets are read off the creature prefab at
// runtime, so the race ages into exactly the tints the game itself uses - and follows
// them if a patch ever changes them.
public const int OneStarState = 4; // Bonemass
public const int TwoStarState = 8; // Fader
// Those offsets are authored against a dverger's own texture. Ours is a multiplier over
// the human skin, where white means "no tint at all" - so an offset that brightens and
// desaturates far enough lands on white and hands back an ordinary pink human. That is
// exactly what the two-star tier did. These bounds keep every tier recognisably the same
// colour, shifted rather than washed out.
public const float StarMinSaturation = 0.25f;
public const float StarMinValue = 0.20f;
public const float StarMaxValue = 0.85f;
// Two stars is hand-picked rather than derived, because the derivation cannot express
// what it is asking for. A multiplier can darken a texture and it can bias a texture, but
// it cannot desaturate one: the pink is in the human skin map, and multiplying by grey
// keeps every bit of it, only dimmer. So the two-star tier says "stone" the only way this
// channel can - dark, and cold enough to sit on top of the pink rather than under it.
//
// To tune: raise all three together for a lighter dvergr, and widen the gap between R and
// B for a colder one. Keeping R below B is what holds the flesh tone down.
public static readonly Color TwoStarSkinColor = new Color(0.34f, 0.37f, 0.44f, 1f);
// ─── Glowing eyes ────────────────────────────────────────────────────
// A player's eyes are painted into the skin texture, and Custom/Player has no emission
// channel to light them with - so a Dvergar wears two small emissive quads over them
// instead. Nothing else in the mod does this, so there was no working example to copy;
// the Aswid's red eyes were never built at all, only cleaned up.
//
// Metres from the head bone, which sits at the base of the skull, along the player's own
// forward and up. The eyes are parented to that bone, so all of this rides the head
// animation, and every offset scales with the race.
//
// Do not reintroduce Character.m_eye as a starting point. It reads like the right
// reference and is not: it is where the camera goes, half a metre above the head bone,
// and starting from it put the eyes in the treetops. That was measured, not guessed -
// the trace is in the commit history.
// These are pre-scale numbers: a Dvergar renders at 0.78, so 0.105 forward lands about
// 0.082m out from the bone at the base of the skull.
//
// EyeForward has less room than it looks, and both ends of it are measured rather than
// guessed: 0.067 buries the eyes completely behind the face, 0.140 stands them off the
// skull in profile. 0.105 is the far end of what still reads as inset.
//
// The eye is a large ball buried deep, not a small one balanced on the surface. What shows
// is the slice of it that breaks the face - a spherical cap - so the face itself decides
// the shape and the glow can never float off the cheek. Push the centre in to shrink the
// cap, pull it out to grow one.
//
// Sized off two measurements. At a centre of 82mm with an 8mm radius the eyes were
// visible; at 74mm with the same radius they were gone. So the face sits about 86mm from
// the head bone. All values here are pre-scale - a Dvergar renders at 0.78.
//
// The cap grows far faster than the depth that makes it, and faster still on a big ball:
// a 30mm radius clearing the face by 9mm showed a 43mm cap, most of a face. Radius is
// halved for that reason - it does not only shrink the cap, it halves how violently the
// cap answers to a millimetre of depth, which is the difference between tuning this and
// fighting it. 15mm of radius clearing by 4mm gives about 20mm of eye.
// Depth and radius move together. The centre can only go deeper if the ball grows to
// reach the face from further back - sink one without the other and the eye is simply
// gone, since at a 15mm radius it cleared the face by 2mm and had nothing to spare.
//
// So a centimetre further in is a centimetre more radius: centre ~63mm out, radius ~24mm,
// still clearing by about 2mm. Same size of eye, sitting deeper, and the cap is flatter
// for it - which is what reads as set into the skull rather than resting on it.
public static readonly float EyeSeparation = 0.032f; // half the distance between them
public static readonly float EyeForward = 0.081f; // centre ~63mm out
public static readonly float EyeHeight = 0.181f; // ~15mm lower than before
public static readonly float EyeSize = 0.062f; // ~48mm across, so a 24mm radius
// How hard the eyes burn. The colours the game gives a starred dverger are HDR - one star
// is (0, 4, 3.3) - and anything past 1 clips to white on the way to the bloom pass, which
// is why the centres read as white lamps rather than as teal. Scaling them down brings
// the colour back as much as it lowers the brightness.
public static readonly float EyeGlowStrength = 0.3f;
// Applied to the model's left eye alone - the one on your right as you look at it.
//
// The two are placed symmetrically and do not come out symmetrical, because the face they
// emerge through is not flat: nearer the midline the skull juts forward, nearer the temple
// it falls away, so a ball that meets the receding side shows more of itself. With a 24mm
// radius spanning that curve the difference is a visible few millimetres of cap. Rather
// than shrink both and lose the socket depth, the one that comes out proud is taken down
// on its own.
//
// If the wrong eye shrinks, the sideways axis resolved the other way round: apply this to
// index 1 in PlaceEyes instead of index 0.
public static readonly float LeftEyeSizeMultiplier = 0.85f;
// Base glow, before any star. The tiers replace it with the emissive colours the game
// itself gives a starred dverger - RGBA(0, 4, 3.3) at one star and RGBA(12, 0, 8.8) at
// two, both far past 1, which is exactly what makes them bloom rather than just look
// bright.
public static readonly Color BaseEyeColor = new Color(0f, 2.2f, 1.8f, 1f);
// ─── Cosmetic hood ───────────────────────────────────────────────────
// The helmet slot itself stays free — whatever the player equips keeps all of its stats,
// only the mesh is swapped.

View file

@ -339,11 +339,23 @@ namespace RacesOfValheim
if (__instance == null || !__instance.m_isPlayer) return;
Player player = __instance.GetComponent<Player>();
if (player == null || !DvergarVisuals.IsDvergarPlayer(player)) return;
if (player == null) return;
// Before the race check, because it takes the eyes off anyone who has stopped
// being a Dvergar as well as putting them on anyone who is one. Here rather than
// in the UpdateVisuals postfix so that the tier refresh DvergarRace forces on a
// boss kill recolours them at the same moment it recolours the skin.
DvergarVisuals.ApplyEyes(player);
if (!DvergarVisuals.IsDvergarPlayer(player)) return;
if (__instance.m_bodyModel != null && __instance.m_bodyModel.material != null)
{
__instance.m_bodyModel.material.SetColor("_SkinColor", DvergarConfig.SkinColor);
// Not the flat config colour any more: it carries the star shift a dverger of
// this standing would wear, so the race visibly ages at Bonemass and again at
// Fader.
__instance.m_bodyModel.material.SetColor("_SkinColor", DvergarVisuals.GetSkinColor(player));
}
TintRenderers(Traverse.Create(__instance).Field("m_hairItemInstance").GetValue<GameObject>());

View file

@ -18,6 +18,7 @@ namespace RacesOfValheim
// NaN so that the very first frame always counts as a change and pushes the malus through.
private float lastAppliedMalus = float.NaN;
private int lastAppliedStarTier = -1;
private void Awake()
{
@ -68,6 +69,10 @@ namespace RacesOfValheim
DvergarVisuals.ApplyHood(player);
// Every frame, because the eyes are placed onto the head bone in world space rather
// than parented to it - see ApplyEyes for why.
DvergarVisuals.ApplyEyes(player);
// Max health is recomputed by Player.UpdateFood, which runs on its own schedule. Left
// to itself the malus would only take effect at the next food tick, so a change of
// race or of tier is pushed through immediately - this is also what makes the health
@ -101,6 +106,18 @@ namespace RacesOfValheim
nview.GetZDO().Set(DvergarConfig.StateZdoKey, state);
}
// The skin tint is only written from the UpdateColors postfix, which Valheim runs on
// its own schedule - so crossing into a new star tier would otherwise not show until
// something else happened to refresh the visuals. Push one through, the same way the
// health malus above pushes a food update.
int starTier = DvergarVisuals.GetStarTier(state);
if (starTier != lastAppliedStarTier)
{
lastAppliedStarTier = starTier;
VisEquipment visEq = player.GetComponent<VisEquipment>();
if (visEq != null) Traverse.Create(visEq).Method("UpdateColors").GetValue();
}
DvergarAbilities.Tick(player, state);
}
}

View file

@ -47,6 +47,443 @@ namespace RacesOfValheim
public static bool IsDvergarPlayer(Player player) => GetPlayerRace(player) == DvergarConfig.RaceId;
// ─── Star colours ────────────────────────────────────────────────────
// Read once per session, failure included.
private static LevelEffects.LevelSetup[] cachedStarSetups;
private static bool starSetupsResolved;
/// <summary>
/// How many stars the Dvergar's colouring has earned: one at Bonemass, two at Fader.
/// </summary>
public static int GetStarTier(int state)
{
if (state >= DvergarConfig.TwoStarState) return 2;
if (state >= DvergarConfig.OneStarState) return 1;
return 0;
}
/// <summary>
/// The skin tint for a player at their current standing: the race's own slate blue-grey,
/// shifted by the hue/saturation/value offsets a real dverger of that star count wears.
///
/// Valheim does not give a starred creature a different model or a different colour - it
/// gives the same material an HSV offset through LevelEffects. Reading those offsets off
/// the creature prefab rather than picking two colours by eye means the tiers land on the
/// exact tints the game uses, and keeps following them if the prefab ever changes.
/// </summary>
public static Color GetSkinColor(Player player)
{
int tier = GetStarTier(GetProgressionState(player));
// Two stars stops deriving and states a colour outright. The creature's own two-star
// offset brightens and desaturates, which through a multiplier over the human skin
// texture means "tint it less" - and landed the tier a shade away from ordinary
// flesh, which is the opposite of what two stars should read as. Stone grey says it
// in the one language a multiplier speaks.
if (tier >= 2) return DvergarConfig.TwoStarSkinColor;
LevelEffects.LevelSetup setup = GetStarSetup(tier);
if (setup == null) return DvergarConfig.SkinColor;
return ShiftHsv(DvergarConfig.SkinColor, setup.m_hue, setup.m_saturation, setup.m_value);
}
/// <summary>
/// The tier this particular Dvergar should be coloured for. DvergarRace publishes it to
/// the ZDO every frame, so a remote player is shown at their own standing rather than the
/// observer's - which matters the moment anyone runs personal progression. Falls back to
/// this client's own reckoning when there is no ZDO, which is the main-menu preview.
/// </summary>
private static int GetProgressionState(Player player)
{
ZNetView nview = player != null ? player.GetComponent<ZNetView>() : null;
if (nview != null && nview.IsValid())
{
int published = nview.GetZDO().GetInt(DvergarConfig.StateZdoKey, 0);
if (published > 0) return published;
}
return BossProgressionManager.GetCurrentProgressionState();
}
// ─── Glowing eyes ────────────────────────────────────────────────────
private const string EyesName = "DvergarEyes";
/// <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.
/// </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>
/// Keeps two small emissive quads sitting over the player's painted-on eyes, coloured by
/// star tier. Safe to call for anyone: it removes them again from whoever is not a living
/// Dvergar. Call it every frame - it builds once and then only follows the head.
///
/// The holder hangs off the player root, which is unscaled, and is placed onto the head
/// bone in world space each frame. That is deliberate. Parenting straight to the head
/// bone would drag in the 100x scale the armature is authored at, and parenting to
/// Character.m_eye - the first attempt - put them outside the scaled rig entirely, which
/// is why they floated above a shrunken Dvergar and turned with the camera instead of the
/// face. Reading the bone's position and the player's facing sidesteps both.
/// </summary>
public static void ApplyEyes(Player player)
{
if (player == null) return;
Transform headBone = FindHeadBone(player);
if (headBone == null) return; // rig not up yet; try again next frame
Transform eyes = headBone.Find(EyesName);
if (!IsDvergarPlayer(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(player, headBone);
if (eyes == null) return; // already logged once by the resolver
PlaceEyes(player, headBone, eyes);
Color glow = GetEyeColor(player);
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);
}
}
/// <summary>
/// The head bone the body mesh is actually skinned to.
///
/// Not the Animator's. Asking the avatar for HumanBodyBones.Head returned a transform that
/// moves with the player but is not the one the head animation drives - which is why the
/// eyes tracked the body faithfully and ignored every idle bob of the head while being
/// parented to it, a thing a child transform cannot otherwise do. The rest of this mod has
/// always taken the head off VisEquipment.m_bodyModel.bones, the array the skinned mesh
/// deforms with, and that is the rig that moves.
/// </summary>
private static Transform FindHeadBone(Player player)
{
VisEquipment visEq = player.GetComponent<VisEquipment>();
if (visEq != null && visEq.m_bodyModel != null && visEq.m_bodyModel.bones != null)
{
Transform bone = FindBoneByName(visEq.m_bodyModel.bones, DvergarConfig.PlayerHeadBoneName);
if (bone != null) 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;
}
/// <summary>The scale the race is currently rendering its body at; 1 for anyone not resized.</summary>
private static float GetVisualScale(Player player)
{
GameObject visual = Traverse.Create(player).Field("m_visual").GetValue<GameObject>();
return visual != null ? visual.transform.localScale.x : 1f;
}
/// <summary>
/// One star and two stars use the emissive colours the game gives a starred dverger, read
/// off the same LevelSetup list the skin tint comes from. Only the base tier is ours.
/// </summary>
private static Color GetEyeColor(Player player)
{
LevelEffects.LevelSetup setup = GetStarSetup(GetStarTier(GetProgressionState(player)));
Color glow = setup != null && setup.m_setEmissiveColor
? setup.m_emissiveColor
: DvergarConfig.BaseEyeColor;
// Dimmed on the way out. Alpha is left alone - it is not part of the brightness.
float strength = DvergarConfig.EyeGlowStrength;
return new Color(glow.r * strength, glow.g * strength, glow.b * strength, glow.a);
}
/// <summary>
/// Puts the two eyes where the face is, in the head bone's own coordinates, every frame.
///
/// The placement is measured rather than guessed. Character.m_eye is the game's own answer
/// to "where are this player's eyes", and asking the head bone to express that point in
/// its local space gives an offset that is correct by construction - no working out which
/// way the bone points, no hand-picked distance from the base of the skull. Being local,
/// it then rides every head animation for free.
///
/// The config offsets stay, as small adjustments in metres on top of that measurement.
/// </summary>
private static void PlaceEyes(Player player, Transform headBone, Transform holder)
{
float lossy = headBone.lossyScale.x;
if (Mathf.Abs(lossy) < 0.0001f) return;
Transform root = player.transform;
// Metres -> the head bone's local units, which the armature authors at roughly 100x.
float toLocal = 1f / lossy;
// Read back, never recomputed. Deriving these from the player root every frame is
// what kept the eyes from turning with the head: as the head rotates,
// InverseTransformDirection returns a direction rotated by exactly the opposite
// amount, so the offset counter-rotated and cancelled the head's own movement out.
// The eyes moved with the head and never turned with it, which is precisely what it
// looked like. Measured once at build time, they are fixed in the skull's frame and
// ride every animation for free.
EyeFrame frame = holder.GetComponent<EyeFrame>();
if (frame == null) return;
Vector3 localForward = frame.LocalForward;
Vector3 localUp = frame.LocalUp;
Vector3 localRight = frame.LocalRight;
// Measured from the head bone itself, and from nothing else.
//
// The previous version started from Character.m_eye, on the reasoning that it is the
// game's own answer to where a player's eyes are. It is not - it is where the camera
// goes, and the trace showed it sitting 0.51m straight above the head bone. That half
// metre was the entire drift: the offsets below are under a centimetre in local units
// and never stood a chance of mattering next to it.
float raceScale = GetVisualScale(player);
Vector3 baseLocal = localForward * (DvergarConfig.EyeForward * raceScale * toLocal)
+ localUp * (DvergarConfig.EyeHeight * raceScale * toLocal);
float eyeLocalSize = DvergarConfig.EyeSize * raceScale * 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 - the
// one on your right as you face it. It gets its own size, because the face is
// curved and the two sides do not present the same surface to a ball of this
// radius.
float side = i == 0 ? -1f : 1f;
float size = i == 0 ? eyeLocalSize * DvergarConfig.LeftEyeSizeMultiplier : eyeLocalSize;
eye.localPosition = baseLocal + localRight * (side * DvergarConfig.EyeSeparation * raceScale * toLocal);
eye.localScale = Vector3.one * size;
}
}
/// <summary>
/// Rounds a direction to the nearest of the six axis directions. Whichever component is
/// largest wins, 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));
}
private static Transform BuildEyes(Player player, Transform headBone)
{
Shader glow = ResolveGlowShader();
if (glow == null) return null;
// Straight onto the head bone, with no rotation of its own: everything underneath is
// expressed in the bone's own local space by PlaceEyes, so position and rotation are
// inherited from the skull rather than recomputed against the body.
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 then round the answer to the skull's own
// axes. The raw measurement is taken at whatever pose the head happens to be in on
// this frame, so it arrives tilted: a "forward" leaning 20 degrees down put the eyes
// at the jaw instead of the eye line. A bone's real axes are square, and the tilt is
// nothing but the pose at the moment of asking, so it is rounded away.
Transform root = player.transform;
EyeFrame frame = holder.AddComponent<EyeFrame>();
frame.LocalForward = SnapToAxis(headBone.InverseTransformDirection(root.forward));
frame.LocalUp = SnapToAxis(headBone.InverseTransformDirection(root.up));
// Right is derived, never snapped. Rounding all three independently guarantees
// nothing about the angles between them, and a "right" that shares an axis with
// forward stops being sideways: the separation then pushes one eye out of the face
// and pulls the other into it, which is one eye sitting proud of a forehead while its
// twin sits correctly. A cross product cannot be anything but perpendicular.
frame.LocalRight = Vector3.Cross(frame.LocalUp, frame.LocalForward).normalized;
for (int i = 0; i < 2; i++)
{
float side = i == 0 ? -1f : 1f;
// Spheres, not quads. A quad has no thickness: seen edge-on it is a line and the
// eyes vanish, which is why they 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;
// A primitive comes with a collider, which on a player's face would be its own
// kind of bug.
foreach (Collider collider in eye.GetComponents<Collider>())
{
Object.Destroy(collider);
}
// Position and size are PlaceEyes' business, and it runs immediately after this.
eye.transform.SetParent(holder.transform, false);
eye.transform.localPosition = Vector3.zero;
eye.transform.localRotation = Quaternion.identity;
eye.transform.localScale = Vector3.zero;
Renderer renderer = eye.GetComponent<Renderer>();
renderer.material = new Material(glow);
renderer.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off;
renderer.receiveShadows = false;
}
return holder.transform;
}
/// <summary>
/// Finds a shader that will render a flat colour past 1 so the bloom pass picks it up.
/// Unity strips shaders nothing references, so this asks for several and reports which one
/// the game actually shipped rather than assuming.
///
/// Opaque first, deliberately. The first version took Sprites/Default, which is a
/// transparent shader with depth writing switched off - so the eyes drew over the head
/// from angles that should have hidden them, and were visible from behind because it also
/// disables backface culling. An unlit opaque shader is occluded by the skull like any
/// other solid thing, which is the whole point of putting them in the face.
/// </summary>
private static Shader ResolveGlowShader()
{
if (glowShaderResolved) return cachedGlowShader;
glowShaderResolved = true;
string[] candidates = { "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($"[Dvergar] Eye glow shader resolved to '{name}'.");
cachedGlowShader = shader;
return cachedGlowShader;
}
Jotunn.Logger.LogWarning(
"[Dvergar] No glow shader resolved (" + string.Join(", ", candidates) + "); eyes stay unlit.");
return null;
}
// ─── Shader survey ───────────────────────────────────────────────────
// What the player's body material can be asked to do, surveyed once and recorded here
// rather than logged every session:
//
// Custom/Player, 13 properties, of which exactly one is a colour - _SkinColor.
// No _Hue, no _Saturation, no _Value, no _Brightness, no _Grayscale.
//
// Which settles why a pale Dvergar is out of reach, and settles it as a property of the
// shader rather than of the numbers anyone picks. A real dverger goes pale at two stars
// through saturation -1 on the creature shader, which genuinely desaturates its texture.
// The player body has no such control: _SkinColor multiplies the human skin map, and a
// multiply can darken or bias but never desaturate - the pink is in the texture and
// survives being multiplied by grey. White is the multiplier's identity, so "paler" and
// "more human" are the same direction, which is what every attempt walked into.
//
// Getting there would mean replacing _MainTex with a desaturated copy of the skin texture,
// a per-player blit through a custom shader. Disproportionate for a cosmetic tier.
private static LevelEffects.LevelSetup GetStarSetup(int tier)
{
if (tier <= 0) return null;
LevelEffects.LevelSetup[] setups = ResolveStarSetups();
if (setups == null || setups.Length == 0) return null;
// m_levelSetups[0] is one star, [1] is two - the game indexes it as level - 2.
int index = Mathf.Min(tier - 1, setups.Length - 1);
return setups[index];
}
private static LevelEffects.LevelSetup[] ResolveStarSetups()
{
if (starSetupsResolved) return cachedStarSetups;
starSetupsResolved = true;
GameObject prefab = PrefabManager.Cache.GetPrefab<GameObject>(DvergarConfig.DvergerPrefabName);
LevelEffects effects = prefab != null ? prefab.GetComponentInChildren<LevelEffects>(true) : null;
if (effects == null || effects.m_levelSetups == null || effects.m_levelSetups.Count == 0)
{
Jotunn.Logger.LogWarning(
$"[Dvergar] No LevelEffects setups on '{DvergarConfig.DvergerPrefabName}'; " +
"star colouring stays at the base tint.");
return null;
}
cachedStarSetups = effects.m_levelSetups.ToArray();
// The offsets themselves, so a tier that lands on the wrong colour can be tuned
// against the real numbers rather than by eye.
for (int i = 0; i < cachedStarSetups.Length; i++)
{
LevelEffects.LevelSetup setup = cachedStarSetups[i];
Jotunn.Logger.LogInfo(
$"[Dvergar] Star {i + 1}: hue={setup.m_hue:F3} saturation={setup.m_saturation:F3} " +
$"value={setup.m_value:F3} emissive={(setup.m_setEmissiveColor ? setup.m_emissiveColor.ToString() : "none")} " +
$"-> skin {ShiftHsv(DvergarConfig.SkinColor, setup.m_hue, setup.m_saturation, setup.m_value)}");
}
return cachedStarSetups;
}
/// <summary>
/// Applies a star's HSV offset to our tint. Hue wraps the way the creature shader's does;
/// saturation and value are bounded rather than merely clamped to 0..1.
///
/// The bounds are the whole trick. The shader applies these offsets to a dverger's own
/// texture, where a bright desaturated result is a pale dverger. Ours multiplies the human
/// skin texture, where the same result is *white* - and a white multiplier is no tint at
/// all, which is why the two-star Dvergar came out looking like an ordinary pink human.
/// Keeping saturation off the floor and value off the ceiling means every tier stays a
/// colour.
/// </summary>
private static Color ShiftHsv(Color color, float hue, float saturation, float value)
{
Color.RGBToHSV(color, out float h, out float s, out float v);
h = Mathf.Repeat(h + hue, 1f);
s = Mathf.Clamp(s + saturation, DvergarConfig.StarMinSaturation, 1f);
v = Mathf.Clamp(v + value, DvergarConfig.StarMinValue, DvergarConfig.StarMaxValue);
Color shifted = Color.HSVToRGB(h, s, v);
shifted.a = color.a;
return shifted;
}
// ─── Scale ───────────────────────────────────────────────────────────
/// <summary>

View file

@ -244,19 +244,22 @@ namespace RacesOfValheim
if (!__instance.m_isPlayer) return;
Player p = __instance.GetComponent<Player>();
if (p == null) return;
ZNetView nview = p.GetComponent<ZNetView>();
if (nview == null || !nview.IsValid()) return;
string race = nview.GetZDO().GetString("RacesOfValheim_Race", "Human");
if (race == "Skeleton")
// Race and tier both come through SkeletonVisuals, which falls back to
// m_customData when there is no ZNetView. That is the whole of what was keeping
// the race off the main-menu character preview: the preview player carries its
// saved custom data but has no network view, so an unconditional ZDO read gave up
// before it could find out it was looking at a Skeleton.
string race = SkeletonVisuals.GetPlayerRace(p);
if (race == SkeletonVisuals.RaceId)
{
if (__instance.m_bodyModel != null)
{
// Ensure the base model is hidden
__instance.m_bodyModel.enabled = false;
int state = nview.GetZDO().GetInt("RacesOfValheim_SkeletonState", 0);
int state = SkeletonVisuals.GetProgressionState(p);
SkeletonProgression.SkeletonRules rules = SkeletonProgression.GetRules(state);
string targetBodyName = $"SkeletonBody_{rules.ModelPrefab}";
@ -332,6 +335,7 @@ namespace RacesOfValheim
HideItemInstances(__instance, "m_hairItemInstances");
HideItemInstances(__instance, "m_beardItemInstances");
SetHelmetVisible(__instance, false);
}
}
else
@ -355,10 +359,41 @@ namespace RacesOfValheim
ShowItemInstances(__instance, "m_hairItemInstances");
ShowItemInstances(__instance, "m_beardItemInstances");
SetHelmetVisible(__instance, true);
}
}
}
/// <summary>
/// A helmet on a skull looks like a helmet floating in a skull, so the race hides it.
///
/// SkeletonRace does this every frame in a world, but it only ever runs for the local
/// player - which is why the helmet came back on the main-menu preview once the body
/// swap started working there. Doing it here covers the menu, remote players and the
/// first frame after a race change, all of which reach this postfix and none of which
/// reach SkeletonRace.
///
/// Scaled rather than deactivated, because Valheim re-enables the instance whenever it
/// refreshes visuals - the approach the Dvergar's hood already proved out.
/// </summary>
private static void SetHelmetVisible(VisEquipment visEq, bool visible)
{
GameObject helmet = Traverse.Create(visEq).Field<GameObject>("m_helmetItemInstance").Value;
if (helmet == null) return;
Vector3 wanted = visible ? Vector3.one : Vector3.zero;
// Only ever undo our own hiding: another race may legitimately be scaling this.
if (!visible && helmet.transform.localScale != Vector3.zero)
{
helmet.transform.localScale = wanted;
}
else if (visible && helmet.transform.localScale == Vector3.zero)
{
helmet.transform.localScale = wanted;
}
}
private static void HideItemInstances(VisEquipment visEq, string fieldName)
{
try

View file

@ -16,6 +16,55 @@ namespace RacesOfValheim
/// </summary>
public static class SkeletonVisuals
{
public const string RaceId = "Skeleton";
/// <summary>
/// Reads the race off the ZDO, falling back to m_customData.
///
/// The fallback is what makes the race show up on the main-menu character preview.
/// FejdStartup.SetupCharacterPreview instantiates a Player and calls
/// PlayerProfile.LoadPlayerData on it, which restores m_customData - so the preview does
/// know it is a Skeleton. What it has no business having is a ZNetView, and reading the
/// race from the ZDO alone meant the body swap gave up before it ever looked.
/// </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 IsSkeletonPlayer(Player player) => GetPlayerRace(player) == RaceId;
/// <summary>
/// The tier a given player's body should be built for. The ZDO carries it so remote
/// players render at their own standing; without one - the menu preview - fall back to
/// whatever this client can work out, which in the menu is the base tier, since there is
/// no world loaded to have killed anything.
/// </summary>
public static int GetProgressionState(Player player)
{
ZNetView nview = player != null ? player.GetComponent<ZNetView>() : null;
if (nview != null && nview.IsValid())
{
return nview.GetZDO().GetInt("RacesOfValheim_SkeletonState", 0);
}
return BossProgressionManager.GetCurrentProgressionState();
}
// Fire sources in preference order. The torch is an item every world has; the ground
// torch and the fire pit are the building pieces to fall back on.
private static readonly string[] FlameSourcePrefabs =

View file

@ -100,6 +100,7 @@ namespace RacesOfValheim
// Scale is handled for every player by the Player.Update postfix; this only keeps
// the hood and the hidden helmet asserted between equipment refreshes.
DvergarVisuals.ApplyHood(m_player);
DvergarVisuals.ApplyEyes(m_player);
}
else
{