feat: Skeletons can show their helmet

New "Show Helmet" option under Skeleton - Visuals, off by default. The owner's
choice is written to the ZDO, so other players see the helmet the way its owner
picked.

On a skull the helmet moves up and back and grows to fit, since the skull is
bigger than the viking head the helmet hangs for. Hoods and the other skinned
helmets can't be moved by their transform: their Head bone is swapped for a
fitted child bone, so the head part follows the skull and the shoulder parts
stay put. A viking body gets the vanilla placement and bones back.
This commit is contained in:
kanym 2026-10-29 01:08:07 +01:00
commit e972ca5ea4
5 changed files with 259 additions and 30 deletions

View file

@ -59,6 +59,41 @@ namespace RacesOfValheim
public static bool ShowsSkeletonBody(Player player) =>
SkeletonConfig.BodyModelEnabled.Value && IsSkeletonPlayer(player);
// The owner's "Show Helmet" choice, so every other client draws this skeleton's helmet the
// way its owner picked rather than the way the onlooker's own setting says.
public const string ShowHelmetZdoKey = "RacesOfValheim_SkeletonShowHelmet";
/// <summary>
/// Whether this skeleton wears its helmet visibly over the skull. The local player and the
/// menu preview (which has no ZDO and is always this client's own character) go by this
/// client's setting; anyone else by what their owner published.
/// </summary>
public static bool ShowsHelmet(Player player)
{
if (player == null) return false;
ZNetView nview = player.GetComponent<ZNetView>();
if (player == Player.m_localPlayer || nview == null || !nview.IsValid())
{
return SkeletonConfig.ShowHelmet.Value;
}
return nview.GetZDO().GetBool(ShowHelmetZdoKey, false);
}
/// <summary>Writes the local player's choice to its ZDO when it differs. Owner only.</summary>
public static void PublishShowHelmet(Player player)
{
ZNetView nview = player != null ? player.GetComponent<ZNetView>() : null;
if (nview == null || !nview.IsValid() || !nview.IsOwner()) return;
bool show = SkeletonConfig.ShowHelmet.Value;
if (nview.GetZDO().GetBool(ShowHelmetZdoKey, false) != show)
{
nview.GetZDO().Set(ShowHelmetZdoKey, show);
}
}
/// <summary>
/// Fully hides (or restores) one equipped item instance - a helmet, typically.
///
@ -71,11 +106,11 @@ namespace RacesOfValheim
/// is reasserted the same way (Valheim's own visual refresh re-enables the instance and
/// resets its scale, so both must be redone every time visuals rebuild).
/// </summary>
public static void SetEquipmentPieceHidden(GameObject instance, bool hidden)
public static void SetEquipmentPieceHidden(GameObject instance, bool hidden, float shownSize = 1f)
{
if (instance == null) return;
Vector3 wantedScale = hidden ? Vector3.zero : Vector3.one;
Vector3 wantedScale = hidden ? Vector3.zero : Vector3.one * shownSize;
if (instance.transform.localScale != wantedScale)
{
instance.transform.localScale = wantedScale;
@ -90,6 +125,218 @@ namespace RacesOfValheim
}
}
/// <summary>
/// Where VisEquipment.AttachItem put the helmet: zero, or the prefab's own "equipoffset".
/// Kept on the instance so the fit is always a delta on it, and so taking the fit off
/// puts the helmet back exactly. A re-equip makes a new instance without one.
/// </summary>
private class HelmetBasePose : MonoBehaviour
{
public Vector3 Position;
// Skinned parts whose Head bone was swapped for the fit bone, with the bone list
// AttachItem gave them, so a viking body gets its own head back.
public readonly List<SkinnedMeshRenderer> Fitted = new List<SkinnedMeshRenderer>();
public readonly List<Transform[]> OriginalBones = new List<Transform[]>();
}
private const string FitBoneName = "SkeletonHelmetFitBone";
// The helmet on a skull: metres up and forward, and size. Dialled in on screen with
// Configuration Manager sliders (playtest, 2026-10-29) on the bronze, drake and flametal
// helmets, then written down here; the sliders are gone. One set fits all three bodies.
private const float HelmetFitUp = 0.068f;
private const float HelmetFitForward = -0.053f;
private const float HelmetFitSize = 1.298f;
// The same for the fit bone of skinned helmets (the 16 vanilla prefabs with an
// "attach_skin" child: hoods, but also Padded, Carapace, Sweatband and others). Tuned on
// the Fenring hood, then checked on nearly all the rest (2026-10-29). It scales from the
// Head bone's pivot rather than the helmet joint's, hence the different numbers.
private const float HoodFitUp = 0.041f;
private const float HoodFitForward = -0.071f;
private const float HoodFitSize = 1.246f;
// Which of the helmet joint's own axes are the skull's up and forward. Every player wears
// the same rig, so this is found once and kept. Re-picking it every frame made the
// offset jump sideways whenever the head turned far enough for another axis to win.
private static bool fitAxesFound;
private static Vector3 fitUpAxis, fitForwardAxis;
/// <summary>
/// Picks the axes only while the head faces straight ahead, so a turned head on the
/// first frame cannot lock in the wrong ones. False until then.
/// </summary>
private static bool FindFitAxes(Transform joint, Player player)
{
Vector3 up = ClosestLocalAxis(joint, player.transform.up);
Vector3 forward = ClosestLocalAxis(joint, player.transform.forward);
if (Vector3.Dot(joint.TransformDirection(up), player.transform.up) < 0.8f ||
Vector3.Dot(joint.TransformDirection(forward), player.transform.forward) < 0.8f)
{
return false;
}
fitUpAxis = up;
fitForwardAxis = forward;
fitAxesFound = true;
Jotunn.Logger.LogInfo($"[Skeleton] Helmet fit on '{joint.name}': up = local {up}, forward = local {forward}, joint scale {joint.lossyScale}.");
return true;
}
/// <summary>
/// The helmet on a skull: hidden, or shown and moved to fit the skull, which is bigger
/// and sits higher and further back than the viking head the helmet hangs for. Hidden
/// unless the owner turned on "Show Helmet" (ShowsHelmet).
///
/// Called from the VisEquipment postfix as well as SkeletonRace and ZdoVisualSync:
/// SkeletonRace only ever runs for the local player, which is why the helmet once came
/// back on the main-menu preview. The postfix covers the menu, remote players and the
/// first frame after a race change.
///
/// Up and forward are the player's, carried over to whichever of the helmet joint's own
/// axes points closest to them. The joint turns with the head, so the helmet keeps its
/// place on the skull when the player looks up or down.
///
/// A hood ("attach_skin") is skinned to the player's own bones, so moving its transform
/// does nothing. Its parts weighted to the Head bone get a fit bone instead: a child of
/// the real Head carrying the same kind of move and size. The parts weighted to the neck
/// and shoulders stay put, so the hood stretches between the two like it would over a
/// bigger head. Rigid helmets with a skinned chain or cloth piece get the same treatment
/// for that piece.
/// </summary>
public static void FitHelmet(Player player, VisEquipment vis, bool show)
{
GameObject helmet = vis != null ? HarmonyLib.Traverse.Create(vis).Field<GameObject>("m_helmetItemInstance").Value : null;
if (helmet == null) return;
if (!show)
{
SetEquipmentPieceHidden(helmet, true);
return;
}
// Always the helmet joint, never the instance's parent: a hood hangs off the body
// container, whose axes are not the head's.
Transform joint = HarmonyLib.Traverse.Create(vis).Field<Transform>("m_helmet").Value;
bool rigid = joint != null && helmet.transform.parent == joint;
SetEquipmentPieceHidden(helmet, false, rigid ? HelmetFitSize : 1f);
HelmetBasePose pose = helmet.GetComponent<HelmetBasePose>();
if (pose == null)
{
pose = helmet.AddComponent<HelmetBasePose>();
pose.Position = helmet.transform.localPosition;
}
if (joint == null) return;
if (!fitAxesFound && !FindFitAxes(joint, player)) return;
if (rigid)
{
Vector3 worldOffset = FitOffset(joint, HelmetFitUp, HelmetFitForward);
Vector3 wanted = pose.Position + joint.InverseTransformVector(worldOffset);
if (helmet.transform.localPosition != wanted)
{
helmet.transform.localPosition = wanted;
}
}
FitSkinnedParts(player, helmet, pose, joint);
}
private static Vector3 FitOffset(Transform joint, float up, float forward) =>
joint.TransformDirection(fitUpAxis) * up + joint.TransformDirection(fitForwardAxis) * forward;
private static readonly HashSet<string> loggedCloth = new HashSet<string>();
/// <summary>
/// Points every skinned part of the helmet that uses the Head bone at this player's fit
/// bone, and keeps the fit bone posed. The bone list is the part's own copy (Unity
/// copies on get and on set), so the body and the other armour keep the real Head.
/// </summary>
private static void FitSkinnedParts(Player player, GameObject helmet, HelmetBasePose pose, Transform joint)
{
Animator anim = player.GetComponentInChildren<Animator>();
Transform head = anim != null ? anim.GetBoneTransform(HumanBodyBones.Head) : null;
if (head == null) return;
Transform fitBone = null;
foreach (SkinnedMeshRenderer smr in helmet.GetComponentsInChildren<SkinnedMeshRenderer>(true))
{
if (pose.Fitted.Contains(smr)) continue;
Transform[] bones = smr.bones;
int index = System.Array.IndexOf(bones, head);
if (index < 0) continue;
if (fitBone == null) fitBone = GetFitBone(head);
pose.Fitted.Add(smr);
pose.OriginalBones.Add((Transform[])bones.Clone());
bones[index] = fitBone;
smr.bones = bones;
if (smr.GetComponent<Cloth>() != null && loggedCloth.Add(helmet.name))
{
Jotunn.Logger.LogInfo($"[Skeleton] Helmet '{helmet.name}': skinned part '{smr.name}' carries Cloth; its Head bone was swapped for the fit bone.");
}
}
if (pose.Fitted.Count == 0) return;
if (fitBone == null) fitBone = GetFitBone(head);
Vector3 wantedPos = head.InverseTransformVector(FitOffset(joint, HoodFitUp, HoodFitForward));
Vector3 wantedScale = Vector3.one * HoodFitSize;
if (fitBone.localPosition != wantedPos) fitBone.localPosition = wantedPos;
if (fitBone.localScale != wantedScale) fitBone.localScale = wantedScale;
}
/// <summary>This head's fit bone, made the first time a skinned helmet part needs it.</summary>
private static Transform GetFitBone(Transform head)
{
Transform fitBone = head.Find(FitBoneName);
if (fitBone != null) return fitBone;
fitBone = new GameObject(FitBoneName).transform;
fitBone.SetParent(head, false);
fitBone.localRotation = Quaternion.identity;
return fitBone;
}
/// <summary>Shows the helmet where vanilla put it, undoing any fit. For a viking body.</summary>
public static void UnfitHelmet(VisEquipment vis)
{
GameObject helmet = vis != null ? HarmonyLib.Traverse.Create(vis).Field<GameObject>("m_helmetItemInstance").Value : null;
if (helmet == null) return;
SetEquipmentPieceHidden(helmet, false);
HelmetBasePose pose = helmet.GetComponent<HelmetBasePose>();
if (pose == null) return;
if (helmet.transform.localPosition != pose.Position)
{
helmet.transform.localPosition = pose.Position;
}
for (int i = 0; i < pose.Fitted.Count; i++)
{
if (pose.Fitted[i] != null) pose.Fitted[i].bones = pose.OriginalBones[i];
}
pose.Fitted.Clear();
pose.OriginalBones.Clear();
}
private static Vector3 ClosestLocalAxis(Transform joint, Vector3 worldDir)
{
Vector3 local = joint.InverseTransformDirection(worldDir);
Vector3 abs = new Vector3(Mathf.Abs(local.x), Mathf.Abs(local.y), Mathf.Abs(local.z));
if (abs.x >= abs.y && abs.x >= abs.z) return new Vector3(Mathf.Sign(local.x), 0f, 0f);
if (abs.y >= abs.z) return new Vector3(0f, Mathf.Sign(local.y), 0f);
return new Vector3(0f, 0f, Mathf.Sign(local.z));
}
/// <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