Merge branch 'feat-free-bat-flight': Free Bat Flight as a choice

This commit is contained in:
kanym 2026-10-29 19:34:07 +01:00
commit 0fe91dd52f
8 changed files with 176 additions and 23 deletions

View file

@ -6,11 +6,22 @@ namespace RacesOfValheim
/// <summary>
/// Whether a player is a bat, on any client.
///
/// This file used to be AswidBatAggro: while the bat flew on vanilla's debug-fly flag, vanilla
/// read that flag as "this player is not really here" - no monster could see, hear or wake for
/// it, and every hit on it was dropped - and six patches here lied about the flag in exactly
/// those places. The bat now flies on m_flying (DirectedFlight.cs), which vanilla's AI and
/// damage never look at, so monsters notice and hurt it with no help, and the lie went.
/// Stamina Flight flies on m_flying (DirectedFlight.cs), which vanilla's AI and damage never
/// look at, so monsters notice and hurt that bat with no help.
///
/// Free Flight flies on vanilla's debug-fly flag, and vanilla reads that flag as "this player
/// is not really here". Six places, read out of assembly_valheim:
///
/// BaseAI.CanHearTarget, BaseAI.CanSeeTarget and BaseAI's HuntPlayer fallback ask
/// Player.InDebugFlyMode() and drop the player.
/// MonsterAI.UpdateSleep asks IsDebugFlying() and will not wake, twice over.
/// Character.ApplyDamage and Character.RPC_Damage ask IsDebugFlying() and drop the hit.
///
/// The patches below keep the flag (it IS the flight) and lie about it in exactly those
/// places, for bats only. InDebugFlyMode() is forced false flat: those three AI paths are its
/// only callers. IsDebugFlying() cannot be: Character.UpdateMotion reads it to hold the bat in
/// the air, so it reads false only while the call stack is inside one of the methods that push
/// the counter. The patches were removed with the old flight in v1.6.1 and came back with it.
/// </summary>
public static class AswidBatForm
{
@ -22,6 +33,14 @@ namespace RacesOfValheim
private static readonly int BatFormHash = "SE_BatForm".GetStableHashCode();
// How deep we are inside vanilla calls that must not see the debug-fly flag. A counter,
// not a bool: ApplyDamage runs inside RPC_Damage, so the frames nest.
private static int unmaskDepth;
public static bool Unmasked => unmaskDepth > 0;
public static void PushUnmask() { unmaskDepth++; }
public static void PopUnmask() { if (unmaskDepth > 0) unmaskDepth--; }
/// <summary>
/// The ZDO first and the status effect only as a fallback: the ZDO is the one that is true
/// on every client, and the status effect covers the local player during the frames of the
@ -40,6 +59,77 @@ namespace RacesOfValheim
}
}
/// <summary>Free Flight: monsters see and hear a bat. See AswidBatForm for why this one is safe flat.</summary>
[HarmonyPatch(typeof(Player), "InDebugFlyMode")]
public static class Aswid_BatIsVisibleToAI_Patch
{
public static void Postfix(Player __instance, ref bool __result)
{
if (__result && AswidBatForm.IsBat(__instance)) __result = false;
}
}
/// <summary>
/// The scoped half: false only inside the methods that push the counter, so flight, motion,
/// the camera and UpdateStats still read the flag as true.
/// </summary>
[HarmonyPatch(typeof(Player), "IsDebugFlying")]
public static class Aswid_BatIsDebugFlying_Patch
{
public static void Postfix(Player __instance, ref bool __result)
{
if (!__result || !AswidBatForm.Unmasked) return;
if (AswidBatForm.IsBat(__instance)) __result = false;
}
}
/// <summary>
/// A hit landing on a free-flying bat. Finalizer rather than Postfix: the counter has to come
/// down even when the method throws, and a void Finalizer leaves the exception alone.
/// </summary>
[HarmonyPatch(typeof(Character), "ApplyDamage")]
public static class Aswid_BatTakesDamage_Patch
{
public static void Prefix(Character __instance, ref bool __state)
{
__state = __instance is Player player && AswidBatForm.IsBat(player);
if (__state) AswidBatForm.PushUnmask();
}
public static void Finalizer(bool __state)
{
if (__state) AswidBatForm.PopUnmask();
}
}
/// <summary>The networked half of the same thing: a hit sent by another machine.</summary>
[HarmonyPatch(typeof(Character), "RPC_Damage")]
public static class Aswid_BatTakesRemoteDamage_Patch
{
public static void Prefix(Character __instance, ref bool __state)
{
__state = __instance is Player player && AswidBatForm.IsBat(player);
if (__state) AswidBatForm.PushUnmask();
}
public static void Finalizer(bool __state)
{
if (__state) AswidBatForm.PopUnmask();
}
}
/// <summary>
/// Sleepers. UpdateSleep picks the closest player itself, possibly a remote bat, so the counter
/// goes up for the whole call and the bat test happens in the IsDebugFlying postfix, which only
/// runs its test for a player already debug flying.
/// </summary>
[HarmonyPatch(typeof(MonsterAI), "UpdateSleep")]
public static class Aswid_BatWakesSleepers_Patch
{
public static void Prefix() { AswidBatForm.PushUnmask(); }
public static void Finalizer() { AswidBatForm.PopUnmask(); }
}
/// <summary>
/// The revert path cannot handle a bat that dies: AswidRace.Update() returns early on IsDead(),
/// so the coroutine that takes the form down never starts. The flight flag would stay on and

