warvulture

This commit is contained in:
Ferdinando 2026-08-09 21:54:56 +02:00
commit e9f41a86e3
11 changed files with 2318 additions and 7 deletions

View file

@ -0,0 +1,109 @@
using BepInEx.Configuration;
namespace RacesOfValheim
{
/// <summary>
/// Every tunable number behind the War Vulture, bound as BepInEx ConfigEntry so it shows up in
/// Configuration Manager - same shape as TrolConfig, which is the house model for this.
///
/// The three numbers most likely to need a pass in game are deliberately here rather than in
/// code: MountSize, MountOffsetY and MountOffsetZ. Where a bird sits under a rider is the one
/// thing the last attempt lost three rounds to (section 16.6 of the design doc: measure a
/// relation, never pick a number in metres from the armchair), and a value that can be dragged
/// in the menu while standing in the world beats another compile.
///
/// No keybind is bound here on purpose. The mount answers to LEFT CLICK on the item and to the
/// vanilla run key, so there is nothing new to learn and nothing new to rebind.
/// </summary>
public static class WarVultureConfig
{
// ─── Access ────────────────────────────────────────────────────────────
public static ConfigEntry<string> AllowedRaces;
// ─── Flight ────────────────────────────────────────────────────────────
public static ConfigEntry<float> CruiseSpeed;
public static ConfigEntry<float> SprintSpeed;
public static ConfigEntry<float> SprintSeconds;
public static ConfigEntry<float> RechargeSeconds;
public static ConfigEntry<float> LandingSpeed;
// ─── Model ─────────────────────────────────────────────────────────────
public static ConfigEntry<float> HandModelScale;
public static ConfigEntry<float> MountSize;
public static ConfigEntry<string> SeatBone;
public static ConfigEntry<float> SeatNudgeY;
public static ConfigEntry<float> SeatNudgeZ;
// ─── Interface ─────────────────────────────────────────────────────────
public static ConfigEntry<bool> ShowStaminaBar;
public static void Bind(ConfigFile config)
{
const string access = "War Vulture - Access";
AllowedRaces = config.Bind(access, "Allowed races", "Furling,Dvergar",
new ConfigDescription("Comma separated list of race ids that can call the vulture. " +
"In anyone else's hands the item is an inert trophy on a stick. " +
"Leave empty to let every race ride."));
const string flight = "War Vulture - Flight";
// 7 and 13 are not proposals: they are m_flySlowSpeed and m_flyFastSpeed read off the
// vanilla Volture at runtime (design doc 15.13). A number read from the game survives a
// Valheim patch; a number invented here does not.
CruiseSpeed = config.Bind(flight, "Cruise speed", 7f,
new ConfigDescription("Metres per second with the run key up. This one is unlimited - " +
"vultures stay up for hours."));
SprintSpeed = config.Bind(flight, "Sprint speed", 13f,
new ConfigDescription("Metres per second while the run key is held and the bird still " +
"has wind in it."));
SprintSeconds = config.Bind(flight, "Sprint seconds", 10f,
new ConfigDescription("How long full speed lasts before the bird drops back to cruise."));
RechargeSeconds = config.Bind(flight, "Recharge seconds", 10f,
new ConfigDescription("How long a spent bird takes to fill up again. It recharges in the " +
"air as soon as the run key is released - landing is not required."));
LandingSpeed = config.Bind(flight, "Landing speed", 12f,
new ConfigDescription("Metres per second of the automatic descent after the dismount " +
"click. The controls are ignored until the ground arrives."));
const string model = "War Vulture - Model";
HandModelScale = config.Bind(model, "Hand model scale", 0.6f,
new ConfigDescription("Size of the vulture trophy carried in hand, as a fraction of the " +
"real trophy. 0.6 is the 40% smaller that was asked for."));
MountSize = config.Bind(model, "Mount size", 7.75f,
new ConfigDescription("Largest dimension of the bird under the rider, in metres. 7.75 is " +
"the vanilla Volture's own mesh, wings included."));
// The rider is glued to a BONE, not to a height: the bird's back rises and falls with
// every wingbeat, and any offset in metres can only be right on one frame of that.
SeatBone = config.Bind(model, "Seat bone", "",
new ConfigDescription("Name (or part of a name) of the bone on the vulture's skeleton the " +
"rider sits on. Empty picks the last spine/chest bone automatically, " +
"which is what the bird actually flies with."));
SeatNudgeY = config.Bind(model, "Seat nudge Y", 0f,
new ConfigDescription("Fine adjustment up (+) or down (-) from the seat bone, in metres. " +
"Zero means exactly on the bone."));
SeatNudgeZ = config.Bind(model, "Seat nudge Z", 0f,
new ConfigDescription("Fine adjustment forward (+) or back (-) from the seat bone, in metres."));
const string ui = "War Vulture - Interface";
ShowStaminaBar = config.Bind(ui, "Show stamina bar", true,
new ConfigDescription("Draws the bird's own wind as a bar under the player's stamina, " +
"cloned from vanilla's mount stamina bar."));
}
/// <summary>
/// Whether a race id may call the bird. An empty list means everyone, which is the honest
/// reading of "no restriction" and is also what makes this testable on any character.
/// </summary>
public static bool RaceAllowed(string race)
{
string list = AllowedRaces != null ? AllowedRaces.Value : null;
if (string.IsNullOrEmpty(list)) return true;
if (string.IsNullOrEmpty(race)) return false;
foreach (string entry in list.Split(','))
{
if (entry.Trim().Equals(race.Trim(), System.StringComparison.OrdinalIgnoreCase)) return true;
}
return false;
}
}
}

