diff --git a/JotunnModStub/Dvergur/DvergurConfig.cs b/JotunnModStub/Dvergur/DvergurConfig.cs index 775b605..11e406c 100644 --- a/JotunnModStub/Dvergur/DvergurConfig.cs +++ b/JotunnModStub/Dvergur/DvergurConfig.cs @@ -40,11 +40,16 @@ namespace RacesOfValheim // ─── Skin ──────────────────────────────────────────────────────────── // Written straight onto the body material's _SkinColor by the UpdateColors postfix, which // is the only thing that actually tints a player - see the comment on that patch. - // Ashen grey with a blue cast, to read as one of the deep folk. - public static readonly Color SkinColor = new Color(0.72f, 0.74f, 0.82f, 1f); + // + // This is a multiplier over the human skin texture, not a replacement, so a value near + // (1,1,1) changes nothing anyone can see. The first attempt at (0.72, 0.74, 0.82) was + // exactly that mistake: correct code, invisible result. Every race that reads clearly + // commits to a channel - Trol (0.1, 0.6, 0.7), Furling (0.3, 0.8, 0.3) - so the Dvergur + // does too: a cold, dark slate blue-grey. + public static readonly Color SkinColor = new Color(0.42f, 0.52f, 0.68f, 1f); // Dvergr are white-haired. The hood hides most of it, but the beard shows. - public static readonly Color HairColor = new Color(0.88f, 0.88f, 0.90f, 1f); + public static readonly Color HairColor = new Color(0.85f, 0.87f, 0.92f, 1f); // ─── Cosmetic hood ─────────────────────────────────────────────────── // The helmet slot itself stays free — whatever the player equips keeps all of its stats, @@ -53,32 +58,30 @@ namespace RacesOfValheim // The hood is lifted straight off the Dvergr NPC rather than off the Dverger Circlet item: // the circlet is a metal band, not the hood the race is meant to wear. // - // 'Dverger' turned out to carry a single renderer named 'dvergr' with the hood baked into - // the same mesh as the body, so a whole-object lift was never going to work. Resolution now - // tries, in order: a separate renderer object; a submesh of a combined mesh picked out by - // its material; and finally an index pinned by hand below. + // Two facts out of dumpdverger decide how this is done. + // + // The prefab holds one renderer, 'dvergr', whose mesh reports zero triangles - it ships + // with Read/Write disabled, so its vertices and indices cannot be touched at runtime and + // no amount of submesh carving will ever produce geometry. + // + // But its rig carries a dedicated hat1/hat2/hat3 bone chain under 'head'. The hood is + // skinned to those bones and nothing else is, so the hood can be isolated by collapsing + // every other bone to zero scale rather than by editing the mesh at all. public const string DvergerPrefabName = "Dverger"; - // Scanned in order. The mage variants are included because they wear a different hood and - // may well keep it as its own object. - public static readonly string[] DvergerPrefabCandidates = - { - "Dverger", "DvergerMage", "DvergerMageFire", "DvergerMageIce", "DvergerMageSupport" - }; + // The child of the prefab holding the armature and the renderer. + public const string DvergerVisualName = "Visual"; - // Matched against renderer object names, lowercased, by Contains. - public static readonly string[] HoodRendererNames = { "hat", "hood", "helmet", "cap" }; + // Root of the hat bone chain, and the bone whose collapse hides everything else. + public const string HoodBoneName = "hat1"; + public const string BodyRootBoneName = "Root"; - // Matched against material names when the hood is a submesh of a combined mesh. - public static readonly string[] HoodMaterialNames = { "hat", "hood", "helm", "cap", "head" }; + // Bone the hood is hung from on the player's own rig. + public const string PlayerHeadBoneName = "Head"; - // Escape hatch for when neither name matches: pin the prefab and the submesh index by hand - // from what `dumpdverger` reports. An empty prefab or a negative index means "auto". - public const string HoodForcedPrefab = ""; - public const int HoodForcedSubmeshIndex = -1; - - // Applied on top of whatever the rig positions the hood at. Identity is correct when the - // bone remap succeeds; these exist so a stubborn mesh can be nudged without a code change. + // Nudges on top of the automatic alignment, which already puts the hat bone on the player's + // head bone. Scale is the one most likely to need a look: the hood is authored for a Dvergr + // skull, not a human one. public static readonly Vector3 HoodOffsetPosition = Vector3.zero; public static readonly Vector3 HoodOffsetRotation = Vector3.zero; public static readonly float HoodExtraScale = 1f; diff --git a/JotunnModStub/Dvergur/DvergurVisuals.cs b/JotunnModStub/Dvergur/DvergurVisuals.cs index 3110267..0a8c43f 100644 --- a/JotunnModStub/Dvergur/DvergurVisuals.cs +++ b/JotunnModStub/Dvergur/DvergurVisuals.cs @@ -5,7 +5,7 @@ using UnityEngine; namespace RacesOfValheim { /// - /// The Dvergur's looks: a short body, dverger skin, and a hood that is always worn. + /// The Dvergur's looks: a short body, dvergr skin, 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, so @@ -18,10 +18,11 @@ namespace RacesOfValheim { private const string HoodName = "DvergurHood"; - // The hood only has to be looked up once per session; the search walks a whole creature - // prefab and would otherwise run again for every player that comes into view. - private static HoodSource cachedHoodSource; - private static bool hoodSourceResolved; + // The source is looked up once per session; the search walks a whole creature prefab and + // would otherwise run again for every player that comes into view. The failure is cached + // too, so a missing prefab cannot turn into a per-frame log. + private static GameObject cachedVisual; + private static bool visualResolved; /// /// Reads the race off the ZDO so remote players render correctly, falling back to @@ -114,129 +115,103 @@ namespace RacesOfValheim } } + /// + /// Hangs the dvergr hood on the player's head. + /// + /// The Dvergr ships as a single renderer whose mesh has Read/Write disabled - it reports + /// zero triangles - so the hood cannot be carved out of it as a submesh, which is what the + /// previous two attempts tried in one form or another. What the prefab does give us is a + /// hat1/hat2/hat3 bone chain that nothing but the hood is skinned to. + /// + /// So the whole dvergr body is instantiated and then made to disappear: the hat chain is + /// detached from the skull, and the armature root is collapsed to zero scale, which drags + /// every vertex weighted to it into a single point. Only the hood is left standing, and it + /// is still skinned, so it keeps its own shape. + /// private static void EnsureHood(VisEquipment visEq) { if (visEq.m_bodyModel == null || visEq.m_bodyModel.bones == null) return; - Transform parent = visEq.m_bodyModel.transform.parent; - if (parent == null) return; + Transform playerHead = FindBoneByName(visEq.m_bodyModel.bones, DvergurConfig.PlayerHeadBoneName); + if (playerHead == null) return; - Transform existing = parent.Find(HoodName); - if (existing != null) + if (playerHead.Find(HoodName) != null) return; // already wearing it + + GameObject sourceVisual = ResolveDvergerVisual(); + if (sourceVisual == null) return; // already logged once by the resolver + + bool wasActive = sourceVisual.activeSelf; + sourceVisual.SetActive(false); + GameObject hood = Object.Instantiate(sourceVisual, playerHead, false); + sourceVisual.SetActive(wasActive); + + hood.name = HoodName; + StripComponents(hood); + hood.SetActive(true); + + Transform hatBone = FindChildByName(hood.transform, DvergurConfig.HoodBoneName); + Transform bodyRoot = FindChildByName(hood.transform, DvergurConfig.BodyRootBoneName); + + if (hatBone == null) { - if (!existing.gameObject.activeSelf) existing.gameObject.SetActive(true); + Jotunn.Logger.LogWarning( + $"[Dvergur] No '{DvergurConfig.HoodBoneName}' bone in the instantiated dvergr; hood dropped."); + Object.Destroy(hood); return; } - HoodSource source = ResolveHoodSource(); - if (!source.Valid) return; // already logged once by the resolver + // Detached first: the hat chain hangs off the skull, so collapsing the body without + // this would collapse the hood along with it. + hatBone.SetParent(hood.transform, true); + if (bodyRoot != null) bodyRoot.localScale = Vector3.zero; - Transform[] playerBones = visEq.m_bodyModel.bones; - GameObject hood = source.SubmeshIndex >= 0 - ? BuildFromSubmesh(source.Skinned, source.SubmeshIndex, parent, playerBones) - : BuildFromObject(source.Separate, parent, playerBones); - - if (hood == null) return; - - hood.name = HoodName; - hood.transform.localPosition = DvergurConfig.HoodOffsetPosition; + // Scale and rotation before alignment, since both move the hat bone. hood.transform.localRotation = Quaternion.Euler(DvergurConfig.HoodOffsetRotation); hood.transform.localScale = Vector3.one * DvergurConfig.HoodExtraScale; - hood.SetActive(true); - } - /// - /// Carves one submesh out of a combined skinned mesh and rebuilds it as a standalone - /// renderer bound to the player's rig. - /// - /// This is what the Dvergr needs: its prefab holds a single renderer, 'dvergr', with the - /// hood, the body and the clothes all in one mesh, so there is no object to lift out. Every - /// vertex, bone weight and bindpose is kept - only the triangle list is narrowed to the one - /// submesh - which means the skinning still lines up and the rig places the hood for us. - /// - private static GameObject BuildFromSubmesh(SkinnedMeshRenderer source, int submeshIndex, Transform parent, Transform[] playerBones) - { - Mesh sourceMesh = source.sharedMesh; - if (sourceMesh == null || submeshIndex >= sourceMesh.subMeshCount) return null; + // The hat now sits wherever the dvergr's own skull was. Shifting the whole object by + // the gap between that and the player's head bone lands it correctly without a single + // hand-measured offset. + hood.transform.position += playerHead.position - hatBone.position; + hood.transform.localPosition += DvergurConfig.HoodOffsetPosition; - Mesh mesh = new Mesh(); - // Must be set before the vertex array on meshes above 65535 verts, or the indices - // silently truncate. - mesh.indexFormat = sourceMesh.indexFormat; - mesh.vertices = sourceMesh.vertices; - mesh.normals = sourceMesh.normals; - mesh.tangents = sourceMesh.tangents; - mesh.uv = sourceMesh.uv; - mesh.boneWeights = sourceMesh.boneWeights; - mesh.bindposes = sourceMesh.bindposes; - mesh.subMeshCount = 1; - mesh.SetTriangles(sourceMesh.GetTriangles(submeshIndex), 0); - mesh.RecalculateBounds(); - - GameObject obj = new GameObject(HoodName); - obj.transform.SetParent(parent, false); - - SkinnedMeshRenderer renderer = obj.AddComponent(); - renderer.sharedMesh = mesh; - - Material[] sourceMaterials = source.sharedMaterials; - if (submeshIndex < sourceMaterials.Length) + foreach (SkinnedMeshRenderer renderer in hood.GetComponentsInChildren(true)) { - renderer.sharedMaterials = new[] { sourceMaterials[submeshIndex] }; - } - - RebindBones(renderer, source.bones, source.rootBone, playerBones); - ApplyDitherShader(obj); - return obj; - } - - private static GameObject BuildFromObject(GameObject source, Transform parent, Transform[] playerBones) - { - if (source == null) return null; - - bool wasActive = source.activeSelf; - source.SetActive(false); - GameObject hood = Object.Instantiate(source, parent, false); - source.SetActive(wasActive); - - StripBehaviours(hood); - - // Instantiated as-is, a skinned mesh keeps bones pointing at the source prefab's - // transforms and so renders nowhere; rebinding to the player's own bones by name is - // what the Skeleton does for whole bodies. - bool rebound = false; - foreach (SkinnedMeshRenderer smr in hood.GetComponentsInChildren(true)) - { - RebindBones(smr, smr.bones, smr.rootBone, playerBones); - rebound = true; - } - - if (!rebound) - { - // A rigid hood has no bones to rebind, so it is simply hung off the head the way - // the Furling's head is. - Transform headBone = FindBoneByName(playerBones, "Head"); - if (headBone != null) hood.transform.SetParent(headBone, false); + // The collapsed bones leave the mesh's own bounds meaningless, and a skinned + // renderer culls against those - without this the hood vanishes at some angles. + renderer.updateWhenOffscreen = true; } ApplyDitherShader(hood); - return hood; } - private static void RebindBones(SkinnedMeshRenderer renderer, Transform[] sourceBones, Transform sourceRoot, Transform[] playerBones) + /// + /// Strips everything that would make a decorative mesh behave like a creature: AI, hover + /// prompts and physics, plus the Animator and LODGroup, which are not MonoBehaviours and + /// would otherwise keep driving or hiding the rig. + /// + private static void StripComponents(GameObject obj) { - if (playerBones == null || playerBones.Length == 0 || sourceBones == null) return; - - Transform[] remapped = new Transform[sourceBones.Length]; - for (int i = 0; i < sourceBones.Length; i++) + foreach (MonoBehaviour comp in obj.GetComponentsInChildren(true)) { - Transform match = sourceBones[i] != null ? FindBoneByName(playerBones, sourceBones[i].name) : null; - remapped[i] = match != null ? match : playerBones[0]; + Object.DestroyImmediate(comp); + } + foreach (Animator animator in obj.GetComponentsInChildren(true)) + { + Object.DestroyImmediate(animator); + } + foreach (LODGroup lod in obj.GetComponentsInChildren(true)) + { + Object.DestroyImmediate(lod); + } + foreach (Rigidbody body in obj.GetComponentsInChildren(true)) + { + Object.DestroyImmediate(body); + } + foreach (Collider col in obj.GetComponentsInChildren(true)) + { + Object.DestroyImmediate(col); } - renderer.bones = remapped; - renderer.rootBone = sourceRoot != null - ? (FindBoneByName(playerBones, sourceRoot.name) ?? playerBones[0]) - : playerBones[0]; } /// @@ -254,138 +229,44 @@ namespace RacesOfValheim } } - private static void StripBehaviours(GameObject obj) + private static GameObject ResolveDvergerVisual() { - // Anything that would make a decorative mesh behave like a world object - hover - // prompts, pickup triggers, AI, physics. - foreach (MonoBehaviour comp in obj.GetComponentsInChildren(true)) - { - Object.DestroyImmediate(comp); - } - foreach (Rigidbody body in obj.GetComponentsInChildren(true)) - { - Object.DestroyImmediate(body); - } - foreach (Collider col in obj.GetComponentsInChildren(true)) - { - Object.DestroyImmediate(col); - } - } + if (visualResolved) return cachedVisual; + visualResolved = true; - /// - /// Digs the headgear out of the Dvergr NPC prefab. Resolved once and remembered, including - /// the failure, so a missing prefab cannot turn into a per-frame log. - /// - private static HoodSource ResolveHoodSource() - { - if (hoodSourceResolved) return cachedHoodSource; - hoodSourceResolved = true; - - // A hand-pinned prefab and index wins outright, for when neither name search finds it. - if (!string.IsNullOrEmpty(DvergurConfig.HoodForcedPrefab) && DvergurConfig.HoodForcedSubmeshIndex >= 0) + GameObject prefab = PrefabManager.Cache.GetPrefab(DvergurConfig.DvergerPrefabName); + if (prefab == null) { - GameObject forced = PrefabManager.Cache.GetPrefab(DvergurConfig.HoodForcedPrefab); - SkinnedMeshRenderer forcedRenderer = forced != null ? forced.GetComponentInChildren(true) : null; - if (forcedRenderer != null) - { - Jotunn.Logger.LogInfo($"[Dvergur] Hood pinned to '{DvergurConfig.HoodForcedPrefab}' submesh {DvergurConfig.HoodForcedSubmeshIndex}."); - cachedHoodSource = HoodSource.FromSubmesh(forcedRenderer, DvergurConfig.HoodForcedSubmeshIndex); - return cachedHoodSource; - } + Jotunn.Logger.LogWarning($"[Dvergur] Prefab '{DvergurConfig.DvergerPrefabName}' not found; no hood."); + return null; } - System.Text.StringBuilder report = new System.Text.StringBuilder(); - - foreach (string prefabName in DvergurConfig.DvergerPrefabCandidates) + Transform visual = prefab.transform.Find(DvergurConfig.DvergerVisualName); + if (visual == null) { - GameObject prefab = PrefabManager.Cache.GetPrefab(prefabName); - if (prefab == null) continue; - - // First choice: the hood is its own object. - foreach (Renderer renderer in prefab.GetComponentsInChildren(true)) - { - if (!MatchesAny(renderer.gameObject.name, DvergurConfig.HoodRendererNames)) continue; - - Jotunn.Logger.LogInfo($"[Dvergur] Hood resolved to object '{renderer.gameObject.name}' in '{prefabName}'."); - cachedHoodSource = HoodSource.FromObject(renderer.gameObject); - return cachedHoodSource; - } - - // Second choice: it is a submesh of a combined mesh, identified by its material. - foreach (SkinnedMeshRenderer smr in prefab.GetComponentsInChildren(true)) - { - Material[] materials = smr.sharedMaterials; - for (int i = 0; i < materials.Length; i++) - { - if (materials[i] == null || !MatchesAny(materials[i].name, DvergurConfig.HoodMaterialNames)) continue; - - Jotunn.Logger.LogInfo($"[Dvergur] Hood resolved to submesh {i} ('{materials[i].name}') of '{smr.name}' in '{prefabName}'."); - cachedHoodSource = HoodSource.FromSubmesh(smr, i); - return cachedHoodSource; - } - - // Nothing matched here, so record what this renderer actually offers. - report.Append($"\n {prefabName}/{smr.name}: submeshes={smr.sharedMesh?.subMeshCount ?? 0} materials=["); - for (int i = 0; i < materials.Length; i++) - { - report.Append(i).Append(':').Append(materials[i] != null ? materials[i].name : "null").Append(' '); - } - report.Append(']'); - } + // Fall back to whatever holds the renderer, in case the child is ever renamed. + SkinnedMeshRenderer renderer = prefab.GetComponentInChildren(true); + visual = renderer != null ? renderer.transform.parent : null; } - // Say exactly what was on offer: that turns a silently invisible hood into a one-line - // fix in DvergurConfig, either a new keyword or a pinned submesh index. - Jotunn.Logger.LogWarning( - $"[Dvergur] No hood found. Object names tried [{string.Join(", ", DvergurConfig.HoodRendererNames)}], " + - $"material names tried [{string.Join(", ", DvergurConfig.HoodMaterialNames)}]." + - $" Candidates:{report}"); - return HoodSource.None; - } - - /// Where the hood mesh comes from: a whole object, or one submesh of a shared mesh. - private struct HoodSource - { - public GameObject Separate; - public SkinnedMeshRenderer Skinned; - public int SubmeshIndex; - - public bool Valid => Separate != null || (Skinned != null && SubmeshIndex >= 0); - - public static HoodSource None => new HoodSource { SubmeshIndex = -1 }; - - public static HoodSource FromObject(GameObject obj) => - new HoodSource { Separate = obj, SubmeshIndex = -1 }; - - public static HoodSource FromSubmesh(SkinnedMeshRenderer renderer, int index) => - new HoodSource { Skinned = renderer, SubmeshIndex = index }; - } - - private static bool MatchesAny(string name, string[] keywords) - { - if (string.IsNullOrEmpty(name)) return false; - string lower = name.ToLower(); - foreach (string keyword in keywords) + if (visual == null) { - if (lower.Contains(keyword)) return true; + Jotunn.Logger.LogWarning( + $"[Dvergur] '{DvergurConfig.DvergerPrefabName}' has no '{DvergurConfig.DvergerVisualName}' child and no renderer; no hood."); + return null; } - return false; + + Jotunn.Logger.LogInfo($"[Dvergur] Hood source resolved to '{DvergurConfig.DvergerPrefabName}/{visual.name}'."); + cachedVisual = visual.gameObject; + return cachedVisual; } private static void RemoveHood(VisEquipment visEq) { - if (visEq.m_bodyModel == null) return; - - Transform parent = visEq.m_bodyModel.transform.parent; - Transform hood = parent != null ? parent.Find(HoodName) : null; - - // Fall back to the head bone for the rigid-hood case, which parents itself there. - if (hood == null && visEq.m_bodyModel.bones != null) - { - Transform headBone = FindBoneByName(visEq.m_bodyModel.bones, "Head"); - if (headBone != null) hood = headBone.Find(HoodName); - } + if (visEq.m_bodyModel == null || visEq.m_bodyModel.bones == null) return; + Transform playerHead = FindBoneByName(visEq.m_bodyModel.bones, DvergurConfig.PlayerHeadBoneName); + Transform hood = playerHead != null ? playerHead.Find(HoodName) : null; 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 @@ -400,6 +281,8 @@ namespace RacesOfValheim } } + // ─── Bone lookup ───────────────────────────────────────────────────── + private static Transform FindBoneByName(Transform[] bones, string targetBoneName) { if (bones == null || string.IsNullOrEmpty(targetBoneName)) return null; @@ -418,5 +301,19 @@ namespace RacesOfValheim } return null; } + + /// Depth-first search by exact name; the dvergr rig nests bones many levels deep. + private static Transform FindChildByName(Transform root, string name) + { + if (root == null) return null; + if (root.name == name) return root; + + for (int i = 0; i < root.childCount; i++) + { + Transform found = FindChildByName(root.GetChild(i), name); + if (found != null) return found; + } + return null; + } } }