View file

@ -74,8 +74,24 @@ namespace RacesOfValheim
// The bat flies on the same directed flight as the Skadi's drakes (DirectedFlight.cs),
// with its own numbers. It used to fly on vanilla's debug-fly flag: 50 m/s, free, blind
// to carry weight, and ignored by every monster until AswidBatAggro lied to six vanilla
// methods about it. None of that is left.
// methods about it. The old flight came back as Free Flight, for players who want it
// (building tall); AswidBatForm holds the aggro patches it needs.
public enum EncumberedMode { Allowed, Blocked }
public enum BatFlightRuleMode { PlayerChoice, AlwaysStaminaFlight, AlwaysFreeFlight }
public static ConfigEntry<bool> FreeBatFlight;
public static ConfigEntry<BatFlightRuleMode> BatFlightRule;
/// <summary>Which flight a bat taken now gets: the server's rule first, then the player's own pick.</summary>
public static bool UsesFreeBatFlight()
{
switch (BatFlightRule.Value)
{
case BatFlightRuleMode.AlwaysStaminaFlight: return false;
case BatFlightRuleMode.AlwaysFreeFlight: return true;
default: return FreeBatFlight.Value;
}
}
public static ConfigEntry<float> BatTurnSpeed;
public static ConfigEntry<float> BatGlideSpeed;
@ -240,6 +256,10 @@ namespace RacesOfValheim
new ConfigDescription("How far the camera rolls. 1 is about 4 degrees. Local.", new AcceptableValueRange<float>(0f, 3f)));
const string batform = "Aswid - Bat Form";
FreeBatFlight = config.Bind(batform, "Free Bat Flight", false,
new ConfigDescription("Off: Stamina Flight, the settings below. On: the old Free Flight, up to 50 m/s with no stamina cost and no weight limit; Jump rises, Left Ctrl sinks. Your own choice, unless the server's Bat Flight Rule forces one. Takes effect the next time you become a bat."));
BatFlightRule = config.Bind(batform, "Bat Flight Rule", BatFlightRuleMode.PlayerChoice,
new ConfigDescription("Server rule. PlayerChoice: each player's Free Bat Flight setting decides. AlwaysStaminaFlight / AlwaysFreeFlight: every bat flies that way. On a server only the host's or the server's value counts."));
// Same controls as the Skadi's drake: aim with the camera, W beats forward, Shift
// sprints, S beats backwards, and letting go hovers briefly before gliding down.
BatTurnSpeed = config.Bind(batform, "Turn Speed", 180f,

View file

@ -14,17 +14,25 @@ namespace RacesOfValheim
///
/// Other clients learn the bat is airborne from Aswid_IsBatForm in the ZDO, which
/// Aswid_MultiplayerVisuals_Patch mirrors into their copy's m_flying.
///
/// FREE FLIGHT. A player who picks it (or a server that forces it, AswidConfig.UsesFreeBatFlight)
/// gets the old flight back: vanilla's debug fly, both halves (the field for the local physics,
/// s_debugFly in the ZDO for everyone else), and no DirectedFlight. The mode is read once, when
/// the form goes up. AswidBatForm keeps monsters seeing and hurting a free-flying bat.
/// </summary>
public class BatFormBehavior : MonoBehaviour, IDirectedFlyer
{
private static readonly System.Reflection.FieldInfo FlyingField =
AccessTools.Field(typeof(Character), "m_flying");
private static readonly System.Reflection.FieldInfo DebugFlyField =
AccessTools.Field(typeof(Player), "m_debugFly");
private Animator anim;
private AswidProgression.FormRules formRules;
private float startTime;
private bool warnedTooHeavy;
private bool expired;
private bool free;
public void Initialize(AswidProgression.FormRules rules)
{
@ -73,8 +81,9 @@ namespace RacesOfValheim
anim = GetComponentInChildren<Animator>();
startTime = Time.time;
LastPoweredTime = Time.time;
DirectedFlight.Register(this);
SetFlying(true);
free = AswidConfig.UsesFreeBatFlight();
if (!free) DirectedFlight.Register(this);
Hold();
}
private void Update()
@ -85,16 +94,20 @@ namespace RacesOfValheim
// Held every frame rather than set once, for the same reason the debug-fly flag was:
// anything that clears it mid-form (a vanilla reset, another mod) would drop the bat
// into walking with the model still on.
SetFlying(true);
Hold();
if (!CanPower && !warnedTooHeavy)
// Free Flight ignores weight, so only Stamina Flight warns about it.
if (!free)
{
warnedTooHeavy = true;
player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_aswid_bat_too_heavy_to_beat"));
}
else if (CanPower)
{
warnedTooHeavy = false;
if (!CanPower && !warnedTooHeavy)
{
warnedTooHeavy = true;
player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_aswid_bat_too_heavy_to_beat"));
}
else if (CanPower)
{
warnedTooHeavy = false;
}
}
float max = MaxDuration();
@ -120,15 +133,37 @@ namespace RacesOfValheim
SetFlying(false);
}
private void Hold()
{
if (free) SetDebugFly(true);
else SetFlying(true);
}
/// <summary>
/// The local half of flight. The remote half is the Aswid_IsBatForm ZDO flag AswidRace
/// already writes, so there is nothing to replicate here.
/// The local half of Stamina Flight. The remote half is the Aswid_IsBatForm ZDO flag
/// AswidRace already writes, so there is nothing to replicate here. Turning it off also
/// turns debug fly off, so every exit path ends both flights whichever one was up.
/// </summary>
public static void SetFlying(bool flying)
{
Player player = Player.m_localPlayer;
if (player == null || FlyingField == null) return;
FlyingField.SetValue(player, flying);
if (player == null) return;
if (FlyingField != null) FlyingField.SetValue(player, flying);
if (!flying) SetDebugFly(false);
}
/// <summary>
/// Both halves of debug fly, for Free Flight. The ZDO write every frame is not network
/// spam: ZDO.Set returns early when the value is unchanged.
/// </summary>
private static void SetDebugFly(bool flying)
{
Player player = Player.m_localPlayer;
if (player == null) return;
if (DebugFlyField != null) DebugFlyField.SetValue(player, flying);
ZNetView nview = player.GetComponent<ZNetView>();
if (nview != null && nview.IsValid() && nview.IsOwner()) nview.GetZDO().Set(ZDOVars.s_debugFly, flying);
}
}
}

