RacesOfValheim/JotunnModStub/Aswid/AswidSpectralClaw.cs
kanym b177c89c71 feat(text): item, piece and creature names come from translation files
The mod's own items, build pieces and summoned creatures now carry
$rov_item_, $rov_piece_ and $rov_creature_ tokens for their names and
descriptions, and items.json holds the texts in English and Italian.
Valheim localizes these fields wherever it shows them: tooltips, hover
texts, messages, the build menu.

Where a name doubles as an identifier, both sides use the same constant,
so the comparisons still hold. The Aswid foods keep their prefix as a
constant for the refinery's check and now name the creature with its
vanilla token, so "Boar" translates too. The Furling crops get one whole
description per crop instead of an English sentence with the metal dropped
in. The Race Menu Ward's panel title is a mod UI Text, so it reads the
translation directly.

Saves are unaffected: items and eaten foods are stored by prefab name.
The Sverm hive's goods stay for the merchant step.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-26 19:58:53 +02:00

300 lines
13 KiB
C#

using UnityEngine;
using Jotunn.Managers;
using Jotunn.Entities;
using HarmonyLib;
namespace RacesOfValheim
{
/// <summary>
/// A translucent, greenish spectral claw (the "Flesh Rippers" fist weapon model), permanently
/// present in inventory slot 1 and undroppable. The player equips/unequips it manually like
/// any other weapon - no automatic equip management. An earlier version tried to auto-equip
/// it whenever the player was unarmed and step aside when they picked a real weapon, but
/// EquipItem/GetCurrentWeapon disagreed with each other every tick when driven from code
/// outside the normal input flow, causing a permanent equip/unequip flicker no amount of
/// tweaking (durability, quest-item flag, reference tracking) fixed. Simpler and stable wins.
///
/// Damage scales with boss progression via a Harmony patch rather than by mutating the shared
/// item definition, so it stays correct per-player in multiplayer even if two Aswid are at
/// different tiers.
/// </summary>
public static class AswidSpectralClaw
{
public const string CloneName = "AswidSpectralClaw";
public const float BaseSlashDamage = 5f;
public const float SlashDamagePerBoss = 10f;
private const string SourceItemSharedName = "$item_fistweapon_fenris"; // "Flesh Rippers"
private const int Quality = 1;
private static bool registered = false;
private static bool resolveAttempted = false;
private static ItemDrop clonedItemDrop;
private static ItemDrop.ItemData activeClaw;
public static void EnsureInInventory(Player player)
{
if (player == null) return;
if (!registered)
{
if (resolveAttempted) return;
resolveAttempted = true;
if (!TryRegister())
{
Jotunn.Logger.LogWarning("[Aswid] Could not create the spectral claw item.");
return;
}
registered = true;
}
Inventory inv = player.GetInventory();
if (inv == null) return;
SanitizeInventory(inv);
// Checking by held reference (inv.ContainsItem(activeClaw)) kept going stale - the
// game apparently rebuilds the inventory's ItemData objects on its own from time to
// time (network sync, save snapshot, ...), which orphans whatever C# reference we
// cached without actually removing the item, so we kept "finding" it missing and
// minting another one. Searching by name every time is slower but can't go stale.
ItemDrop.ItemData existing = inv.GetItem(CloneName, Quality, true);
if (existing != null)
{
activeClaw = existing;
return;
}
activeClaw = clonedItemDrop.m_itemData.Clone();
activeClaw.m_stack = 1;
activeClaw.m_quality = Quality;
activeClaw.m_durability = 1000000f;
inv.AddItem(activeClaw);
PlaceInQuickSlotIfFree(inv, activeClaw);
}
// Can't hide it from the inventory outright (an off-grid position crashes InventoryGui),
// so at least keep it out of the way in hotbar slot 1 rather than wherever it happened
// to land - but only if that slot is actually free, never bumping something the player
// put there themselves.
private static void PlaceInQuickSlotIfFree(Inventory inv, ItemDrop.ItemData claw)
{
if (inv.GetItemAt(0, 0) == null)
{
claw.m_gridPos = new Vector2i(0, 0);
}
}
// A corrupted item (m_dropPrefab destroyed/null - left behind by an earlier build's
// registration timing, before the character's inventory finished loading) crashes both
// Inventory.GetItem and the inventory UI the moment either touches it, since they call
// .name on it without a null check. Purge any such entry straight from the backing list,
// which is safe because the Unity == null check (unlike .name) handles a destroyed
// native object correctly.
private static void SanitizeInventory(Inventory inv)
{
var rawList = HarmonyLib.Traverse.Create(inv)
.Field<System.Collections.Generic.List<ItemDrop.ItemData>>("m_inventory").Value;
if (rawList == null) return;
rawList.RemoveAll(item => item == null || item.m_dropPrefab == null);
}
public static void RemoveClaw(Player player)
{
if (player == null) return;
Inventory inv = player.GetInventory();
if (inv == null) return;
ItemDrop.ItemData claw = (activeClaw != null && inv.ContainsItem(activeClaw))
? activeClaw
: inv.GetItem(CloneName, Quality, true);
if (claw == null) return;
if (player.IsItemEquiped(claw)) player.UnequipItem(claw, false);
inv.RemoveItem(claw);
activeClaw = null;
}
// Feature disabled for now (kept minting a fresh copy every tick instead of finding the
// existing one - not fixed yet). Every duplicate it left behind is m_questItem, so the
// player can't drop them by hand; strip every copy straight out of the backing list
// (bypassing GetItem/ContainsItem entirely, since those were exactly what was unreliable)
// so a cluttered inventory from tonight's testing cleans itself up on next load.
public static void PurgeAll(Player player)
{
if (player == null) return;
Inventory inv = player.GetInventory();
if (inv == null) return;
var rawList = HarmonyLib.Traverse.Create(inv)
.Field<System.Collections.Generic.List<ItemDrop.ItemData>>("m_inventory").Value;
if (rawList == null) return;
int removed = rawList.RemoveAll(item =>
item != null && item.m_dropPrefab != null && item.m_dropPrefab.name == CloneName);
if (removed > 0)
{
Jotunn.Logger.LogInfo($"[Aswid] Purged {removed} spectral claw cop{(removed == 1 ? "y" : "ies")} from inventory.");
}
activeClaw = null;
}
private static bool TryRegister()
{
GameObject original = FindItemPrefabBySharedName(SourceItemSharedName);
if (original == null) return false;
GameObject clone = Object.Instantiate(original);
clone.name = CloneName;
Object.DontDestroyOnLoad(clone);
ApplySpectralVisual(clone);
ItemDrop itemDrop = clone.GetComponent<ItemDrop>();
if (itemDrop == null) return false;
itemDrop.m_itemData.m_shared.m_name = "$rov_item_aswid_spectralclaw_name";
itemDrop.m_itemData.m_shared.m_description = "$rov_item_aswid_spectralclaw_desc";
itemDrop.m_itemData.m_shared.m_weight = 0f;
itemDrop.m_itemData.m_shared.m_useDurability = false;
itemDrop.m_itemData.m_shared.m_questItem = true; // undroppable, unsellable
itemDrop.m_itemData.m_shared.m_value = 0;
CustomItem customItem = new CustomItem(clone, fixReference: true);
if (customItem?.ItemDrop == null) return false;
clonedItemDrop = itemDrop;
ItemManager.Instance.AddItem(customItem);
int hash = clone.name.GetStableHashCode();
// Belt and braces: registration this late (mid session, not at the normal Jotunn
// startup hook) doesn't reliably reach every lookup table Valheim's own systems use,
// so patch the clone into both directly.
if (ObjectDB.instance != null)
{
if (!ObjectDB.instance.m_items.Contains(clone))
{
ObjectDB.instance.m_items.Add(clone);
}
var itemByHash = Traverse.Create(ObjectDB.instance)
.Field<System.Collections.Generic.Dictionary<int, GameObject>>("m_itemByHash").Value;
if (itemByHash != null && !itemByHash.ContainsKey(hash))
{
itemByHash[hash] = clone;
}
}
if (ZNetScene.instance != null)
{
var prefabs = Traverse.Create(ZNetScene.instance)
.Field<System.Collections.Generic.List<GameObject>>("m_prefabs").Value;
if (prefabs != null && !prefabs.Contains(clone))
{
prefabs.Add(clone);
}
var namedPrefabs = Traverse.Create(ZNetScene.instance)
.Field<System.Collections.Generic.Dictionary<int, GameObject>>("m_namedPrefabs").Value;
if (namedPrefabs != null && !namedPrefabs.ContainsKey(hash))
{
namedPrefabs[hash] = clone;
}
}
return true;
}
private static void ApplySpectralVisual(GameObject clone)
{
// Greenish tint multiplied over whatever the base texture already carries, with low
// alpha - keeps some texture detail instead of flattening to a solid color, while
// reading as translucent, spectral energy rather than solid flesh. True transparency
// may not actually render on this item's shader (Custom/Creature, opaque-only) - the
// blend-mode properties below are a best-effort attempt, harmless no-ops if the
// shader doesn't expose them.
Color tint = new Color(0.35f, 1f, 0.55f, 0.35f);
foreach (Renderer r in clone.GetComponentsInChildren<Renderer>(true))
{
Material[] sourceMats = r.sharedMaterials;
Material[] newMats = new Material[sourceMats.Length];
for (int i = 0; i < sourceMats.Length; i++)
{
Material mat = new Material(sourceMats[i]);
if (mat.HasProperty("_Color"))
{
Color baseColor = mat.GetColor("_Color");
mat.SetColor("_Color", new Color(baseColor.r * tint.r, baseColor.g * tint.g, baseColor.b * tint.b, tint.a));
}
if (mat.HasProperty("_Mode")) mat.SetFloat("_Mode", 3f);
if (mat.HasProperty("_SrcBlend")) mat.SetFloat("_SrcBlend", (float)UnityEngine.Rendering.BlendMode.SrcAlpha);
if (mat.HasProperty("_DstBlend")) mat.SetFloat("_DstBlend", (float)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha);
if (mat.HasProperty("_ZWrite")) mat.SetFloat("_ZWrite", 0f);
mat.SetOverrideTag("RenderType", "Transparent");
mat.EnableKeyword("_ALPHABLEND_ON");
mat.DisableKeyword("_ALPHATEST_ON");
mat.DisableKeyword("_ALPHAPREMULTIPLY_ON");
mat.renderQueue = 3000;
newMats[i] = mat;
}
r.sharedMaterials = newMats;
}
}
private static GameObject FindItemPrefabBySharedName(string sharedName)
{
if (ObjectDB.instance == null) return null;
foreach (GameObject prefab in ObjectDB.instance.m_items)
{
ItemDrop id = prefab.GetComponent<ItemDrop>();
if (id != null && id.m_itemData != null && id.m_itemData.m_shared.m_name == sharedName)
{
return prefab;
}
}
return null;
}
}
[HarmonyPatch(typeof(Character), "Damage")]
public static class Aswid_SpectralClawDamage_Patch
{
public static void Prefix(HitData hit)
{
if (hit == null) return;
Character attacker = hit.GetAttacker();
if (attacker == null || attacker != Player.m_localPlayer) return;
if (!AswidRace.IsAswid()) return;
ItemDrop.ItemData weapon = Player.m_localPlayer.GetCurrentWeapon();
if (weapon == null || weapon.m_dropPrefab == null || weapon.m_dropPrefab.name != AswidSpectralClaw.CloneName) return;
int bossesDefeated = BossProgressionManager.GetCurrentProgressionState() - BossProgressionManager.MinState;
float slashDamage = AswidSpectralClaw.BaseSlashDamage + AswidSpectralClaw.SlashDamagePerBoss * bossesDefeated;
hit.m_damage.m_damage = 0f;
hit.m_damage.m_blunt = 0f;
hit.m_damage.m_slash = slashDamage;
hit.m_damage.m_pierce = 0f;
hit.m_damage.m_chop = 0f;
hit.m_damage.m_pickaxe = 0f;
hit.m_damage.m_fire = 0f;
hit.m_damage.m_frost = 0f;
hit.m_damage.m_lightning = 0f;
hit.m_damage.m_poison = 0f;
hit.m_damage.m_spirit = 0f;
}
}
}