RacesOfValheim/JotunnModStub/Trenta/TrentaPatches.cs
kanym fdc0fdcedc fix(trenta): stamina trickles back while a Bonemass Trenta swims
Vanilla Player.UpdateStats stops stamina regen while swimming off the
ground, and drowning starts at 0 stamina. The Bonemass unlock only
waived the stroke cost, so a Trenta who went into the water empty never
got a point back and drowned in water it swims for free.

A postfix on UpdateStats adds the regen vanilla held back, with the same
formula, times the new Trenta - Bonemass / Swim Stamina Regen (0.1, slow
on purpose). The compendium line says so in all three languages.
2026-10-29 02:21:24 +01:00

250 lines
13 KiB
C#

using HarmonyLib;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// Every hook the Trenta needs. The patches only ever decide *whether* a perk applies; *how
/// much* it applies always comes from TrentaProgression, which in turn reads TrentaConfig.
///
/// Two rules the other races learned the hard way and that hold here too:
///
/// - Health is changed through Player.GetTotalFoodValue, never through
/// Character.GetMaxHealth. Patching the getter makes it lie to the rest of the game and
/// leaves current health unclamped and the bar flashing every food tick. See the long
/// comment on Dvergar_GetTotalFoodValue_Patch.
///
/// - Every patch guards on `__instance == Player.m_localPlayer` before it guards on the
/// race, so a remote player never trips the local player's perks.
/// </summary>
public static class TrentaPatches
{
// ─── Skin ────────────────────────────────────────────────────────────
/// <summary>
/// Tints the Trenta the pale green of a young leaf, with dark foliage-green hair and beard.
///
/// VisEquipment.SetSkinColor followed by UpdateColors does nothing on its own - UpdateColors
/// rebuilds the body material from Valheim's own state on every refresh, so the tint has to
/// be written *after* it runs. This postfix is that write; see the long comment on
/// Dvergar_VisEquipment_UpdateColors_Patch for the full story of why.
///
/// 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 Trenta.
/// </summary>
[HarmonyPatch(typeof(VisEquipment), "UpdateColors")]
public static class Trenta_VisEquipment_UpdateColors_Patch
{
public static void Postfix(VisEquipment __instance)
{
if (__instance == null || !__instance.m_isPlayer) return;
Player player = __instance.GetComponent<Player>();
if (player == null || !TrentaVisuals.IsTrentaPlayer(player)) return;
if (__instance.m_bodyModel != null && __instance.m_bodyModel.material != null)
{
__instance.m_bodyModel.material.SetColor("_SkinColor", TrentaConfig.SkinColor);
}
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", TrentaConfig.HairColor);
}
}
}
/// <summary>
/// Hangs the crown of branches on, for every player local and remote, whenever Valheim
/// rebuilds their visuals - which is also the moment a rebuilt body model would have
/// thrown the old crown away with the old head bone.
/// </summary>
[HarmonyPatch(typeof(VisEquipment), "UpdateVisuals")]
public static class Trenta_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;
TrentaVisuals.ApplyCrown(player);
}
}
// Diet (vegan restriction, digestion doubling, awakened seeds) lives in
// TrentaFoodPatches.cs, the way DraughFoodPatches.cs holds the Draugh's equivalent.
// ─── Bonemass passives ──────────────────────────────────────────────
/// <summary>
/// Marks whether the current call into Player.UseStamina was reached from inside
/// Player.OnSwimming, for a Bonemass-tier Trenta specifically. Player.OnSwimming is the
/// only call site that spends stamina to swim - Character.UpdateSwimming itself never
/// touches stamina at all, confirmed by reading its IL - but UseStamina is also the same
/// method sprinting, jumping, blocking and attacking all spend through. Blocking it
/// outright, the way Player_UseStamina_Patch does wholesale for Skeleton/Aswid/Draugh,
/// would give the Trenta free sprint and free attacks along with free swimming. This flag
/// is what keeps the waiver scoped to swimming alone.
/// </summary>
[HarmonyPatch(typeof(Player), "OnSwimming")]
public static class Trenta_Player_OnSwimming_Patch
{
public static void Prefix(Player __instance)
{
if (__instance != Player.m_localPlayer) return;
swimStaminaWaived = TrentaRace.IsTrenta() &&
BossProgressionManager.GetCurrentProgressionState() >= TrentaConfig.BonemassDefeatedState;
}
public static void Postfix(Player __instance)
{
if (__instance == Player.m_localPlayer) swimStaminaWaived = false;
}
}
private static bool swimStaminaWaived = false;
[HarmonyPatch(typeof(Player), "UseStamina")]
public static class Trenta_Player_UseStamina_SwimWaiver_Patch
{
public static bool Prefix(Player __instance)
{
if (!swimStaminaWaived) return true;
if (__instance != Player.m_localPlayer) return true;
return false; // Swimming - waived, everything else still costs stamina normally
}
}
/// <summary>
/// A trickle of stamina regen while swimming, for a Bonemass-tier Trenta. Vanilla's
/// Player.UpdateStats stops regen outright while swimming off the ground, and drowning starts
/// at 0 stamina, so the free stroke above was not enough: a Trenta who went in empty never
/// got a point back and drowned in water it swims for free. The same formula vanilla uses on
/// land, times Swim Stamina Regen (slow on purpose).
/// </summary>
[HarmonyPatch(typeof(Player), "UpdateStats", new[] { typeof(float) })]
public static class Trenta_Player_SwimStaminaRegen_Patch
{
private static readonly AccessTools.FieldRef<Player, float> RegenTimer =
AccessTools.FieldRefAccess<Player, float>("m_staminaRegenTimer");
public static void Postfix(Player __instance, float dt)
{
if (__instance != Player.m_localPlayer || !TrentaRace.IsTrenta()) return;
if (BossProgressionManager.GetCurrentProgressionState() < TrentaConfig.BonemassDefeatedState) return;
// Only where vanilla held regen at zero for the water alone.
if (!__instance.IsSwimming() || __instance.IsOnGround()) return;
if (__instance.InAttack() || __instance.InDodge() || __instance.IsEncumbered()) return;
float share = TrentaConfigManagement.SwimStaminaRegen.Value;
if (share <= 0f || RegenTimer(__instance) > 0f) return;
float max = __instance.GetMaxStamina();
float stamina = __instance.GetStamina();
if (max <= 0f || stamina >= max) return;
float regen = __instance.m_staminaRegen +
(1f - stamina / max) * __instance.m_staminaRegen * __instance.m_staminaRegenTimeMultiplier;
float multiplier = 1f;
__instance.GetSEMan().ModifyStaminaRegen(ref multiplier);
__instance.AddStamina(regen * multiplier * share * dt * Game.m_staminaRegenRate);
}
}
/// <summary>
/// Blocks the Wet status effect from ever landing on a Bonemass-tier Trenta.
///
/// Wet has no damage type of its own, so unlike Poison this cannot go through
/// SE_TrentaStats.m_mods - it has to be stopped at the door instead. Player.
/// UpdateEnvStatusEffects (confirmed by reading its IL) is the only vanilla caller that
/// ever adds Wet, always through this exact four-argument SEMan.AddStatusEffect overload,
/// so patching that call is equivalent to patching every path Wet could arrive by.
/// </summary>
// Valheim 1.0 appended a 'short variant' parameter to this overload. The type array has to
// match it exactly or the patch silently fails to bind and PatchAll throws.
[HarmonyPatch(typeof(SEMan), "AddStatusEffect", new System.Type[] { typeof(int), typeof(bool), typeof(int), typeof(float), typeof(short) })]
public static class Trenta_SEMan_AddStatusEffect_WetImmunity_Patch
{
public static bool Prefix(SEMan __instance, int nameHash)
{
if (nameHash != SEMan.s_statusEffectWet) return true;
if (Player.m_localPlayer == null || __instance != Player.m_localPlayer.GetSEMan()) return true;
if (!TrentaRace.IsTrenta()) return true;
if (BossProgressionManager.GetCurrentProgressionState() < TrentaConfig.BonemassDefeatedState) return true;
return false; // Never gets wet
}
}
// ─── Moder passives ─────────────────────────────────────────────────
// Last Stand (the armor bonus that scales with missing health) lives in
// SE_TrentaStats.ModifyArmorMods - nothing to intercept there either, same reasoning as
// the damage m_mods above.
//
// Camouflage (stand still by a tree, become unsensable + fade to 50% alpha) was tried and
// pulled: neither half worked out reliably even after two rebuilds - Valheim's own systems
// kept fighting the visual fade, and the CanSenseTarget block never visibly stopped mobs
// aggroing either, for a reason that was never pinned down given the tools at hand.
// Replaced with something far simpler and much easier to trust: Thorns.
/// <summary>
/// Thorns: reflects a flat percentage of every hit taken back at whoever landed it.
///
/// A Postfix, not a Prefix - it runs after Character.Damage has already applied the hit to
/// the Trenta, so the reflected amount is read off the same HitData the Trenta itself just
/// took rather than being computed separately. Guards against hitting a hit with no
/// attacker (fall damage, drowning, environmental sources) and against reflecting a
/// creature's damage back onto itself.
/// </summary>
[HarmonyPatch(typeof(Character), "Damage")]
public static class Trenta_Character_Damage_Thorns_Patch
{
public static void Postfix(Character __instance, HitData hit)
{
if (__instance != Player.m_localPlayer) return;
if (!TrentaRace.IsTrenta()) return;
if (BossProgressionManager.GetCurrentProgressionState() < TrentaConfig.ModerDefeatedState) return;
if (hit == null || !hit.HaveAttacker()) return;
Character attacker = hit.GetAttacker();
if (attacker == null || attacker == __instance || attacker.IsDead()) return;
float reflected = hit.GetTotalDamage() * TrentaConfig.ThornsReflectPercent;
if (reflected <= 0f) return;
HitData thorns = new HitData();
thorns.m_damage.m_damage = reflected;
thorns.SetAttacker(__instance);
thorns.m_point = attacker.GetCenterPoint();
thorns.m_dir = Vector3.zero;
attacker.Damage(thorns);
}
}
// TODO: the race's remaining perks, one nested [HarmonyPatch] class per hook.
//
// [HarmonyPatch(typeof(Player), "GetTotalFoodValue")]
// public static class Trenta_GetTotalFoodValue_Patch
// {
// public static void Postfix(Player __instance, ref float hp)
// {
// if (__instance == null || __instance != Player.m_localPlayer) return;
// if (!TrentaRace.IsTrenta()) return;
//
// hp += TrentaProgression.Current.HealthBonus;
// }
// }
}
}