View file

@ -47,6 +47,8 @@ namespace RacesOfValheim
// Each player picks their own True Form: a player model mod (VRM and the like) breaks
// under the troll costume, so a server cannot be allowed to force the costume on.
"legacy true form",
// The player's own pick of bat flight; the synced Bat Flight Rule can override it.
"free bat flight",
};
public static void Apply(ConfigFile config)

View file

@ -516,9 +516,12 @@ namespace RacesOfValheim
if (state >= 2)
{
sb.AppendLine(ModText.Get("rov_compendium_aswid_bat_form_g_key_night"));
sb.AppendLine(ModText.Get("rov_compendium_aswid_bat_flight",
AswidConfig.BatPoweredStaminaPerSecond.Value.ToString("0.#"),
AswidConfig.BatSprintStaminaPerSecond.Value.ToString("0.#")));
if (AswidConfig.UsesFreeBatFlight())
sb.AppendLine(ModText.Get("rov_compendium_aswid_bat_free_flight"));
else
sb.AppendLine(ModText.Get("rov_compendium_aswid_bat_flight",
AswidConfig.BatPoweredStaminaPerSecond.Value.ToString("0.#"),
AswidConfig.BatSprintStaminaPerSecond.Value.ToString("0.#")));
}
if (state >= 2)

View file

