RacesOfValheim/JotunnModStub/Dvergar/DvergarPatches.cs
kanym b0d18b0654 feat(text): on-screen messages come from translation files
Every message the mod puts in the middle or corner of the screen now reads
its text through ModText.Get, and messages.json holds 191 texts in English
and Italian. Values computed in code become $1, $2 in the text, so a
translator can put them wherever the sentence needs them. Branching
messages get one key per branch.

A few messages travel through a field before they are shown: thralls'
refusals and the building limits now hold a token or key there. Boss and
form names inside messages use tokens too, the bosses the game's own, so
"The Elder" arrives translated.

ModText.Get now localizes each argument before inserting it. A token
argument left for a later pass ran into the text after it: "$1's power"
became the unknown token "enemy_eikthyr's".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-26 20:30:03 +02:00

398 lines
19 KiB
C#

using System.Collections.Generic;
using System.Reflection;
using HarmonyLib;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// Every hook the Dvergar needs. The patches only ever decide *whether* a perk applies; *how
/// much* it applies always comes from DvergarProgression, which in turn reads DvergarConfig.
/// </summary>
public static class DvergarPatches
{
// ─── Health malus ────────────────────────────────────────────────────
/// <summary>
/// The Dvergar is a small frame, and carries less health for it.
///
/// The malus is taken off the food total rather than off Character.GetMaxHealth, which is
/// what the first attempt did and what produced the bug where the bar shrank but the
/// number stayed put and the border flashed. Patching the getter makes it lie to the rest
/// of the game: Character.SetMaxHealth is the only thing that clamps current health down
/// to the new maximum, and it never saw a lower number, so m_health stayed at 58. Worse,
/// Player.SetMaxHealth flashes the bar whenever the new maximum is above GetMaxHealth() -
/// against a getter that always read low, every food tick looked like a health *increase*
/// and re-triggered the flash.
///
/// GetTotalFoodValue is upstream of both: UpdateFood feeds its result straight into
/// SetMaxHealth, so Valheim does its own clamping and its own flash logic on an honest
/// number and bar, value and animation all agree.
/// </summary>
[HarmonyPatch(typeof(Player), "GetTotalFoodValue")]
public static class Dvergar_GetTotalFoodValue_Patch
{
public static void Postfix(Player __instance, ref float hp)
{
if (__instance == null || __instance != Player.m_localPlayer) return;
if (!DvergarRace.IsDvergar()) return;
float malus = DvergarProgression.Current.HealthMalus;
if (malus <= 0f) return;
hp = Mathf.Max(DvergarConfig.MinMaxHealth, hp - malus);
}
}
// ─── Scale ───────────────────────────────────────────────────────────
/// <summary>
/// Sizing runs off Player.Update, which is where the Trol does it and the only place it
/// holds: Trol's own postfix forces every non-Trol player's visual back to scale 1 on the
/// same frame, so a scale applied from anywhere else was simply overwritten. Being a
/// postfix on the same method puts the Dvergar on equal footing, and RaceScale keeps the
/// two from undoing each other.
/// </summary>
[HarmonyPatch(typeof(Player), "Update")]
public static class Dvergar_PlayerUpdate_Scale_Patch
{
public static void Postfix(Player __instance)
{
if (__instance == null) return;
DvergarVisuals.ApplyScale(__instance, DvergarVisuals.IsDvergarPlayer(__instance));
}
}
// ─── Weapon affinity: damage ─────────────────────────────────────────
/// <summary>
/// Bonus damage with hammer, bow, axe and crossbow as each is unlocked, and the payoff for
/// a held Runic Overcharge. Neither touches skill XP: the Dvergar is at home with these
/// weapons, not faster at learning them.
/// </summary>
[HarmonyPatch(typeof(Character), "Damage")]
public static class Dvergar_WeaponAffinity_Damage_Patch
{
public static void Prefix(Character __instance, HitData hit)
{
if (hit == null || Player.m_localPlayer == null) return;
if (hit.GetAttacker() != Player.m_localPlayer) return;
if (!DvergarRace.IsDvergar()) return;
int state = BossProgressionManager.GetCurrentProgressionState();
// Runic Spark, before the weapon check: the lightning rides every blow the Dvergar
// lands, favoured weapon or not, exactly as Skadi's frost does in SkadiDamagePatch.
float elemental = DvergarProgression.GetRules(state).ElementalDamage;
if (elemental > 0f)
{
AddFlat(hit, DvergarConfig.ElementalDamageType, elemental);
}
DvergarConfig.WeaponAffinity? found = DvergarProgression.GetAffinity(hit.m_skill, state);
if (!found.HasValue) return;
DvergarConfig.WeaponAffinity affinity = found.Value;
if (affinity.DamagePercent > 0f)
{
ScalePhysical(hit, 1f + affinity.DamagePercent);
}
if (affinity.FlatDamage > 0f)
{
AddFlat(hit, affinity.FlatDamageType, affinity.FlatDamage);
}
// Overcharge only ever discharges into a favoured weapon, which is why it is
// spent here rather than on the first hit of any kind.
if (DvergarProgression.GetRules(state).RunicOvercharge &&
DvergarAbilities.ConsumeOvercharge(Player.m_localPlayer))
{
ScalePhysical(hit, DvergarConfig.RunicOverchargeMultiplier);
Player.m_localPlayer.Message(MessageHud.MessageType.TopLeft, ModText.Get("rov_msg_dvergar_runic_overcharge_discharges"));
}
}
private static void ScalePhysical(HitData hit, float multiplier)
{
hit.m_damage.m_blunt *= multiplier;
hit.m_damage.m_slash *= multiplier;
hit.m_damage.m_pierce *= multiplier;
}
private static void AddFlat(HitData hit, HitData.DamageType type, float amount)
{
switch (type)
{
case HitData.DamageType.Blunt: hit.m_damage.m_blunt += amount; break;
case HitData.DamageType.Slash: hit.m_damage.m_slash += amount; break;
case HitData.DamageType.Pierce: hit.m_damage.m_pierce += amount; break;
case HitData.DamageType.Fire: hit.m_damage.m_fire += amount; break;
case HitData.DamageType.Frost: hit.m_damage.m_frost += amount; break;
case HitData.DamageType.Lightning: hit.m_damage.m_lightning += amount; break;
case HitData.DamageType.Poison: hit.m_damage.m_poison += amount; break;
case HitData.DamageType.Spirit: hit.m_damage.m_spirit += amount; break;
default: hit.m_damage.m_damage += amount; break;
}
}
}
// ─── Mining affinity ─────────────────────────────────────────────────
/// <summary>
/// Set for the duration of a mining hit so the drop patch below can tell an ore roll made
/// by this player apart from every other DropTable call in the world. Same flag-around-the
/// -call approach the Furling uses for its doubled ore.
/// </summary>
private static bool isDvergarMining = false;
private static bool BeginMiningHit(HitData hit)
{
if (hit == null || Player.m_localPlayer == null) return false;
if (hit.GetAttacker() != Player.m_localPlayer) return false;
if (!DvergarRace.IsDvergar()) return false;
if (!DvergarProgression.Current.MiningAffinity) return false;
// A pickaxe swing is what the affinity is about - chopping and combat hits on the same
// objects go through here too and must be left alone.
if (hit.m_damage.m_pickaxe <= 0f) return false;
hit.m_damage.m_pickaxe *= DvergarConfig.MiningDamageMultiplier;
isDvergarMining = true;
return true;
}
private static void EndMiningHit(bool began)
{
if (began) isDvergarMining = false;
}
[HarmonyPatch(typeof(MineRock5), "DamageArea")]
public static class Dvergar_MineRock5_DamageArea_Patch
{
public static void Prefix(HitData hit, out bool __state) => __state = BeginMiningHit(hit);
public static void Postfix(bool __state) => EndMiningHit(__state);
}
[HarmonyPatch(typeof(MineRock), "RPC_Hit")]
public static class Dvergar_MineRock_RPC_Hit_Patch
{
public static void Prefix(HitData hit, out bool __state) => __state = BeginMiningHit(hit);
public static void Postfix(bool __state) => EndMiningHit(__state);
}
[HarmonyPatch(typeof(Destructible), "RPC_Damage")]
public static class Dvergar_Destructible_RPC_Damage_Patch
{
public static void Prefix(HitData hit, out bool __state) => __state = BeginMiningHit(hit);
public static void Postfix(bool __state) => EndMiningHit(__state);
}
[HarmonyPatch(typeof(DropTable), "GetDropList", new System.Type[] { typeof(int) })]
public static class Dvergar_DropTable_GetDropList_Patch
{
public static void Postfix(ref List<GameObject> __result)
{
if (!isDvergarMining || __result == null) return;
if (DvergarConfig.MiningExtraDropChance <= 0f) return;
List<GameObject> extra = new List<GameObject>();
foreach (GameObject drop in __result)
{
if (drop == null || !IsOre(drop.name)) continue;
if (Random.value <= DvergarConfig.MiningExtraDropChance) extra.Add(drop);
}
__result.AddRange(extra);
}
private static bool IsOre(string prefabName)
{
string lower = prefabName.ToLower();
foreach (string ore in DvergarConfig.OreDropNames)
{
if (lower.Contains(ore)) return true;
}
return false;
}
}
// ─── Smithing and jewelry ────────────────────────────────────────────
/// <summary>
/// Metal saved when crafting and upgrading. Requirement.GetAmount is the single point both
/// the crafting panel and Player.ConsumeResources go through, so the figure the player is
/// quoted and the figure they are charged can never drift apart.
///
/// Scoped to the metals and gems in DvergarConfig.DiscountedResourceNames, which is what
/// keeps this a smithing perk rather than a blanket discount on every wooden wall.
/// </summary>
[HarmonyPatch(typeof(Piece.Requirement), "GetAmount")]
public static class Dvergar_Requirement_GetAmount_Patch
{
public static void Postfix(Piece.Requirement __instance, ref int __result)
{
if (__result <= 1 || Player.m_localPlayer == null) return;
if (!DvergarRace.IsDvergar()) return;
float discount = DvergarProgression.Current.SmithingDiscount;
if (discount <= 0f) return;
if (__instance == null || __instance.m_resItem == null) return;
if (!IsDiscounted(__instance.m_resItem.gameObject.name)) return;
__result = Mathf.Max(1, Mathf.RoundToInt(__result * (1f - discount)));
}
private static bool IsDiscounted(string prefabName)
{
string lower = prefabName.ToLower();
foreach (string resource in DvergarConfig.DiscountedResourceNames)
{
if (lower == resource || lower.Contains(resource)) return true;
}
return false;
}
}
// ─── Haldor and Hildir's favour ──────────────────────────────────────
/// <summary>
/// The buying half. Both traders are Trader components, so patching the shared source of
/// the stock list covers Haldor and Hildir at once.
///
/// The discounted entries are fresh TradeItem instances rather than edited originals: the
/// list Valheim hands back holds the trader's own objects, and rewriting their prices in
/// place would permanently mark down the shop for everyone, Dvergar or not.
/// </summary>
[HarmonyPatch(typeof(Trader), "GetAvailableItems")]
public static class Dvergar_Trader_GetAvailableItems_Patch
{
public static void Postfix(ref List<Trader.TradeItem> __result)
{
if (__result == null || Player.m_localPlayer == null) return;
if (!DvergarRace.IsDvergar()) return;
float discount = DvergarProgression.Current.TraderBuyDiscount;
if (discount <= 0f) return;
List<Trader.TradeItem> discounted = new List<Trader.TradeItem>(__result.Count);
foreach (Trader.TradeItem item in __result)
{
if (item == null) continue;
// A full copy, not a hand-picked one: Valheim 1.0 hangs name, tooltip, icon,
// buy/increment keys and buy effects off TradeItem, and StoreGui reads some
// of them without null checks. Only the price is ours to change.
var copy = (Trader.TradeItem)MemberwiseCloneMethod.Invoke(item, null);
copy.m_price = Mathf.Max(1, Mathf.RoundToInt(item.m_price * (1f - discount)));
discounted.Add(copy);
}
__result = discounted;
}
private static readonly System.Reflection.MethodInfo MemberwiseCloneMethod =
AccessTools.Method(typeof(object), "MemberwiseClone");
}
/// <summary>
/// The selling half - trophies and hunting rewards fetch more. GetValue is what the sell
/// button both displays and pays out, and it is not consulted for purchases, so the bonus
/// lands on exactly the side of the counter it is meant to.
/// </summary>
[HarmonyPatch(typeof(ItemDrop.ItemData), "GetValue")]
public static class Dvergar_ItemData_GetValue_Patch
{
public static void Postfix(ref int __result)
{
if (__result <= 0 || Player.m_localPlayer == null) return;
if (!DvergarRace.IsDvergar()) return;
float bonus = DvergarProgression.Current.TraderSellBonus;
if (bonus <= 0f) return;
__result = Mathf.RoundToInt(__result * (1f + bonus));
}
}
// ─── Skin ────────────────────────────────────────────────────────────
/// <summary>
/// Tints the Dvergar ashen grey.
///
/// The first attempt did this the way the race-selection menu appears to - VisEquipment's
/// SetSkinColor followed by UpdateColors - and nothing happened, because that pair is not
/// what actually colours a player. UpdateColors rebuilds the body material from Valheim's
/// own state on every refresh, so any tint has to be written *after* it runs. That is why
/// every race in this mod that visibly changes colour has a postfix here writing
/// _SkinColor onto the material directly, and why the SetSkinColor calls in the selection
/// menu are, on their own, decorative.
///
/// No local-player check and no saved original: the race is read from the ZDO with a
/// m_customData fallback so the main-menu preview and the first spawn frame are covered
/// too, and the tint simply stops being applied once the player is no longer a Dvergar.
/// </summary>
[HarmonyPatch(typeof(VisEquipment), "UpdateColors")]
public static class Dvergar_VisEquipment_UpdateColors_Patch
{
public static void Postfix(VisEquipment __instance)
{
if (__instance == null || !__instance.m_isPlayer) return;
Player player = __instance.GetComponent<Player>();
if (player == null) return;
// Before the race check, because it takes the eyes off anyone who has stopped
// being a Dvergar as well as putting them on anyone who is one. Here rather than
// in the UpdateVisuals postfix so that the tier refresh DvergarRace forces on a
// boss kill recolours them at the same moment it recolours the skin.
DvergarVisuals.ApplyEyes(player);
if (!DvergarVisuals.IsDvergarPlayer(player)) return;
if (__instance.m_bodyModel != null && __instance.m_bodyModel.material != null)
{
// Not the flat config colour any more: it carries the star shift a dverger of
// this standing would wear, so the race visibly ages at Bonemass and again at
// Fader.
__instance.m_bodyModel.material.SetColor("_SkinColor", DvergarVisuals.GetSkinColor(player));
}
TintRenderers(Traverse.Create(__instance).Field("m_hairItemInstance").GetValue<GameObject>());
TintRenderers(Traverse.Create(__instance).Field("m_beardItemInstance").GetValue<GameObject>());
}
private static void TintRenderers(GameObject instance)
{
if (instance == null) return;
foreach (Renderer renderer in instance.GetComponentsInChildren<Renderer>())
{
if (renderer.material != null) renderer.material.SetColor("_SkinColor", DvergarConfig.HairColor);
}
}
}
// ─── Cosmetic hood ───────────────────────────────────────────────────
/// <summary>
/// Runs for every player, local and remote, whenever Valheim rebuilds their visuals - the
/// point at which a newly equipped helmet has just been instantiated and needs hiding
/// again behind the hood.
/// </summary>
[HarmonyPatch(typeof(VisEquipment), "UpdateVisuals")]
public static class Dvergar_VisEquipment_UpdateVisuals_Patch
{
public static void Postfix(VisEquipment __instance)
{
if (__instance == null || !__instance.m_isPlayer) return;
Player player = __instance.GetComponent<Player>();
if (player == null) return;
DvergarVisuals.ApplyHood(player);
}
}
}
}