RacesOfValheim/JotunnModStub/Furling/FurlingPatches.cs
kanym 95c8a7b1b6 fix(furling): other players see a Furling at Furling size
The 0.81 scale was applied from a Player.Update postfix that returned for
anyone but the local player and read the race from the local m_customData.
Scale is not replicated, so a Furling was small only on their own screen.
The postfix now sizes every player, with the race read off the ZDO the way
the Dvergar and the Trol already do it.
2026-10-23 19:03:58 +02:00

666 lines
32 KiB
C#

using HarmonyLib;
using UnityEngine;
using Jotunn.Managers;
namespace RacesOfValheim
{
public static class FurlingPatches
{
[HarmonyPatch(typeof(Player), "Update")]
public static class Furling_PlayerUpdate_Patch
{
public static void Postfix(Player __instance)
{
if (__instance == null) return;
// Every player, not only the local one, with the race read off the ZDO. Scale is not
// replicated: each client sizes the characters it draws. When this sized only the
// local player from its own m_customData, a Furling was small on their own screen
// and full height on everybody else's.
if (DvergarVisuals.GetPlayerRace(__instance) == "Furling")
{
// Scale player visuals down by 19% (0.9 * 0.9 = 0.81)
GameObject visual = Traverse.Create(__instance).Field("m_visual").GetValue<GameObject>();
if (visual != null && visual.transform.localScale != new Vector3(0.81f, 0.81f, 0.81f))
{
visual.transform.localScale = new Vector3(0.81f, 0.81f, 0.81f);
}
}
else
{
// Reset scale if not Furling
GameObject visual = Traverse.Create(__instance).Field("m_visual").GetValue<GameObject>();
if (visual != null && visual.transform.localScale == new Vector3(0.81f, 0.81f, 0.81f))
{
visual.transform.localScale = Vector3.one;
}
}
}
}
// +10% movement speed — fixed, does not scale with progression
[HarmonyPatch(typeof(Character), "GetRunSpeedFactor")]
public static class Furling_GetRunSpeedFactor_Patch
{
public static void Postfix(Character __instance, ref float __result)
{
if (__instance == null || __instance != Player.m_localPlayer) return;
if (!FurlingRace.IsFurling()) return;
__result *= 1.1f;
}
}
/// <summary>
/// The Furling's truce with the Plains. Every name here is the game's actual internal prefab
/// id, checked against the shipped asset manifest one at a time, because the display names do
/// not predict them at all - this is the family where "Fuling" is the word the game shows the
/// player and "Goblin" is the word the game uses in code.
///
/// The full roster under Assets/Characters, so nothing is missed by accident:
/// Goblin ............... Fuling (NOT "Fuling" - that prefab does not exist)
/// GoblinArcher ......... Fuling Archer (was missing entirely)
/// GoblinBrute .......... Fuling Berserker
/// GoblinShaman ......... Fuling Shaman
/// GoblinKing ........... Yagluth - a boss, stays hostile
/// GoblinBruteBros, GoblinBrute_Hildir, GoblinShaman_Hildir (+ _nochest variants)
/// Hildir's quest bosses - arena fights, they stay hostile too
/// The old code checked for "goblinking" inside a branch it could never reach, which is a
/// good sign the list was written from the display names rather than from the assets.
/// </summary>
private static readonly System.Collections.Generic.HashSet<string> FurlingFriends =
new System.Collections.Generic.HashSet<string>
{
"Goblin", "GoblinArcher", "GoblinBrute", "GoblinShaman",
"Lox", "Deathsquito", "Troll",
};
[HarmonyPatch(typeof(BaseAI), "IsEnemy", typeof(Character), typeof(Character))]
public static class Furling_BaseAI_IsEnemy_Patch
{
public static void Postfix(Character a, Character b, ref bool __result)
{
if (!FactionsConfig.Hostility) return;
if (!__result || !FurlingRace.IsFurling() || Player.m_localPlayer == null) return;
Character playerChar = Player.m_localPlayer;
Character otherChar = null;
if (a == playerChar) otherChar = b;
else if (b == playerChar) otherChar = a;
if (otherChar == null) return;
// Trimmed as well as stripped: a stray "(Clone)" leaves a trailing space behind, and
// an exact-match set is unforgiving about it in a way the old ToLower chain also was.
string name = otherChar.gameObject.name.Replace("(Clone)", "").Trim();
if (FurlingFriends.Contains(name)) __result = false;
}
}
[HarmonyPatch(typeof(VisEquipment), "UpdateVisuals")]
public static class Furling_VisEquipment_UpdateVisuals_Patch
{
public static string GetPlayerRace(VisEquipment visEq)
{
Player player = visEq.GetComponent<Player>();
if (player != null)
{
ZNetView nview = player.GetComponent<ZNetView>();
if (nview != null && nview.IsValid())
{
return nview.GetZDO().GetString("RacesOfValheim_Race", "Human");
}
// Main Menu handling and local fallback
if (player.m_customData != null && player.m_customData.TryGetValue("Race", out string r))
{
return r;
}
}
return "Human";
}
public static void Postfix(VisEquipment __instance)
{
if (!__instance.m_isPlayer) return;
string race = GetPlayerRace(__instance);
if (race == "Furling")
{
// Ensure the base model IS shown
if (__instance.m_bodyModel != null)
{
__instance.m_bodyModel.enabled = true;
Transform headBone = FindBoneByName(__instance.m_bodyModel.bones, "Head");
if (headBone != null)
{
Transform furlingHead = headBone.Find("FurlingHead_Trophy");
if (furlingHead == null)
{
GameObject trophyPrefab = PrefabManager.Cache.GetPrefab<ItemDrop>("TrophyGoblin")?.gameObject;
if (trophyPrefab != null)
{
bool wasActive = trophyPrefab.activeSelf;
trophyPrefab.SetActive(false);
GameObject trophyVisual = UnityEngine.Object.Instantiate(trophyPrefab, headBone, false);
trophyPrefab.SetActive(wasActive);
trophyVisual.name = "FurlingHead_Trophy";
// Rimuoviamo tutti gli script (HoverText, ZNetView, ItemDrop, ecc.) per evitare prompt a schermo
foreach (var comp in trophyVisual.GetComponentsInChildren<MonoBehaviour>())
{
UnityEngine.Object.DestroyImmediate(comp);
}
if (trophyVisual.GetComponent<Rigidbody>() != null)
UnityEngine.Object.DestroyImmediate(trophyVisual.GetComponent<Rigidbody>());
foreach (var col in trophyVisual.GetComponentsInChildren<Collider>())
{
UnityEngine.Object.DestroyImmediate(col);
}
trophyVisual.SetActive(true);
// Valheim rig scales are huge (100).
// Spostiamo la testa leggermente in alto (asse Y = 0.0015) e 5cm indietro rispetto al centro (asse X positivo = 0.0005)
trophyVisual.transform.localPosition = new Vector3(0.0005f, 0.0015f, 0f);
// Torniamo allo stato precedente (Z=90) ma ruotiamo sull'asse delle orecchie (X) di -90
trophyVisual.transform.localRotation = Quaternion.Euler(-90, 0, 90);
// Rimpiccioliamo la testa affinché entri in quella umana (ulteriore 20% in meno -> 0.005832)
trophyVisual.transform.localScale = new Vector3(0.005832f, 0.005832f, 0.005832f);
// Risolve il problema della trasparenza (dither):
// Non possiamo applicare m_bodyModel.material perché i modelli (UV map) non coincidono e l'oggetto diventa invisibile.
// Ripristiniamo il materiale originale del trofeo, ma cambiamo il suo shader in Custom/Creature per fargli
// supportare la dissolvenza (dither) della telecamera, mantenendo le sue texture originali (che sono già verdi).
foreach (var mr in trophyVisual.GetComponentsInChildren<Renderer>())
{
if (mr.material != null)
{
Shader ditherShader = Shader.Find("Custom/Creature");
if (ditherShader != null)
{
mr.material.shader = ditherShader;
}
}
}
}
}
else
{
furlingHead.gameObject.SetActive(true);
}
}
int modelIndex = Traverse.Create(__instance).Field<int>("m_modelIndex").Value;
if (modelIndex == 0)
{
HideItem(__instance, "m_hairItemInstance");
HideItem(__instance, "m_hairItemInstances"); // In case it's a list in some versions
}
HideItem(__instance, "m_beardItemInstance");
HideItem(__instance, "m_beardItemInstances");
// Restore helmet visibility — let the game manage it normally
ShowItem(__instance, "m_helmetItemInstance");
}
}
else
{
// Not a furling, cleanup
if (__instance.m_bodyModel != null)
{
__instance.m_bodyModel.enabled = true;
Transform headBone = FindBoneByName(__instance.m_bodyModel.bones, "Head");
if (headBone != null)
{
Transform furlingHead = headBone.Find("FurlingHead_Trophy");
if (furlingHead != null)
{
furlingHead.gameObject.SetActive(false);
}
// Distruggiamo il tappo del collo (se c'era in precedenza) per sicurezza
Transform neckCap = headBone.Find("FulingNeckCap");
if (neckCap != null)
{
UnityEngine.Object.Destroy(neckCap.gameObject);
}
}
ShowItem(__instance, "m_hairItemInstance");
ShowItem(__instance, "m_beardItemInstance");
ShowItem(__instance, "m_hairItemInstances");
ShowItem(__instance, "m_beardItemInstances");
}
}
}
private static void HideItem(VisEquipment visEq, string fieldName)
{
try
{
var field = typeof(VisEquipment).GetField(fieldName, System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
if (field != null)
{
object val = field.GetValue(visEq);
if (val is GameObject go && go != null)
{
go.SetActive(false);
}
else if (val is System.Collections.Generic.List<GameObject> list)
{
foreach (var item in list) if (item != null) item.SetActive(false);
}
}
}
catch (System.Exception) { }
}
private static void ShowItem(VisEquipment visEq, string fieldName)
{
try
{
var field = typeof(VisEquipment).GetField(fieldName, System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
if (field != null)
{
object val = field.GetValue(visEq);
if (val is GameObject go && go != null)
{
go.SetActive(true);
}
else if (val is System.Collections.Generic.List<GameObject> list)
{
foreach (var item in list) if (item != null) item.SetActive(true);
}
}
}
catch (System.Exception) { }
}
private static Transform FindBoneByName(Transform[] bones, string targetBoneName)
{
// Exact match first
foreach (Transform b in bones)
{
if (b != null && b.name == targetBoneName) return b;
}
// Fuzzy match
string sName = targetBoneName.ToLower().Replace("goblin_", "").Replace("furling_", "").Replace(" goblin", "");
// Common valheim mappings
if (sName == "pelvis") sName = "hips";
if (sName == "clavicle.l") sName = "leftshoulder";
if (sName == "clavicle.r") sName = "rightshoulder";
if (sName == "upperarm.l") sName = "leftarm";
if (sName == "upperarm.r") sName = "rightarm";
if (sName == "lowerarm.l") sName = "leftforearm";
if (sName == "lowerarm.r") sName = "rightforearm";
if (sName == "thigh.l") sName = "leftupleg";
if (sName == "thigh.r") sName = "rightupleg";
if (sName == "calf.l") sName = "leftleg";
if (sName == "calf.r") sName = "rightleg";
foreach (Transform b in bones)
{
if (b != null)
{
string pName = b.name.ToLower();
if (pName == sName || pName.Contains(sName) || sName.Contains(pName))
{
return b;
}
}
}
return null;
}
}
[HarmonyPatch(typeof(Skills), "RaiseSkill")]
public static class Furling_Skills_RaiseSkill_Patch
{
public static void Prefix(Skills __instance, Skills.SkillType skillType, ref float factor)
{
// Check if this Skills instance belongs to the local player
Player player = HarmonyLib.Traverse.Create(__instance).Field("m_player").GetValue<Player>();
if (player != null && player == Player.m_localPlayer && FurlingRace.IsFurling())
{
// The Art of War: Double XP for weapon skills (always active)
bool isWeaponSkill = (skillType == Skills.SkillType.Swords ||
skillType == Skills.SkillType.Knives ||
skillType == Skills.SkillType.Clubs ||
skillType == Skills.SkillType.Polearms ||
skillType == Skills.SkillType.Spears ||
skillType == Skills.SkillType.Axes ||
skillType == Skills.SkillType.Bows ||
skillType == Skills.SkillType.Crossbows ||
skillType == Skills.SkillType.Unarmed ||
skillType == Skills.SkillType.Blocking);
if (isWeaponSkill)
{
factor *= 2f;
}
else if (BossProgressionManager.GetCurrentProgressionState() >= 6)
{
// The King is Dead: in Plains, ALL other skills (including magic) get 2x XP
if (EnvMan.instance != null && EnvMan.instance.GetCurrentBiome() == Heightmap.Biome.Plains)
{
factor *= 2f;
}
}
}
}
}
[HarmonyPatch(typeof(Character), "AddNoise")]
public static class Furling_Character_AddNoise_Patch
{
public static bool Prefix(Character __instance, float range)
{
if (__instance != null && __instance == Player.m_localPlayer && FurlingRace.IsFurling())
{
// Check if it's nighttime or inside a dungeon
if (BossProgressionManager.GetCurrentProgressionState() >= 2) // Master of Shadows (Eikthyr)
{
if (range <= 15f)
{
return false;
}
}
}
return true;
}
}
[HarmonyPatch(typeof(Character), "Damage")]
public static class Furling_Character_Damage_Patch
{
public static void Prefix(Character __instance, HitData hit)
{
if (__instance != null && __instance == Player.m_localPlayer && FurlingRace.IsFurling())
{
int state = BossProgressionManager.GetCurrentProgressionState();
if (state >= 8) // Through Fire and Flames (Fader): full fire immunity
{
hit.m_damage.m_fire = 0f;
if (hit.m_damage.m_poison > 0) hit.m_damage.m_poison *= 0.5f;
}
else if (state >= 3) // The Wickerman: -50% fire and poison
{
if (hit.m_damage.m_fire > 0) hit.m_damage.m_fire *= 0.5f;
if (hit.m_damage.m_poison > 0) hit.m_damage.m_poison *= 0.5f;
}
}
}
}
[HarmonyPatch(typeof(Projectile), "Setup")]
public static class Furling_Projectile_Setup_Patch
{
public static void Prefix(Character owner, Vector3 velocity, float hitNoise, HitData hitData, ItemDrop.ItemData item, ItemDrop.ItemData ammo)
{
if (owner != null && owner == Player.m_localPlayer && FurlingRace.IsFurling())
{
if (BossProgressionManager.GetCurrentProgressionState() >= 3) // The Wickerman (Elder)
{
// Check if it's an arrow or a bolt (either by skill or by checking if a bow/crossbow/ammo was used)
if ((hitData != null && (hitData.m_skill == Skills.SkillType.Bows || hitData.m_skill == Skills.SkillType.Crossbows)) ||
(ammo != null && (ammo.m_shared.m_skillType == Skills.SkillType.Bows || ammo.m_shared.m_skillType == Skills.SkillType.Crossbows)))
{
// If the arrow doesn't already have significant fire damage, add it
if (hitData != null && hitData.m_damage.m_fire < 22f)
{
// Adds fire damage equivalent to a standard fire arrow
hitData.m_damage.m_fire = Mathf.Max(hitData.m_damage.m_fire, 22f);
}
}
}
}
}
}
[HarmonyPatch(typeof(InventoryGui), "DoCrafting")]
public static class Furling_InventoryGui_DoCrafting_Patch
{
public static void Postfix(InventoryGui __instance, Player player)
{
if (Player.m_localPlayer != null && FurlingRace.IsFurling())
{
if (BossProgressionManager.GetCurrentProgressionState() >= 4) // Dance of the Dead (Bonemass)
{
Recipe craftRecipe = HarmonyLib.Traverse.Create(__instance).Field("m_craftRecipe").GetValue<Recipe>();
if (craftRecipe == null || craftRecipe.m_item == null) return;
ItemDrop itemDrop = craftRecipe.m_item;
string prefabName = itemDrop.gameObject.name.ToLower();
ItemDrop.ItemData.ItemType type = itemDrop.m_itemData.m_shared.m_itemType;
bool isMead = prefabName.Contains("mead") || prefabName.Contains("potion") || prefabName.Contains("wine");
bool isBomb = prefabName.Contains("bomb") || prefabName.Contains("oozeboomb") || prefabName.Contains("bile");
bool isAmmo = type == ItemDrop.ItemData.ItemType.Ammo;
if (isMead || isBomb || isAmmo)
{
int amount = craftRecipe.m_amount;
ItemDrop.ItemData craftUpgradeItem = HarmonyLib.Traverse.Create(__instance).Field("m_craftUpgradeItem").GetValue<ItemDrop.ItemData>();
int quality = craftUpgradeItem != null ? craftUpgradeItem.m_quality + 1 : 1;
int craftVariant = HarmonyLib.Traverse.Create(__instance).Field("m_craftVariant").GetValue<int>();
ItemDrop.ItemData addedItem = player.GetInventory().AddItem(itemDrop.gameObject.name, amount, quality, craftVariant, player.GetPlayerID(), player.GetPlayerName(), false);
if (addedItem == null)
{
// Inventory full, drop on ground
GameObject go = UnityEngine.Object.Instantiate(itemDrop.gameObject, player.transform.position + player.transform.forward + Vector3.up, Quaternion.identity);
ItemDrop drop = go.GetComponent<ItemDrop>();
drop.m_itemData.m_stack = amount;
drop.m_itemData.m_quality = quality;
drop.m_itemData.m_variant = craftVariant;
}
}
}
}
}
}
[HarmonyPatch(typeof(VisEquipment), "UpdateColors")]
public static class FurlingSkinColorPatch
{
public static void Postfix(VisEquipment __instance)
{
if (!__instance.m_isPlayer) return;
string race = Furling_VisEquipment_UpdateVisuals_Patch.GetPlayerRace(__instance);
if (race == "Furling")
{
if (__instance.m_bodyModel != null && __instance.m_bodyModel.material != null)
{
// Verde più acceso/brillante (Goblin)
Color furlingColor = new Color(0.4f, 0.75f, 0.25f, 1f);
__instance.m_bodyModel.material.SetColor("_SkinColor", furlingColor);
}
int modelIndex = Traverse.Create(__instance).Field<int>("m_modelIndex").Value;
if (modelIndex == 1) // Female
{
var hairInst = Traverse.Create(__instance).Field("m_hairItemInstance").GetValue<GameObject>();
if (hairInst != null)
{
foreach (var r in hairInst.GetComponentsInChildren<Renderer>())
{
if (r.material != null) r.material.SetColor("_SkinColor", Color.red);
}
}
}
}
}
}
public static bool IsMining = false;
[HarmonyPatch(typeof(CharacterDrop), "GenerateDropList")]
public static class Furling_CharacterDrop_GenerateDropList_Patch
{
public static void Postfix(CharacterDrop __instance, ref System.Collections.Generic.List<System.Collections.Generic.KeyValuePair<GameObject, int>> __result)
{
if (Player.m_localPlayer == null || !FurlingRace.IsFurling()) return;
if (BossProgressionManager.GetCurrentProgressionState() < 5) return;
Character character = __instance.GetComponent<Character>();
if (character != null && (character.IsBoss() || character.gameObject.name.ToLower().Contains("boss"))) return;
float distance = Vector3.Distance(Player.m_localPlayer.transform.position, __instance.transform.position);
if (distance > 25f) return;
var newList = new System.Collections.Generic.List<System.Collections.Generic.KeyValuePair<GameObject, int>>();
foreach (var drop in __result)
{
var go = drop.Key;
int amount = drop.Value;
if (go != null)
{
var itemDrop = go.GetComponent<ItemDrop>();
if (itemDrop != null && itemDrop.m_itemData.m_shared.m_itemType == ItemDrop.ItemData.ItemType.Trophy)
{
amount *= 2;
}
}
newList.Add(new System.Collections.Generic.KeyValuePair<GameObject, int>(go, amount));
}
Character character2 = __instance.GetComponent<Character>();
int stars = character2 != null ? character2.GetLevel() - 1 : 0;
if (stars > 0)
{
GameObject coinsPrefab = Jotunn.Managers.PrefabManager.Cache.GetPrefab<GameObject>("Coins");
if (coinsPrefab != null)
{
int extraCoins = stars * UnityEngine.Random.Range(1, 26);
newList.Add(new System.Collections.Generic.KeyValuePair<GameObject, int>(coinsPrefab, extraCoins));
}
}
__result = newList;
}
}
[HarmonyPatch(typeof(MineRock5), "DamageArea")]
public static class Furling_MineRock5_DamageArea_Patch
{
public static void Prefix(HitData hit, out bool __state)
{
__state = false;
if (hit == null) return;
Character attacker = hit.GetAttacker();
if (attacker != null && attacker == Player.m_localPlayer && FurlingRace.IsFurling() && BossProgressionManager.GetCurrentProgressionState() >= 5)
{
IsMining = true;
__state = true;
}
}
public static void Postfix(bool __state)
{
if (__state) IsMining = false;
}
}
[HarmonyPatch(typeof(MineRock), "RPC_Hit")]
public static class Furling_MineRock_RPC_Damage_Patch
{
public static void Prefix(HitData hit, out bool __state)
{
__state = false;
if (hit == null) return;
Character attacker = hit.GetAttacker();
if (attacker != null && attacker == Player.m_localPlayer && FurlingRace.IsFurling() && BossProgressionManager.GetCurrentProgressionState() >= 5)
{
IsMining = true;
__state = true;
}
}
public static void Postfix(bool __state)
{
if (__state) IsMining = false;
}
}
[HarmonyPatch(typeof(Destructible), "RPC_Damage")]
public static class Furling_Destructible_RPC_Damage_Patch
{
public static void Prefix(HitData hit, out bool __state)
{
__state = false;
if (hit == null) return;
Character attacker = hit.GetAttacker();
if (attacker != null && attacker == Player.m_localPlayer && FurlingRace.IsFurling() && BossProgressionManager.GetCurrentProgressionState() >= 5)
{
IsMining = true;
__state = true;
}
}
public static void Postfix(bool __state)
{
if (__state) IsMining = false;
}
}
[HarmonyPatch(typeof(DropTable), "GetDropList", new System.Type[] { typeof(int) })]
public static class Furling_DropTable_GetDropList_Patch
{
public static void Postfix(ref System.Collections.Generic.List<GameObject> __result)
{
if (IsMining && __result != null)
{
var extraDrops = new System.Collections.Generic.List<GameObject>();
foreach (var go in __result)
{
if (go == null) continue;
string lower = go.name.ToLower();
if (lower.Contains("copperore") || lower.Contains("tinore") || lower.Contains("ironscrap") || lower.Contains("silverore") || lower.Contains("blackmetalscrap") || lower.Contains("flametalore"))
{
extraDrops.Add(go);
}
}
__result.AddRange(extraDrops);
}
}
}
// ── "In the Mist He/She Was Standing" (The Queen, state >= 7) ─────────
// Eitr foods (blue foods) have double digestion time.
// We halve the rate at which food m_time decrements for eitr foods.
[HarmonyPatch(typeof(Player), "UpdateFood")]
public static class Furling_UpdateFood_EitrDuration_Patch
{
// Prefix: halve dt for eitr foods by doubling the denominator via a custom flag
// Easiest approach: Postfix after the vanilla update, then undo half the time consumed.
public static void Postfix(Player __instance, float dt)
{
if (__instance != Player.m_localPlayer) return;
if (!FurlingRace.IsFurling()) return;
if (BossProgressionManager.GetCurrentProgressionState() < 7) return;
// Valheim decrements food.m_time by dt each call.
// We give back half of dt for eitr foods, effectively halving consumption.
var foods = HarmonyLib.Traverse.Create(__instance).Field<System.Collections.Generic.List<Player.Food>>("m_foods").Value;
if (foods == null) return;
foreach (var food in foods)
{
if (food == null || food.m_item == null) continue;
// Blue food = eitr > 0
if (food.m_item.m_shared.m_foodEitr > 0f)
{
// Give back half of dt that vanilla subtracted
food.m_time += dt * 0.5f;
// Clamp to max burn time so we don't exceed the original duration
float maxTime = food.m_item.m_shared.m_foodBurnTime;
if (food.m_time > maxTime) food.m_time = maxTime;
}
}
}
}
}
}