On a chair the player sits on the seat, and the form stood inside the chair at seat height. The form's root now goes 0.5 m in front of the seat, on whatever is under that point, skipping the seat's own colliders. The seat is found by a short raycast under the player, so it works for onlookers too, who have no attach point. Back to zero on standing up; the sit key is untouched.
367 lines
18 KiB
C#
367 lines
18 KiB
C#
using UnityEngine;
|
|
|
|
namespace RacesOfValheim
|
|
{
|
|
/// <summary>What every Fenrir form shares: whether the local player wears one at all.</summary>
|
|
internal static class FenrirForms
|
|
{
|
|
private static readonly int FenringHash = "SE_FenrirForm".GetStableHashCode();
|
|
private static readonly int WolfHash = "SE_WolfForm".GetStableHashCode();
|
|
private static readonly int CultistHash = "SE_CultistForm".GetStableHashCode();
|
|
|
|
/// <summary>
|
|
/// Any of the four forms. The Wolf and the Ulv share SE_WolfForm, the Fenring has
|
|
/// SE_FenrirForm and the Cultist SE_CultistForm. Checking only SE_FenrirForm, as the attack
|
|
/// block used to, left three of the four forms out.
|
|
/// </summary>
|
|
/// <summary>True while the local form is inside an attack, a howl or a breath. Cleared by the
|
|
/// form's own routines, and on every revert.</summary>
|
|
public static bool LocalAttacking { get; set; }
|
|
|
|
public static bool LocalInForm(Character character)
|
|
{
|
|
if (character == null || character != Player.m_localPlayer) return false;
|
|
SEMan seman = character.GetSEMan();
|
|
if (seman == null) return false;
|
|
return seman.HaveStatusEffect(FenringHash) || seman.HaveStatusEffect(WolfHash) || seman.HaveStatusEffect(CultistHash);
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// The movement half of a form's Animator, copied from the hidden player's. Shared by the four
|
|
/// local behaviours and RemoteFenrirAnimator so both views of the same wolf agree.
|
|
///
|
|
/// WHY THE GRACE PERIOD. Valheim writes onGround = IsOnGround() every frame, and running over
|
|
/// uneven ground that drops to false for a frame or two at every bump. The player's own
|
|
/// controller rides that out on its transitions. The forms used to read it raw and zero the
|
|
/// speed the same frame, so the creature dropped from run to idle and back about once a second
|
|
/// on any hillside - the flicker a player reported in all four forms.
|
|
/// </summary>
|
|
internal class FormLocomotion
|
|
{
|
|
// Long enough to cover a bump, short enough that a real jump still reads as one.
|
|
private const float AirborneGrace = 0.25f;
|
|
|
|
private float airborneFor;
|
|
|
|
// Whether this form's controller has a "sleeping" bool, asked once per Animator: MonsterAI
|
|
// drives the creature's own sleep through it, and not every creature has one.
|
|
private Animator sleepChecked;
|
|
private bool hasSleeping;
|
|
private int sleepState;
|
|
private bool wasSitting;
|
|
// Read off ulv_animator with scripts/dump_controller.py: the entry state "check sleeping" goes
|
|
// to Sleep only at start-up, and Movement has no way back into it. "Base Layer.Sleep" is the
|
|
// real path; the short name stays as a fallback for another creature built the same way.
|
|
private static readonly string[] SleepStateNames = { "Base Layer.Sleep", "Sleep" };
|
|
private static readonly System.Collections.Generic.HashSet<string> sleepLogged = new System.Collections.Generic.HashSet<string>();
|
|
|
|
/// <summary>Copies the movement parameters, and says whether the form counts as grounded.</summary>
|
|
public bool Mirror(Animator form, Animator playerAnim, Player player)
|
|
{
|
|
bool touching = playerAnim.GetBool("onGround");
|
|
airborneFor = touching ? 0f : airborneFor + Time.deltaTime;
|
|
bool grounded = airborneFor <= AirborneGrace;
|
|
|
|
// try/catch as the behaviours always did it: a controller missing one of these must not
|
|
// throw once per frame.
|
|
try { form.SetBool("onGround", grounded); } catch {}
|
|
try { form.SetBool("inWater", playerAnim.GetBool("inWater")); } catch {}
|
|
|
|
// Only airborne reads as standing still now. Crouching used to as well, so a player
|
|
// sneaking in a form slid across the ground in the idle pose. Crouched, the player moves
|
|
// at sneaking speed, and the creature's controller picks its walk for a speed that low:
|
|
// the sneak a player asked for, from animations the creature already has.
|
|
//
|
|
// Sitting reads as still too. The seated player's own Animator keeps a forward_speed that
|
|
// is not zero, and passed through it kept the Ulv in its Walk clip - on the spot, and out
|
|
// of reach of its Sleep state, which only leaves from idle. Seen in the log: sitting,
|
|
// sleeping=true, clip 'Walk'.
|
|
bool sitting = IsSitting(player);
|
|
bool still = !grounded || sitting;
|
|
try { form.SetFloat("forward_speed", still ? 0f : playerAnim.GetFloat("forward_speed")); } catch {}
|
|
try { form.SetFloat("sideway_speed", still ? 0f : playerAnim.GetFloat("sideway_speed")); } catch {}
|
|
|
|
// Sitting puts the creature to sleep, on the "sleeping" bool its own MonsterAI uses - the
|
|
// Ulv curls up. IsSitting reads the animator's state, which is replicated, so it is right
|
|
// for an onlooker's copy too.
|
|
if (sleepChecked != form)
|
|
{
|
|
sleepChecked = form;
|
|
hasSleeping = false;
|
|
foreach (AnimatorControllerParameter p in form.parameters)
|
|
{
|
|
if (p.type == AnimatorControllerParameterType.Bool && p.name == "sleeping") { hasSleeping = true; break; }
|
|
}
|
|
|
|
// The state's name is not readable at runtime, only testable - but it is readable offline,
|
|
// see SleepStateNames.
|
|
sleepState = 0;
|
|
string found = "none";
|
|
if (hasSleeping)
|
|
{
|
|
foreach (string candidate in SleepStateNames)
|
|
{
|
|
int hash = Animator.StringToHash(candidate);
|
|
if (!form.HasState(0, hash)) continue;
|
|
sleepState = hash;
|
|
found = candidate;
|
|
break;
|
|
}
|
|
}
|
|
string controller = form.runtimeAnimatorController != null ? form.runtimeAnimatorController.name : form.name;
|
|
if (sleepLogged.Add(controller))
|
|
{
|
|
Jotunn.Logger.LogInfo($"[FenrirForm] '{controller}' {(hasSleeping ? "has" : "has no")} sleeping animation; " +
|
|
(hasSleeping ? $"sitting puts it to sleep (state '{found}')." : "sitting keeps it idle."));
|
|
}
|
|
}
|
|
if (hasSleeping)
|
|
{
|
|
form.SetBool("sleeping", sitting);
|
|
|
|
// The bool alone never put the Ulv to sleep. A vanilla Ulv is BORN asleep: its
|
|
// controller enters Sleep from the start and only knows the way out (Sleep, then
|
|
// 'Sleep to Idle' once the bool drops). Nothing leads from Idle back into Sleep, so
|
|
// the state is entered by hand when the player sits; standing up drops the bool and
|
|
// the controller's own wake-up plays.
|
|
if (sitting && !wasSitting && sleepState != 0) form.CrossFadeInFixedTime(sleepState, 0.4f, 0);
|
|
}
|
|
wasSitting = sitting;
|
|
|
|
PlaceOnChair(form, player);
|
|
|
|
return grounded;
|
|
}
|
|
|
|
// How far in front of the seat a creature on a chair settles, in metres.
|
|
private const float ChairForward = 0.5f;
|
|
private static readonly int ChairGroundMask = LayerMask.GetMask("Default", "static_solid", "terrain", "piece", "vehicle");
|
|
private static readonly RaycastHit[] chairHits = new RaycastHit[16];
|
|
private Transform placedRoot;
|
|
|
|
/// <summary>
|
|
/// On a chair the player sits on the seat itself, and a creature there stood inside the chair,
|
|
/// at seat height. It goes half a metre in front of the seat instead, standing on whatever is
|
|
/// under that point. Moves the form's own root (the child of the player), never the player.
|
|
/// The sit key is left alone: the player is on the ground already.
|
|
/// </summary>
|
|
private void PlaceOnChair(Animator form, Player player)
|
|
{
|
|
Transform root = RootUnder(form.transform, player != null ? player.transform : null);
|
|
if (root == null) return;
|
|
|
|
bool onChair = player.IsSitting();
|
|
if (!onChair)
|
|
{
|
|
if (placedRoot == root && root.localPosition != Vector3.zero) root.localPosition = Vector3.zero;
|
|
return;
|
|
}
|
|
placedRoot = root;
|
|
|
|
Transform body = player.transform;
|
|
Piece seat = SeatUnder(body.position);
|
|
Vector3 target = body.position + body.forward * ChairForward;
|
|
|
|
float groundY = target.y;
|
|
int count = Physics.RaycastNonAlloc(target + Vector3.up * 1.5f, Vector3.down, chairHits, 4f, ChairGroundMask);
|
|
float best = float.MaxValue;
|
|
for (int i = 0; i < count; i++)
|
|
{
|
|
Collider c = chairHits[i].collider;
|
|
if (c == null || c.transform.IsChildOf(body)) continue;
|
|
if (seat != null && c.GetComponentInParent<Piece>() == seat) continue;
|
|
if (chairHits[i].distance < best) { best = chairHits[i].distance; groundY = chairHits[i].point.y; }
|
|
}
|
|
|
|
root.localPosition = body.InverseTransformPoint(new Vector3(target.x, groundY, target.z));
|
|
}
|
|
|
|
/// <summary>The chair or bench the player sits on: the first piece straight under them.</summary>
|
|
private static Piece SeatUnder(Vector3 position)
|
|
{
|
|
int count = Physics.RaycastNonAlloc(position + Vector3.up * 0.3f, Vector3.down, chairHits, 1.5f, ChairGroundMask);
|
|
Piece seat = null;
|
|
float best = float.MaxValue;
|
|
for (int i = 0; i < count; i++)
|
|
{
|
|
Piece piece = chairHits[i].collider != null ? chairHits[i].collider.GetComponentInParent<Piece>() : null;
|
|
if (piece != null && chairHits[i].distance < best) { best = chairHits[i].distance; seat = piece; }
|
|
}
|
|
return seat;
|
|
}
|
|
|
|
private static Transform RootUnder(Transform t, Transform player)
|
|
{
|
|
if (player == null) return null;
|
|
while (t != null && t.parent != player) t = t.parent;
|
|
return t;
|
|
}
|
|
|
|
/// <summary>
|
|
/// The sit key, or a chair. The sit key is an EMOTE, not the "sitting" animator tag that
|
|
/// Humanoid.IsSitting asks about - that tag belongs to chairs and benches - so IsSitting alone
|
|
/// never saw it and the Ulv stayed on its feet. Player.StartEmote writes the emote's name on the
|
|
/// ZDO, which every client reads, so this is right for an onlooker's copy as well.
|
|
/// </summary>
|
|
private static bool IsSitting(Player player)
|
|
{
|
|
if (player == null) return false;
|
|
if (player.IsSitting()) return true;
|
|
|
|
ZNetView nview = player.GetComponent<ZNetView>();
|
|
return nview != null && nview.IsValid() && nview.GetZDO().GetString(ZDOVars.s_emote, "") == "sit";
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Two ways a form's Animator and its attack lock got stuck, shared by all four forms.
|
|
///
|
|
/// The idle howl is a looping clip the attack triggers cannot leave: a click during it queued a
|
|
/// trigger the Animator never took, and the model stood frozen until the form was dropped.
|
|
/// And an exception inside an attack routine left isAttacking true for good - Update does
|
|
/// nothing at all while it is - so the watchdog gives any lock a ceiling.
|
|
/// </summary>
|
|
internal static class FormAnimGuard
|
|
{
|
|
/// <summary>Longer than the longest legitimate routine (the Ulv's howl, 3.8 s, plus a margin).</summary>
|
|
private const float MaxLockSeconds = 8f;
|
|
|
|
/// <summary>If the Animator is inside a howl clip, puts it back on its default state so the
|
|
/// trigger set next lands on the idle and not on the loop. Call after isAttacking is set.</summary>
|
|
public static void LeaveHowl(Animator animator)
|
|
{
|
|
if (animator == null) return;
|
|
|
|
try
|
|
{
|
|
foreach (AnimatorClipInfo clip in animator.GetCurrentAnimatorClipInfo(0))
|
|
{
|
|
if (clip.clip == null) continue;
|
|
|
|
string lower = clip.clip.name.ToLower();
|
|
if (!lower.Contains("hawl") && !lower.Contains("howl")) continue;
|
|
|
|
animator.Rebind();
|
|
animator.Update(0f);
|
|
return;
|
|
}
|
|
}
|
|
catch {}
|
|
}
|
|
|
|
/// <summary>True once the lock has been held longer than any routine can legitimately hold
|
|
/// it. Call every Update; <paramref name="since"/> is the caller's own field.</summary>
|
|
public static bool Stuck(bool locked, ref float since)
|
|
{
|
|
if (!locked)
|
|
{
|
|
since = -1f;
|
|
return false;
|
|
}
|
|
|
|
if (since < 0f)
|
|
{
|
|
since = Time.time;
|
|
return false;
|
|
}
|
|
|
|
if (Time.time - since <= MaxLockSeconds) return false;
|
|
|
|
since = -1f;
|
|
Jotunn.Logger.LogWarning("[FenrirForm] An attack lock held for more than " + MaxLockSeconds +
|
|
" s was released; something in a routine did not finish.");
|
|
return true;
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Whether a melee swing of a form can reach what it found, shared by the four claw and bite
|
|
/// attacks.
|
|
///
|
|
/// The old test was one Linecast from the eyes to the centre of the collider, against terrain,
|
|
/// pieces and the Default layer. Two ways it threw hits away: the line clipped the ground on
|
|
/// any slope or against anything lower than the eyes, and against a tree, a rock or a nest the
|
|
/// line hit the target's own collider - those live on exactly the layers it tested - so they
|
|
/// could never be damaged at all. Now the target's own colliders do not count as cover, and a
|
|
/// swing lands if either the eyes or the point of the attack have a clear line to it.
|
|
/// </summary>
|
|
internal static class FormMelee
|
|
{
|
|
private static readonly int CoverMask = LayerMask.GetMask("Default", "static_solid", "terrain", "piece");
|
|
private static readonly RaycastHit[] rayHits = new RaycastHit[16];
|
|
|
|
public static bool CanReach(Vector3 eye, Vector3 attackPoint, Collider hit, IDestructible target, out string blockedBy)
|
|
{
|
|
Bounds bounds = hit.bounds;
|
|
if (Clear(eye, bounds.center, target, out blockedBy)) return true;
|
|
return Clear(attackPoint, bounds.ClosestPoint(attackPoint), target, out _);
|
|
}
|
|
|
|
private static bool Clear(Vector3 from, Vector3 to, IDestructible target, out string blockedBy)
|
|
{
|
|
blockedBy = null;
|
|
Vector3 delta = to - from;
|
|
float distance = delta.magnitude;
|
|
if (distance < 0.01f) return true;
|
|
|
|
int count = Physics.RaycastNonAlloc(from, delta / distance, rayHits, distance, CoverMask);
|
|
for (int i = 0; i < count; i++)
|
|
{
|
|
Collider cover = rayHits[i].collider;
|
|
if (cover == null) continue;
|
|
if (ReferenceEquals(cover.GetComponentInParent<IDestructible>(), target)) continue;
|
|
blockedBy = cover.name;
|
|
return false;
|
|
}
|
|
return true;
|
|
}
|
|
|
|
/// <summary>
|
|
/// One line per rejected candidate while "Debug: Log Form Hits" is on, so the next "my bite
|
|
/// did nothing" report comes with the reason in the log.
|
|
/// </summary>
|
|
public static void LogMiss(string form, Collider hit, string reason)
|
|
{
|
|
if (!FenrirConfig.DebugFormHits.Value) return;
|
|
Jotunn.Logger.LogInfo($"[FenrirForm] {form} swing skipped '{hit.name}' (layer {LayerMask.LayerToName(hit.gameObject.layer)}): {reason}.");
|
|
}
|
|
|
|
public static void LogHit(string form, IDestructible target, float damage)
|
|
{
|
|
if (!FenrirConfig.DebugFormHits.Value) return;
|
|
string name = target is MonoBehaviour behaviour && behaviour != null ? behaviour.name : target.ToString();
|
|
Jotunn.Logger.LogInfo($"[FenrirForm] {form} swing hit '{name}' for {damage:0}.");
|
|
}
|
|
|
|
public static void LogSwing(string form, int candidates)
|
|
{
|
|
if (!FenrirConfig.DebugFormHits.Value) return;
|
|
Jotunn.Logger.LogInfo($"[FenrirForm] {form} swing: {candidates} collider(s) in reach.");
|
|
}
|
|
}
|
|
/// <summary>
|
|
/// Holds the player still through a form's attack clips, the way a human stands to swing. The
|
|
/// hidden player kept walking under the creature, so the bite slid toward whatever WASD held.
|
|
/// SkeletonRiseControlsPatch's arrangement: the move direction is SetControls' first argument,
|
|
/// bound by position. The Fenring's and the Ulv's leaps move the body directly and are untouched.
|
|
/// </summary>
|
|
[HarmonyLib.HarmonyPatch(typeof(Player), "SetControls")]
|
|
public static class Fenrir_FormHoldStill_Patch
|
|
{
|
|
public static void Prefix(Player __instance, ref Vector3 __0, ref bool jump, ref bool crouch, ref bool dodge)
|
|
{
|
|
if (__instance != Player.m_localPlayer || !FenrirForms.LocalAttacking) return;
|
|
if (!FenrirForms.LocalInForm(__instance))
|
|
{
|
|
FenrirForms.LocalAttacking = false;
|
|
return;
|
|
}
|
|
|
|
__0 = Vector3.zero;
|
|
jump = false;
|
|
crouch = false;
|
|
dodge = false;
|
|
}
|
|
}
|
|
}
|