diff --git a/JotunnModStub/RacesOfValheim.cs b/JotunnModStub/RacesOfValheim.cs index be4bdcf..0465b1f 100644 --- a/JotunnModStub/RacesOfValheim.cs +++ b/JotunnModStub/RacesOfValheim.cs @@ -89,6 +89,7 @@ namespace RacesOfValheim CommandManager.Instance.AddConsoleCommand(new AlfarEitrCommand()); CommandManager.Instance.AddConsoleCommand(new AlfarHpCommand()); CommandManager.Instance.AddConsoleCommand(new DumpAnimCommand()); + CommandManager.Instance.AddConsoleCommand(new TrolPoseCommand()); CommandManager.Instance.AddConsoleCommand(new EvilLaughCommand()); } diff --git a/JotunnModStub/Trol/TrolPoseCommand.cs b/JotunnModStub/Trol/TrolPoseCommand.cs new file mode 100644 index 0000000..69ba819 --- /dev/null +++ b/JotunnModStub/Trol/TrolPoseCommand.cs @@ -0,0 +1,112 @@ +using System.Globalization; +using Jotunn.Entities; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// [DEBUG] Tries troll states as the True Form guard and roll, live, until the right frame is + /// found and baked into TrolTrueFormModel. Nothing is saved: a restart goes back to the defaults. + /// + public class TrolPoseCommand : ConsoleCommand + { + // Off troll_animator with scripts/dump_controller.py. Wakeup? and the AnyState entries left + // out: an entry check and transitions, not poses. + private static readonly string[] States = + { + "Movement", "attack", "jump", "punch", "throw", "swing log V", "swing log H", + "Stagger", "Summon", "Sleeping", "Wakeup", "In Water", + }; + + public override string Name => "trolpose"; + + public override string Help => + "[DEBUG] trolpose guard [0-1] - the frame True Form holds while blocking. " + + "trolpose play - plays a state whole on your troll. " + + "trolpose dodge [speed] - the state played when you roll, and how fast. trolpose - lists states and current values."; + + public override void Run(string[] args) + { + if (args.Length == 0) + { + Print($"guard: '{TrolTrueFormModel.GuardState}' at {TrolTrueFormModel.GuardTime:0.00}, " + + $"dodge: '{TrolTrueFormModel.DodgeState ?? "off"}' at speed {TrolTrueFormModel.DodgeSpeed:0.00}"); + Print("states: " + string.Join(", ", States)); + return; + } + + string verb = args[0].ToLowerInvariant(); + float time = -1f; + int nameEnd = args.Length; + // The trailing number: the frame for guard, the speed for dodge. + if ((verb == "guard" || verb == "dodge") && args.Length > 2 && + float.TryParse(args[args.Length - 1], NumberStyles.Float, CultureInfo.InvariantCulture, out float number)) + { + time = number; + nameEnd--; + } + + string typed = string.Join(" ", args, 1, Mathf.Max(0, nameEnd - 1)); + + if (verb == "dodge" && typed.ToLowerInvariant() == "off") + { + TrolTrueFormModel.DodgeState = null; + Print("dodge: off"); + return; + } + + string state = Match(typed); + if (state == null) + { + Print($"unknown state '{typed}'. states: " + string.Join(", ", States)); + return; + } + + switch (verb) + { + case "guard": + TrolTrueFormModel.GuardState = state; + if (time >= 0f) TrolTrueFormModel.GuardTime = Mathf.Clamp01(time); + Print($"guard: '{state}' at {TrolTrueFormModel.GuardTime:0.00}. Hold right click in True Form to see it."); + break; + + case "dodge": + TrolTrueFormModel.DodgeState = state; + if (time > 0f) TrolTrueFormModel.DodgeSpeed = Mathf.Clamp(time, 0.25f, 5f); + Print($"dodge: '{state}' at speed {TrolTrueFormModel.DodgeSpeed:0.00}. Block and jump in True Form to roll."); + break; + + case "play": + Animator anim = TrolTrueFormModel.LocalAnimator; + if (anim == null) + { + Print("play needs True Form on (not Legacy)."); + return; + } + anim.speed = 1f; + anim.CrossFadeInFixedTime("Base Layer." + state, 0.1f, 0, 0f); + Print($"playing '{state}'."); + break; + + default: + Print(Help); + break; + } + } + + private static string Match(string typed) + { + foreach (string s in States) + { + if (string.Equals(s, typed, System.StringComparison.OrdinalIgnoreCase)) return s; + } + return null; + } + + private static void Print(string line) + { + Jotunn.Logger.LogInfo("[Trol] trolpose " + line); + if (Console.instance != null) Console.instance.Print(line); + } + } +} diff --git a/JotunnModStub/Trol/TrolTrueFormBehavior.cs b/JotunnModStub/Trol/TrolTrueFormBehavior.cs index 65ef184..710f2b2 100644 --- a/JotunnModStub/Trol/TrolTrueFormBehavior.cs +++ b/JotunnModStub/Trol/TrolTrueFormBehavior.cs @@ -27,6 +27,9 @@ namespace RacesOfValheim private bool isAttacking; private float busySince = -1f; + private bool guarding; + private bool dodging; + private readonly TrolGuardPose guardPose = new TrolGuardPose(); private GameObject heldLog; private string heldLogName; @@ -42,6 +45,8 @@ namespace RacesOfValheim private void OnDestroy() { TrolTrueFormModel.LocalAttacking = false; + TrolTrueFormModel.EndDodge(); + if (guarding && Player.m_localPlayer != null) TrolTrueFormModel.PublishGuard(Player.m_localPlayer, false); } private void Start() @@ -84,22 +89,60 @@ namespace RacesOfValheim SetAttacking(false); } + // The guard: right click blocks, as it does for the human underneath, and the troll + // holds a pose for it. A roll out of the guard drops it, so the roll is not hidden + // behind a frozen troll. + bool guard = !isAttacking && !player.IsDead() && player.IsBlocking() && !player.InDodge(); + TrolTrueFormModel.TickDodge(); + if (guard) TrolTrueFormModel.EndDodge(); + Guard(player, guard); + if (isAttacking || player.IsDead()) return; bool grounded = locomotion.Mirror(anim, playerAnim, player); + if (guard) return; + + if (player.InDodge()) + { + if (!dodging) TrolTrueFormModel.PlayDodge(anim); + dodging = true; + return; + } + dodging = false; + if (!grounded || !RaceInput.Allowed) return; + // Left punches, middle slams: the vanilla primary and secondary attack. Right click is + // the block, so the slam no longer goes off every time the troll raises its guard. bool log = heldLogName != null; if (RaceInput.AttackDown(0)) { Play(log ? TrolTrueFormModel.AttackKind.LogSwingH : TrolTrueFormModel.AttackKind.Punch); } - else if (RaceInput.AttackDown(1)) + else if (RaceInput.AttackDown(2)) { Play(log ? TrolTrueFormModel.AttackKind.LogSwingV : TrolTrueFormModel.AttackKind.Slam); } } + /// Holds the guard pose while blocking and lets go after, and tells every other + /// client which pose to hold. + private void Guard(Player player, bool on) + { + if (on) + { + guardPose.Hold(anim, TrolTrueFormModel.GuardState, TrolTrueFormModel.GuardTime); + TrolTrueFormModel.PublishGuard(player, true); + guarding = true; + } + else if (guarding) + { + guardPose.Release(anim); + TrolTrueFormModel.PublishGuard(player, false); + guarding = false; + } + } + private void Play(TrolTrueFormModel.AttackKind kind) { TrolTrueFormModel.Profile profile = TrolTrueFormModel.Get(kind); @@ -406,6 +449,8 @@ namespace RacesOfValheim private Animator playerAnim; private ZNetView nview; private string lastAttack; + private bool guarding; + private readonly TrolGuardPose guardPose = new TrolGuardPose(); private readonly FormLocomotion locomotion = new FormLocomotion(); private GameObject heldLog; @@ -438,6 +483,17 @@ namespace RacesOfValheim ReplayAttack(); locomotion.Mirror(anim, playerAnim, player); + + if (TrolTrueFormModel.ReadGuard(nview.GetZDO(), out string guardState, out float guardTime)) + { + guardPose.Hold(anim, guardState, guardTime); + guarding = true; + } + else if (guarding) + { + guardPose.Release(anim); + guarding = false; + } } private void ReplayAttack() diff --git a/JotunnModStub/Trol/TrolTrueFormModel.cs b/JotunnModStub/Trol/TrolTrueFormModel.cs index ef02c33..7ab23e2 100644 --- a/JotunnModStub/Trol/TrolTrueFormModel.cs +++ b/JotunnModStub/Trol/TrolTrueFormModel.cs @@ -79,6 +79,8 @@ namespace RacesOfValheim public static bool LocalActive => localModel != null; + public static Animator LocalAnimator => localModel != null ? localModel.GetComponentInChildren() : null; + /// True while the local troll is in the middle of a swing, a slam or a throw. /// Trol_TrueFormHoldStill_Patch holds the player still for exactly that long. public static bool LocalAttacking { get; set; } @@ -434,6 +436,105 @@ namespace RacesOfValheim nview.GetZDO().Set(AttackTriggerKey, trigger + "#" + attackSeq); } + // ─── Guard and roll poses ──────────────────────────────────────────── + + // The troll has no block or roll of its own, so the guard is one frame of another state held + // still. State names are read off troll_animator with scripts/dump_controller.py: Movement, + // attack, jump, punch, throw, swing log V, swing log H, Stagger, Summon, Sleeping, Wakeup, + // In Water. Both are settable live with the trolpose command until the right frame is found. + public const string MovementState = "Movement"; + // Picked in game with trolpose: the troll half risen out of its Wakeup, arms up. + public static string GuardState = "Wakeup"; + public static float GuardTime = 0.13f; + + /// The state played whole when the player rolls; null plays nothing and the troll + /// slides along with the roll. + public static string DodgeState = "jump"; + + /// How fast the roll state plays: the troll's jump runs longer than a roll, so at 1 + /// the troll was still leaping after the roll had ended. + public static float DodgeSpeed = 2f; + + // The local troll's Animator while its roll state plays, null otherwise. + // Trol_TrueFormDodgeSpeed_Patch keeps its speed up through every FixedUpdate. + private static Animator dodgeAnimator; + private static float dodgeStarted; + + /// Set while the owner's troll holds its guard, to "state|time", so every other + /// client's copy holds the same frame. Empty when it is not guarding. + public const string GuardKey = "RacesOfValheim_TrolTrueFormGuard"; + + public static bool HasState(Animator anim, string state) + { + return anim != null && !string.IsNullOrEmpty(state) && anim.HasState(0, Animator.StringToHash("Base Layer." + state)); + } + + public static void PlayDodge(Animator anim) + { + if (!HasState(anim, DodgeState)) return; + anim.speed = DodgeSpeed; + anim.CrossFadeInFixedTime("Base Layer." + DodgeState, 0.1f, 0, 0f); + dodgeAnimator = anim; + dodgeStarted = Time.time; + } + + /// + /// Called every frame: keeps the roll state at DodgeSpeed while it plays, and puts the speed + /// back once the troll has left it. The first moments are skipped, because the cross-fade + /// into the state only starts on the Animator's next update. + /// + public static void TickDodge() + { + if (dodgeAnimator == null) return; + + int hash = Animator.StringToHash("Base Layer." + DodgeState); + bool inState = dodgeAnimator.GetCurrentAnimatorStateInfo(0).fullPathHash == hash || + (dodgeAnimator.IsInTransition(0) && dodgeAnimator.GetNextAnimatorStateInfo(0).fullPathHash == hash); + + if (inState || Time.time - dodgeStarted < 0.15f) dodgeAnimator.speed = DodgeSpeed; + else EndDodge(); + } + + public static void EndDodge() + { + if (dodgeAnimator != null) dodgeAnimator.speed = 1f; + dodgeAnimator = null; + } + + /// The troll's CharacterAnimEvent sets its Animator back to speed 1 in every + /// FixedUpdate; this sets the roll's speed again right after. + [HarmonyPatch(typeof(CharacterAnimEvent), nameof(CharacterAnimEvent.CustomFixedUpdate))] + public static class Trol_TrueFormDodgeSpeed_Patch + { + public static void Postfix(CharacterAnimEvent __instance) + { + if (dodgeAnimator != null && __instance.gameObject == dodgeAnimator.gameObject) dodgeAnimator.speed = DodgeSpeed; + } + } + + public static void PublishGuard(Player player, bool on) + { + ZNetView nview = player != null ? player.GetComponent() : null; + if (nview == null || !nview.IsValid()) return; + + string value = on ? GuardState + "|" + GuardTime.ToString(System.Globalization.CultureInfo.InvariantCulture) : ""; + if (nview.GetZDO().GetString(GuardKey, "") != value) nview.GetZDO().Set(GuardKey, value); + } + + /// The pose another client's troll should hold, read back off the owner's ZDO. + public static bool ReadGuard(ZDO zdo, out string state, out float time) + { + state = null; + time = 0f; + string value = zdo.GetString(GuardKey, ""); + int bar = value.LastIndexOf('|'); + if (bar <= 0) return false; + + state = value.Substring(0, bar); + return float.TryParse(value.Substring(bar + 1), System.Globalization.NumberStyles.Float, + System.Globalization.CultureInfo.InvariantCulture, out time); + } + /// /// The damage a troll attack deals for this player right now: the troll's own numbers, times /// Troll Attack Damage, times the same random Clubs factor a club would get. @@ -465,6 +566,35 @@ namespace RacesOfValheim crouch = false; dodge = false; } + + /// + /// Rooted while guarding, so the held pose cannot slide across the ground. Cleared after + /// SetControls, not before: the block-and-jump roll takes its direction from the move + /// input inside SetControls, and an input zeroed first sent every roll backwards. + /// + public static void Postfix(Player __instance) + { + if (__instance != Player.m_localPlayer || !LocalActive || LocalAttacking) return; + if (__instance.IsBlocking() && !__instance.InDodge()) MoveDir(__instance) = Vector3.zero; + } + + private static readonly AccessTools.FieldRef MoveDir = + AccessTools.FieldRefAccess("m_moveDir"); + } + + // Share of a normal roll's distance the troll covers. The roll moves by root motion, and + // under True Form two animators feed it: the hidden human's dodge and the troll's jump. + private const float RollDistance = 0.5f; + + /// A shorter roll for the troll: every bit of root motion that reaches the player + /// during a True Form roll is scaled, whichever of the two clips it came from. + [HarmonyPatch(typeof(Character), nameof(Character.AddRootMotion))] + public static class Trol_TrueFormRollDistance_Patch + { + public static void Prefix(Character __instance, ref Vector3 vel) + { + if (__instance == Player.m_localPlayer && LocalActive && __instance.InDodge()) vel *= RollDistance; + } } [HarmonyPatch(typeof(Humanoid), "StartAttack")] @@ -502,4 +632,86 @@ namespace RacesOfValheim } } } + + /// + /// Holds one troll at one frame of a state, for the True Form guard. It blends in the way it + /// blends out: a cross-fade into the frame first, then the frame pinned once the fade is over. + /// Pinned again every frame it holds: the troll's own CharacterAnimEvent puts the Animator back + /// to speed 1 in every FixedUpdate, so a speed of 0 set once would not stay. + /// + internal class TrolGuardPose + { + private const float Fade = 0.2f; + + // Each state's length, learned the first time it is held: the fade starts that far ahead of + // the frame, so the state lands on it when the fade ends instead of running past it. + private static readonly Dictionary lengths = new Dictionary(); + + private int state; + private float target; + private float fadeStarted; + private bool fading; + private float pinned; + + public void Hold(Animator anim, string name, float time) + { + if (!TrolTrueFormModel.HasState(anim, name)) return; + int hash = Animator.StringToHash("Base Layer." + name); + time = Mathf.Clamp01(time); + + if (hash != state || time != target) + { + state = hash; + target = time; + StartFade(anim); + } + + if (fading) + { + anim.speed = 1f; + if (Time.time - fadeStarted < Fade || anim.IsInTransition(0)) return; + + AnimatorStateInfo info = anim.GetCurrentAnimatorStateInfo(0); + if (info.fullPathHash == state && info.length > 0f) + { + lengths[state] = info.length; + pinned = info.normalizedTime < 1f ? info.normalizedTime : target; + } + else + { + pinned = target; + } + fading = false; + } + + anim.Play(state, 0, pinned); + anim.speed = 0f; + } + + private void StartFade(Animator anim) + { + // CrossFade takes its duration as a share of the state being left, so turn the seconds + // into that share. + float from = anim.GetCurrentAnimatorStateInfo(0).length; + float lead = lengths.TryGetValue(state, out float length) && length > 0f ? Fade / length : 0f; + + anim.speed = 1f; + anim.CrossFade(state, from > 0f ? Fade / from : Fade, 0, Mathf.Max(0f, target - lead)); + fadeStarted = Time.time; + fading = true; + } + + public void Release(Animator anim) + { + state = 0; + fading = false; + if (anim == null) return; + + anim.speed = 1f; + if (TrolTrueFormModel.HasState(anim, TrolTrueFormModel.MovementState)) + { + anim.CrossFadeInFixedTime("Base Layer." + TrolTrueFormModel.MovementState, Fade, 0); + } + } + } }