From 835ff89ed5934443e41123da38225b9a5cd6e2bf Mon Sep 17 00:00:00 2001 From: BoroBongo Date: Sun, 22 Nov 2026 02:31:35 +0000 Subject: [PATCH] fix: NPCs change their look when they change armor at runtime - G2 Greg wears the farmer clothes you give him - An already built NPC whose visual body changes (NpcVisualBodyChanged: armor (un)equipped, Mdl_SetVisualBody) gets its body's skinned meshes swapped on its existing skeleton (NpcMeshBuilder.RebuildBody via MeshService.RebuildNpcBody, listener in NpcService). The skeleton is put into its rest pose for the rebuild, as bind poses are written into the cached, shared mesh. Fatness/ghost looks are applied again. The hero is skipped. - Armor attachments go into an own child of their bone, so the old armor's ones (Greg's captain hat) are removed. - Color-only (untextured) sub meshes of NPC bodies are drawn in their color instead of being skipped, which also shifted every following material by one sub mesh. Ported from the experimental branch (b44135034, 2c1352259) onto develop's builders. --- .../Meshes/Builder/AbstractMeshBuilder.cs | 129 +++++++++++------- .../Domain/Meshes/Builder/NpcMeshBuilder.cs | 76 +++++++++++ .../Domain/Npc/NpcInitializerDomain.cs | 27 ++++ .../Scripts/Services/Meshes/MeshService.cs | 19 +++ .../Scripts/Services/Npc/NpcService.cs | 2 + 5 files changed, 202 insertions(+), 51 deletions(-) diff --git a/Assets/Gothic-Core/Scripts/Domain/Meshes/Builder/AbstractMeshBuilder.cs b/Assets/Gothic-Core/Scripts/Domain/Meshes/Builder/AbstractMeshBuilder.cs index 40966a7cf..d5ebc33d3 100644 --- a/Assets/Gothic-Core/Scripts/Domain/Meshes/Builder/AbstractMeshBuilder.cs +++ b/Assets/Gothic-Core/Scripts/Domain/Meshes/Builder/AbstractMeshBuilder.cs @@ -290,58 +290,9 @@ protected virtual GameObject[] BuildViaMdmAndMdh() } //// Fill GameObjects with Meshes from "original" Mesh - var meshCounter = 0; - foreach (var softSkinMesh in Mdm.Meshes) - { - var mesh = softSkinMesh.Mesh; - - var meshObj = new GameObject($"ZM_{meshCounter}"); - meshObj.SetParent(RootGo); - - var meshFilter = meshObj.AddComponent(); - var meshRenderer = meshObj.AddComponent(); - - meshRenderer.material = Constants.LoadingMaterial; - - // Recalculate bbox based on current bones pose+rot when playing animations. - // This can become a performance issue which we need to monitor carefully. - // On top, the name is misleading: updateWhenOffscreen calculates the bbox at all. - // If not set, then no recalculation is done. - // @see https://docs.unity3d.com/2022.2/Documentation/Manual/class-SkinnedMeshRenderer.html - meshRenderer.updateWhenOffscreen = true; - - // HINT: rootBone setting removed. If used, with updateWhenOffscreen e.g. a sitting animation is adding - // too much bound size during animation. - // Custom AnimationsSystem also played nicely when removing the rootBone. - // meshRenderer.rootBone = nodeObjects[0].transform; - - PrepareMeshFilter(meshFilter, softSkinMesh, meshRenderer, meshCounter); - PrepareMeshRenderer(meshRenderer, mesh); - - meshRenderer.sharedMesh = meshFilter.sharedMesh; + var meshCounter = CreateSoftSkinMeshes(nodeObjects); - CreateBonesData(RootGo, nodeObjects, meshRenderer, softSkinMesh); - - meshCounter++; - } - - var attachments = GetFilteredAttachments(Mdm.Attachments); - - // Fill GameObjects with Meshes from attachments - foreach (var subMesh in attachments) - { - var meshObj = nodeObjects.First(bone => bone.name == subMesh.Key); - var meshFilter = meshObj.TryAddComponent(); - var meshRenderer = meshObj.TryAddComponent(); - meshRenderer.material = Constants.LoadingMaterial; - - PrepareMeshFilter(meshFilter, subMesh.Value, meshRenderer, meshCounter); - PrepareMeshRenderer(meshRenderer, subMesh.Value); - PrepareMeshCollider(meshObj, meshFilter.sharedMesh, subMesh.Value); - - // As Attachments are also just meshes, we need to increase the mesh counter for Filter's meshCache index. - meshCounter++; - } + CreateAttachments(nodeObjects, meshCounter); SetPosAndRot(RootGo, RootPosition, RootRotation); @@ -929,6 +880,82 @@ protected Material GetWaterMaterial() return new Material(Constants.ShaderWater); } + /// + /// Skinned meshes of the .mdm on the given bones (ZM_0, ZM_1, ...). Returns the mesh counter for the attachments. + /// Also used to swap an NPC's body (armor) at runtime on its existing skeleton (NpcMeshBuilder.RebuildBody). + /// + protected int CreateSoftSkinMeshes(GameObject[] nodeObjects) + { + var meshCounter = 0; + foreach (var softSkinMesh in Mdm.Meshes) + { + var mesh = softSkinMesh.Mesh; + + var meshObj = new GameObject($"ZM_{meshCounter}"); + meshObj.SetParent(RootGo); + + var meshFilter = meshObj.AddComponent(); + var meshRenderer = meshObj.AddComponent(); + + meshRenderer.material = Constants.LoadingMaterial; + + // Recalculate bbox based on current bones pose+rot when playing animations. + // This can become a performance issue which we need to monitor carefully. + // On top, the name is misleading: updateWhenOffscreen calculates the bbox at all. + // If not set, then no recalculation is done. + // @see https://docs.unity3d.com/2022.2/Documentation/Manual/class-SkinnedMeshRenderer.html + meshRenderer.updateWhenOffscreen = true; + + // HINT: rootBone setting removed. If used, with updateWhenOffscreen e.g. a sitting animation is adding + // too much bound size during animation. + // Custom AnimationsSystem also played nicely when removing the rootBone. + // meshRenderer.rootBone = nodeObjects[0].transform; + + PrepareMeshFilter(meshFilter, softSkinMesh, meshRenderer, meshCounter); + PrepareMeshRenderer(meshRenderer, mesh); + + meshRenderer.sharedMesh = meshFilter.sharedMesh; + + CreateBonesData(RootGo, nodeObjects, meshRenderer, softSkinMesh); + + meshCounter++; + } + + return meshCounter; + } + + /// + /// Rigid meshes of the .mdm attached to bones (e.g. a hat of an armor, a skeleton's skull). + /// + protected void CreateAttachments(GameObject[] nodeObjects, int meshCounter) + { + var attachments = GetFilteredAttachments(Mdm.Attachments); + + // Fill GameObjects with Meshes from attachments + foreach (var subMesh in attachments) + { + var meshObj = GetAttachmentGo(nodeObjects.First(bone => bone.name == subMesh.Key)); + var meshFilter = meshObj.TryAddComponent(); + var meshRenderer = meshObj.TryAddComponent(); + meshRenderer.material = Constants.LoadingMaterial; + + PrepareMeshFilter(meshFilter, subMesh.Value, meshRenderer, meshCounter); + PrepareMeshRenderer(meshRenderer, subMesh.Value); + PrepareMeshCollider(meshObj, meshFilter.sharedMesh, subMesh.Value); + + // As Attachments are also just meshes, we need to increase the mesh counter for Filter's meshCache index. + meshCounter++; + } + } + + /// + /// The GameObject which holds an attachment's mesh. Default: the bone itself. + /// + protected virtual GameObject GetAttachmentGo(GameObject node) + { + return node; + } + protected void SetPosAndRot(GameObject obj, Matrix4x4 matrix) { SetPosAndRot(obj, matrix.ToUnityMatrix()); diff --git a/Assets/Gothic-Core/Scripts/Domain/Meshes/Builder/NpcMeshBuilder.cs b/Assets/Gothic-Core/Scripts/Domain/Meshes/Builder/NpcMeshBuilder.cs index 21038c301..037334711 100644 --- a/Assets/Gothic-Core/Scripts/Domain/Meshes/Builder/NpcMeshBuilder.cs +++ b/Assets/Gothic-Core/Scripts/Domain/Meshes/Builder/NpcMeshBuilder.cs @@ -19,6 +19,8 @@ public class NpcMeshBuilder : AbstractMeshBuilder { [Inject] private readonly NpcArmorPositionCacheService _npcArmorCacheService; + // Attachments live in an own child of their bone, so an armor change can remove them again. + private const string _attachmentGoName = "_Attachment"; protected ExtSetVisualBodyData BodyData; private bool _isHitboxExpected; @@ -45,6 +47,68 @@ public override GameObject Build() return RootGo; } + /// + /// Runtime armor change (EquipItem, AI_EquipArmor, Mdl_SetVisualBody, a script taking the armor): replaces + /// the body's skinned meshes (ZM_*) and the armor's attachments (e.g. Greg's hat) with the ones of the current + /// .mdm on the NPC's existing skeleton. Head, weapons, helmet, colliders and the animation stay untouched. + /// + public bool RebuildBody() + { + if (Mdh == null || Mdm == null) + { + Logger.LogWarning($"[ArmorVisual] No .mdh/.mdm '{MeshName}' for {RootGo.name} - body not rebuilt.", + LogCat.Mesh); + return false; + } + + var nodeObjects = new GameObject[Mdh.Nodes.Count]; + for (var i = 0; i < Mdh.Nodes.Count; i++) + { + nodeObjects[i] = RootGo.FindChildRecursively(Mdh.Nodes[i].Name); + if (nodeObjects[i] == null) + { + Logger.LogWarning($"[ArmorVisual] Bone '{Mdh.Nodes[i].Name}' missing on {RootGo.name} - body not " + + "rebuilt.", LogCat.Mesh); + return false; + } + } + + foreach (Transform child in RootGo.transform) + { + if (child.name.StartsWith("ZM_") && child.GetComponent() != null) + Object.Destroy(child.gameObject); + } + + // Attachments of the old armor (e.g. Greg's captain hat) go with it. + foreach (var oldAttachment in RootGo.GetComponentsInChildren(true)) + { + if (oldAttachment.name == _attachmentGoName) + Object.Destroy(oldAttachment.gameObject); + } + + // Bind poses are calculated from the bones' current pose (CreateBonesData) and written into the cached, + // shared mesh. An animated NPC would bake its current pose into it - mangled armor for everyone wearing it. + // The skeleton goes into its rest pose (like during the initial build) for the rebuild, then back. + var animatedPositions = new UnityEngine.Vector3[nodeObjects.Length]; + var animatedRotations = new Quaternion[nodeObjects.Length]; + for (var i = 0; i < nodeObjects.Length; i++) + { + nodeObjects[i].transform.GetLocalPositionAndRotation(out animatedPositions[i], out animatedRotations[i]); + + SetPosAndRot(nodeObjects[i], Mdh.Nodes[i].Transform); + if (Mdh.Nodes[i].ParentIndex == -1) + nodeObjects[i].transform.localPosition = Mdh.RootTranslation.ToUnityVector(); + } + + var meshCounter = CreateSoftSkinMeshes(nodeObjects); + CreateAttachments(nodeObjects, meshCounter); + + for (var i = 0; i < nodeObjects.Length; i++) + nodeObjects[i].transform.SetLocalPositionAndRotation(animatedPositions[i], animatedRotations[i]); + + return true; + } + protected override GameObject[] BuildViaMdmAndMdh() { var nodeObjects = base.BuildViaMdmAndMdh(); @@ -93,6 +157,18 @@ protected override Dictionary GetFilteredAttachmen return newAttachments; } + /// + /// An attachment goes into an own child of its bone: a hat on BIP01 HEAD would otherwise share the bone's + /// MeshFilter, and RebuildBody can remove the old armor's attachments again. + /// + protected override GameObject GetAttachmentGo(GameObject node) + { + var attachmentGo = new GameObject(_attachmentGoName); + attachmentGo.transform.SetParent(node.transform, false); + attachmentGo.layer = node.layer; + return attachmentGo; + } + /// /// Positions in mdm files for NPC armor isn't what it seems to be. We need to calculate the real data from weights. /// Please check the Cache class for more details. diff --git a/Assets/Gothic-Core/Scripts/Domain/Npc/NpcInitializerDomain.cs b/Assets/Gothic-Core/Scripts/Domain/Npc/NpcInitializerDomain.cs index f78fb9ec5..1fc1659f3 100644 --- a/Assets/Gothic-Core/Scripts/Domain/Npc/NpcInitializerDomain.cs +++ b/Assets/Gothic-Core/Scripts/Domain/Npc/NpcInitializerDomain.cs @@ -473,6 +473,33 @@ public void InitNpc(NpcInstance npcInstance, GameObject lazyLoadGo) _npcLookService.Apply(npcData); } + /// + /// The NPC's visual body changed (NpcVisualBodyChanged: an armor (un)equipped, Mdl_SetVisualBody) after its mesh + /// was built: the body is swapped on the existing skeleton, like the engine (G2 Greg putting on the farmer + /// clothes). Not built yet (lazy loading): InitNpc builds it from props.MdmName later. The hero is skipped - his + /// GameObject is the player rig, the VR hero body rebuilds itself. + /// + public void RebuildBody(NpcContainer npc) + { + if (npc?.Go == null || npc.Vob == null || npc.Vob.Player) + return; + + var props = npc.Props; + if (string.IsNullOrEmpty(props.MdmName)) + return; + + var mdhName = string.IsNullOrEmpty(props.MdhNameOverlay) + ? props.MdhNameBase + : props.MdhNameOverlay; + if (!_meshService.RebuildNpcBody(npc.Go, props.MdmName, mdhName, props.BodyData)) + return; + + // Fatness and ghosts are set on the body's materials - the new ones need them too. + _npcLookService.Apply(npc); + Logger.Log($"[ArmorVisual] {npc.Instance.GetName(NpcNameSlot.Slot0)}: body rebuilt as '{props.MdmName}'", + LogCat.Npc); + } + [CanBeNull] private WayNetPoint GetSpawnPoint(NpcContainer npc, string fallbackSpawnPoint) { diff --git a/Assets/Gothic-Core/Scripts/Services/Meshes/MeshService.cs b/Assets/Gothic-Core/Scripts/Services/Meshes/MeshService.cs index ab2302d6b..96562553f 100644 --- a/Assets/Gothic-Core/Scripts/Services/Meshes/MeshService.cs +++ b/Assets/Gothic-Core/Scripts/Services/Meshes/MeshService.cs @@ -39,6 +39,9 @@ public GameObject CreateNpc(string npcName, string mdmName, string mdhName, ExtS npcBuilder.SetMdm(mdmName); npcBuilder.SetBodyData(bodyData); npcBuilder.SetHitboxExpected(isHitboxExpected); + // Color-only armor parts (e.g. Greg's captain hat, material KOPFTUCH) are drawn in their color like in the + // engine. Skipping them hid the part and shifted all following materials by one sub mesh. + npcBuilder.SetAllowUntextured(true); var npcGo = npcBuilder.Build(); @@ -53,6 +56,22 @@ public GameObject CreateNpc(string npcName, string mdmName, string mdhName, ExtS return npcGo; } + /// + /// Swaps the body/armor mesh of an already built NPC (runtime armor change) on its existing skeleton. + /// + public bool RebuildNpcBody(GameObject npcRoot, string mdmName, string mdhName, ExtSetVisualBodyData bodyData) + { + var npcBuilder = new NpcMeshBuilder().Inject(); + npcBuilder.SetGameObject(npcRoot); + npcBuilder.SetMeshName(mdmName); + npcBuilder.SetMdh(mdhName); + npcBuilder.SetMdm(mdmName); + npcBuilder.SetBodyData(bodyData); + npcBuilder.SetAllowUntextured(true); + + return npcBuilder.RebuildBody(); + } + public GameObject CreateNpcWeapon(GameObject npcGo, ItemInstance itemData, VmGothicEnums.ItemFlags mainFlag, VmGothicEnums.ItemFlags flags, bool isEquipped = false) { diff --git a/Assets/Gothic-Core/Scripts/Services/Npc/NpcService.cs b/Assets/Gothic-Core/Scripts/Services/Npc/NpcService.cs index d916fa836..78a44b9ea 100644 --- a/Assets/Gothic-Core/Scripts/Services/Npc/NpcService.cs +++ b/Assets/Gothic-Core/Scripts/Services/Npc/NpcService.cs @@ -82,6 +82,8 @@ public void Init() GlobalEventDispatcher.NpcMeshCullingChanged.AddListener(EventNpcMeshCullingChanged); GlobalEventDispatcher.CreateNpc.AddListener(CreateVobNpc); + // An armor change of an already built NPC swaps its body mesh (G2 Greg in the farmer clothes). + GlobalEventDispatcher.NpcVisualBodyChanged.AddListener(_initializerDomain.RebuildBody); } public void ClearQueues()