diff --git a/JotunnModStub/Factions/FactionHostilityPatch.cs b/JotunnModStub/Factions/FactionHostilityPatch.cs index c171a84..f8f873f 100644 --- a/JotunnModStub/Factions/FactionHostilityPatch.cs +++ b/JotunnModStub/Factions/FactionHostilityPatch.cs @@ -126,12 +126,43 @@ namespace RacesOfValheim return player.m_customData.TryGetValue("Race", out string race) ? race : null; } + // The truce used to cover the player only. A thrall is tamed, so it sits in the Players + // faction, and a wild mob of the player's own faction still saw it as fair game: a wild + // Rancid Remains walked up to a Skeleton's bone pile, ignored the Skeleton and tore into + // the garrison. The thrall's own race is on the prefab (m_commandingRace), so the same + // faction sets answer for it without needing its owner nearby. + // + // The truce breaks the moment that wild mob holds a grudge against any player: it is + // fighting the thralls' master, and the thralls should fight back. + private static bool IsThrallTruce(Character thrallSide, Character wildSide) + { + if (wildSide.IsPlayer() || wildSide.IsTamed()) return false; + + RaisedThrall thrall = thrallSide.GetComponent(); + if (thrall == null || string.IsNullOrEmpty(thrall.m_commandingRace)) return false; + if (wildSide.GetComponent() != null) return false; + + if (!IsAlliedMob(thrall.m_commandingRace, wildSide.gameObject.name)) return false; + + foreach (Player player in Player.GetAllPlayers()) + { + if (RaceGrudge.Holds(wildSide, player)) return false; + } + return true; + } + public static void Postfix(Character a, Character b, ref bool __result) { if (!FactionsConfig.Hostility) return; if (!__result) return; // already not enemies, nothing to add if (a == null || b == null) return; + if (IsThrallTruce(a, b) || IsThrallTruce(b, a)) + { + __result = false; + return; + } + Character playerCharacter = a.IsPlayer() ? a : (b.IsPlayer() ? b : null); Character monster = a.IsPlayer() ? b : (b.IsPlayer() ? a : null); if (!(playerCharacter is Player p) || monster == null) return; diff --git a/JotunnModStub/Skeleton/SkeletonBonePile.cs b/JotunnModStub/Skeleton/SkeletonBonePile.cs index 9c6d6c1..af65819 100644 --- a/JotunnModStub/Skeleton/SkeletonBonePile.cs +++ b/JotunnModStub/Skeleton/SkeletonBonePile.cs @@ -326,8 +326,10 @@ namespace RacesOfValheim piece.m_resources = new Piece.Requirement[0]; piece.m_name = PieceDisplayName; piece.m_canBeRemoved = true; - piece.m_groundPiece = true; - piece.m_groundOnly = true; + // Neither flag: a garrison belongs inside the house as much as outside it, so the pile + // goes on floors and foundations too, not only on terrain. + piece.m_groundPiece = false; + piece.m_groundOnly = false; piece.m_icon = BorrowIcon("TrophySkeleton"); // A Piece added to world scenery is born with no icon and no place effect - the Furling's diff --git a/JotunnModStub/Skeleton/SkeletonPatches.cs b/JotunnModStub/Skeleton/SkeletonPatches.cs index e28239a..b977f35 100644 --- a/JotunnModStub/Skeleton/SkeletonPatches.cs +++ b/JotunnModStub/Skeleton/SkeletonPatches.cs @@ -613,6 +613,9 @@ namespace RacesOfValheim int state = BossProgressionManager.GetCurrentProgressionState(); var rules = SkeletonProgression.GetRules(state); + // Half in the ground: nothing lands on a Skeleton while it climbs back out. + if (__instance == Player.m_localPlayer && SkeletonRise.IsRising(Player.m_localPlayer)) return false; + // Auto-Resurrect check if (__instance == Player.m_localPlayer && SkeletonRace.IsSkeleton() && rules.AutoResurrect) { @@ -633,6 +636,9 @@ namespace RacesOfValheim UnityEngine.Object.Instantiate(vfx, Player.m_localPlayer.transform.position, Quaternion.identity); } + // The body climbs out of the ground the way a crypt skeleton does. + SkeletonRise.Begin(Player.m_localPlayer); + Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_skeleton_have_been_resurrected_by_dark")); return false; // Skip applying this lethal damage } diff --git a/JotunnModStub/Skeleton/SkeletonRise.cs b/JotunnModStub/Skeleton/SkeletonRise.cs new file mode 100644 index 0000000..d44cd75 --- /dev/null +++ b/JotunnModStub/Skeleton/SkeletonRise.cs @@ -0,0 +1,278 @@ +using System; +using System.Collections.Generic; +using HarmonyLib; +using Jotunn.Managers; +using UnityEngine; +using Object = UnityEngine.Object; + +namespace RacesOfValheim +{ + /// + /// The Skeleton's auto-resurrection, played as the crypt rise: the body climbs out of the ground + /// instead of simply staying on its feet. + /// + /// The player cannot play that clip itself. A Skeleton player is the human rig wearing a + /// skeleton's meshes (see VisEquipment_UpdateVisuals_Patch), and the human controller has no + /// rise state - "wakeup" lives in the skeleton creature's own controller. So for the few seconds + /// of the rise the player's Visual is hidden and a costume is worn in its place: the creature's + /// animated model, stripped down to renderers and its Animator, with the same "wakeup" bool set + /// that vanilla's CreatureSpawner sets on a Spawner_Skeleton_rise skeleton. + /// + /// The start time goes on the ZDO, so every client that can see this player plays the same rise. + /// While it runs the local player takes no damage and does not move: they are half in the ground. + /// + public static class SkeletonRise + { + public const string ZdoKey = "RoV_skelRiseAt"; + + // How long after the start a client that only just noticed the key still bothers to play it. + // A player who walks into view a minute later should not see a resurrection replayed. + private const float RemoteLateStartSeconds = 2f; + + private const float FallbackSeconds = 3f; + private const float MaxSeconds = 6f; + + // Clips that look like a rise, by name. Matched loosely and logged once, so a wrong pick + // shows up in the log with every clip the controller actually has. + private static readonly string[] RiseClipWords = { "wake", "rise", "spawn", "getup", "emerge" }; + + private static readonly Dictionary templates = new Dictionary(); + private static readonly Dictionary riseSeconds = new Dictionary(); + + public static bool IsRising(Player player) + { + if (player == null) return false; + SkeletonRiseCostume costume = player.GetComponent(); + return costume != null && costume.IsPlaying; + } + + /// Starts the rise for the local player and tells everyone else. + public static void Begin(Player player) + { + if (player == null || ZNet.instance == null) return; + + long ticks = ZNet.instance.GetTime().Ticks; + ZNetView nview = player.GetComponent(); + if (nview != null && nview.IsValid()) nview.GetZDO().Set(ZdoKey, ticks); + + Play(player, ticks); + } + + /// For a remote player: plays a rise this client has not played yet, if it is fresh. + public static void CheckRemote(Player player) + { + if (player == null || ZNet.instance == null) return; + + ZNetView nview = player.GetComponent(); + if (nview == null || !nview.IsValid()) return; + + long ticks = nview.GetZDO().GetLong(ZdoKey, 0L); + if (ticks == 0L) return; + + SkeletonRiseCostume costume = player.GetComponent(); + if (costume != null && costume.StartedTicks == ticks) return; + + double age = (ZNet.instance.GetTime() - new DateTime(ticks)).TotalSeconds; + if (age < 0 || age > RemoteLateStartSeconds) + { + // Remember it anyway, so the age is not worked out again every frame. + if (costume == null) costume = player.gameObject.AddComponent(); + costume.StartedTicks = ticks; + return; + } + + Play(player, ticks); + } + + private static void Play(Player player, long ticks) + { + string model = SkeletonVisuals.GetModel(player, SkeletonVisuals.GetProgressionState(player)); + GameObject template = GetTemplate(model); + if (template == null) return; + + SkeletonRiseCostume costume = player.GetComponent() + ?? player.gameObject.AddComponent(); + costume.StartedTicks = ticks; + costume.Play(template, riseSeconds.TryGetValue(model, out float seconds) ? seconds : FallbackSeconds); + } + + /// + /// The creature's animated model, stripped once per model name. Built into an inactive + /// holder, so nothing on the copy wakes before the strip - the rule ModelBorrow exists for. + /// + private static GameObject GetTemplate(string modelPrefab) + { + if (templates.TryGetValue(modelPrefab, out GameObject cached)) return cached; + templates[modelPrefab] = null; + + GameObject source = PrefabManager.Cache.GetPrefab(modelPrefab); + Animator sourceAnim = source != null ? source.GetComponentInChildren(true) : null; + if (sourceAnim == null) + { + Jotunn.Logger.LogWarning($"[Skeleton] Rise: no animated model on '{modelPrefab}'; the resurrection plays without the rise."); + return null; + } + + GameObject holder = new GameObject("SkeletonRiseTemplate_" + modelPrefab); + Object.DontDestroyOnLoad(holder); + holder.SetActive(false); // BEFORE Instantiate: nothing on the copy gets to Awake. + + GameObject copy = Object.Instantiate(sourceAnim.gameObject, holder.transform); + copy.name = "model"; + copy.transform.localPosition = sourceAnim.transform.localPosition; + copy.transform.localRotation = sourceAnim.transform.localRotation; + copy.transform.localScale = sourceAnim.transform.localScale; + + // Everything that is not a Renderer, a Transform or the Animator. Animator is a Behaviour, + // not a MonoBehaviour, so the first loop never touches it. + foreach (MonoBehaviour behaviour in copy.GetComponentsInChildren(true)) + { + if (behaviour != null) Object.DestroyImmediate(behaviour); + } + foreach (Collider collider in copy.GetComponentsInChildren(true)) + { + if (collider != null) Object.DestroyImmediate(collider); + } + foreach (Rigidbody body in copy.GetComponentsInChildren(true)) + { + if (body != null) Object.DestroyImmediate(body); + } + + riseSeconds[modelPrefab] = MeasureRise(sourceAnim, modelPrefab); + templates[modelPrefab] = copy; + return copy; + } + + private static float MeasureRise(Animator animator, string modelPrefab) + { + RuntimeAnimatorController controller = animator.runtimeAnimatorController; + if (controller == null) return FallbackSeconds; + + AnimationClip best = null; + List names = new List(); + foreach (AnimationClip clip in controller.animationClips) + { + if (clip == null) continue; + names.Add($"{clip.name} ({clip.length:0.00}s)"); + + string lower = clip.name.ToLower(); + foreach (string word in RiseClipWords) + { + if (!lower.Contains(word)) continue; + if (best == null || clip.length > best.length) best = clip; + break; + } + } + + float seconds = best != null ? Mathf.Clamp(best.length, 1f, MaxSeconds) : FallbackSeconds; + Jotunn.Logger.LogInfo( + $"[Skeleton] Rise on '{modelPrefab}': clip '{(best != null ? best.name : "none, fallback")}', {seconds:0.00}s. " + + $"Clips: {string.Join(", ", names.ToArray())}"); + return seconds; + } + } + + /// The worn costume for one rise. Lives on the player and is reused for the next one. + public class SkeletonRiseCostume : MonoBehaviour + { + private const string HiderContext = "skeleton-rise"; + + public long StartedTicks; + + private Player m_player; + private GameObject m_model; + private float m_endsAt; + + public bool IsPlaying => m_model != null; + + public void Play(GameObject template, float seconds) + { + m_player = GetComponent(); + End(); + + m_model = Instantiate(template, transform); + m_model.name = "SkeletonRiseCostume"; + m_model.transform.localPosition = template.transform.localPosition; + m_model.transform.localRotation = template.transform.localRotation; + m_model.transform.localScale = template.transform.localScale; + + Animator anim = m_model.GetComponentInChildren(); + if (anim != null) + { + // Same settings the other borrowed costumes use: the clip must not walk the model off + // its wearer, its events have no receivers left, and it keeps animating close to the + // camera. + anim.applyRootMotion = false; + anim.fireEvents = false; + anim.cullingMode = AnimatorCullingMode.AlwaysAnimate; + + bool hasWakeup = false; + foreach (AnimatorControllerParameter param in anim.parameters) + { + if (param.type == AnimatorControllerParameterType.Bool && param.name == "wakeup") hasWakeup = true; + } + + if (hasWakeup) + { + anim.SetBool("wakeup", true); + // Settle into the rise now, so the first rendered frame is not a standing skeleton. + anim.Update(0f); + anim.Update(0f); + } + else + { + Jotunn.Logger.LogWarning("[Skeleton] Rise: the model's Animator has no 'wakeup' bool; it will stand instead of rising."); + } + } + + PlayerVisualHider.Hide(transform.Find("Visual"), HiderContext); + m_endsAt = Time.time + seconds; + } + + private void Update() + { + if (m_model == null) return; + if (Time.time >= m_endsAt || m_player == null || m_player.IsDead()) End(); + } + + private void End() + { + if (m_model == null) return; + + // Switched off first: Destroy waits for the end of the frame, and nothing on the costume + // should run in between. + m_model.SetActive(false); + Destroy(m_model); + m_model = null; + + PlayerVisualHider.Show(transform.Find("Visual"), HiderContext); + } + + private void OnDestroy() => End(); + } + + /// + /// Holds the local player still while they climb out. The movement direction is bound by + /// position, not name: it is the first argument of Player.SetControls. + /// + [HarmonyPatch(typeof(Player), "SetControls")] + public static class SkeletonRiseControlsPatch + { + public static void Prefix(Player __instance, ref Vector3 __0, + ref bool attack, ref bool attackHold, + ref bool secondaryAttack, ref bool secondaryAttackHold, + ref bool jump, ref bool crouch, ref bool dodge) + { + if (__instance != Player.m_localPlayer || !SkeletonRise.IsRising(__instance)) return; + + __0 = Vector3.zero; + attack = false; + attackHold = false; + secondaryAttack = false; + secondaryAttackHold = false; + jump = false; + crouch = false; + dodge = false; + } + } +} diff --git a/JotunnModStub/Skeleton/SkeletonSentry.cs b/JotunnModStub/Skeleton/SkeletonSentry.cs index dd96949..93137e5 100644 --- a/JotunnModStub/Skeleton/SkeletonSentry.cs +++ b/JotunnModStub/Skeleton/SkeletonSentry.cs @@ -150,8 +150,10 @@ namespace RacesOfValheim piece.m_resources = new Piece.Requirement[0]; piece.m_name = DisplayName; piece.m_canBeRemoved = true; - piece.m_groundPiece = true; - piece.m_groundOnly = true; + // Neither flag: a sentry is meant to stand on a wall walk or a floor as much as on the + // ground outside it. + piece.m_groundPiece = false; + piece.m_groundOnly = false; piece.m_icon = BorrowIcon("TrophySkeleton"); PieceManager.Instance.AddPiece(new CustomPiece(prefab, fixReference: false, new PieceConfig diff --git a/JotunnModStub/ZdoVisualSync.cs b/JotunnModStub/ZdoVisualSync.cs index 15fd55a..0df6988 100644 --- a/JotunnModStub/ZdoVisualSync.cs +++ b/JotunnModStub/ZdoVisualSync.cs @@ -65,6 +65,7 @@ namespace RacesOfValheim if (race == "Skeleton") { UpdateSkeletonVisuals(); + SkeletonRise.CheckRemote(m_player); } else if (race == "Fenrir") {