RacesOfValheim/JotunnModStub/RaceInput.cs
kanym ba7f56550d fix(forms): no form attacks in build mode; chair pose 1 m out, turned
RaceInput.AttackDown and AttackHeld now return false while the player
is in place mode (hammer, hoe, cultivator). Right click removes a piece
there and middle click picks a snap point, and every form read both as
its own attacks. Allowed only covered the piece selection panel. Every
form reads the mouse through RaceInput, so all of them are covered.

On a chair the form now settles 1 m in front of the seat and turns a
quarter counter-clockwise, at the player's request after the first try.
2026-10-17 19:34:51 +02:00

267 lines
13 KiB
C#

using System.Reflection;
using BepInEx.Configuration;
using HarmonyLib;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// Gate for race ability input.
///
/// UnityEngine.Input reads the device directly, so abilities bound to keys or mouse buttons
/// kept firing while the map, the inventory, a chest, the chat or a menu had focus - dragging
/// an item inside a container also swung the transformed attack, for instance. Valheim runs
/// its own controls through Player.TakeInput, which reports false for exactly those states
/// (InventoryGui covers the backpack and chests alike), so mirror that instead of maintaining
/// a parallel list of GUI checks that would drift as the game changes.
///
/// TWO GUIS THAT TakeInput DOES NOT COVER. The first is the hammer's piece selection panel. Read off the IL,
/// TakeInput tests Chat, Console, TextInput, StoreGui, InventoryGui, Menu, TextViewer, the map,
/// free-fly and the barber - and nothing else. Vanilla does not need it there because build
/// input is handled separately in UpdatePlacement, but a mod ability reading the device
/// directly does: Skadi's cold spell is bound to middle mouse and kept casting while the build
/// menu was open. Hud.IsPieceSelectionVisible is static, public and null-safe on its own
/// instance, so it costs one call and no reflection.
///
/// The second is the radial menu, and it is handled in AttackDown rather than here - see
/// RadialOpen for why the difference matters.
/// </summary>
public static class RaceInput
{
// Not public on Player, hence the reflection; resolved once rather than per frame.
private static readonly MethodInfo TakeInputMethod = AccessTools.Method(typeof(Player), "TakeInput");
/// <summary>
/// Hammer, hoe or cultivator in hand. Right click removes a piece there and middle click picks
/// a snap point, and a form read both as its own attacks: an Ulv building a wall bit the air
/// on every click. Allowed only covered the piece selection panel, not the build mode itself.
/// </summary>
private static bool InBuildMode => Player.m_localPlayer != null && Player.m_localPlayer.InPlaceMode();
public static bool Allowed
{
get
{
Player player = Player.m_localPlayer;
if (player == null) return false;
// Checked before TakeInput, so it holds even on the fail-open path below.
if (Hud.IsPieceSelectionVisible()) return false;
// Fail open: if a game update ever renames the method, abilities stay usable
// rather than silently going dead.
if (TakeInputMethod == null) return true;
return (bool)TakeInputMethod.Invoke(player, null);
}
}
// Aswid/Skadi/Fenrir all borrow the native "gpower" Animator trigger to get its
// arms-raised cast gesture for their own transformations. The "gpower" clip carries a
// baked-in Animation Event that calls Player.ActivateGuardianPower() partway through -
// that fires no matter who requested the animation, so borrowing the trigger silently
// cast the player's real Guardian Power (and put it on cooldown) whenever it happened
// to be available. Races set this right before SetTrigger("gpower") to swallow that one
// call. Time-based rather than a plain latch, so a skipped/interrupted animation can't
// leave the real power blocked forever.
public static float SuppressGuardianPowerUntil = -1f;
public static void SuppressGuardianPowerBriefly(float seconds = 2f)
{
SuppressGuardianPowerUntil = Time.time + seconds;
}
/// <summary>
/// What KeyboardShortcut.IsDown() should have been for a game key.
///
/// BepInEx's own IsDown() ends in a check that no key outside the shortcut is being held
/// (ModifierKeyTest -> _modifierBlockKeyCodes.All(c => !GetKey(c) || allKeys.Contains(c))),
/// which is right for a config-menu hotkey and completely wrong for a game ability: it
/// only exempts the mouse buttons, so holding W - or any other movement key - silently
/// killed every bound ability in the mod, in every race, including the ones bound to mouse
/// buttons. Vanilla attacks kept working because they go through ZInput instead, which is
/// what made it look like the abilities specifically had broken.
///
/// This keeps the part that matters (main key down, every modifier held) and drops the
/// blocking rule, so an ability fires while the player is moving.
/// </summary>
public static bool IsDownIgnoringHeldKeys(this KeyboardShortcut shortcut)
{
// The queued press is taken FIRST and without any gate, because that is the radial menu
// firing this very ability - see Press(). Everything below is the device being read raw.
if (ConsumePress(shortcut)) return true;
if (shortcut.MainKey == KeyCode.None) return false;
// A keybind that sits on a mouse button is the radial's own click as far as the device is
// concerned, so the wheel closes this door too. AttackDown covers the forms' attacks;
// this covers abilities bound to a button instead - Skadi's cold spell is on middle
// mouse, and middle-clicking an entry in the wheel used to cast it. Keys at the keyboard
// are left alone: nothing about the wheel makes pressing K ambiguous.
if (RadialOpen && IsMouseButton(shortcut.MainKey)) return false;
if (!Input.GetKeyDown(shortcut.MainKey)) return false;
foreach (KeyCode modifier in shortcut.Modifiers)
{
if (!Input.GetKey(modifier)) return false;
}
return true;
}
/// <summary>Held-down counterpart of <see cref="IsDownIgnoringHeldKeys"/>.</summary>
public static bool IsPressedIgnoringHeldKeys(this KeyboardShortcut shortcut)
{
if (shortcut.MainKey == KeyCode.None) return false;
if (!Input.GetKey(shortcut.MainKey)) return false;
foreach (KeyCode modifier in shortcut.Modifiers)
{
if (!Input.GetKey(modifier)) return false;
}
return true;
}
// A key press that came from somewhere other than the keyboard - the race group in the radial
// menu (RaceRadial). Held for a short window rather than one frame, because the radial closes
// with an animation and the race reading the key may not run on the very next frame; the
// first matching read takes it, so it fires once.
private const float PressWindow = 0.5f;
private static KeyboardShortcut pressed = KeyboardShortcut.Empty;
private static float pressedUntil = -1f;
public static void Press(KeyboardShortcut shortcut)
{
pressed = shortcut;
pressedUntil = Time.time + PressWindow;
}
/// <summary>True once if <paramref name="shortcut"/> was pressed through <see cref="Press"/>.
/// IsDownIgnoringHeldKeys already asks; the two readers still on BepInEx's own IsDown() ask
/// directly.</summary>
public static bool ConsumePress(KeyboardShortcut shortcut)
{
if (Time.time > pressedUntil) return false;
if (shortcut.MainKey == KeyCode.None || shortcut.MainKey != pressed.MainKey) return false;
if (!System.Linq.Enumerable.SequenceEqual(shortcut.Modifiers, pressed.Modifiers)) return false;
pressedUntil = -1f;
return true;
}
// Gamepad counterparts of the three mouse buttons, indexed like Input.GetMouseButton.
// Not a free choice: ZInput.ResetKBMButtons binds Attack to Mouse0, Block to Mouse1 and
// SecondaryAttack to Mouse2, so each form attack lands on the pad button vanilla already
// pairs with the same mouse button - and does whatever that button does in vanilla at the
// same time, exactly as the mouse already did. Going through ZInput rather than raw
// joystick buttons also follows the pad layout picked in the game settings.
private static readonly string[] PadAttackButtons = { "JoyAttack", "JoyBlock", "JoySecondaryAttack" };
/// <summary>
/// Transformed-form attack input: the mouse button, or its gamepad counterpart. Forms read
/// the device directly instead of going through Humanoid.StartAttack, so before this a
/// gamepad player had no way to attack in any of them.
/// </summary>
public static bool AttackDown(int mouseButton)
{
if (RadialOpen || InBuildMode) return false;
return Input.GetMouseButtonDown(mouseButton) || PadAttackDown(mouseButton);
}
/// <summary>Held-down counterpart of <see cref="AttackDown"/>.</summary>
public static bool AttackHeld(int mouseButton)
{
if (RadialOpen || InBuildMode) return false;
return Input.GetMouseButton(mouseButton) || PadAttackHeld(mouseButton);
}
/// <summary>
/// Whether the radial menu is up, which is a third GUI TakeInput knows nothing about.
///
/// Clicking an entry in the wheel was also swinging the transformed form's attack: the click
/// picks the entry AND is read here as a raw mouse button. Vanilla attacks are untouched by
/// this because they go through ZInput, which the radial already blocks - only input read
/// straight off the device gets through, which is all of ours.
///
/// CHECKED HERE AND NOT IN <see cref="Allowed"/>, deliberately. The radial fires an ability by
/// queueing its keybind through Press(), and the ability's own reader picks that up inside an
/// Allowed gate - so blocking Allowed while the wheel is open would risk the wheel swallowing
/// the very abilities it exists to trigger. The queued press does survive, since it holds for
/// PressWindow rather than a single frame, but there is no reason to lean on that when only
/// the mouse reads are the problem. Keybinds pressed at the keyboard while the wheel is open
/// are left alone for the same reason.
/// </summary>
private static bool IsMouseButton(KeyCode key)
{
return key >= KeyCode.Mouse0 && key <= KeyCode.Mouse6;
}
// Said once for each answer it ever gives, and then never again. The whole gate rests on what
// Hud.InRadial() means, and that was read off the method's name rather than its body - so it
// is worth one line of proof in every player's log that it reports False with no wheel on
// screen. If it ever logs only True, the gate is eating input it has no business eating.
private static bool loggedOpen;
private static bool loggedClosed;
private static bool RadialOpen
{
get
{
try
{
bool open = Hud.InRadial();
if (open && !loggedOpen)
{
loggedOpen = true;
Jotunn.Logger.LogInfo("[RaceInput] Radial menu open: form attacks and mouse-bound abilities are held.");
}
else if (!open && !loggedClosed)
{
loggedClosed = true;
Jotunn.Logger.LogInfo("[RaceInput] Radial menu closed: form attacks and mouse-bound abilities are live.");
}
return open;
}
catch
{
// Fail open, like the TakeInput path above: a game update that moves this must
// cost the fix, not every attack in every form.
return false;
}
}
}
/// <summary>The gamepad half of <see cref="AttackDown"/> alone, for attacks whose mouse
/// side is a rebindable KeyboardShortcut rather than a fixed button.</summary>
public static bool PadAttackDown(int mouseButton)
{
string button = PadButton(mouseButton);
return button != null && ZInput.GetButtonDown(button);
}
public static bool PadAttackHeld(int mouseButton)
{
string button = PadButton(mouseButton);
return button != null && ZInput.GetButton(button);
}
private static string PadButton(int mouseButton)
{
return mouseButton >= 0 && mouseButton < PadAttackButtons.Length ? PadAttackButtons[mouseButton] : null;
}
}
[HarmonyPatch(typeof(Player), "ActivateGuardianPower")]
public static class Player_ActivateGuardianPower_SuppressBorrowed_Patch
{
public static bool Prefix(Player __instance)
{
if (__instance != Player.m_localPlayer) return true;
if (Time.time > RaceInput.SuppressGuardianPowerUntil) return true;
RaceInput.SuppressGuardianPowerUntil = -1f; // one-shot: don't block real future casts
return false;
}
}
}