View file

@ -0,0 +1,116 @@
using System.Reflection;
using HarmonyLib;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The bird's wind, as a bar under the player's stamina.
///
/// It is a CLONE of vanilla's own mount stamina bar, not a bar drawn from scratch, for two
/// reasons: it is already skinned, sized and animated like every other bar in the game, and it
/// is semantically the same thing - Hud.UpdateMount drives that bar from Sadle.GetStamina for
/// the asksvin. Ours is the same idea with a different animal underneath.
///
/// Vanilla's copy cannot simply be borrowed where it stands: Hud.UpdateMount switches the whole
/// mount panel off on every frame in which the player is not on a Sadle, and it would take the
/// bar with it. The clone is reparented out of that panel, so vanilla never touches it again.
///
/// Everything here is reflection because GuiBar lives in assembly_guiutils, which this project
/// does not reference - and adding a reference to the csproj is a bigger change than a bar is
/// worth. Every step is null-checked: a bar that fails to build costs the bar and nothing else,
/// which is the right trade for an ornament on a flying mount.
/// </summary>
public class WarVultureHud
{
private const float BelowStaminaPixels = 24f;
private readonly WarVultureMount mount;
private readonly GameObject barObject;
private readonly Component guiBar;
private readonly MethodInfo setValue;
private WarVultureHud(WarVultureMount mount, GameObject barObject, Component guiBar, MethodInfo setValue)
{
this.mount = mount;
this.barObject = barObject;
this.guiBar = guiBar;
this.setValue = setValue;
}
public static WarVultureHud Create(WarVultureMount mount)
{
Hud hud = Hud.instance;
if (hud == null) return null;
Component template = Traverse.Create(hud).Field("m_mountStaminaBar").GetValue<Component>();
RectTransform staminaRoot = hud.m_staminaBar2Root;
if (template == null || staminaRoot == null || staminaRoot.parent == null)
{
Jotunn.Logger.LogWarning("[WarVulture] The vanilla mount stamina bar or the stamina bar root " +
"could not be found, so the bird flies without a gauge.");
return null;
}
GameObject clone = Object.Instantiate(template.gameObject, staminaRoot.parent);
clone.name = "WarVultureWindBar";
// Anchored off the stamina bar rather than off the screen: the stamina bar moves with
// the player's HUD layout, and anything positioned against the screen would drift away
// from it the moment that layout changes.
RectTransform rect = clone.GetComponent<RectTransform>();
if (rect != null)
{
rect.anchorMin = staminaRoot.anchorMin;
rect.anchorMax = staminaRoot.anchorMax;
rect.pivot = staminaRoot.pivot;
rect.anchoredPosition = staminaRoot.anchoredPosition + new Vector2(0f, -BelowStaminaPixels);
rect.localScale = staminaRoot.localScale;
}
clone.SetActive(true);
Component bar = clone.GetComponent("GuiBar");
MethodInfo setter = bar != null
? bar.GetType().GetMethod("SetValue", new[] { typeof(float) })
: null;
if (setter == null)
{
Jotunn.Logger.LogWarning("[WarVulture] The cloned bar has no GuiBar.SetValue(float) to drive, " +
"so it would have sat there full forever; it was removed.");
Object.Destroy(clone);
return null;
}
TintBrown(bar);
return new WarVultureHud(mount, clone, bar, setter);
}
/// <summary>
/// Optional, and treated as such: if GuiBar ever loses SetColor the bar simply keeps
/// vanilla's colour instead of costing an exception every summon.
/// </summary>
private static void TintBrown(Component bar)
{
MethodInfo setColor = bar.GetType().GetMethod("SetColor", new[] { typeof(Color) });
if (setColor == null) return;
setColor.Invoke(bar, new object[] { new Color(0.72f, 0.55f, 0.32f, 1f) });
}
public void Refresh()
{
if (barObject == null || guiBar == null || setValue == null) return;
if (mount == null) return;
setValue.Invoke(guiBar, new object[] { mount.WindFraction });
}
public void Dispose()
{
if (barObject != null) Object.Destroy(barObject);
}
}
}

View file

