389 lines
17 KiB
C#
389 lines
17 KiB
C#
using HarmonyLib;
|
|
using Jotunn.Managers;
|
|
using UnityEngine;
|
|
|
|
namespace RacesOfValheim
|
|
{
|
|
/// <summary>
|
|
/// The ride itself. Lives on the local player while they are mounted, and nowhere else.
|
|
///
|
|
/// THE ONE IDEA THIS FILE IS BUILT ON: the PLAYER flies, the bird is how it looks from outside.
|
|
/// That inversion is what makes a flying mount a small feature instead of a large one - it
|
|
/// removes the ZDO owner problem, the AI, the taming, the passivity and the whole saddle, all
|
|
/// of which cost a session each the first time round. The flight itself is the Aswid's bat
|
|
/// form: Player.m_debugFly, and nothing else.
|
|
///
|
|
/// THE ONE TRAP: a real attach and a self-driven player are enemies in vanilla, and the game
|
|
/// says so twice.
|
|
/// - Player.SetControls: if the player is attached, has no doodad controller and presses ANY
|
|
/// movement key, vanilla calls AttachStop. That is how you stand up from a chair.
|
|
/// - Player.SetDoodadControlls: giving it a doodad controller instead is worse - it zeroes
|
|
/// moveDir, run and autoRun unconditionally after handing them to the controller, so the
|
|
/// rider could not move at all.
|
|
/// Both were read out of the assembly, not guessed. The way through is the third door: the
|
|
/// attach point is the PLAYER'S OWN TRANSFORM, so Player.UpdateAttach - which copies position
|
|
/// and rotation from the attach point every frame, and would otherwise nail the rider in place
|
|
/// - provably copies the player onto themselves and does nothing. The bird hangs off the
|
|
/// player, not the other way round. The one remaining conflict, the AttachStop above, is
|
|
/// switched off for the duration in WarVultureControlsPatch.
|
|
///
|
|
/// What the attach is still there FOR, after all that, is the pose: AttachStart ends with
|
|
/// m_zanim.SetBool(attachAnimation, true), and ZSyncAnimation replicates it - so every other
|
|
/// player sees the rider sitting, for free, with no code of ours involved.
|
|
/// </summary>
|
|
public class WarVultureMount : MonoBehaviour
|
|
{
|
|
/// <summary>The ZDO flag other clients watch to know they should draw a bird under this player.</summary>
|
|
public const string MountedKey = "WarVulture_Mounted";
|
|
|
|
private const string Label = "WarVulture";
|
|
private const string HolderName = "WarVultureMountModel";
|
|
|
|
/// <summary>How long after the summon a click is ignored, so one press cannot do both.</summary>
|
|
private const float ClickGuardSeconds = 0.6f;
|
|
|
|
/// <summary>The one live mount. There is at most one: this is the local player's own ride.</summary>
|
|
public static WarVultureMount Active { get; private set; }
|
|
|
|
private Player player;
|
|
private WarVultureRig rig;
|
|
private Transform seat;
|
|
private WarVultureHud hud;
|
|
|
|
private float wind; // seconds of full speed left in the bird
|
|
private bool landing; // dismount asked for; coming down before it takes effect
|
|
private float landingStartedAt;
|
|
private float summonedAt;
|
|
|
|
// ---------------------------------------------------------------- public surface
|
|
|
|
public static bool IsRiding(Player candidate)
|
|
{
|
|
return Active != null && candidate != null && Active.player == candidate;
|
|
}
|
|
|
|
/// <summary>Fraction of the bird's wind left, for the bar. 1 = fresh, 0 = spent.</summary>
|
|
public float WindFraction
|
|
{
|
|
get
|
|
{
|
|
float max = Mathf.Max(0.01f, WarVultureConfig.SprintSeconds.Value);
|
|
return Mathf.Clamp01(wind / max);
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// The SUMMON, and only the summon. Called from WarVultureCastPatch, which has already
|
|
/// established that the thing being swung is ours and that the player is not already up.
|
|
///
|
|
/// The dismount used to come through here too, and it did not work: the click fires
|
|
/// Attack.OnAttackTrigger, which the game raises from an animation event partway through
|
|
/// the cast clip - and in the saddle that clip loses to the sitting pose before it ever
|
|
/// gets there. The rider was trapped in the air with a click that did nothing. The dismount
|
|
/// is now read straight off the button in Update, where no animation can swallow it.
|
|
/// </summary>
|
|
public static void Toggle(Player caster)
|
|
{
|
|
if (caster == null || caster != Player.m_localPlayer) return;
|
|
if (Active != null && Active.player == caster) return;
|
|
|
|
Summon(caster);
|
|
}
|
|
|
|
/// <summary>
|
|
/// The dismount button, read from the device rather than from the animation.
|
|
///
|
|
/// RaceInput.Allowed is the same gate every ability in this mod uses, and it is here for a
|
|
/// reason worth remembering: it reads Player.TakeInput, which is FALSE while the console is
|
|
/// open. A dismount that "does not work" during a test session is usually the console.
|
|
/// </summary>
|
|
private static bool DismountPressed()
|
|
{
|
|
if (!RaceInput.Allowed) return false;
|
|
return ZInput.GetButtonDown("Attack") || ZInput.GetButtonDown("JoyAttack");
|
|
}
|
|
|
|
// ---------------------------------------------------------------- summon
|
|
|
|
private static void Summon(Player rider)
|
|
{
|
|
string race = null;
|
|
if (rider.m_customData != null) rider.m_customData.TryGetValue("Race", out race);
|
|
|
|
if (!WarVultureConfig.RaceAllowed(race))
|
|
{
|
|
rider.Message(MessageHud.MessageType.Center, "The bird does not know you.");
|
|
return;
|
|
}
|
|
|
|
if (!WarVultureVisual.Ready)
|
|
{
|
|
rider.Message(MessageHud.MessageType.Center, "The vulture does not answer.");
|
|
Jotunn.Logger.LogWarning($"[{Label}] Call refused: the stripped model template was never built, " +
|
|
"so there is no bird to show. The reason is logged at startup - and " +
|
|
"refusing is deliberate, because the alternative is putting an unstripped " +
|
|
"creature prefab in the world.");
|
|
return;
|
|
}
|
|
|
|
ZNetView nview = rider.GetComponent<ZNetView>();
|
|
if (nview == null || !nview.IsValid())
|
|
{
|
|
Jotunn.Logger.LogWarning($"[{Label}] Call refused: the player has no valid ZNetView yet, so " +
|
|
"the flight state could not be published and no one else would see " +
|
|
"the bird.");
|
|
return;
|
|
}
|
|
|
|
WarVultureMount mount = rider.gameObject.AddComponent<WarVultureMount>();
|
|
mount.player = rider;
|
|
mount.Begin(nview);
|
|
}
|
|
|
|
private void Begin(ZNetView nview)
|
|
{
|
|
Active = this;
|
|
summonedAt = Time.time;
|
|
wind = WarVultureConfig.SprintSeconds.Value;
|
|
|
|
// No lift, and that is the point: the rider is not raised above anything. The bird is
|
|
// moved so that its BACK BONE arrives under the rider, every frame, in WarVultureRig.
|
|
rig = WarVultureVisual.Spawn(player.transform, HolderName);
|
|
Seat();
|
|
SetFlying(nview, true);
|
|
nview.GetZDO().Set(MountedKey, true);
|
|
|
|
if (WarVultureConfig.ShowStaminaBar.Value) hud = WarVultureHud.Create(this);
|
|
}
|
|
|
|
/// <summary>
|
|
/// The attach, and the reason it is harmless: the seat is a child of the player sitting
|
|
/// exactly on the player's own origin, so UpdateAttach's every-frame "put the rider on the
|
|
/// attach point" is the identity.
|
|
///
|
|
/// The pose string is READ from the lox's own Sadle rather than typed from memory - the
|
|
/// same rule as prefab names, applied to an animation.
|
|
///
|
|
/// hideWeapons is false on purpose: hiding the hand items unequips them, and the item in
|
|
/// that hand is the only way back down.
|
|
/// </summary>
|
|
private void Seat()
|
|
{
|
|
seat = new GameObject("WarVultureSeat").transform;
|
|
seat.SetParent(player.transform, false);
|
|
seat.localPosition = Vector3.zero;
|
|
seat.localRotation = Quaternion.identity;
|
|
|
|
player.AttachStart(seat, null, false, false, false, ReadSaddlePose(), Vector3.zero, null);
|
|
}
|
|
|
|
private static string ReadSaddlePose()
|
|
{
|
|
GameObject lox = PrefabManager.Cache.GetPrefab<GameObject>("Lox");
|
|
Sadle sadle = lox != null ? lox.GetComponentInChildren<Sadle>(true) : null;
|
|
if (sadle != null && !string.IsNullOrEmpty(sadle.m_attachAnimation)) return sadle.m_attachAnimation;
|
|
|
|
Jotunn.Logger.LogWarning($"[{Label}] Could not read the lox saddle's attach animation; " +
|
|
"falling back to 'attach_chair'. The rider may sit oddly.");
|
|
return "attach_chair";
|
|
}
|
|
|
|
// ---------------------------------------------------------------- per frame
|
|
|
|
private void Update()
|
|
{
|
|
if (player == null || player != Player.m_localPlayer) { Dismount(); return; }
|
|
if (player.IsDead()) { Dismount(); return; }
|
|
|
|
ZNetView nview = player.GetComponent<ZNetView>();
|
|
if (nview == null || !nview.IsValid())
|
|
{
|
|
// Not an ordinary way down: the rider's own networking went away mid-flight, so it
|
|
// is worth a line even though the dismount itself is silent.
|
|
Jotunn.Logger.LogWarning($"[{Label}] The rider's ZNetView went away mid-flight; dismounting.");
|
|
Dismount();
|
|
return;
|
|
}
|
|
|
|
// Held on every frame rather than set once: the same thing BatFormBehavior does, for
|
|
// the same reason - anything else in the game (or in this mod) that clears debug fly
|
|
// would otherwise drop the rider out of the sky without a word.
|
|
SetFlying(nview, true);
|
|
|
|
DriveAnimator();
|
|
|
|
// The guard is not superstition: the summoning click is still physically down on the
|
|
// frame the mount is created, and without it the bird would be called and dismissed by
|
|
// the same press.
|
|
if (Time.time - summonedAt > ClickGuardSeconds && DismountPressed())
|
|
{
|
|
// A second click during the descent lets go there and then.
|
|
if (landing) Dismount();
|
|
else BeginLanding();
|
|
return;
|
|
}
|
|
|
|
if (landing) UpdateLanding();
|
|
|
|
if (hud != null) hud.Refresh();
|
|
}
|
|
|
|
private void DriveAnimator()
|
|
{
|
|
if (rig == null) return;
|
|
|
|
Vector3 velocity = player.GetVelocity();
|
|
rig.Drive(new Vector3(velocity.x, 0f, velocity.z).magnitude);
|
|
}
|
|
|
|
/// <summary>
|
|
/// The descent. The rider's own controls are not disabled - they are simply overruled in
|
|
/// ApplyFlight, which writes the velocity last and therefore wins.
|
|
/// </summary>
|
|
private void BeginLanding()
|
|
{
|
|
landing = true;
|
|
landingStartedAt = Time.time;
|
|
player.Message(MessageHud.MessageType.Center, "The vulture spirals down.");
|
|
}
|
|
|
|
private void UpdateLanding()
|
|
{
|
|
Vector3 position = player.transform.position;
|
|
|
|
float floor = -10000f;
|
|
if (ZoneSystem.instance != null)
|
|
{
|
|
// Over open water the solid height is the seabed, which would mean a long swim
|
|
// down. The surface is the floor there.
|
|
floor = Mathf.Max(ZoneSystem.instance.GetSolidHeight(position), ZoneSystem.instance.m_waterLevel);
|
|
}
|
|
|
|
if (position.y - floor <= 0.6f) { Dismount(); return; }
|
|
|
|
// A descent that never ends is worse than a hard landing: if the ground cannot be
|
|
// found at all, let go anyway rather than trap the rider in a falling animation.
|
|
if (Time.time - landingStartedAt > 20f)
|
|
{
|
|
Jotunn.Logger.LogWarning($"[{Label}] The descent found no ground in 20s; letting go anyway.");
|
|
Dismount();
|
|
}
|
|
}
|
|
|
|
// ---------------------------------------------------------------- flight, called from the physics step
|
|
|
|
/// <summary>
|
|
/// Called from WarVultureFlightPatch, right after vanilla's UpdateDebugFly has written the
|
|
/// rider's velocity for this physics step.
|
|
///
|
|
/// Speed is applied as a FACTOR on what vanilla just computed rather than as a fresh
|
|
/// velocity, and that is deliberate: vanilla lerps towards its target, so scaling the
|
|
/// result keeps every bit of its smoothing - the ramp up, the ease off, the standstill at
|
|
/// zero input - and only changes how fast the whole thing runs. Writing a velocity of our
|
|
/// own would have thrown all of that away.
|
|
///
|
|
/// The wind is spent here, in the physics step, because this is the only place that knows
|
|
/// the rider is actually flying.
|
|
/// </summary>
|
|
public void ApplyFlight(bool runHeld, ref Vector3 currentVelocity, Rigidbody body)
|
|
{
|
|
float dt = Time.fixedDeltaTime;
|
|
|
|
if (landing)
|
|
{
|
|
currentVelocity = Vector3.down * WarVultureConfig.LandingSpeed.Value;
|
|
if (body != null) body.linearVelocity = currentVelocity;
|
|
return;
|
|
}
|
|
|
|
bool sprinting = runHeld && wind > 0f && currentVelocity.sqrMagnitude > 0.01f;
|
|
|
|
if (sprinting)
|
|
{
|
|
wind = Mathf.Max(0f, wind - dt);
|
|
if (wind <= 0f)
|
|
{
|
|
player.Message(MessageHud.MessageType.Center, "The vulture settles into a glide.");
|
|
}
|
|
}
|
|
else if (wind < WarVultureConfig.SprintSeconds.Value)
|
|
{
|
|
// Refills in the air the moment the run key is released. A vulture can stay up for
|
|
// hours; what it cannot do is keep stooping.
|
|
float perSecond = WarVultureConfig.SprintSeconds.Value /
|
|
Mathf.Max(0.01f, WarVultureConfig.RechargeSeconds.Value);
|
|
wind = Mathf.Min(WarVultureConfig.SprintSeconds.Value, wind + perSecond * dt);
|
|
}
|
|
|
|
float wanted = sprinting ? WarVultureConfig.SprintSpeed.Value : WarVultureConfig.CruiseSpeed.Value;
|
|
|
|
// What vanilla aimed for this step: m_debugFlySpeed, times 2.5 when the run key is
|
|
// down. Read from the game rather than assumed, so a Valheim retune cannot silently
|
|
// double our speeds.
|
|
float vanilla = WarVultureFlightPatch.DebugFlySpeed * (runHeld ? 2.5f : 1f);
|
|
if (vanilla <= 0.01f) return;
|
|
|
|
currentVelocity *= wanted / vanilla;
|
|
if (body != null) body.linearVelocity = currentVelocity;
|
|
}
|
|
|
|
// ---------------------------------------------------------------- dismount
|
|
|
|
private void Dismount()
|
|
{
|
|
Player rider = player;
|
|
|
|
if (rider != null)
|
|
{
|
|
ZNetView nview = rider.GetComponent<ZNetView>();
|
|
if (nview != null && nview.IsValid())
|
|
{
|
|
SetFlying(nview, false);
|
|
nview.GetZDO().Set(MountedKey, false);
|
|
}
|
|
else
|
|
{
|
|
// No ZDO to write to, but the local field still has to come off or the player
|
|
// keeps flying on foot.
|
|
Traverse.Create(rider).Field("m_debugFly").SetValue(false);
|
|
}
|
|
|
|
rider.AttachStop();
|
|
}
|
|
|
|
if (hud != null) { hud.Dispose(); hud = null; }
|
|
// Destroy, never DestroyImmediate: a dismount can be a click, which arrives from an
|
|
// animation event callback where immediate destruction is refused. The whole reason
|
|
// this feature had a live vulture in it once.
|
|
if (rig != null) { Destroy(rig.gameObject); rig = null; }
|
|
if (seat != null) { Destroy(seat.gameObject); seat = null; }
|
|
|
|
if (Active == this) Active = null;
|
|
|
|
Destroy(this);
|
|
}
|
|
|
|
private void OnDestroy()
|
|
{
|
|
// Belt and braces for a component torn off by something other than Dismount (a scene
|
|
// change, a reload). Leaving debug fly on would be the worst possible parting gift.
|
|
if (Active != this) return;
|
|
Active = null;
|
|
|
|
if (player == null) return;
|
|
Traverse.Create(player).Field("m_debugFly").SetValue(false);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Both halves of debug fly. The field is what the local rider's own physics reads; the ZDO
|
|
/// var is what every OTHER client reads (Character.IsDebugFlying consults the ZDO when it
|
|
/// is not the owner). BatFormBehavior only ever wrote the field, which is why a bat looked
|
|
/// wrong to everyone else - this writes both.
|
|
/// </summary>
|
|
private void SetFlying(ZNetView nview, bool flying)
|
|
{
|
|
Traverse.Create(player).Field("m_debugFly").SetValue(flying);
|
|
nview.GetZDO().Set(ZDOVars.s_debugFly, flying);
|
|
}
|
|
}
|
|
}
|