@ -31,6 +31,7 @@
"rov_compendium_aswid_aswid_s_curse": "The Aswid's Curse\n",
"rov_compendium_aswid_bat_form_g_key_night": "[Eikthyr Unlock] Bat Form ('G' Key, night only): Take the shape of a bat.\n",
"rov_compendium_aswid_bat_flight": "The bat flies where you look: W beats forward for $1 stamina a second, Shift sprints for $2 more, S beats backwards, and letting go holds you still for a moment before you glide down. Out of stamina, you can only glide.\n",
"rov_compendium_aswid_bat_free_flight": "Free Flight: the bat flies fast and free, with no stamina cost and no weight limit. Jump rises, Left Ctrl sinks, Shift goes faster.\n",
"rov_compendium_aswid_bat_form_now_answers_by": "[The Elder Unlock] Bat Form now answers by day as well as night.\n",
"rov_compendium_aswid_benedictus_et_afflictus": "[Base Passive] Benedictus et Afflictus:",
"rov_compendium_aswid_claws_beast_s_grows_blackened": "[Base Passive] Claws of the Beast ([K], $1s): Grows blackened claws for a limited time instead of a weapon. Bare-handed blows land at $2% of a full-grown pair's weight, all of it as slash, and they grow with every boss that falls. Draw a sword and they wait, sheathe it and they are back, until the timer runs out and they retract on their own - no slot wasted between casts. They cannot be dropped, traded or stolen while grown - and in bat or mist form you have no hands to hold them with.\n",

View file

@ -31,6 +31,7 @@
"rov_compendium_aswid_aswid_s_curse": "La maledizione degli Aswid\n",
"rov_compendium_aswid_bat_form_g_key_night": "[Sblocco Eikthyr] Forma di pipistrello (tasto 'G', solo di notte): prendi la forma di un pipistrello.\n",
"rov_compendium_aswid_bat_flight": "Il pipistrello vola dove guardi: W batte le ali in avanti per $1 stamina al secondo, Shift scatta per altri $2, S batte all'indietro, e se lasci tutto resti fermo un attimo prima di planare giù. Senza stamina puoi solo planare.\n",
"rov_compendium_aswid_bat_free_flight": "Volo libero: il pipistrello vola veloce e libero, senza costo di stamina e senza limite di peso. Salto sale, Ctrl sinistro scende, Shift va più veloce.\n",
"rov_compendium_aswid_bat_form_now_answers_by": "[Sblocco Antico] La forma di pipistrello ora risponde di giorno come di notte.\n",
"rov_compendium_aswid_benedictus_et_afflictus": "[Passiva base] Benedictus et Afflictus:",
"rov_compendium_aswid_claws_beast_s_grows_blackened": "[Passiva base] Artigli della Bestia ([K], $1s): per un tempo limitato fai crescere artigli anneriti al posto di un'arma. I colpi a mani nude valgono il $2% del peso di un paio adulto, tutto come danno da taglio, e crescono con ogni boss che cade. Sfodera una spada e aspettano, rinfoderala e tornano, finché il tempo non scade e si ritraggono da soli, senza sprecare uno slot tra un uso e l'altro. Mentre sono fuori non possono essere lasciati cadere, scambiati o rubati, e in forma di pipistrello o di nebbia non hai mani per tenerli.\n",

View file

@ -31,6 +31,7 @@
"rov_compendium_aswid_aswid_s_curse": "Проклятие Асвида\n",
"rov_compendium_aswid_bat_form_g_key_night": "[Награда: Эйктюр] Облик летучей мыши (клавиша «G», только ночью): Примите облик летучей мыши.\n",
"rov_compendium_aswid_bat_flight": "Летучая мышь летит туда, куда вы смотрите: W — полет вперед за $1 выносливости в секунду, Shift — рывок еще за $2, S — полет назад, а если отпустить клавиши, вы ненадолго зависаете, а затем планируете вниз. Без выносливости можно только планировать.\n",
"rov_compendium_aswid_bat_free_flight": "Свободный полет: летучая мышь летает быстро и свободно, без затрат выносливости и без ограничения веса. Прыжок — вверх, левый Ctrl — вниз, Shift — быстрее.\n",
"rov_compendium_aswid_bat_form_now_answers_by": "[Награда: Древний] Облик летучей мыши теперь доступен как ночью, так и днем.\n",
"rov_compendium_aswid_benedictus_et_afflictus": "[Базовое пассивное] Benedictus et Afflictus:",
"rov_compendium_aswid_claws_beast_s_grows_blackened": "[Базовое пассивное] Когти зверя ([K], $1 с): На ограниченное время отращивает черные когти вместо оружия. Удары кулаками наносят $2% от урона зрелых когтей (полностью рубящий урон), и их сила растет с каждым поверженным боссом. Если достать меч — когти спрячутся, убрать его — вернутся, пока не истечет таймер. Не занимают ячейку экипировки. Их нельзя выбросить, передать или украсть, пока они активны. В облике летучей мыши или тумана когти недоступны, так как у вас нет рук.\n",