RacesOfValheim/JotunnModStub/Sverm/SvermClawSlot.cs
kanym c2212df322 Merge branch 'war-vulture' into main
Brings in v1.4.3-v1.4.5 work: Trol's Hammer, Bone Servants, War Vulture
craftability, and the Aswid/Fenrir timed-claws rework, on top of the
bugfixes merged into main since v1.4.2.

Resolved conflicts in 7 files where main's post-v1.4.2 fixes overlapped
war-vulture's claws rework:
- README.md, manifest.json: took war-vulture's v1.4.5 content (main
  hadn't touched either since the v1.4.2 release).
- RacesOfValheim.cs: plugin version -> 1.4.5.
- RaceClaws.cs: kept war-vulture's lazy EnsureRoster() fix for the
  Fenrir claw-registration bug over main's belt-and-suspenders
  Register(this), and dropped the now-stale comment referencing the
  removed static constructor. Main's SetupDragItem race-ownership fix
  carried through untouched.
- AswidConfig.cs/AswidRace.cs/AswidPatches.cs: adopted war-vulture's
  single-key design (I toggles both Vampiric Aura and Devour together)
  to match the documented v1.4.5 trader-safety fix, removing a duplicate
  AuraEnabled field the two branches had each declared independently.
  Kept main's IsDownIgnoringHeldKeys() input fix on top.
- RaceCompendium.cs: kept main's fact-checked Aswid/Fenrir entries
  (war-vulture's copies were pre-fix stubs, one referencing a
  nonexistent variable) and layered in war-vulture's timed-claws
  wording.

Build verified clean (0 errors) after resolution.
2026-08-18 17:36:42 +02:00

307 lines
15 KiB
C#