@ -0,0 +1,308 @@
using HarmonyLib;
using Jotunn.Entities;
using Jotunn.Managers;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The War Vulture item: a Dead Raiser with the skeleton taken out of it and a vulture trophy
/// hung in its place. Clicked, it puts the player on a flying bird; clicked again, it brings
/// them down and takes the bird away.
///
/// Why a staff and not a trinket: the game lets a WEAPON be used without any trickery. Cloning
/// StaffSkeleton buys the click, the cast gesture and the effects for free - which is exactly
/// the reasoning that produced SkadiNokkel, and this file is deliberately that file's twin. If
/// one of them ever needs a fix, the other almost certainly needs the same one.
///
/// Three things are removed from the vanilla staff, and each is removed TWICE on purpose:
/// - the eitr, health and stamina costs are zeroed on the clone AND forced to zero in the
/// getters every cost check flows through (WarVultureFreeCastPatch). The eitr cost is not
/// cosmetic: it is checked BEFORE the attack starts, so a player without eitr would never
/// reach the code that summons;
/// - the summon is nulled on the clone AND the attack trigger itself is taken over, so
/// vanilla's spawn code is not merely defused but unreachable (WarVultureCastPatch);
/// - the staff's model is replaced by the trophy under the item's "attach" child, which is
/// the ONLY child VisEquipment draws - a model hung anywhere else is present, correct and
/// invisible (design doc 15.11, half an hour paid for once already).
/// </summary>
public static class WarVultureItem
{
public const string PrefabName = "WarVulture";
public const string DisplayName = "War Vulture";
private const string SourcePrefab = "StaffSkeleton";
private const string TrophyPrefab = "TrophyVolture";
private const string Label = "WarVulture";
public static void Register()
{
GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(PrefabName, SourcePrefab);
if (prefab == null)
{
Jotunn.Logger.LogWarning($"[{Label}] Could not clone {SourcePrefab}; {DisplayName} not registered.");
return;
}
ItemDrop drop = prefab.GetComponent<ItemDrop>();
if (drop == null || drop.m_itemData == null || drop.m_itemData.m_shared == null)
{
Jotunn.Logger.LogWarning($"[{Label}] {SourcePrefab} clone has no usable ItemDrop; {DisplayName} not registered.");
return;
}
ItemDrop.ItemData.SharedData shared = drop.m_itemData.m_shared;
shared.m_name = DisplayName;
shared.m_description = "A vulture's head, kept. Raise it and the bird comes back under you, " +
"and it will carry you as long as you care to stay up - though it only " +
"has so much haste in it before it settles into a glide.";
shared.m_useDurability = false;
// ItemType is left exactly as the vanilla staff has it: it decides the equip slot and
// which animation set the arms use, and the cast gesture is the whole reason this is a
// staff rather than a trinket.
Strip(shared);
SwapHandModel(prefab);
ItemManager.Instance.AddItem(new CustomItem(prefab, fixReference: false));
// Built HERE and not at the summon, and the comment on WarVultureVisual explains why in
// full: this is a context where components may be destroyed immediately, and the summon
// is not. Getting that wrong once put a live Ashlands predator in the player's world.
WarVultureVisual.BuildTemplate();
// No recipe, on purpose and for now: the item is spawned from the console
// ("spawn WarVulture") while the flight is being proven. A recipe costs nothing to add
// later and would only be materials invented before anyone knows what this is worth.
Jotunn.Logger.LogInfo($"[{Label}] {DisplayName} registered: no eitr, no health, no stamina, no skeleton.");
}
/// <summary>
/// Takes the skeleton staff apart. Every field is zeroed on BOTH attacks, because the
/// secondary is a separate Attack carrying its own copy of every cost.
///
/// The summon hangs off a SpawnAbility on a prefab referenced by the attack, and WHICH
/// field carries it is not knowable from the game files - so all three candidates go.
/// Nulling three fields that might each be the culprit costs nothing; guessing wrong costs
/// a skeleton on every click.
///
/// The animation is the one thing deliberately left alone. It is the whole point: the
/// player raises the trophy, and the bird answers.
/// </summary>
private static void Strip(ItemDrop.ItemData.SharedData shared)
{
StripAttack(shared.m_attack);
StripAttack(shared.m_secondaryAttack);
}
private static void StripAttack(Attack attack)
{
if (attack == null) return;
attack.m_attackEitr = 0f;
attack.m_drawEitrDrain = 0f;
attack.m_reloadEitrDrain = 0f;
attack.m_attackHealth = 0f;
attack.m_attackHealthPercentage = 0f;
attack.m_attackHealthLowBlockUse = false;
attack.m_attackHealthReturnHit = 0f;
attack.m_attackStamina = 0f;
attack.m_drawStaminaDrain = 0f;
attack.m_reloadStaminaDrain = 0f;
attack.m_attackProjectile = null;
attack.m_spawnOnTrigger = null;
attack.m_spawnOnHit = null;
attack.m_spawnOnHitChance = 0f;
}
/// <summary>
/// Puts the vulture trophy in the hand where the staff's model was.
///
/// "attach" is not a name picked for tidiness: VisEquipment instantiates that child and
/// nothing else, so this is the only place a held model can live.
///
/// The size is a MULTIPLIER rather than a measurement in metres, which is the opposite of
/// what ModelBorrow does and is right here for one reason: the brief was "the trophy, 40%
/// smaller". The trophy's own size is the measurement; 0.6 is the relation applied to it.
/// </summary>
private static void SwapHandModel(GameObject prefab)
{
Transform attach = FindChild(prefab.transform, "attach");
if (attach == null)
{
Jotunn.Logger.LogWarning($"[{Label}] The {SourcePrefab} clone has no 'attach' child, so the " +
"held model was left as the vanilla staff. VisEquipment draws " +
"nothing else, so there was nowhere else to put it.");
return;
}
GameObject trophy = PrefabManager.Cache.GetPrefab<GameObject>(TrophyPrefab);
if (trophy == null)
{
Jotunn.Logger.LogWarning($"[{Label}] No '{TrophyPrefab}' to borrow; the item keeps the " +
"skeleton staff's look.");
return;
}
// The old staff mesh goes first, or the hand holds both.
for (int i = attach.childCount - 1; i >= 0; i--)
{
Object.DestroyImmediate(attach.GetChild(i).gameObject);
}
foreach (Renderer renderer in attach.GetComponents<Renderer>())
{
if (renderer != null) Object.DestroyImmediate(renderer);
}
// Instantiate into a holder that is ALREADY INACTIVE - the one line ModelBorrow exists
// for. A trophy is an ItemDrop, and Instantiate runs Awake first: waking one for a
// single frame drops a real trophy on the floor.
GameObject holder = new GameObject("WarVultureTrophy");
holder.transform.SetParent(attach, false);
holder.SetActive(false);
GameObject copy = Object.Instantiate(trophy, holder.transform);
copy.name = "model";
copy.transform.localPosition = Vector3.zero;
copy.transform.localRotation = Quaternion.identity;
copy.transform.localScale = Vector3.one * WarVultureConfig.HandModelScale.Value;
StripToMeshesOnly(copy);
holder.SetActive(true);
}
/// <summary>
/// The trophy reduced to nothing but its shape.
///
/// This used to be a BLACKLIST - scripts, colliders, rigidbodies, ZNetView - and it let
/// through exactly what a blacklist always lets through: the things nobody thought to name.
/// A vanilla item prefab carries the sparkle that makes dropped loot findable in long grass,
/// and that lives in ParticleSystems, ParticleSystemRenderers and Lights. None of those is a
/// MonoBehaviour, so all of them survived, and the item glittered in the player's hand like
/// something they had just thrown away.
///
/// So it is a whitelist now, the same shape as WarVultureVisual's: MeshFilter,
/// MeshRenderer, SkinnedMeshRenderer, Transform. Note it is deliberately NARROWER than the
/// mount's whitelist - "Renderer" would be wrong here, because ParticleSystemRenderer IS a
/// Renderer and it is half of what we are trying to be rid of.
///
/// Passes, because Unity refuses to destroy a component another one still requires, and the
/// refusal only unblocks once the dependent is gone.
/// </summary>
private static void StripToMeshesOnly(GameObject copy)
{
for (int pass = 0; pass < 6; pass++)
{
bool destroyedSomething = false;
foreach (Component component in copy.GetComponentsInChildren<Component>(true))
{
if (component == null) continue;
if (component is Transform) continue;
if (component is MeshFilter) continue;
if (component is MeshRenderer) continue;
if (component is SkinnedMeshRenderer) continue;
Object.DestroyImmediate(component);
if (component == null) destroyedSomething = true;
}
if (!destroyedSomething) break;
}
}
private static Transform FindChild(Transform root, string name)
{
if (root.name == name) return root;
for (int i = 0; i < root.childCount; i++)
{
Transform found = FindChild(root.GetChild(i), name);
if (found != null) return found;
}
return null;
}
public static bool IsWarVulture(ItemDrop.ItemData item)
{
return item != null && item.m_dropPrefab != null && item.m_dropPrefab.name == PrefabName;
}
/// <summary>
/// True when a cost being asked about belongs to this item.
///
/// The fallback on the equipped weapon is necessary rather than belt-and-braces: the cost
/// getters are called from Attack.Start and m_weapon is not guaranteed to be assigned yet.
/// It is only consulted when m_weapon is null, so a creature's own attack cannot be zeroed
/// just because the player happens to be holding the trophy at the time.
/// </summary>
public static bool IsWarVultureContext(ItemDrop.ItemData weapon)
{
if (weapon != null) return IsWarVulture(weapon);
Player local = Player.m_localPlayer;
return local != null && IsWarVulture(local.GetCurrentWeapon());
}
}
/// <summary>
/// The click. Attack.OnAttackTrigger is used rather than Attack.Start because it takes NO
/// parameters - its signature cannot drift - and it fires when the animation reaches its
/// release point, which is when a summon should land.
///
/// A Prefix returning FALSE, so for this item vanilla's attack-trigger code never runs at all.
/// m_weapon and m_character are private on Attack and arrive through Harmony's triple
/// underscore injection, which is checked at patch time: a rename becomes a startup error
/// instead of a silent null on every click.
/// </summary>
[HarmonyPatch(typeof(Attack), "OnAttackTrigger")]
public static class WarVultureCastPatch
{
public static bool Prefix(ItemDrop.ItemData ___m_weapon, Humanoid ___m_character)
{
if (!WarVultureItem.IsWarVulture(___m_weapon)) return true;
// Still returns false while riding, so vanilla's trigger never runs - but the dismount
// is NOT taken from here. In the saddle this event is unreliable: the cast clip loses
// to the sitting pose before its event fires. WarVultureMount reads the button itself.
WarVultureMount.Toggle(___m_character as Player);
return false;
}
}
/// <summary>
/// The item costs nothing, guaranteed.
///
/// Zeroing the fields on the clone ought to be enough by every reading of the game's own code.
/// On the Skadi staff the cost came back in game anyway, which means the write to a clone's
/// SharedData does not survive something - so relying on it alone is relying on a mechanism
/// already observed to fail. These three getters are the single funnel every cost check flows
/// through: Attack.Start asks them before it will start, and the tooltip asks them for what to
/// print. All three are private and take no parameters, so they are addressed by name.
/// </summary>
[HarmonyPatch]
public static class WarVultureFreeCastPatch
{
[HarmonyTargetMethods]
private static System.Collections.Generic.IEnumerable<System.Reflection.MethodBase> TargetMethods()
{
yield return AccessTools.Method(typeof(Attack), "GetAttackEitr");
yield return AccessTools.Method(typeof(Attack), "GetAttackHealth");
yield return AccessTools.Method(typeof(Attack), "GetAttackStamina");
}
[HarmonyPostfix]
private static void Postfix(ItemDrop.ItemData ___m_weapon, ref float __result)
{
if (__result == 0f) return;
if (!WarVultureItem.IsWarVultureContext(___m_weapon)) return;
__result = 0f;
}
}
}

