diff --git a/JotunnModStub/Skeleton/SkeletonConfig.cs b/JotunnModStub/Skeleton/SkeletonConfig.cs index 62c01fc..dd3935d 100644 --- a/JotunnModStub/Skeleton/SkeletonConfig.cs +++ b/JotunnModStub/Skeleton/SkeletonConfig.cs @@ -47,6 +47,7 @@ namespace RacesOfValheim public static ConfigEntry HeadFireVFXEnabled; public static ConfigEntry BodyModelEnabled; public static ConfigEntry RaiseDeadIcon; + public static ConfigEntry ShowHelmet; public static void Bind(ConfigFile config) { @@ -86,6 +87,7 @@ namespace RacesOfValheim new ConfigDescription("Whether Skeleton players wear the skeleton body. Turn it off if you use a player model mod (EnhancedValheimVRM and the like): Skeletons then keep the vanilla viking body, so the replacement model shows without bones clipping through it. Abilities are unchanged. Client-side, like the option above: it applies to every Skeleton you see, yourself included, and changes nothing for other players.")); RaiseDeadIcon = config.Bind(visuals, "Raise the Dead Icon", true, new ConfigDescription("Shows the Raise the Dead status icon while your Summon on Kill is on.")); - } + ShowHelmet = config.Bind(visuals, "Show Helmet", false, + new ConfigDescription("Off: your helmet stays hidden over the skull. On: the helmet you wear shows. Helmets and hoods are moved and enlarged to fit the skull. Your own choice: other players see you the way you picked. A viking body (Body Model Enabled off) always shows its helmet.")); } } } diff --git a/JotunnModStub/Skeleton/SkeletonPatches.cs b/JotunnModStub/Skeleton/SkeletonPatches.cs index b5e3e93..9121e17 100644 --- a/JotunnModStub/Skeleton/SkeletonPatches.cs +++ b/JotunnModStub/Skeleton/SkeletonPatches.cs @@ -351,7 +351,7 @@ namespace RacesOfValheim HideItemInstances(__instance, "m_hairItemInstance"); HideItemInstances(__instance, "m_beardItemInstance"); - SetHelmetVisible(__instance, false); + SkeletonVisuals.FitHelmet(p, __instance, SkeletonVisuals.ShowsHelmet(p)); // Poses the mandible, once per frame, after the animation. Attached from // here rather than from SkeletonRace because this postfix is the one path @@ -396,7 +396,7 @@ namespace RacesOfValheim ShowItemInstances(__instance, "m_hairItemInstance"); ShowItemInstances(__instance, "m_beardItemInstance"); - SetHelmetVisible(__instance, true); + SkeletonVisuals.UnfitHelmet(__instance); // 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. @@ -405,26 +405,6 @@ namespace RacesOfValheim } } - /// - /// 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. - /// - /// Delegates to SkeletonVisuals.SetEquipmentPieceHidden, which scales the wrapper to - /// zero and disables its renderers - scale alone leaves a skinned piece (bound to the - /// player's own bones rather than its own transform) still drawing, which is what a - /// helmet with a skinned cloth or chain part looked like. - /// - private static void SetHelmetVisible(VisEquipment visEq, bool visible) - { - GameObject helmet = Traverse.Create(visEq).Field("m_helmetItemInstance").Value; - SkeletonVisuals.SetEquipmentPieceHidden(helmet, !visible); - } - private static void HideItemInstances(VisEquipment visEq, string fieldName) { SetItemInstanceActive(visEq, fieldName, false); diff --git a/JotunnModStub/Skeleton/SkeletonRace.cs b/JotunnModStub/Skeleton/SkeletonRace.cs index 69e8712..479af4e 100644 --- a/JotunnModStub/Skeleton/SkeletonRace.cs +++ b/JotunnModStub/Skeleton/SkeletonRace.cs @@ -396,10 +396,11 @@ namespace RacesOfValheim { // Hide Helmets (Valheim uses singular GameObject for helmet). Only over a skull: // a viking body wears its helmet, and the VisEquipment postfix puts it back. + // "Show Helmet" keeps it on the skull too, and is published for other clients. + SkeletonVisuals.PublishShowHelmet(Player.m_localPlayer); if (SkeletonConfig.BodyModelEnabled.Value) { - var helmetObj = HarmonyLib.Traverse.Create(currentVis).Field("m_helmetItemInstance").Value; - SkeletonVisuals.SetEquipmentPieceHidden(helmetObj, true); + SkeletonVisuals.FitHelmet(Player.m_localPlayer, currentVis, SkeletonConfig.ShowHelmet.Value); } // Scale Body Armor (Chest, Legs, Shoulder) by 5% diff --git a/JotunnModStub/Skeleton/SkeletonVisuals.cs b/JotunnModStub/Skeleton/SkeletonVisuals.cs index e91963c..0682e08 100644 --- a/JotunnModStub/Skeleton/SkeletonVisuals.cs +++ b/JotunnModStub/Skeleton/SkeletonVisuals.cs @@ -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"; + + /// + /// 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. + /// + public static bool ShowsHelmet(Player player) + { + if (player == null) return false; + + ZNetView nview = player.GetComponent(); + if (player == Player.m_localPlayer || nview == null || !nview.IsValid()) + { + return SkeletonConfig.ShowHelmet.Value; + } + + return nview.GetZDO().GetBool(ShowHelmetZdoKey, false); + } + + /// Writes the local player's choice to its ZDO when it differs. Owner only. + public static void PublishShowHelmet(Player player) + { + ZNetView nview = player != null ? player.GetComponent() : 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); + } + } + /// /// 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). /// - 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 } } + /// + /// 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. + /// + 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 Fitted = new List(); + public readonly List OriginalBones = new List(); + } + + 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; + + /// + /// 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. + /// + 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; + } + + /// + /// 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. + /// + public static void FitHelmet(Player player, VisEquipment vis, bool show) + { + GameObject helmet = vis != null ? HarmonyLib.Traverse.Create(vis).Field("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("m_helmet").Value; + bool rigid = joint != null && helmet.transform.parent == joint; + + SetEquipmentPieceHidden(helmet, false, rigid ? HelmetFitSize : 1f); + + HelmetBasePose pose = helmet.GetComponent(); + if (pose == null) + { + pose = helmet.AddComponent(); + 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 loggedCloth = new HashSet(); + + /// + /// 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. + /// + private static void FitSkinnedParts(Player player, GameObject helmet, HelmetBasePose pose, Transform joint) + { + Animator anim = player.GetComponentInChildren(); + Transform head = anim != null ? anim.GetBoneTransform(HumanBodyBones.Head) : null; + if (head == null) return; + + Transform fitBone = null; + foreach (SkinnedMeshRenderer smr in helmet.GetComponentsInChildren(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() != 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; + } + + /// This head's fit bone, made the first time a skinned helmet part needs it. + 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; + } + + /// Shows the helmet where vanilla put it, undoing any fit. For a viking body. + public static void UnfitHelmet(VisEquipment vis) + { + GameObject helmet = vis != null ? HarmonyLib.Traverse.Create(vis).Field("m_helmetItemInstance").Value : null; + if (helmet == null) return; + + SetEquipmentPieceHidden(helmet, false); + + HelmetBasePose pose = helmet.GetComponent(); + 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)); + } + /// /// 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 diff --git a/JotunnModStub/ZdoVisualSync.cs b/JotunnModStub/ZdoVisualSync.cs index 4f1326f..9716e9b 100644 --- a/JotunnModStub/ZdoVisualSync.cs +++ b/JotunnModStub/ZdoVisualSync.cs @@ -127,11 +127,10 @@ namespace RacesOfValheim vis.SetHairItem(0); vis.SetBeardItem(0); - // Hide Helmet + // Hide Helmet, unless its owner chose to show it if (SkeletonConfig.BodyModelEnabled.Value) { - var helmetObj = HarmonyLib.Traverse.Create(vis).Field("m_helmetItemInstance").Value; - SkeletonVisuals.SetEquipmentPieceHidden(helmetObj, true); + SkeletonVisuals.FitHelmet(m_player, vis, SkeletonVisuals.ShowsHelmet(m_player)); } // Scale Body Armor