using System.Collections.Generic;
using HarmonyLib;
using Jotunn.Managers;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The Chitin Claws as a REAL equipped weapon, sitting in the inventory in plain sight and
/// refusing to be moved.
///
/// WHY THIS REPLACED THE COSMETIC VERSION. Bolting a model to the hand bones worked, but the
/// carapace beside it did not: the game rebuilds equipment visuals from what is ACTUALLY in
/// the slots, so every unequip wiped the lot and something had to put it back, one frame late
/// and visibly. A real item in a real slot removes the whole class of problem - there is
/// nothing to put back, because nothing was ever faked.
///
/// The trade, accepted deliberately: a real weapon occupies the right hand, so drawing a sword
/// puts the claws away. Three rules make that read as intended rather than as a bug:
///
/// 1. sheathe anything else and the claws come straight back (UnequipItem postfix);
/// 2. the holster key cannot put the claws away - a Sverm is never empty-handed
/// (HideHandItems prefix);
/// 3. the claws cannot be dragged, moved or dropped (SetupDragItem prefix, quest-item flag).
///
/// VISIBLE, NOT HIDDEN, and that is the second design this file has had. The first reserved
/// the rightmost column and switched its slots off in the inventory window - which meant
/// patching InventoryGrid.UpdateGui, a method that runs for every chest and every grid in the
/// game, to hide something in exactly one of them. It also cost the player four slots.
/// Showing the claws and refusing to let them move is less code, touches no UI, and tells the
/// player something true: they are carrying them, and they always will be.
///
/// The last resort behind all three rules is that Maintain re-issues the claws whenever they
/// are missing. However they get lost - a tombstone, a mod, a bug in this file - they are back
/// within half a second.
/// </summary>
public static class SvermClawSlot
{
/// <summary>
/// The prefab id, and it keeps the old spelling on purpose: it is what every save on disk
/// names the item by, and renaming it would leave a Sverm holding an item ObjectDB can no
/// longer resolve. The display name below is the only half a player ever reads.
/// </summary>
public const string ItemName = "SvermMaulclaws";
public const string ItemDisplayName = "Chitin Claws";
/// <summary>Row in the reserved column the claws sit on. The other three await the carapace.</summary>
private const int ClawRow = 0;
private static bool registered;
// ─── Registration ────────────────────────────────────────────────────
/// <summary>
/// Clones whichever of the four candidate prefabs this build actually has. Deferred until
/// ObjectDB is up, so it is driven from the first player spawn rather than from Awake.
/// </summary>
public static void EnsureRegistered()
{
if (registered) return;
if (ObjectDB.instance != null && ObjectDB.instance.GetItemPrefab(ItemName) != null)
{
registered = true;
return;
}
GameObject source = SvermClaws.GetPrefab();
if (source == null) return; // already logged once by the resolver
GameObject clone = PrefabManager.Instance.CreateClonedPrefab(ItemName, source);
if (clone == null)
{
Jotunn.Logger.LogWarning($"[Sverm] Could not clone '{source.name}'; the claws stay unregistered.");
return;
}
ItemDrop drop = clone.GetComponent<ItemDrop>();
if (drop != null && drop.m_itemData != null && drop.m_itemData.m_shared != null)
{
ItemDrop.ItemData.SharedData shared = drop.m_itemData.m_shared;
shared.m_name = ItemDisplayName;
shared.m_description = "Grown, not forged. They do not come off.";
// Quest item: Valheim refuses to drop, trade or stack these. It is the cheapest
// honest way to say "this is part of your body" without a patch per verb.
shared.m_questItem = true;
shared.m_teleportable = true;
shared.m_weight = 0f;
shared.m_maxQuality = 1;
// INDESTRUCTIBLE, and it has to be the flag rather than a big number. The claws are
// never crafted, so no workbench will ever repair them: left on normal durability
// they wear down to zero and Humanoid.EquipItem then refuses to put them back in
// hand, which strands the Sverm bare-fisted for good. m_useDurability = false is the
// single switch every path reads - the attack drain, the broken-item check, the
// inventory bar and the tooltip line all skip the item entirely.
shared.m_useDurability = false;
shared.m_canBeReparied = false;
// No recipe and no station: this item is never crafted, only issued.
}
ItemManager.Instance.AddItem(new Jotunn.Entities.CustomItem(clone, fixReference: false));
registered = true;
Jotunn.Logger.LogInfo($"[Sverm] Registered '{ItemName}' from '{source.name}'.");
}
// ─── Issue and re-equip ──────────────────────────────────────────────
/// <summary>
/// Makes sure the player owns exactly one pair and is holding them whenever both hands are
/// free. Safe to call on a timer: every step checks first.
/// </summary>
/// <summary>
/// Guards against re-entry, and it is not belt-and-braces - it is the fix for a crash.
///
/// Maintain equips the claws. Humanoid.EquipItem unequips the right hand first, which
/// fires the UnequipItem postfix, which calls Maintain, which equips the claws... Mono
/// answers an unbounded recursion by killing the process outright, with no exception and a
/// log file that ends mid-word. Switching race was enough to trigger it every time.
///
/// The null check in the postfix closes the specific door; this closes the corridor.
/// </summary>
private static bool maintaining;
public static void Maintain(Player player)
{
if (maintaining) return;
if (player == null || player != Player.m_localPlayer) return;
if (!SvermVisuals.IsSvermPlayer(player)) return;
maintaining = true;
try { MaintainInner(player); }
finally { maintaining = false; }
}
private static void MaintainInner(Player player)
{
EnsureRegistered();
Inventory inventory = player.GetInventory();
if (inventory == null) return;
ItemDrop.ItemData claws = Find(inventory);
if (claws == null)
{
GameObject prefab = ObjectDB.instance != null ? ObjectDB.instance.GetItemPrefab(ItemName) : null;
if (prefab == null) return;
// The GameObject overload, deliberately: it is the one that is public in the
// shipped assembly. The overloads that take a grid position are private there, and
// the project compiles against the shipped assembly rather than the publicized
// copy - so anything else would build on this machine and not on a clean one.
if (!inventory.AddItem(prefab, 1)) return;
claws = Find(inventory);
if (claws == null) return;
// Tidied into the bottom-right corner IF that corner is free, and left wherever
// the inventory put them otherwise. Nothing of the player's is ever displaced to
// make room: an item that cannot be moved has no business shoving one that can.
Vector2i corner = new Vector2i(inventory.GetWidth() - 1, inventory.GetHeight() - 1);
if (corner.x >= 0 && ItemAt(inventory, corner.x, corner.y) == null)
{
claws.m_gridPos = corner;
}
Jotunn.Logger.LogInfo("[Sverm] Issued the Chitin Claws.");
}
// A pair issued before the claws stopped wearing out is still carrying whatever it had
// ground down to. Nothing reads that number any more, but it is saved with the item, so
// it is put back to full once rather than left as a stale figure in the save file.
if (claws.m_durability < claws.GetMaxDurability()) claws.m_durability = claws.GetMaxDurability();
// Empty-handed means clawed. Anything else in the right hand wins until it is put
// away, which is the whole compromise.
ItemDrop.ItemData held = Traverse.Create((Humanoid)player).Field<ItemDrop.ItemData>("m_rightItem").Value;
if (held == null && !player.InAttack() && !player.IsDead())
{
player.EquipItem(claws, false);
}
}
/// <summary>
/// What is sitting at this grid position, read from the items themselves.
///
/// Inventory.GetItemAt is private in the shipped assembly, and every item already carries
/// its own m_gridPos, so a scan over GetAllItems answers the same question with nothing
/// but public members. An inventory holds a few dozen items; this is not a hot path.
/// </summary>
private static ItemDrop.ItemData ItemAt(Inventory inventory, int x, int y)
{
foreach (ItemDrop.ItemData item in inventory.GetAllItems())
{
if (item != null && item.m_gridPos.x == x && item.m_gridPos.y == y) return item;
}
return null;
}
public static ItemDrop.ItemData Find(Inventory inventory)
{
if (inventory == null) return null;
foreach (ItemDrop.ItemData item in inventory.GetAllItems())
{
if (item != null && item.m_dropPrefab != null && item.m_dropPrefab.name == ItemName) return item;
if (item != null && item.m_shared != null && item.m_shared.m_name == ItemDisplayName) return item;
}
return null;
}
public static bool IsClaws(ItemDrop.ItemData item)
{
if (item == null || item.m_shared == null) return false;
if (item.m_dropPrefab != null && item.m_dropPrefab.name == ItemName) return true;
return item.m_shared.m_name == ItemDisplayName;
}
}
// ─── Patches ─────────────────────────────────────────────────────────────
/// <summary>
/// Put anything else away and the claws come straight back.
///
/// A postfix rather than doing it inside UnequipItem's own flow: the game is mid-way through
/// tearing down the old item's visuals when the prefix would run, and equipping there leaves
/// the new item without a model.
/// </summary>
[HarmonyPatch(typeof(Humanoid), nameof(Humanoid.UnequipItem))]
public static class Sverm_UnequipItem_Patch
{
public static void Postfix(Humanoid __instance, ItemDrop.ItemData item)
{
// NULL IS THE IMPORTANT CASE. Humanoid.EquipItem calls UnequipItem(m_rightItem) before
// putting a weapon in the hand, and an empty hand means that argument is null. Without
// this line the postfix treats "nothing was unequipped" as "something was unequipped",
// calls Maintain, which equips the claws, which unequips null again - and Mono kills
// the process on the recursion, instantly and silently.
if (item == null) return;
Player player = __instance as Player;
if (player == null || player != Player.m_localPlayer) return;
if (!SvermVisuals.IsSvermPlayer(player)) return;
if (SvermClawSlot.IsClaws(item)) return; // do not re-equip what was just taken off
SvermClawSlot.Maintain(player);
}
}
/// <summary>
/// The holster key cannot put the claws away.
///
/// HideHandItems is what R calls. Refused only while the claws ARE the thing in hand: holding
/// a sword, R sheathes the sword normally, and the unequip postfix above hands the claws back
/// on the same action. So the key keeps working and simply never leaves a Sverm empty-handed.
/// </summary>
[HarmonyPatch(typeof(Humanoid), nameof(Humanoid.HideHandItems))]
public static class Sverm_HideHandItems_Patch
{
public static bool Prefix(Humanoid __instance)
{
Player player = __instance as Player;
if (player == null || player != Player.m_localPlayer) return true;
if (!SvermVisuals.IsSvermPlayer(player)) return true;
ItemDrop.ItemData held = Traverse.Create(__instance).Field<ItemDrop.ItemData>("m_rightItem").Value;
return !SvermClawSlot.IsClaws(held);
}
}
/// <summary>
/// The claws cannot be picked up with the mouse.
///
/// SetupDragItem is the single door every manual move goes through - within the inventory, out
/// to a chest, onto the ground, into a crafting slot. Refusing here closes all of them with
/// one prefix, instead of one patch per destination, and leaves every OTHER item's handling
/// completely untouched.
///
/// It replaces an earlier design that hid the rightmost column outright. That one had to patch
/// InventoryGrid.UpdateGui - a method that runs for every chest and every grid in the game -
/// in order to change exactly one of them, and it cost the player four slots. The claws are
/// visible now, which is also more honest: they are part of the character, and the character
/// can see them.
///
/// Only refused while the player IS CURRENTLY a Sverm. A player who has switched race carries
/// a pair that RaceItemCleanup should have already removed, but this check is what stops a
/// leftover pair from being undraggable forever if that cleanup has not run yet for any
/// reason - the quest-item flag already keeps them off the ground and out of a tombstone, so
/// a race check missing here was the one thing standing between "stuck until logout" and
/// "stuck permanently".
/// </summary>
[HarmonyPatch(typeof(InventoryGui), "SetupDragItem")]
public static class Sverm_SetupDragItem_Patch
{
public static bool Prefix(ItemDrop.ItemData item)
{
if (!SvermClawSlot.IsClaws(item)) return true;
if (Player.m_localPlayer == null || !SvermVisuals.IsSvermPlayer(Player.m_localPlayer)) return true;
Player.m_localPlayer.Message(MessageHud.MessageType.Center, "They are part of your hands.");
return false;
}
}
}