RacesOfValheim/JotunnModStub/RaceClaws.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

903 lines
43 KiB
C#

using System.Collections.Generic;
using HarmonyLib;
using Jotunn.Entities;
using Jotunn.Managers;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// Claws that are part of the body, for the races that grow a pair - as an ACTIVE SKILL. A
/// keypress (RaceClawsConfig.ActivateKey) grows them for RaceClawsConfig.DurationSeconds, and
/// they retract - unequipped and removed from the inventory outright - the moment that timer
/// runs out. Recasting mid-window simply restarts the timer.
///
/// This is SvermClawSlot generalised, not reinvented: the Sverm's Chitin Claws worked out
/// the whole shape of the problem, and the Aswid and the Fenrir are asking for the same object
/// with a different face. So the machinery moved here and each race supplies only what is
/// genuinely its own - the item name, the model to wear, and whether it is currently a wolf.
/// The Sverm still runs its own copy, untouched (permanent, not timed), because it also carries
/// a carapace, a stinger form and a fire term at Fader that none of this knows about.
///
/// WHY A REAL ITEM AND NOT A COSMETIC. Bolting a model to the hand bones works right up until
/// the game rebuilds equipment visuals - which it does on every equip - and wipes it. A real
/// item in a real slot has nothing to put back. The trade is that a real weapon occupies the
/// right hand, so three rules keep that reading as intended rather than as a bug: sheathe
/// anything else and the claws come back (while the skill is still running), the holster key
/// cannot put them away, and they cannot be dragged, moved or dropped. None of that costs an
/// inventory slot outside the two-minute window any more, which was the whole reason to move
/// off the earlier "issued once, forever" version: a slot permanently occupied by an
/// unremovable item was a standing annoyance, not a feature.
///
/// BALANCE IS SHARED ON PURPOSE. The damage is not read from the model each race wears - the
/// Fenrir's flesh rippers and the Bjorn claw are not worth the same, and a race should not be
/// stronger because its claws are prettier. Every set reads the Sverm's own reference weapon at
/// quality 4 and the Sverm's own per-tier percentages, so all three races hit for identical
/// numbers at identical tiers. What differs here is the shape of the damage: these two land it
/// entirely as slash, where the Sverm splits it three ways and lights it on fire at Fader. The
/// damage bonus itself only applies while the claws are the thing actually equipped - see
/// ApplyToUnarmedHit - so a bare-fisted punch after they retract is a bare-fisted punch.
/// </summary>
public abstract class RaceClawSet
{
// ─── What a race has to say about its own claws ──────────────────────
/// <summary>The race string in the ZDO, e.g. "Aswid".</summary>
public abstract string RaceId { get; }
/// <summary>Prefab id of the cloned item. Never seen by a player.</summary>
public abstract string ItemName { get; }
/// <summary>What the item is called in the inventory.</summary>
public abstract string DisplayName { get; }
public abstract string Description { get; }
/// <summary>
/// Models to clone, in order of preference. A list rather than a name because the install's
/// manifest carries several near-identical claw ids and only some of them resolve - see
/// SvermConfig.ClawPrefabFallbacks, which is where that lesson was learned. The winner is
/// logged; a miss is a warning rather than two empty hands and silence.
/// </summary>
public abstract string[] ModelPrefabs { get; }
/// <summary>ZDO key carrying this race's progression state, or null if it publishes none.</summary>
public virtual string StateZdoKey => null;
/// <summary>Multiplied into the model's own colours. Null leaves the model as authored.</summary>
public virtual Color? Tint => null;
/// <summary>
/// True while the player is wearing another body entirely - a bat, mist, a wolf. Claws are
/// neither issued nor counted while that is the case: the form does its own damage and has
/// its own hands, and a weapon equipped underneath it is at best invisible and at worst the
/// thing the game decides to swing.
/// </summary>
public abstract bool IsTransformed(Player player);
// ─── Registry ────────────────────────────────────────────────────────
private static readonly List<RaceClawSet> sets = new List<RaceClawSet>();
private static bool rosterBuilt;
/// <summary>
/// The roster. Kept here rather than in RacesOfValheim.Awake so the whole feature is this
/// file plus one short file per race, and adding a third clawed race is one line - not one
/// line here and another one three hundred lines away in the plugin's startup.
///
/// BUILT LAZILY, AND NOT FROM A STATIC CONSTRUCTOR. That is the fix for a bug that cost the
/// Fenrir this entire feature while the Aswid worked perfectly, which is exactly what made
/// it hard to see: the item registered, the model resolved, the patch ran, and the race
/// resolved to "Fenrir" - the set simply was not in this list.
///
/// The trap is .NET type initialisation re-entrancy. FenrirRace.CreateModAssets touches
/// FenrirClaws.Instance first (before AswidRace does its own), which starts FenrirClaws's
/// type initialiser; constructing that instance triggers this base type's static
/// constructor, which reaches back for FenrirClaws.Instance - still null, because its field
/// initialiser is halfway through running further down the same stack. The CLR does not
/// wait and does not re-run it: it hands back null. Register(null) then returned quietly and
/// the Fenrir was absent from the roster forever, while the Aswid - reached from inside the
/// static constructor rather than from outside it - was added normally.
///
/// Called from For/SetOwning, which only ever run from Player.Update and the inventory GUI,
/// long after every type initialiser has finished. Register also complains about a null now
/// rather than swallowing it, so this class of failure is loud the next time.
/// </summary>
private static void EnsureRoster()
{
if (rosterBuilt) return;
rosterBuilt = true; // set first: a re-entrant call must not build the list twice
Register(AswidClaws.Instance);
Register(FenrirClaws.Instance);
List<string> names = new List<string>();
foreach (RaceClawSet set in sets) names.Add(set.RaceId);
Jotunn.Logger.LogInfo($"[RaceClaws] Roster: {(names.Count > 0 ? string.Join(", ", names.ToArray()) : "EMPTY")}.");
}
public static void Register(RaceClawSet set)
{
if (set == null)
{
Jotunn.Logger.LogWarning("[RaceClaws] Refused to register a null claw set - that race will have no claws.");
return;
}
if (sets.Contains(set)) return;
sets.Add(set);
}
/// <summary>The set that belongs to this player's race, or null for everyone else.</summary>
public static RaceClawSet For(Player player)
{
if (player == null) return null;
EnsureRoster();
string race = GetRace(player);
foreach (RaceClawSet set in sets)
{
if (set.RaceId == race) return set;
}
return null;
}
/// <summary>True if the item is any registered race's claws.</summary>
public static RaceClawSet SetOwning(ItemDrop.ItemData item)
{
if (item == null || item.m_shared == null) return null;
EnsureRoster();
foreach (RaceClawSet set in sets)
{
if (set.IsClaws(item)) return set;
}
return null;
}
/// <summary>
/// Reads the race off the ZDO, falling back to m_customData - the same order every visual
/// in this mod reads it in, so a remote player and the menu preview both answer correctly.
///
/// "Human" in the ZDO is treated as no answer rather than as an answer, and that is not
/// cosmetic: ResetRace writes exactly that string into the ZDO before reopening the
/// selection menu, so a client whose ZDO write lost the race afterwards would otherwise be
/// stuck reading "Human" forever with a perfectly correct "Fenrir" sitting in m_customData
/// right next to it. Falling through to m_customData costs one dictionary lookup and closes
/// that hole.
/// </summary>
private static string GetRace(Player player)
{
ZNetView nview = player.GetComponent<ZNetView>();
if (nview != null && nview.IsValid())
{
string race = nview.GetZDO().GetString("RacesOfValheim_Race", "");
if (!string.IsNullOrEmpty(race) && race != "Human") return race;
}
if (player.m_customData != null && player.m_customData.TryGetValue("Race", out string custom))
{
return custom;
}
return "Human";
}
/// <summary>
/// Both raw values the race is read from, for the diagnostic line. Kept next to GetRace so
/// the two cannot drift apart.
/// </summary>
internal static string DescribeRaceSources(Player player)
{
if (player == null) return "player is null";
ZNetView nview = player.GetComponent<ZNetView>();
string zdo = nview == null ? "no ZNetView"
: !nview.IsValid() ? "ZDO not valid"
: $"'{nview.GetZDO().GetString("RacesOfValheim_Race", "")}'";
string custom = player.m_customData == null ? "no customData"
: player.m_customData.TryGetValue("Race", out string c) ? $"'{c}'"
: "absent";
return $"ZDO={zdo}, customData={custom}, resolved='{GetRace(player)}'";
}
// ─── Registration of the item ────────────────────────────────────────
private bool registered;
private bool warnedModel;
private bool loggedMaterials;
private readonly List<Material> ownedMaterials = new List<Material>();
/// <summary>
/// Clones whichever of the candidate models this build actually has. Deferred until ObjectDB
/// is up, so it is driven from the maintain tick rather than from Awake.
/// </summary>
public void EnsureRegistered()
{
if (registered) return;
if (ObjectDB.instance != null && ObjectDB.instance.GetItemPrefab(ItemName) != null)
{
registered = true;
return;
}
GameObject source = ResolveModel();
if (source == null) return; // already warned once by the resolver
GameObject clone = PrefabManager.Instance.CreateClonedPrefab(ItemName, source);
if (clone == null)
{
Jotunn.Logger.LogWarning($"[{RaceId}] 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 = DisplayName;
shared.m_description = Description;
// 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 race 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.
}
TakeOwnershipOfMaterials(clone);
ItemManager.Instance.AddItem(new Jotunn.Entities.CustomItem(clone, fixReference: false));
registered = true;
Jotunn.Logger.LogInfo($"[{RaceId}] Registered '{ItemName}' from '{source.name}'.");
RegisterActiveStatusEffect(drop);
RefreshTint();
}
/// <summary>
/// The buff the player sees while the claws are out: the claw item's OWN icon, with the
/// countdown the game draws under any effect carrying a m_ttl. No custom HUD, no second
/// timer to keep in sync with this one - vanilla already draws exactly this.
///
/// Registered from here, which is to say from CreateModAssets, and that timing is the whole
/// point rather than a detail: an earlier version created this effect lazily on the first
/// activation and it never appeared, because Jotunn only takes new entries into ObjectDB at
/// OnVanillaPrefabsAvailable. SEMan.AddStatusEffect then looked the name up, found nothing,
/// and did nothing - silently, exactly the way the claws themselves failed the first time
/// round (see the WarnOnce in MaintainInner).
///
/// The icon is read off the cloned item rather than named here, so each race shows its own
/// claws and nobody has to remember to update a second list when a model changes.
/// </summary>
private void RegisterActiveStatusEffect(ItemDrop drop)
{
Sprite icon = drop != null && drop.m_itemData != null && drop.m_itemData.m_shared != null &&
drop.m_itemData.m_shared.m_icons != null && drop.m_itemData.m_shared.m_icons.Length > 0
? drop.m_itemData.m_shared.m_icons[0]
: null;
if (icon == null)
{
// Worth saying out loud: the effect still works and still counts down, but a buff
// with no icon is nearly invisible in the HUD, which would read as "the timer is
// broken" rather than "the sprite was missing".
Jotunn.Logger.LogWarning($"[{RaceId}] '{ItemName}' carries no icon, so the claws' buff will show without one.");
}
StatusEffect se = ScriptableObject.CreateInstance<StatusEffect>();
se.name = ActiveSeName;
se.m_name = DisplayName;
se.m_tooltip = "Your claws are out. They retract when this runs out.";
se.m_icon = icon;
ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(se, fixReference: false));
Jotunn.Logger.LogInfo($"[{RaceId}] Registered the claws' buff '{ActiveSeName}'.");
}
private GameObject ResolveModel()
{
foreach (string name in ModelPrefabs)
{
// PrefabManager's cache first, ObjectDB second: the cache answers earlier in the
// load, and ObjectDB is still empty when the plugin wakes.
GameObject candidate = PrefabManager.Cache.GetPrefab<GameObject>(name);
if (candidate == null && ObjectDB.instance != null)
{
candidate = ObjectDB.instance.GetItemPrefab(name);
}
if (candidate != null)
{
Jotunn.Logger.LogInfo($"[{RaceId}] Claw model resolved to '{name}'.");
return candidate;
}
}
// Warned once, but NOT latched: a later call may run when more of the game is loaded,
// and a race with no hands is worth retrying for.
if (!warnedModel)
{
warnedModel = true;
Jotunn.Logger.LogWarning($"[{RaceId}] None of " + string.Join(", ", ModelPrefabs) +
" resolved yet; retrying as the game loads.");
}
return null;
}
/// <summary>
/// Gives the clone its own copies of every material it draws with.
///
/// A cloned prefab still points at the ORIGINAL material assets, so tinting them straight
/// would repaint the vanilla weapon in every hand in the world - a thing that would show up
/// as "why are the flesh rippers black now" and take an hour to trace back here. Copies
/// also make the tint live: an instantiated item shares these same material objects, so
/// writing a colour on them reaches the pair already in the player's hands.
/// </summary>
private void TakeOwnershipOfMaterials(GameObject clone)
{
ownedMaterials.Clear();
foreach (Renderer renderer in clone.GetComponentsInChildren<Renderer>(true))
{
Material[] materials = renderer.sharedMaterials;
if (materials == null) continue;
for (int i = 0; i < materials.Length; i++)
{
if (materials[i] == null) continue;
Material copy = new Material(materials[i]);
copy.name = materials[i].name + "_" + ItemName;
materials[i] = copy;
ownedMaterials.Add(copy);
}
renderer.sharedMaterials = materials;
}
}
/// <summary>
/// Repaints the claws. Called on the maintain tick as well as at registration, so a tint
/// driven by config moves while the game is running.
///
/// Every colour property the shader turns out to have is written rather than guessing which
/// one it uses: writing a property a shader does not have is an error, writing all the ones
/// it does is free.
/// </summary>
public void RefreshTint()
{
if (Tint == null || ownedMaterials.Count == 0) return;
Color tint = Tint.Value;
foreach (Material material in ownedMaterials)
{
if (material == null) continue;
if (material.HasProperty("_Color")) material.SetColor("_Color", tint);
if (material.HasProperty("_BaseColor")) material.SetColor("_BaseColor", tint);
if (material.HasProperty("_MainColor")) material.SetColor("_MainColor", tint);
// A claw is not a lamp. Whatever the source model glowed with goes out, or the
// tint fights a bloom it cannot win against.
if (material.HasProperty("_EmissionColor")) material.SetColor("_EmissionColor", Color.black);
}
if (loggedMaterials) return;
loggedMaterials = true;
foreach (Material material in ownedMaterials)
{
if (material == null) continue;
List<string> properties = new List<string>();
foreach (string name in new[] { "_Color", "_BaseColor", "_MainColor", "_EmissionColor" })
{
if (material.HasProperty(name)) properties.Add(name);
}
Jotunn.Logger.LogInfo(
$"[{RaceId}] Claw material '{material.name}' shader " +
$"'{(material.shader != null ? material.shader.name : "none")}' " +
$"colour properties: {(properties.Count > 0 ? string.Join(", ", properties.ToArray()) : "none")}");
}
}
// ─── Active skill: grow, then retract ─────────────────────────────────
/// <summary>
/// Time.time at which the skill's current window ends. Starts in the past, so a set that
/// has never been activated - including a save carried over from before this was a timed
/// skill - reads as inactive and MaintainInner strips whatever leftover item it finds.
/// </summary>
private float activeUntil = -1f;
/// <summary>True while the two-minute window is still running.</summary>
public bool IsActive => Time.time < activeUntil;
/// <summary>Seconds left on the window, floored at zero. What the HUD timer counts down.</summary>
public float SecondsRemaining => Mathf.Max(0f, activeUntil - Time.time);
/// <summary>
/// Published on the local player's own ZDO every Maintain tick, one flag shared by both
/// races (whichever set is running is the only one that could ever be true for a given
/// player, since a player is only ever one race). Read back for a REMOTE attacker in
/// ApplyToUnarmedHit - IsActive itself is this client's own timer and answers nothing about
/// somebody else's, the same problem GetState solves for progression tier.
/// </summary>
private const string ClawsActiveZdoKey = "RacesOfValheim_ClawsActive";
/// <summary>
/// Grows the claws for RaceClawsConfig.DurationSeconds. Safe to call again mid-window - it
/// just restarts the timer rather than stacking or refusing.
/// </summary>
public void Activate(Player player)
{
if (player == null || player != Player.m_localPlayer) return;
// Logged rather than silent: this is the one path a keypress can go nowhere from, and
// "nothing happened" with no line in the log is exactly the failure mode that cost the
// registration timing bug an evening (see the comment in MaintainInner).
if (For(player) != this)
{
Jotunn.Logger.LogInfo(
$"[{RaceId}] Grow-claws key ignored: this player's race is not {RaceId} " +
$"({DescribeRaceSources(player)}).");
return;
}
if (player.IsDead())
{
Jotunn.Logger.LogInfo($"[{RaceId}] Grow-claws key ignored: player is dead.");
return;
}
if (IsTransformed(player))
{
Jotunn.Logger.LogInfo($"[{RaceId}] Grow-claws key ignored: player is currently transformed.");
return;
}
activeUntil = Time.time + RaceClawsConfig.DurationSeconds.Value;
ApplyActiveIcon(RaceClawsConfig.DurationSeconds.Value);
Jotunn.Logger.LogInfo($"[{RaceId}] Grow-claws key pressed: growing the {DisplayName} for {RaceClawsConfig.DurationSeconds.Value}s.");
// Issues and equips immediately rather than waiting for the next throttled Maintain
// tick, so the keypress reads as instant rather than landing up to half a second late.
Maintain(player);
PlayGrowAnimation(player);
}
/// <summary>
/// The draw gesture, so the claws arrive with a movement rather than simply being in hand
/// on the next frame.
///
/// "equip_hip" is not a guess and not a borrowed approximation: it is the trigger vanilla's
/// own Humanoid.ShowHandItems fires when it takes a sheathed weapon back out, read out of
/// assembly_valheim rather than assumed. That makes it exactly the right motion here - the
/// claws are being drawn - and it carries no baked Animation Event, unlike the "gpower"
/// gesture the transformations borrow, which needed a suppressor to stop it casting the
/// player's real Guardian Power (see RaceInput.SuppressGuardianPowerBriefly).
/// </summary>
private static void PlayGrowAnimation(Player player)
{
ZSyncAnimation zanim = player.GetComponent<ZSyncAnimation>();
if (zanim != null) zanim.SetTrigger("equip_hip");
}
// ─── The buff the player sees ────────────────────────────────────────
/// <summary>
/// One effect per race rather than one shared between them, so each shows its own claws in
/// the buff bar. Derived from the item name, so a new clawed race needs nothing here.
/// </summary>
private string ActiveSeName => "SE_" + ItemName + "Active";
/// <summary>
/// Puts the buff up (or restarts it, if the skill was recast mid-window) and gives it the
/// remaining time. The countdown under the icon is the game's own - see
/// RegisterActiveStatusEffect.
/// </summary>
private void ApplyActiveIcon(float seconds)
{
if (Player.m_localPlayer == null || seconds <= 0f) return;
int hash = ActiveSeName.GetStableHashCode();
SEMan seman = Player.m_localPlayer.GetSEMan();
seman.RemoveStatusEffect(hash, true);
seman.AddStatusEffect(hash, true);
StatusEffect se = seman.GetStatusEffect(hash);
if (se != null) se.m_ttl = seconds;
}
/// <summary>
/// Takes the buff down. The effect's own m_ttl already expires on its own when the window
/// runs out normally; this is for the retractions that happen off the clock - a race change,
/// or a form taken while the claws were still out.
/// </summary>
private void ClearActiveIcon(Player player)
{
if (player == null) return;
player.GetSEMan().RemoveStatusEffect(ActiveSeName.GetStableHashCode(), true);
}
// ─── Issue and re-equip ──────────────────────────────────────────────
/// <summary>
/// Guards against re-entry, and it is not belt-and-braces - it is the fix for a crash the
/// Sverm hit first. Maintain equips the claws; Humanoid.EquipItem unequips the right hand
/// first, which fires the UnequipItem postfix, which calls Maintain... Mono answers an
/// unbounded recursion by killing the process outright, with no exception and a log file
/// that ends mid-word.
/// </summary>
private static bool maintaining;
/// <summary>
/// While the skill is active: makes sure the player owns exactly one pair and is holding
/// them whenever both hands are free. Once the window closes: takes that pair back off the
/// player entirely. Safe to call on a timer either way - every step checks first.
/// </summary>
public void Maintain(Player player)
{
if (maintaining) return;
if (player == null || player != Player.m_localPlayer) return;
if (For(player) != this) return;
if (player.IsDead() || IsTransformed(player)) return;
maintaining = true;
try { MaintainInner(player); }
finally { maintaining = false; }
}
private void MaintainInner(Player player)
{
EnsureRegistered();
RefreshTint();
ZNetView nview = player.GetComponent<ZNetView>();
if (nview != null && nview.IsValid()) nview.GetZDO().Set(ClawsActiveZdoKey, IsActive);
Inventory inventory = player.GetInventory();
if (inventory == null) return;
ItemDrop.ItemData claws = Find(inventory);
// The window has closed (or never opened this session). Retract: unequip if still in
// hand, then remove the item outright - no slot sits occupied between activations,
// which is the entire point of moving this off the old "issued once, forever" design.
if (!IsActive)
{
if (claws != null)
{
if (player.IsItemEquiped(claws)) player.UnequipItem(claws, false);
inventory.RemoveItem(claws);
ClearActiveIcon(player);
Jotunn.Logger.LogInfo($"[{RaceId}] The {DisplayName} retracted.");
}
return;
}
if (claws == null)
{
GameObject prefab = ObjectDB.instance != null ? ObjectDB.instance.GetItemPrefab(ItemName) : null;
if (prefab == null)
{
// The failure that cost the first version of this feature an evening. The item
// registers, logs its success, tints its materials - and is not in ObjectDB,
// because Jotunn only takes new items at OnVanillaPrefabsAvailable and this ran
// afterwards. It looked from the log exactly like everything had worked.
WarnOnce("missing-from-objectdb",
$"'{ItemName}' is registered but not in ObjectDB, so it cannot be issued. " +
"It has to be registered from CreateModAssets (PrefabManager.OnVanillaPrefabsAvailable), not later.");
return;
}
// The GameObject overload, deliberately: it is the one that is public in the
// shipped assembly, and this project compiles against that rather than against the
// publicized copy - so anything else would build here and not on a clean machine.
if (!inventory.AddItem(prefab, 1))
{
WarnOnce("inventory-full", $"No room in the inventory for the {DisplayName}; retrying.");
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: 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($"[{RaceId}] Issued the {DisplayName}.");
}
// 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.EquipItem(claws, false);
}
}
private readonly HashSet<string> warned = new HashSet<string>();
/// <summary>
/// Says a thing once. The maintain tick runs twice a second, so a plain warning here is a
/// log file rather than a message - which is the other half of why this failure was silent.
/// </summary>
private void WarnOnce(string key, string message)
{
if (!warned.Add(key)) return;
Jotunn.Logger.LogWarning($"[{RaceId}] {message}");
}
/// <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 answers the same question with nothing but public members.
/// </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 ItemDrop.ItemData Find(Inventory inventory)
{
if (inventory == null) return null;
foreach (ItemDrop.ItemData item in inventory.GetAllItems())
{
if (IsClaws(item)) return item;
}
return null;
}
public 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 == DisplayName;
}
// ─── Damage ──────────────────────────────────────────────────────────
/// <summary>
/// The tier this player is fighting at. Remote players answer from their own ZDO where the
/// race publishes one; where it does not, this falls back to the local player's progression
/// - the same compromise SvermVisuals.GetRenderState makes, and it only ever matters for
/// somebody else's claws on a shared world.
/// </summary>
private int GetState(Player player)
{
if (player != null && player != Player.m_localPlayer && !string.IsNullOrEmpty(StateZdoKey))
{
ZNetView nview = player.GetComponent<ZNetView>();
if (nview != null && nview.IsValid())
{
int remote = nview.GetZDO().GetInt(StateZdoKey, 0);
if (remote > 0)
{
return Mathf.Clamp(remote, BossProgressionManager.MinState, BossProgressionManager.MaxState);
}
}
}
return BossProgressionManager.GetCurrentProgressionState();
}
/// <summary>
/// Rewrites a bare-handed blow into a claw blow, as slash and nothing else - but only while
/// the claws are actually the thing in hand, which since this became a timed skill is no
/// longer every unarmed hit by default.
///
/// The figure is the Sverm's - its reference weapon at quality 4, times its percentage for
/// this tier - but where the Sverm keeps the weapon's own three-way split, this collapses
/// the whole physical total into slash. Claws cut. The total is preserved rather than the
/// slash component copied, so the three races stay worth the same and only the damage type
/// differs, which is the entire point of the exercise.
/// </summary>
public void ApplyToUnarmedHit(HitData hit, Player attacker)
{
if (hit == null || attacker == null) return;
if (IsTransformed(attacker)) return; // the form is doing its own damage
// Outside the skill's window this is just a bare fist - vanilla's own unarmed damage,
// not the claw tier. IsActive answers for the local player; a remote Aswid/Fenrir's
// punch reads the same flag published on their own ZDO, the same fallback GetState
// uses for progression tier - inventories are not something a remote client can read.
bool active;
if (attacker == Player.m_localPlayer)
{
active = IsActive;
}
else
{
ZNetView nview = attacker.GetComponent<ZNetView>();
active = nview != null && nview.IsValid() && nview.GetZDO().GetBool(ClawsActiveZdoKey, false);
}
if (!active) return;
HitData.DamageTypes reference = SvermClaws.GetReferenceDamage();
float percent = SvermClaws.GetDamagePercent(GetState(attacker));
if (percent <= 0f) return;
float total = (reference.m_slash + reference.m_pierce + reference.m_blunt) * percent;
// Nothing to give: the reference item did not resolve. Leave vanilla's fist alone
// rather than zeroing the player's only attack.
if (total <= 0f) return;
hit.m_damage.m_slash = total;
hit.m_damage.m_pierce = 0f;
hit.m_damage.m_blunt = 0f;
}
}
// ─── Patches ─────────────────────────────────────────────────────────────
/// <summary>
/// Reads the activation key every frame (a keypress lasts one frame, so this cannot be
/// throttled), then issues/retracts the claws and puts them back in hand on a throttle - that
/// half is a handful of checks that all short-circuit once state matches the target.
/// </summary>
[HarmonyPatch(typeof(Player), "Update")]
public static class RaceClaws_PlayerUpdate_Patch
{
private const float Interval = 0.5f;
private static float next;
public static void Postfix(Player __instance)
{
if (__instance != Player.m_localPlayer) return;
RaceClawSet set = RaceClawSet.For(__instance);
if (set == null) return;
if (RaceClawsConfig.ActivateKey.Value.IsDown())
{
if (RaceInput.Allowed)
{
set.Activate(__instance);
}
else
{
Jotunn.Logger.LogInfo($"[{set.RaceId}] Grow-claws key pressed but ignored: RaceInput.Allowed is false (a menu/GUI has focus).");
}
}
if (Time.time < next) return;
next = Time.time + Interval;
set.Maintain(__instance);
}
}
/// <summary>
/// Put anything else away and the claws come straight back. A postfix rather than a prefix: the
/// game is mid-way through tearing down the old item's visuals when a prefix would run, and
/// equipping there leaves the new item without a model.
/// </summary>
[HarmonyPatch(typeof(Humanoid), nameof(Humanoid.UnequipItem))]
public static class RaceClaws_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",
// and the recursion that follows kills the process silently.
if (item == null) return;
Player player = __instance as Player;
if (player == null || player != Player.m_localPlayer) return;
RaceClawSet set = RaceClawSet.For(player);
if (set == null) return;
if (set.IsClaws(item)) return; // do not re-equip what was just taken off
set.Maintain(player);
}
}
/// <summary>
/// The holster key cannot put the claws away. Refused only while the claws ARE the thing in
/// hand: holding a sword, R sheathes the sword normally and the unequip postfix hands the claws
/// back on the same action. So the key keeps working and simply never leaves the race
/// empty-handed.
/// </summary>
[HarmonyPatch(typeof(Humanoid), nameof(Humanoid.HideHandItems))]
public static class RaceClaws_HideHandItems_Patch
{
public static bool Prefix(Humanoid __instance)
{
Player player = __instance as Player;
if (player == null || player != Player.m_localPlayer) return true;
RaceClawSet set = RaceClawSet.For(player);
if (set == null) return true;
ItemDrop.ItemData held = Traverse.Create(__instance).Field<ItemDrop.ItemData>("m_rightItem").Value;
return !set.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 - so refusing here closes all of them with one prefix.
///
/// Only refused while the item is CURRENTLY that race's claws - checked against SetOwning
/// (whose set the item is) against RaceClawSet.For (what race the player is right now), not
/// merely "is this any race's claws at all". A player who has since switched race carries a
/// pair that RaceItemCleanup should have already removed, but if it has not run yet for any
/// reason, this is the difference between an item merely undraggable and one undraggable
/// forever: without the race check, nothing the player does - not death, not a tombstone, not
/// closing the item's own quest-item flag - would ever let them shed it again.
/// </summary>
[HarmonyPatch(typeof(InventoryGui), "SetupDragItem")]
public static class RaceClaws_SetupDragItem_Patch
{
public static bool Prefix(ItemDrop.ItemData item)
{
RaceClawSet owner = RaceClawSet.SetOwning(item);
if (owner == null) return true;
if (Player.m_localPlayer == null || owner != RaceClawSet.For(Player.m_localPlayer)) return true;
Player.m_localPlayer.Message(MessageHud.MessageType.Center, "They are part of your hands.");
return false;
}
}
/// <summary>
/// The tier's damage, on any bare-handed blow - RaceClawSet.ApplyToUnarmedHit itself checks
/// whether the claws are actually equipped, so a genuinely empty hand (skill not running, or
/// still mid-retract) falls through to vanilla's own unarmed damage instead.
/// </summary>
[HarmonyPatch(typeof(Character), nameof(Character.Damage))]
public static class RaceClaws_Damage_Patch
{
public static void Prefix(HitData hit)
{
if (hit == null || hit.m_skill != Skills.SkillType.Unarmed) return;
Player attacker = hit.GetAttacker() as Player;
if (attacker == null) return;
RaceClawSet set = RaceClawSet.For(attacker);
if (set == null) return;
set.ApplyToUnarmedHit(hit, attacker);
}
}
}