View file

@ -0,0 +1,389 @@
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);
}
}
}

View file

@ -0,0 +1,193 @@
using System.Reflection;
using HarmonyLib;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The one patch that makes a seated player able to fly.
///
/// Player.SetControls opens with: if the player is attached and presses any movement key, and
/// there is no doodad controller, call AttachStop. That is vanilla's "stand up from the chair",
/// read straight out of the assembly - and against a rider who drives themselves it fires on
/// the first tap of W.
///
/// Giving the game a doodad controller instead is not the way out: SetDoodadControlls zeroes
/// moveDir, run and autoRun unconditionally afterwards, so the rider would stay attached and
/// be unable to move. Both doors are shut, which is why this one is a patch.
///
/// So m_attached is lifted for the duration of SetControls and put straight back. Nothing else
/// in that method reads it (checked instruction by instruction), and everything else in the
/// game still sees an attached player - including ZSyncAnimation, which is what keeps the
/// sitting pose on everyone else's screen.
///
/// AND THE SECOND HALF, added after the first flight. Lifting m_attached hands the rider back
/// every action a standing player has, and three of them have no business happening in a
/// saddle: jump, dodge and crouch each played their own animation for half a second before the
/// sitting pose snapped back, which is what a rider trying to gain height actually saw.
///
/// They are suppressed here, at the source, and it costs nothing that was wanted: vanilla's
/// UpdateDebugFly does NOT read these arguments. It reads ZInput directly - GetButton("Jump")
/// to climb and KeyCode.LeftControl to descend - so taking them out of SetControls removes the
/// jump and keeps the climb. Same for the click: while riding, the dismount is read straight
/// off ZInput in WarVultureMount, so the attack is suppressed here rather than left to fight
/// the saddle pose for an animation it was never going to win.
///
/// It costs one boolean read per frame when nobody is riding.
/// </summary>
[HarmonyPatch(typeof(Player), "SetControls")]
public static class WarVultureControlsPatch
{
public static void Prefix(Player __instance, ref bool ___m_attached,
ref bool attack, ref bool attackHold,
ref bool secondaryAttack, ref bool secondaryAttackHold,
ref bool jump, ref bool crouch, ref bool dodge,
out bool __state)
{
__state = false;
if (!WarVultureMount.IsRiding(__instance)) return;
attack = false;
attackHold = false;
secondaryAttack = false;
secondaryAttackHold = false;
jump = false;
crouch = false;
dodge = false;
if (!___m_attached) return;
___m_attached = false;
__state = true;
}
public static void Postfix(ref bool ___m_attached, bool __state)
{
if (__state) ___m_attached = true;
}
}
/// <summary>
/// The speed of the ride, and the bird's wind.
///
/// Character.UpdateDebugFly has just written this physics step's velocity when this runs, so
/// this is the last word on it. The mount scales what vanilla computed rather than replacing
/// it - see WarVultureMount.ApplyFlight for why that keeps the flight feeling smooth.
///
/// m_currentVel, m_body and m_run are all private on Character and arrive through Harmony's
/// field injection, which is verified when the patch is applied: a Valheim rename becomes a
/// startup error instead of a mount that silently stops working.
/// </summary>
[HarmonyPatch(typeof(Character), "UpdateDebugFly")]
public static class WarVultureFlightPatch
{
private static readonly FieldInfo DebugFlySpeedField = AccessTools.Field(typeof(Character), "m_debugFlySpeed");
private static bool warnedAboutSpeedField;
/// <summary>
/// Vanilla's own debug fly speed, read live rather than cached: the game exposes it as a
/// static that can be retuned, and a stale copy here would quietly scale the whole ride.
/// </summary>
public static float DebugFlySpeed
{
get
{
if (DebugFlySpeedField != null) return System.Convert.ToSingle(DebugFlySpeedField.GetValue(null));
if (!warnedAboutSpeedField)
{
warnedAboutSpeedField = true;
Jotunn.Logger.LogWarning("[WarVulture] Character.m_debugFlySpeed could not be found, so the " +
"mount's speeds are being scaled against an assumed 10 m/s. If the " +
"bird flies wrong, this line is why.");
}
return 10f;
}
}
public static void Postfix(Character __instance, ref Vector3 ___m_currentVel, Rigidbody ___m_body, bool ___m_run)
{
WarVultureMount mount = WarVultureMount.Active;
if (mount == null) return;
Player player = __instance as Player;
if (player == null || !WarVultureMount.IsRiding(player)) return;
mount.ApplyFlight(___m_run, ref ___m_currentVel, ___m_body);
}
}
/// <summary>
/// Gives every player a watcher, so a rider on someone else's screen gets a bird under them.
///
/// A second Player.Awake postfix alongside the one in ZdoVisualSync rather than an edit to it:
/// that file belongs to the shared race visuals, this belongs to the vulture, and Harmony is
/// perfectly happy to hold both.
/// </summary>
[HarmonyPatch(typeof(Player), "Awake")]
public static class WarVulturePlayerAwakePatch
{
public static void Postfix(Player __instance)
{
if (__instance.GetComponent<WarVultureRemoteVisual>() == null)
{
__instance.gameObject.AddComponent<WarVultureRemoteVisual>();
}
}
}
/// <summary>
/// The bird as everyone ELSE sees it.
///
/// The rider's own client draws its bird from WarVultureMount; this draws one for every other
/// player who has the flag set on their ZDO. It never touches flight, attachment or input -
/// remote players are moved by their own owner and the pose replicates itself through
/// ZSyncAnimation, so there is nothing here but a model that appears and disappears.
/// </summary>
public class WarVultureRemoteVisual : MonoBehaviour
{
private const string HolderName = "WarVultureRemoteModel";
private Player player;
private WarVultureRig rig;
private void Awake()
{
player = GetComponent<Player>();
}
private void Update()
{
if (player == null) return;
// The local rider is drawn by their own mount; two birds is one too many.
if (player == Player.m_localPlayer) { Hide(); return; }
ZNetView nview = player.GetComponent<ZNetView>();
if (nview == null || !nview.IsValid()) { Hide(); return; }
bool mounted = nview.GetZDO().GetBool(WarVultureMount.MountedKey, false) && !player.IsDead();
if (mounted && rig == null) rig = WarVultureVisual.Spawn(player.transform, HolderName);
else if (!mounted && rig != null) Hide();
if (rig != null)
{
Vector3 velocity = player.GetVelocity();
rig.Drive(new Vector3(velocity.x, 0f, velocity.z).magnitude);
}
}
private void Hide()
{
if (rig == null) return;
Destroy(rig.gameObject);
rig = null;
}
private void OnDestroy()
{
Hide();
}
}
}

