RacesOfValheim/JotunnModStub/Dvergur/DvergurVisuals.cs
kanym 3ec51aeb45 feat(dvergur): add the Dvergur race scaffold
An eighth race built on the existing per-race pattern: a MonoBehaviour driver
registered from Awake, a progression table keyed on the boss state, an SE_Stats
carrier, and Harmony patches for the individual perks.

The helmet slot stays free. Whatever the player equips keeps every one of its
stats and only its mesh is swapped for the dvergr hood, which is the Skeleton's
helmet handling turned into a replacement rather than a plain hide.

Every percentage the spec left open lives in DvergurConfig as a named value and
is marked TODO there, so tuning the race never means touching the logic. The
knobs are static readonly rather than const so that switching a perk off with a
zero does not fold its guard into dead code.
2026-08-02 21:45:44 +02:00

232 lines
9.3 KiB
C#

using HarmonyLib;
using Jotunn.Managers;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The Dvergur's looks: a short body and a hood that is always worn.
///
/// The hood is a pure cosmetic override, not an equipment lock. The helmet slot stays free and
/// whatever the player equips keeps every one of its stats - only its mesh is swapped out, the
/// way the Skeleton hides helmets outright, so armour, resistances and set bonuses all still
/// count. Everything here runs for local and remote players alike, which is why it takes a
/// Player rather than reading Player.m_localPlayer.
/// </summary>
public static class DvergurVisuals
{
private const string HoodName = "DvergurHood";
/// <summary>
/// Reads the race off the ZDO so remote players render correctly, falling back to
/// m_customData for the main-menu preview which has no ZNetView. Same shape as
/// FurlingPatches.GetPlayerRace.
/// </summary>
public static string GetPlayerRace(Player player)
{
if (player == null) return "Human";
ZNetView nview = player.GetComponent<ZNetView>();
if (nview != null && nview.IsValid())
{
return nview.GetZDO().GetString("RacesOfValheim_Race", "Human");
}
if (player.m_customData != null && player.m_customData.TryGetValue("Race", out string race))
{
return race;
}
return "Human";
}
public static bool IsDvergurPlayer(Player player) => GetPlayerRace(player) == DvergurConfig.RaceId;
/// <summary>
/// Brings a player's body in line with their race. Safe to call every frame: each step
/// checks the current value first and does nothing when it already matches.
/// </summary>
public static void Apply(Player player)
{
if (player == null) return;
bool isDvergur = IsDvergurPlayer(player) && !player.IsDead();
ApplyScale(player, isDvergur);
VisEquipment visEq = player.GetComponent<VisEquipment>();
if (visEq == null) return;
if (isDvergur)
{
EnsureHood(visEq);
HideEquippedHelmet(visEq);
}
else
{
RemoveHood(visEq);
}
}
private static void ApplyScale(Player player, bool isDvergur)
{
// Scaling the "Visual" child rather than the root, as Furling does: the root carries
// the collider and the camera pivot, and shrinking those makes the player fall through
// the world geometry they were standing on.
GameObject visual = Traverse.Create(player).Field("m_visual").GetValue<GameObject>();
if (visual == null) return;
Vector3 target = isDvergur ? Vector3.one * DvergurConfig.VisualScale : Vector3.one;
if (isDvergur)
{
if (visual.transform.localScale != target) visual.transform.localScale = target;
}
else if (visual.transform.localScale == Vector3.one * DvergurConfig.VisualScale)
{
// Only undo our own scale - another race may legitimately be scaling this player.
visual.transform.localScale = Vector3.one;
}
}
/// <summary>
/// Blanks the mesh of whatever helmet is equipped. Scaled to zero rather than deactivated
/// because Valheim re-enables the instance whenever it refreshes visuals, and this is the
/// approach the Skeleton already proved out.
/// </summary>
private static void HideEquippedHelmet(VisEquipment visEq)
{
GameObject helmet = Traverse.Create(visEq).Field<GameObject>("m_helmetItemInstance").Value;
if (helmet != null && helmet.transform.localScale != Vector3.zero)
{
helmet.transform.localScale = Vector3.zero;
}
}
private static void EnsureHood(VisEquipment visEq)
{
if (visEq.m_bodyModel == null || visEq.m_bodyModel.bones == null) return;
Transform headBone = FindBoneByName(visEq.m_bodyModel.bones, "Head");
if (headBone == null) return;
Transform existing = headBone.Find(HoodName);
if (existing != null)
{
if (!existing.gameObject.activeSelf) existing.gameObject.SetActive(true);
return;
}
GameObject source = ResolveHoodSource();
if (source == null)
{
// Logged once per player rather than per frame: the early return above means we
// only reach here while the hood is genuinely missing.
Jotunn.Logger.LogWarning(
$"[Dvergur] No hood prefab found among [{string.Join(", ", DvergurConfig.HoodPrefabCandidates)}]; " +
"the helmet slot stays cosmetically empty.");
return;
}
bool wasActive = source.activeSelf;
source.SetActive(false);
GameObject hood = Object.Instantiate(source, headBone, false);
source.SetActive(wasActive);
hood.name = HoodName;
// Strip anything that would make a decorative mesh behave like a world object -
// hover prompts, pickup triggers, physics. Same cleanup the Furling head does.
foreach (MonoBehaviour comp in hood.GetComponentsInChildren<MonoBehaviour>(true))
{
Object.DestroyImmediate(comp);
}
foreach (Rigidbody body in hood.GetComponentsInChildren<Rigidbody>(true))
{
Object.DestroyImmediate(body);
}
foreach (Collider col in hood.GetComponentsInChildren<Collider>(true))
{
Object.DestroyImmediate(col);
}
hood.SetActive(true);
hood.transform.localPosition = DvergurConfig.HoodLocalPosition;
hood.transform.localRotation = Quaternion.Euler(DvergurConfig.HoodLocalRotation);
hood.transform.localScale = Vector3.one * DvergurConfig.HoodLocalScale;
// Without the creature shader the hood ignores the camera's dither fade and blocks
// the view in first person; its own textures are kept.
Shader dither = Shader.Find("Custom/Creature");
if (dither != null)
{
foreach (Renderer renderer in hood.GetComponentsInChildren<Renderer>(true))
{
if (renderer.material != null) renderer.material.shader = dither;
}
}
}
/// <summary>
/// First candidate prefab that resolves wins. A creature prefab is handled specially: the
/// Dvergr's headgear is a child renderer of the creature, not a standalone prefab, so the
/// piece is lifted out rather than the whole NPC being instantiated on the player's head.
/// </summary>
private static GameObject ResolveHoodSource()
{
foreach (string candidate in DvergurConfig.HoodPrefabCandidates)
{
GameObject prefab = PrefabManager.Cache.GetPrefab<GameObject>(candidate);
if (prefab == null) continue;
if (prefab.GetComponent<Character>() == null) return prefab;
foreach (Renderer renderer in prefab.GetComponentsInChildren<Renderer>(true))
{
string name = renderer.gameObject.name.ToLower();
if (name.Contains("helmet") || name.Contains("hat") || name.Contains("hood") || name.Contains("cap"))
{
return renderer.gameObject;
}
}
}
return null;
}
private static void RemoveHood(VisEquipment visEq)
{
if (visEq.m_bodyModel == null || visEq.m_bodyModel.bones == null) return;
Transform headBone = FindBoneByName(visEq.m_bodyModel.bones, "Head");
if (headBone == null) return;
Transform hood = headBone.Find(HoodName);
if (hood == null) return; // never was a Dvergur - leave the helmet alone
// Destroy is deferred to the end of the frame, so the object is renamed first: without
// that, every call until it actually goes away finds it again and re-runs the restore.
hood.name = HoodName + "_Removed";
Object.Destroy(hood.gameObject);
GameObject helmet = Traverse.Create(visEq).Field<GameObject>("m_helmetItemInstance").Value;
if (helmet != null && helmet.transform.localScale == Vector3.zero)
{
helmet.transform.localScale = Vector3.one;
}
}
private static Transform FindBoneByName(Transform[] bones, string targetBoneName)
{
foreach (Transform bone in bones)
{
if (bone != null && bone.name == targetBoneName) return bone;
}
string target = targetBoneName.ToLower();
foreach (Transform bone in bones)
{
if (bone != null && bone.name.ToLower().Contains(target)) return bone;
}
return null;
}
}
}