View file

@ -0,0 +1,376 @@
using UnityEngine;
using Jotunn.Managers;
namespace RacesOfValheim
{
/// <summary>
/// The bird's body: built dead once, then copied.
///
/// WHY IT IS BUILT AT REGISTRATION AND NOT AT THE SUMMON. The first version borrowed the model
/// the way ModelBorrow does it - instantiate into an inactive holder, then DestroyImmediate
/// everything that is not a renderer. That is correct at registration time and wrong at summon
/// time, and the game says so out loud:
///
/// Destroying components immediately is not permitted during physics trigger/contact,
/// animation event callbacks, rendering callbacks or OnValidate.
///
/// The summon runs from Attack.OnAttackTrigger, which the game calls from CharacterAnimEvent -
/// an animation event callback. Every DestroyImmediate was refused, the model kept its
/// Character, its MonsterAI and its ZNetView, and the moment the holder was switched on Awake
/// ran and a real Ashlands predator was born under the player. A live rigidbody ignores its
/// parent transform, so it flew off. Eleven refusal lines sat in the log directly above the
/// "Borrowed 'Volture'" line, which is exactly how it was found.
///
/// So: the stripping happens once, during CreateAllModAssets, where DestroyImmediate is legal.
/// What is kept is a TEMPLATE - an inactive, script-free carcass held in DontDestroyOnLoad -
/// and a summon is a plain Instantiate of it. Instantiate is allowed in any context.
///
/// And it is CHECKED, not assumed. If a single MonoBehaviour survives the strip, the template
/// is thrown away and the item refuses to summon. A bird that does not appear is a bug report;
/// a bird that appears with an AI is a predator in the player's world with a saved ZDO.
/// </summary>
public static class WarVultureVisual
{
private const string SourcePrefab = "Volture";
private const string Label = "WarVulture";
// The three parameters DrakeFormBehavior drives, which is the only animated borrowed
// creature in this mod known to look right.
private const string FlyingParam = "flying";
private const string GroundParam = "onGround";
private const string SpeedParam = "forward_speed";
private static GameObject template;
private static float templateSize = 1f;
public static bool Ready => template != null;
// ---------------------------------------------------------------- the template
/// <summary>
/// Called once from WarVultureItem.Register, i.e. from CreateAllModAssets, i.e. from a
/// context where components may be destroyed immediately.
/// </summary>
public static void BuildTemplate()
{
if (template != null) return;
GameObject source = PrefabManager.Cache.GetPrefab<GameObject>(SourcePrefab);
if (source == null)
{
Jotunn.Logger.LogWarning($"[{Label}] No '{SourcePrefab}' prefab to copy; the mount will refuse " +
"to summon rather than put an invisible rider in the sky.");
return;
}
// Inactive BEFORE the Instantiate - the one line that keeps Awake from running on a
// live predator. Everything else here depends on it.
GameObject root = new GameObject("WarVultureTemplate");
root.SetActive(false);
Object.DontDestroyOnLoad(root);
GameObject copy = Object.Instantiate(source, root.transform);
copy.name = "VoltureModel";
copy.transform.localPosition = Vector3.zero;
copy.transform.localRotation = Quaternion.identity;
copy.transform.localScale = Vector3.one;
int refused = StripToRenderers(copy);
int alive = CountBehaviours(copy);
if (alive > 0)
{
Jotunn.Logger.LogError($"[{Label}] {alive} script(s) survived the strip on '{SourcePrefab}' " +
$"({refused} destroy calls were refused). The template is being thrown " +
"away and the War Vulture will not summon - a half-stripped creature " +
"prefab is a live animal, not a model.");
Object.DestroyImmediate(root);
return;
}
PrepareAnimator(copy);
templateSize = Mathf.Max(0.01f, LargestDimension(copy));
template = copy;
}
/// <summary>
/// Everything that is not geometry or animation, removed in passes.
///
/// Passes rather than one sweep because Unity refuses to destroy a component another
/// component still requires, and the refusal is silent as far as the caller is concerned -
/// it logs and moves on. Repeating until a pass changes nothing lets a dependency chain
/// unwind in whatever order it needs to.
///
/// Returns how many destroy calls were refused on the last pass, purely so the failure
/// above can say something useful.
/// </summary>
private static int StripToRenderers(GameObject copy)
{
int stubborn = 0;
for (int pass = 0; pass < 6; pass++)
{
bool destroyedSomething = false;
stubborn = 0;
foreach (Component component in copy.GetComponentsInChildren<Component>(true))
{
if (component == null) continue;
if (IsKept(component)) continue;
Object.DestroyImmediate(component);
if (component == null) destroyedSomething = true;
else stubborn++;
}
if (!destroyedSomething) break;
}
return stubborn;
}
/// <summary>
/// The whitelist. Anything not on it goes - colliders, rigidbodies, ZNetView, Character,
/// MonsterAI, the lot. Keeping a list of what to KEEP rather than a list of what to remove
/// is the difference between a model and an animal: a new component in a future Valheim
/// patch is removed by default instead of surviving by omission.
///
/// The two MESH renderers by name rather than Renderer as a family, which looks like
/// pedantry and is not: ParticleSystemRenderer is a Renderer, and "keep every Renderer" is
/// how the trophy in the player's hand ended up carrying the sparkle vanilla puts on
/// dropped loot. Meshes and the animator that poses them - nothing else.
/// </summary>
private static bool IsKept(Component component)
{
return component is Transform
|| component is MeshFilter
|| component is MeshRenderer
|| component is SkinnedMeshRenderer
|| component is Animator
|| component is LODGroup;
}
private static int CountBehaviours(GameObject copy)
{
int alive = 0;
foreach (MonoBehaviour behaviour in copy.GetComponentsInChildren<MonoBehaviour>(true))
{
if (behaviour != null) alive++;
}
return alive;
}
/// <summary>
/// Three settings, each preventing one specific failure rather than tidying anything.
///
/// applyRootMotion: clips authored to walk a creature through the world would walk the
/// model out from under its rider.
///
/// cullingMode: the default stops animating when no renderer is on screen, and this bird
/// lives half off the bottom of the screen - a frozen mid-flap reads as a bug.
///
/// fireEvents: the flight clips carry animation events aimed at CharacterAnimEvent, which
/// has just been stripped off. Left on, every wingbeat would log "has no receiver".
/// </summary>
private static void PrepareAnimator(GameObject copy)
{
Animator animator = copy.GetComponentInChildren<Animator>(true);
if (animator == null)
{
Jotunn.Logger.LogWarning($"[{Label}] The stripped '{SourcePrefab}' has no Animator, so the bird " +
"will hang in its bind pose - wings out, legs straight.");
return;
}
animator.applyRootMotion = false;
animator.cullingMode = AnimatorCullingMode.AlwaysAnimate;
animator.fireEvents = false;
animator.enabled = true;
}
// ---------------------------------------------------------------- summoning a copy
/// <summary>
/// Hangs a copy of the template under a rider and returns the rig that keeps it there.
/// Null when the template could not be built, which the caller must treat as "do not
/// summon" rather than "summon an invisible bird".
/// </summary>
public static WarVultureRig Spawn(Transform rider, string holderName)
{
if (template == null || rider == null) return null;
GameObject holder = new GameObject(holderName);
holder.transform.SetParent(rider, false);
holder.transform.localPosition = Vector3.zero;
holder.transform.localRotation = Quaternion.identity;
GameObject model = Object.Instantiate(template, holder.transform);
model.name = "model";
model.transform.localPosition = Vector3.zero;
model.transform.localRotation = Quaternion.identity;
model.transform.localScale = Vector3.one * (WarVultureConfig.MountSize.Value / templateSize);
model.SetActive(true);
WarVultureRig rig = holder.AddComponent<WarVultureRig>();
rig.Bind(rider, model);
return rig;
}
// ---------------------------------------------------------------- animation
/// <summary>
/// One frame of flight, told to the animator. Any parameter this controller does not have
/// is skipped, so a Valheim animator rename costs a stiff-looking bird rather than a wall
/// of errors every frame.
/// </summary>
public static void Drive(Animator animator, float forwardSpeed)
{
if (animator == null || animator.runtimeAnimatorController == null) return;
if (Has(animator, FlyingParam, AnimatorControllerParameterType.Bool)) animator.SetBool(FlyingParam, true);
if (Has(animator, GroundParam, AnimatorControllerParameterType.Bool)) animator.SetBool(GroundParam, false);
if (Has(animator, SpeedParam, AnimatorControllerParameterType.Float)) animator.SetFloat(SpeedParam, forwardSpeed);
}
private static bool Has(Animator animator, string name, AnimatorControllerParameterType type)
{
foreach (AnimatorControllerParameter parameter in animator.parameters)
{
if (parameter.type == type && parameter.name == name) return true;
}
return false;
}
// ---------------------------------------------------------------- the seat bone
/// <summary>
/// The bone the rider sits on.
///
/// A bone rather than an offset in metres, because that is the difference between sitting
/// on the bird and hovering above it: the back moves with every wingbeat, and a fixed
/// offset can only ever be right on one frame of the animation.
///
/// The name is guessed from a priority list and can be overridden in config, because the
/// rig's bone names are not knowable from outside the game. The automatic pick was the right
/// one in play, so the startup dump that found it has been retired.
/// </summary>
public static Transform FindSeatBone(GameObject model)
{
if (model == null) return null;
Transform[] bones = model.GetComponentsInChildren<Transform>(true);
string wanted = WarVultureConfig.SeatBone.Value;
if (!string.IsNullOrEmpty(wanted))
{
Transform named = Match(bones, wanted);
if (named != null) return named;
Jotunn.Logger.LogWarning($"[{Label}] No bone matching '{wanted}' on the vulture; falling back " +
"to the automatic pick. The bone list is in the log from startup.");
}
// Deliberately in this order: the back of a bird is its spine and chest, and the hips
// and root are last-ditch so that SOMETHING is anchored rather than nothing.
foreach (string candidate in new[] { "spine", "chest", "back", "torso", "body", "pelvis", "hip", "root" })
{
Transform found = Match(bones, candidate);
if (found != null) return found;
}
return null;
}
/// <summary>
/// Last match rather than first, on purpose: rigs number their spines outward from the
/// hips, so the last "spine" is the one furthest along the back - which is where a saddle
/// goes, not where the tail joins.
/// </summary>
private static Transform Match(Transform[] bones, string needle)
{
Transform best = null;
foreach (Transform bone in bones)
{
if (bone.name.IndexOf(needle, System.StringComparison.OrdinalIgnoreCase) >= 0) best = bone;
}
return best;
}
// ---------------------------------------------------------------- measuring
private static float LargestDimension(GameObject model)
{
bool any = false;
Bounds bounds = new Bounds();
foreach (Renderer renderer in model.GetComponentsInChildren<Renderer>(true))
{
Mesh mesh = renderer is SkinnedMeshRenderer skinned
? skinned.sharedMesh
: renderer.GetComponent<MeshFilter>()?.sharedMesh;
if (mesh == null) continue;
Bounds local = mesh.bounds;
Matrix4x4 toModel = model.transform.worldToLocalMatrix * renderer.transform.localToWorldMatrix;
for (int corner = 0; corner < 8; corner++)
{
Vector3 point = toModel.MultiplyPoint3x4(local.center + new Vector3(
(corner & 1) == 0 ? -local.extents.x : local.extents.x,
(corner & 2) == 0 ? -local.extents.y : local.extents.y,
(corner & 4) == 0 ? -local.extents.z : local.extents.z));
if (!any) { bounds = new Bounds(point, Vector3.zero); any = true; }
else bounds.Encapsulate(point);
}
}
return any ? Mathf.Max(bounds.size.x, Mathf.Max(bounds.size.y, bounds.size.z)) : 1f;
}
}
/// <summary>
/// Keeps the bird under its rider, one bone at a time.
///
/// In LateUpdate, after the animator has posed the skeleton for this frame, the whole model is
/// slid so that the seat bone lands exactly on the rider's own origin. That is what "sitting on
/// the bird's back" means as a piece of code, and it is why there is no height offset anywhere
/// in this feature any more: the back tells us where it is, every frame, including while it
/// rises and falls with the wingbeat.
///
/// Shared by the rider's own copy and by the copy other players see, so the bird cannot sit in
/// two different places depending on who is looking.
/// </summary>
public class WarVultureRig : MonoBehaviour
{
private Transform rider;
private Transform model;
private Transform seatBone;
private Animator animator;
public void Bind(Transform rider, GameObject model)
{
this.rider = rider;
this.model = model.transform;
seatBone = WarVultureVisual.FindSeatBone(model);
animator = model.GetComponentInChildren<Animator>(true);
}
public void Drive(float forwardSpeed)
{
WarVultureVisual.Drive(animator, forwardSpeed);
}
private void LateUpdate()
{
if (rider == null || model == null) return;
Vector3 seat = rider.position + rider.rotation * new Vector3(
0f, WarVultureConfig.SeatNudgeY.Value, WarVultureConfig.SeatNudgeZ.Value);
if (seatBone != null) model.position += seat - seatBone.position;
else model.position = seat;
}
}
}