Initial commit

This commit is contained in:
Ferdinando 2026-07-30 19:00:13 +02:00
commit c4a24c9fdf
142 changed files with 15491 additions and 0 deletions

View file

@ -0,0 +1,110 @@
using HarmonyLib;
using UnityEngine;
using UnityEngine.UI;
namespace RacesOfValheim
{
[HarmonyPatch]
public static class AswidExtraFoodUI
{
private static GameObject AswidFoodUIBase;
private static Image AswidFoodIcon;
private static GameObject AswidFoodTimeObj;
[HarmonyPatch(typeof(Hud), "Awake")]
[HarmonyPostfix]
public static void Awake_Postfix(Hud __instance)
{
Transform healthPanel = __instance.transform.Find("hudroot/healthpanel");
if (healthPanel == null) return;
Transform food1 = healthPanel.Find("food1");
Transform food2 = healthPanel.Find("food2");
if (food1 == null || food2 == null) return;
// Clone food2
GameObject food3 = UnityEngine.Object.Instantiate(food2.gameObject, healthPanel);
food3.name = "AswidExtraFoodSlot";
// Calculate vertical offset (distance between slot 1 and 2)
float offset = food2.localPosition.y - food1.localPosition.y;
food3.transform.localPosition = food2.localPosition + new Vector3(0, offset, 0);
AswidFoodUIBase = food3;
AswidFoodIcon = food3.transform.Find("foodicon2")?.GetComponent<Image>();
if (AswidFoodIcon == null) AswidFoodIcon = food3.transform.Find("icon")?.GetComponent<Image>(); // Fallback
AswidFoodTimeObj = food3.transform.Find("time")?.gameObject;
AswidFoodUIBase.SetActive(false);
}
[HarmonyPatch(typeof(Hud), "UpdateFood")]
[HarmonyPostfix]
public static void UpdateFood_Postfix(Hud __instance)
{
if (AswidFoodUIBase == null) return;
bool show4th = BossProgressionManager.GetCurrentProgressionState() >= 8;
if (Player.m_localPlayer == null || !AswidRace.IsAswid() || !show4th)
{
AswidFoodUIBase.SetActive(false);
return;
}
AswidFoodUIBase.SetActive(true);
UpdateSlotUI(Player.m_localPlayer, AswidFoodManager.ExtraFoods, AswidFoodIcon, AswidFoodTimeObj);
}
private static void UpdateSlotUI(Player player, System.Collections.Generic.Dictionary<Player, Player.Food> dict, Image icon, GameObject timeObj)
{
if (dict.TryGetValue(player, out Player.Food extraFood) && extraFood != null)
{
if (icon != null)
{
icon.sprite = extraFood.m_item.GetIcon();
icon.gameObject.SetActive(true);
bool canEat = extraFood.m_time >= (extraFood.m_item.m_shared.m_foodBurnTime * 0.5f);
if (canEat) icon.color = new Color(1f, 1f, 1f, Mathf.Sin(Time.time * 10f) * 0.5f + 0.5f);
else icon.color = Color.white;
}
if (timeObj != null)
{
timeObj.SetActive(true);
float remaining = extraFood.m_item.m_shared.m_foodBurnTime - extraFood.m_time;
if (remaining < 0) remaining = 0;
string timeStr = remaining < 60f ? Mathf.CeilToInt(remaining).ToString() + "s" : Mathf.CeilToInt(remaining / 60f).ToString() + "m";
bool canEat = extraFood.m_time >= (extraFood.m_item.m_shared.m_foodBurnTime * 0.5f);
Color timeCol = canEat ? new Color(1f, 0.5f, 0.5f, Mathf.Sin(Time.time * 10f) * 0.5f + 0.5f) : Color.white;
UpdateTextComponent(timeObj, timeStr, timeCol);
}
}
else
{
if (icon != null) icon.gameObject.SetActive(false);
if (timeObj != null) timeObj.SetActive(false);
}
}
private static void UpdateTextComponent(GameObject obj, string text, Color color)
{
var unityText = obj.GetComponent<UnityEngine.UI.Text>();
if (unityText != null)
{
unityText.text = text;
unityText.color = color;
}
var tmpText = obj.GetComponent("TMPro.TMP_Text");
if (tmpText != null)
{
var textProp = tmpText.GetType().GetProperty("text");
if (textProp != null) textProp.SetValue(tmpText, text, null);
var colorProp = tmpText.GetType().GetProperty("color");
if (colorProp != null) colorProp.SetValue(tmpText, color, null);
}
}
}
}

View file

@ -0,0 +1,88 @@
using System.Collections.Generic;
using UnityEngine;
namespace RacesOfValheim
{
public static class AswidFoodManager
{
// Runtime dictionary holding the 4th food slot per player
public static Dictionary<Player, Player.Food> ExtraFoods = new Dictionary<Player, Player.Food>();
// Called when player spawns to load the 4th food from custom data
public static void LoadFood(Player player)
{
if (player == null) return;
// If they are no longer an Aswid, clear it out
if (!AswidRace.IsAswid())
{
ClearFood(player);
return;
}
if (!player.m_customData.ContainsKey("AswidFood_Prefab")) return;
string prefabName = player.m_customData["AswidFood_Prefab"];
GameObject prefab = ObjectDB.instance.GetItemPrefab(prefabName);
if (prefab == null) return;
ItemDrop itemDrop = prefab.GetComponent<ItemDrop>();
if (itemDrop == null) return;
// Build food object
Player.Food food = new Player.Food();
food.m_item = itemDrop.m_itemData.Clone(); // Clone to be safe
// Try parse remaining time
if (player.m_customData.TryGetValue("AswidFood_Time", out string timeStr) && float.TryParse(timeStr, System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out float time))
{
food.m_time = time;
}
food.m_health = itemDrop.m_itemData.m_shared.m_food;
food.m_stamina = itemDrop.m_itemData.m_shared.m_foodStamina;
food.m_eitr = itemDrop.m_itemData.m_shared.m_foodEitr;
ExtraFoods[player] = food;
}
// Called to save the current runtime 4th food to custom data for persistence
public static void SaveFood(Player player)
{
if (player == null) return;
if (ExtraFoods.TryGetValue(player, out Player.Food food) && food != null && food.m_item != null)
{
player.m_customData["AswidFood_Prefab"] = food.m_item.m_dropPrefab.name;
player.m_customData["AswidFood_Time"] = food.m_time.ToString(System.Globalization.CultureInfo.InvariantCulture);
}
else
{
player.m_customData.Remove("AswidFood_Prefab");
player.m_customData.Remove("AswidFood_Time");
}
}
public static void ClearFood(Player player)
{
ExtraFoods.Remove(player);
if (player != null)
{
player.m_customData.Remove("AswidFood_Prefab");
player.m_customData.Remove("AswidFood_Time");
}
}
public static void SetExtraFood(Player player, ItemDrop.ItemData item)
{
Player.Food food = new Player.Food();
food.m_item = item.Clone();
food.m_time = 0f;
food.m_health = item.m_shared.m_food;
food.m_stamina = item.m_shared.m_foodStamina;
food.m_eitr = item.m_shared.m_foodEitr;
ExtraFoods[player] = food;
SaveFood(player);
}
}
}

View file

@ -0,0 +1,776 @@
using HarmonyLib;
using UnityEngine;
using System.Linq;
namespace RacesOfValheim
{
[HarmonyPatch(typeof(VisEquipment), "UpdateColors")]
public static class AswidSkinColorPatch
{
private static readonly Color SkinColor = new Color(0.96f, 0.97f, 0.98f, 1f);
private static readonly Color HairColor = new Color(1f, 1f, 1f, 1f);
public static void Postfix(VisEquipment __instance)
{
if (!__instance.m_isPlayer) return;
Player player = __instance.GetComponent<Player>();
if (player == null) return;
string race = "Human";
ZNetView nview = player.GetComponent<ZNetView>();
if (nview != null && nview.IsValid())
race = nview.GetZDO().GetString("RacesOfValheim_Race", "Human");
else if (player.m_customData != null && player.m_customData.TryGetValue("Race", out string savedRace))
race = savedRace;
if (race != "Aswid") return;
int state = 0;
if (nview != null && nview.IsValid())
state = nview.GetZDO().GetInt("RacesOfValheim_AswidState", 0);
Color currentHairColor = state >= 8 ? new Color(0.02f, 0.02f, 0.02f, 1f) : HairColor;
if (__instance.m_bodyModel != null && __instance.m_bodyModel.material != null)
__instance.m_bodyModel.material.SetColor("_SkinColor", SkinColor);
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", currentHairColor);
var beardInst = Traverse.Create(__instance).Field("m_beardItemInstance").GetValue<GameObject>();
if (beardInst != null)
foreach (var r in beardInst.GetComponentsInChildren<Renderer>())
if (r.material != null) r.material.SetColor("_SkinColor", currentHairColor);
}
}
[HarmonyPatch(typeof(SEMan), "AddStatusEffect", new System.Type[] { typeof(int), typeof(bool), typeof(int), typeof(float) })]
public static class AswidSEManPatch
{
public static bool Prefix(SEMan __instance, ref int nameHash)
{
Character character = Traverse.Create(__instance).Field<Character>("m_character").Value;
if (character == Player.m_localPlayer && AswidRace.IsAswid())
{
int state = BossProgressionManager.GetCurrentProgressionState();
if (state >= 5 && nameHash == "Freezing".GetStableHashCode())
{
return false;
}
// Cold immunity is removed as per user request to test native Cold VFX
// if (nameHash == "Cold".GetStableHashCode())
// {
// return false;
// }
}
return true;
}
}
[HarmonyPatch(typeof(Attack), "Start")]
public static class Aswid_BloodMagicCost_Patch
{
private static float savedHealthCost = 0f;
private static float savedHealthPercentage = 0f;
public static void Prefix(Attack __instance, Humanoid character, ref bool __state)
{
var weapon = Traverse.Create(__instance).Field("m_weapon").GetValue<ItemDrop.ItemData>();
if (weapon == null) weapon = Traverse.Create(__instance).Method("GetWeapon").GetValue<ItemDrop.ItemData>();
if (character == Player.m_localPlayer && AswidRace.IsAswid() && weapon != null && weapon.m_shared.m_skillType == Skills.SkillType.BloodMagic)
{
__state = true;
savedHealthCost = weapon.m_shared.m_attack.m_attackHealth;
savedHealthPercentage = weapon.m_shared.m_attack.m_attackHealthPercentage;
weapon.m_shared.m_attack.m_attackHealth = 0f;
weapon.m_shared.m_attack.m_attackHealthPercentage = 0f;
}
else
{
__state = false;
}
}
public static void Postfix(Attack __instance, Humanoid character, bool __state)
{
var weapon = Traverse.Create(__instance).Field("m_weapon").GetValue<ItemDrop.ItemData>();
if (weapon == null) weapon = Traverse.Create(__instance).Method("GetWeapon").GetValue<ItemDrop.ItemData>();
if (__state && weapon != null)
{
weapon.m_shared.m_attack.m_attackHealth = savedHealthCost;
weapon.m_shared.m_attack.m_attackHealthPercentage = savedHealthPercentage;
}
}
}
public static class AswidPatches
{
public static System.Collections.Generic.Dictionary<ZDOID, float> RecentlyLifeDrained = new System.Collections.Generic.Dictionary<ZDOID, float>();
}
[HarmonyPatch(typeof(Character), "Damage")]
public static class Aswid_LifeDrainKill_Patch
{
public static void Postfix(Character __instance, HitData hit)
{
if (hit != null && hit.m_attacker == Player.m_localPlayer?.GetZDOID())
{
Debug.LogWarning($"[Aswid_Patch] Local player damaged {__instance.name}. IsDead: {__instance.IsDead()}");
}
if (__instance.IsDead() && hit != null)
{
if (Player.m_localPlayer != null && hit.m_attacker == Player.m_localPlayer.GetZDOID())
{
ZNetView cNetView = __instance.GetComponent<ZNetView>();
if (AswidRace.IsAswid() && cNetView != null && cNetView.IsValid())
{
ZDOID zdoid = __instance.GetZDOID();
if (AswidPatches.RecentlyLifeDrained.TryGetValue(zdoid, out float timeHit))
{
if (Time.time - timeHit < 1.0f)
{
Debug.LogWarning($"[Aswid] {__instance.name} died within 1s of LifeDrain. Consuming!");
AswidRace.TryConsumeMob(__instance, __instance.GetMaxHealth());
AswidPatches.RecentlyLifeDrained.Remove(zdoid);
}
}
}
}
}
}
}
[HarmonyPatch(typeof(Character), "Awake")]
public static class Aswid_Awake_Patch
{
public static void Postfix(Character __instance)
{
if (__instance.GetComponent<MonsterAI>() != null && !__instance.IsBoss() && __instance.m_faction != Character.Faction.Demon && __instance.GetComponent<Tameable>() == null)
{
if (__instance.GetComponent<AswidThrall>() == null)
{
__instance.gameObject.AddComponent<AswidThrall>();
}
}
}
}
[HarmonyPatch(typeof(Player), "GetBodyArmor")]
public static class Aswid_ArmorBonus_Patch
{
public static void Postfix(Player __instance, ref float __result)
{
if (__instance == Player.m_localPlayer && AswidRace.IsAswid())
{
int state = BossProgressionManager.GetCurrentProgressionState();
float multiplier = (EnvMan.instance != null && EnvMan.IsNight()) ? 2f : 1f;
__result += 1f * state * multiplier;
}
}
}
[HarmonyPatch]
public static class Aswid_DamageBonus_Patch
{
[HarmonyTargetMethod]
public static System.Reflection.MethodBase TargetMethod()
{
return System.Linq.Enumerable.FirstOrDefault(
HarmonyLib.AccessTools.GetDeclaredMethods(typeof(ItemDrop.ItemData)),
m => m.Name == "GetDamage" && m.ReturnType == typeof(HitData.DamageTypes)
);
}
public static void Postfix(ItemDrop.ItemData __instance, ref HitData.DamageTypes __result)
{
if (Player.m_localPlayer != null && AswidRace.IsAswid() &&
Player.m_localPlayer.GetInventory().ContainsItem(__instance))
{
int state = BossProgressionManager.GetCurrentProgressionState();
if (state > 0)
{
float multiplier = (EnvMan.instance != null && EnvMan.IsNight()) ? 2f : 1f;
float bonus = 2f * state * multiplier;
// Add flat bonus to physical damage types that the weapon already has
if (__result.m_slash > 0) __result.m_slash += bonus;
if (__result.m_blunt > 0) __result.m_blunt += bonus;
if (__result.m_pierce > 0) __result.m_pierce += bonus;
if (__result.m_chop > 0) __result.m_chop += bonus;
if (__result.m_pickaxe > 0) __result.m_pickaxe += bonus;
}
}
}
}
[HarmonyPatch(typeof(Humanoid), "StartAttack")]
public static class Aswid_Attack_Patch
{
public static bool Prefix(Humanoid __instance)
{
if (__instance == Player.m_localPlayer)
{
if (__instance.GetComponentInChildren<BatFormBehavior>() != null)
{
return false;
}
if (__instance.GetSEMan().HaveStatusEffect("SE_MistForm".GetStableHashCode()))
{
return false;
}
}
return true;
}
}
[HarmonyPatch(typeof(Character), "SetRun")]
public static class Aswid_Run_Patch
{
public static void Prefix(Character __instance, ref bool run)
{
if (__instance == Player.m_localPlayer)
{
if (Player.m_localPlayer.GetSEMan().HaveStatusEffect("SE_MistForm".GetStableHashCode()))
{
run = false;
}
}
}
}
[HarmonyPatch(typeof(Character), "Jump")]
public static class Aswid_Jump_Patch
{
public static bool Prefix(Character __instance)
{
if (__instance == Player.m_localPlayer)
{
if (Player.m_localPlayer.GetSEMan().HaveStatusEffect("SE_MistForm".GetStableHashCode()))
{
return false;
}
}
return true;
}
}
[HarmonyPatch(typeof(Player), "OnSpawned")]
public static class Aswid_PlayerOnSpawned_Patch
{
public static void Postfix(Player __instance)
{
if (__instance == Player.m_localPlayer)
{
AswidFoodManager.LoadFood(__instance);
}
}
}
[HarmonyPatch(typeof(Player), "CanConsumeItem")]
public static class Aswid_CanConsumeItem_Patch
{
public static void Postfix(Player __instance, ItemDrop.ItemData item, ref bool __result)
{
if (__instance == Player.m_localPlayer && AswidRace.IsAswid() && item != null && item.m_shared != null && item.m_shared.m_name.StartsWith("Aswid Food:"))
{
var foods = HarmonyLib.Traverse.Create(__instance).Field("m_foods").GetValue<System.Collections.IList>();
if (foods != null)
{
if (foods.Count >= 3)
{
bool canUse4th = BossProgressionManager.GetCurrentProgressionState() >= 8;
bool has4th = AswidFoodManager.ExtraFoods.TryGetValue(__instance, out Player.Food extraFood) && extraFood != null;
if (canUse4th && (!has4th || extraFood.m_time >= (extraFood.m_item.m_shared.m_foodBurnTime * 0.5f)))
{
__result = true; // Consente l'uso del 4° slot se disponibile
}
else
{
__result = false; // Nessuno spazio disponibile, cibo si disintegra
}
}
else
{
__result = true; // Spazio nei primi 3 slot
}
}
}
}
}
[HarmonyPatch(typeof(Player), "EatFood")]
public static class Aswid_EatFood_Patch
{
private static System.Collections.Generic.List<object> hiddenFoods = new System.Collections.Generic.List<object>();
public static bool Prefix(Player __instance, ItemDrop.ItemData item, ref bool __result)
{
hiddenFoods.Clear();
if (__instance == Player.m_localPlayer && AswidRace.IsAswid() && item != null && item.m_shared != null && item.m_shared.m_name.StartsWith("Aswid Food:"))
{
var m_foods = HarmonyLib.Traverse.Create(__instance).Field("m_foods").GetValue<System.Collections.IList>();
if (m_foods != null)
{
if (m_foods.Count >= 3)
{
bool canUse4th = BossProgressionManager.GetCurrentProgressionState() >= 8;
if (canUse4th)
{
bool has4th = AswidFoodManager.ExtraFoods.TryGetValue(__instance, out Player.Food extraFood) && extraFood != null;
if (!has4th || extraFood.m_time >= (extraFood.m_item.m_shared.m_foodBurnTime * 0.5f))
{
AswidFoodManager.SetExtraFood(__instance, item);
// Play consume effects
var consumeEffects = HarmonyLib.Traverse.Create(__instance).Field("m_consumeItemEffects").GetValue<EffectList>();
if (consumeEffects != null)
{
consumeEffects.Create(__instance.transform.position, Quaternion.identity, __instance.transform, 1f, -1);
}
var zanim = HarmonyLib.Traverse.Create(__instance).Field("m_zanim").GetValue<ZSyncAnimation>();
if (zanim != null)
{
zanim.SetTrigger("eat");
}
if (item.m_shared.m_food > 0f)
{
__instance.Heal(item.m_shared.m_food, true);
}
__result = true;
return false; // Skip native EatFood
}
}
// Se pieno e senza 4° slot disponibile, fallisce e disintegra
__result = false;
return false;
}
else
{
// Nascondiamo temporaneamente i duplicati nei primi 3 slot per costringere Valheim ad aggiungere un NUOVO slot
for (int i = m_foods.Count - 1; i >= 0; i--)
{
var foodObj = m_foods[i];
var foodItem = HarmonyLib.Traverse.Create(foodObj).Field("m_item").GetValue<ItemDrop.ItemData>();
if (foodItem != null && foodItem.m_shared.m_name == item.m_shared.m_name)
{
hiddenFoods.Add(foodObj);
m_foods.RemoveAt(i);
}
}
}
}
}
return true;
}
public static void Postfix(Player __instance, ItemDrop.ItemData item, ref bool __result)
{
if (hiddenFoods.Count > 0)
{
var m_foods = HarmonyLib.Traverse.Create(__instance).Field("m_foods").GetValue<System.Collections.IList>();
if (m_foods != null)
{
// Ripristiniamo i duplicati nascosti
foreach (var hf in hiddenFoods)
{
m_foods.Add(hf);
}
}
hiddenFoods.Clear();
}
}
}
[HarmonyPatch(typeof(Tameable), "GetHoverText")]
public static class Aswid_TameHoverText_Patch
{
public static void Postfix(Tameable __instance, ref string __result)
{
if (Player.m_localPlayer == null || !AswidRace.IsAswid()) return;
if (__instance.GetComponent<Character>()?.IsTamed() == true) return;
string prefabName = __instance.gameObject.name.ToLower();
int state = BossProgressionManager.GetCurrentProgressionState();
bool canTame = false;
if (state >= 2 && prefabName.Contains("boar")) canTame = true;
if (state >= 5 && prefabName.Contains("wolf")) canTame = true;
if (state >= 6 && prefabName.Contains("lox")) canTame = true;
if (state >= 8 && prefabName.Contains("asksvin")) canTame = true;
if (canTame)
{
__result += "\n[<color=yellow><b></b></color>] Tame";
}
}
}
[HarmonyPatch(typeof(Tameable), "Interact")]
public static class Aswid_TameInteract_Patch
{
public static bool Prefix(Tameable __instance, Humanoid user, bool hold, bool alt)
{
if (hold || alt) return true;
if (user != Player.m_localPlayer || !AswidRace.IsAswid()) return true;
if (__instance.GetComponent<Character>()?.IsTamed() == true) return true;
string prefabName = __instance.gameObject.name.ToLower();
int state = BossProgressionManager.GetCurrentProgressionState();
bool canTame = false;
if (state >= 2 && prefabName.Contains("boar")) canTame = true;
if (state >= 5 && prefabName.Contains("wolf")) canTame = true;
if (state >= 6 && prefabName.Contains("lox")) canTame = true;
if (state >= 8 && prefabName.Contains("asksvin")) canTame = true;
if (canTame)
{
__instance.GetComponent<Character>()?.SetTamed(true);
HarmonyLib.Traverse.Create(__instance).Method("Tame").GetValue(); // attempt to call Tame for VFX if it exists
__instance.Command(user);
user.Message(MessageHud.MessageType.Center, "Tamed!");
return false; // Skip original interact
}
return true;
}
}
[HarmonyPatch(typeof(Hud), "UpdateStamina")]
public static class Aswid_HideStamina_Patch
{
public static bool Prefix(Hud __instance, Player player)
{
if (player == Player.m_localPlayer && AswidRace.IsAswid())
{
if (__instance.m_staminaBar2Root != null && __instance.m_staminaBar2Root.gameObject.activeSelf)
{
__instance.m_staminaBar2Root.gameObject.SetActive(false);
}
return false;
}
return true;
}
}
[HarmonyPatch(typeof(StatusEffect), "Setup")]
public static class Aswid_ColdStatus_Patch
{
public static void Prefix(StatusEffect __instance, Character character)
{
if (character == Player.m_localPlayer && AswidRace.IsAswid() && (__instance.name.Contains("Cold") || __instance.m_name == "$se_cold_name"))
{
var wraithTrophy = Jotunn.Managers.PrefabManager.Cache.GetPrefab<ItemDrop>("TrophyWraith");
if (wraithTrophy != null && wraithTrophy.m_itemData.m_shared.m_icons.Length > 0)
{
__instance.m_icon = wraithTrophy.m_itemData.m_shared.m_icons[0];
}
else
{
__instance.m_icon = null;
}
__instance.m_name = "Night Aura";
__instance.m_startMessage = ""; // "The darkness empowers you.";
__instance.m_tooltip = "The cold strengthens your beastly senses.";
if (__instance is SE_Stats stats)
{
stats.m_healthRegenMultiplier = 1f;
stats.m_staminaRegenMultiplier = 1f;
stats.m_staminaDrainPerSec = 0f;
stats.m_speedModifier = 0f;
}
}
}
}
[HarmonyPatch(typeof(Player), "Update")]
public static class Aswid_PlayerUpdate_Patch
{
public static void Postfix(Player __instance)
{
if (__instance == null) return;
ZNetView nview = __instance.GetComponent<ZNetView>();
if (nview != null && nview.IsValid() && nview.GetZDO().GetString("RacesOfValheim_Race", "Human") == "Aswid")
{
if (__instance == Player.m_localPlayer && Input.GetKeyDown(KeyCode.I))
{
AswidRace.DevourEnabled = !AswidRace.DevourEnabled;
string msg = AswidRace.DevourEnabled ? "Abilità Divora: ATTIVATA" : "Abilità Divora: DISATTIVATA";
__instance.Message(MessageHud.MessageType.Center, msg);
}
int state = BossProgressionManager.GetCurrentProgressionState();
var rules = AswidProgression.GetRules(state);
if (AswidRace.Instance != null && !AswidRace.Instance.IsTransformed)
{
if (rules != null && rules.HasSurtlingForm)
{
__instance.transform.localScale = new Vector3(1.1f, 1.1f, 1.1f);
}
else
{
__instance.transform.localScale = Vector3.one;
}
}
}
}
}
[HarmonyPatch(typeof(VisEquipment), "UpdateVisuals")]
public static class Aswid_MultiplayerVisuals_Patch
{
public static void Postfix(VisEquipment __instance)
{
if (!__instance.m_isPlayer) return;
Player player = __instance.GetComponent<Player>();
if (player == null || player.IsOwner()) return; // Only process for remote players
ZNetView nview = player.GetComponent<ZNetView>();
if (nview != null && nview.IsValid() && nview.GetZDO().GetString("RacesOfValheim_Race", "Human") == "Aswid")
{
bool isBat = nview.GetZDO().GetBool("Aswid_IsBatForm", false);
bool isMist = nview.GetZDO().GetBool("Aswid_IsMistForm", false);
Transform playerVisual = player.transform.Find("Visual");
// Bat logic
Transform batBody = player.transform.Find("AswidBody_Bat");
if (isBat && batBody == null) {
GameObject batPrefab = Jotunn.Managers.PrefabManager.Cache.GetPrefab<GameObject>("Bat");
if (batPrefab != null) {
GameObject visualPrefab = batPrefab.GetComponentInChildren<Animator>()?.gameObject;
if (visualPrefab != null) {
GameObject batInstance = UnityEngine.Object.Instantiate(visualPrefab, player.transform.position, player.transform.rotation, player.transform);
batInstance.name = "AswidBody_Bat";
batInstance.transform.localPosition = Vector3.zero;
}
}
} else if (!isBat && batBody != null) {
UnityEngine.Object.Destroy(batBody.gameObject);
}
// Mist logic
Transform mistBody = player.transform.Find("AswidBody_Mist");
if (isMist && mistBody == null) {
GameObject wraithPrefab = Jotunn.Managers.PrefabManager.Cache.GetPrefab<GameObject>("Wraith");
if (wraithPrefab != null) {
GameObject visualPrefab = wraithPrefab.transform.Find("Visual")?.gameObject;
if (visualPrefab != null) {
GameObject mistInstance = UnityEngine.Object.Instantiate(visualPrefab, player.transform.position, player.transform.rotation, player.transform);
mistInstance.name = "AswidBody_Mist";
mistInstance.transform.localPosition = Vector3.zero;
mistInstance.transform.localScale = Vector3.one;
foreach (var r in mistInstance.GetComponentsInChildren<Renderer>())
{
if (r.material != null && r.material.HasProperty("_Color"))
{
Color c = r.material.GetColor("_Color");
c.a = 0.3f; // Make transparent
r.material.SetColor("_Color", c);
}
}
}
}
} else if (!isMist && mistBody != null) {
UnityEngine.Object.Destroy(mistBody.gameObject);
}
// Toggle visibility
if (isBat || isMist) {
if (playerVisual != null) playerVisual.gameObject.SetActive(false);
} else {
if (playerVisual != null) playerVisual.gameObject.SetActive(true);
}
}
}
}
[HarmonyPatch(typeof(Player), "Update")]
public static class Aswid_Debug_F8_Patch
{
public static void Postfix(Player __instance)
{
if (__instance == Player.m_localPlayer && UnityEngine.Input.GetKeyDown(UnityEngine.KeyCode.F8))
{
Jotunn.Logger.LogInfo("[AswidDebug] F8 pressed! Finding nearest mob to consume...");
Character nearest = null;
float minDist = 10f;
foreach (Character c in Character.GetAllCharacters())
{
if (c != __instance && c.GetHealth() > 0)
{
float dist = UnityEngine.Vector3.Distance(__instance.transform.position, c.transform.position);
if (dist < minDist)
{
minDist = dist;
nearest = c;
}
}
}
if (nearest != null)
{
Jotunn.Logger.LogInfo($"[AswidDebug] Consuming {nearest.name} via F8!");
AswidRace.TryConsumeMob(nearest, nearest.GetMaxHealth());
HitData hit = new HitData();
hit.m_damage.m_damage = 99999f;
hit.m_hitType = HitData.HitType.Undefined;
hit.m_attacker = __instance.GetZDOID();
nearest.ApplyDamage(hit, true, false);
}
else
{
Jotunn.Logger.LogInfo("[AswidDebug] No mob found near player to consume.");
}
}
}
}
[HarmonyPatch(typeof(Character), "Damage")]
public static class Aswid_Damage_Patch
{
public static void Prefix(Character __instance, HitData hit, out float __state)
{
__state = (__instance != null) ? __instance.GetHealth() : 0f;
}
public static void Postfix(Character __instance, HitData hit, float __state)
{
if (hit == null || __instance == null || __instance.IsPlayer()) return;
// Check if it died from this hit
if (__state > 0f && __instance.GetHealth() <= 0f)
{
Jotunn.Logger.LogInfo($"[AswidDebug] {__instance.name} died. __state: {__state}, CurrentHP: {__instance.GetHealth()}");
Character attacker = hit.GetAttacker();
if (attacker != null) Jotunn.Logger.LogInfo($"[AswidDebug] Attacker is: {attacker.name} / Player: {attacker.IsPlayer()} / Local: {attacker == Player.m_localPlayer}");
if (attacker != null && attacker.IsPlayer() && attacker == Player.m_localPlayer)
{
ZNetView nview = attacker.GetComponent<ZNetView>();
if (nview != null && nview.IsValid() && nview.GetZDO().GetString("RacesOfValheim_Race", "Human") == "Aswid")
{
Jotunn.Logger.LogInfo($"[AswidDebug] Attacker is local Aswid player. Checking damage type...");
// Check if physical attack
if (hit.m_damage.m_blunt > 0 || hit.m_damage.m_slash > 0 || hit.m_damage.m_pierce > 0 || hit.m_damage.m_chop > 0 || hit.m_damage.m_pickaxe > 0 || hit.m_damage.m_damage > 0)
{
Jotunn.Logger.LogInfo($"[AswidDebug] Calling TryConsumeMob for {__instance.name}");
AswidRace.TryConsumeMob(__instance, __instance.GetMaxHealth());
}
}
}
}
}
[HarmonyPatch(typeof(Player), "HaveEitr")]
public static class Player_HaveEitr_Patch
{
public static void Postfix(Player __instance, ref bool __result)
{
if (__instance != null && __instance == Player.m_localPlayer && AswidRace.IsAswid())
{
var weapon = __instance.GetCurrentWeapon();
if (weapon != null && weapon.m_shared != null && weapon.m_shared.m_skillType == Skills.SkillType.BloodMagic)
{
__result = true;
}
}
}
}
[HarmonyPatch(typeof(Player), "UseEitr")]
public static class Player_UseEitr_Patch
{
public static bool Prefix(Player __instance)
{
if (__instance != null && __instance == Player.m_localPlayer && AswidRace.IsAswid())
{
var weapon = __instance.GetCurrentWeapon();
if (weapon != null && weapon.m_shared != null && weapon.m_shared.m_skillType == Skills.SkillType.BloodMagic)
{
return false; // Skip spending Eitr
}
}
return true;
}
}
[HarmonyPatch(typeof(Skills), "RaiseSkill")]
public static class Aswid_Skills_RaiseSkill_Patch
{
public static void Prefix(Skills __instance, Skills.SkillType skillType, ref float factor)
{
Player player = HarmonyLib.Traverse.Create(__instance).Field("m_player").GetValue<Player>();
if (player != null && player == Player.m_localPlayer && AswidRace.IsAswid())
{
if (skillType == Skills.SkillType.BloodMagic)
{
factor *= 2f; // Benedictus et Afflictus: Double speed for Blood Magic
}
}
}
}
}
[HarmonyPatch(typeof(Player), "UpdateFood")]
public static class Aswid_PlayerUpdateFood_Patch
{
public static void Prefix(Player __instance, float dt, bool forceUpdate)
{
if (__instance != Player.m_localPlayer || !AswidRace.IsAswid()) return;
if (AswidFoodManager.ExtraFoods.TryGetValue(__instance, out Player.Food extraFood) && extraFood != null)
{
extraFood.m_time += dt;
if (extraFood.m_item != null && extraFood.m_item.m_shared != null)
{
if (extraFood.m_time >= extraFood.m_item.m_shared.m_foodBurnTime)
{
AswidFoodManager.ClearFood(__instance);
}
else
{
float factor = extraFood.m_time / extraFood.m_item.m_shared.m_foodBurnTime;
extraFood.m_health = Mathf.Lerp(extraFood.m_item.m_shared.m_food, extraFood.m_item.m_shared.m_food * 0.2f, factor);
extraFood.m_stamina = Mathf.Lerp(extraFood.m_item.m_shared.m_foodStamina, extraFood.m_item.m_shared.m_foodStamina * 0.2f, factor);
extraFood.m_eitr = Mathf.Lerp(extraFood.m_item.m_shared.m_foodEitr, extraFood.m_item.m_shared.m_foodEitr * 0.2f, factor);
}
}
}
}
}
[HarmonyPatch(typeof(Player), "GetTotalFoodValue")]
public static class Aswid_PlayerGetTotalFoodValue_Patch
{
public static void Postfix(Player __instance, ref float hp, ref float stamina, ref float eitr)
{
if (__instance != Player.m_localPlayer || !AswidRace.IsAswid()) return;
if (AswidFoodManager.ExtraFoods.TryGetValue(__instance, out Player.Food extraFood) && extraFood != null)
{
hp += extraFood.m_health;
stamina += extraFood.m_stamina;
eitr += extraFood.m_eitr;
}
}
}
}

View file

@ -0,0 +1,62 @@
using System;
using UnityEngine;
namespace RacesOfValheim
{
public static class AswidProgression
{
public enum FormType
{
None,
Bat
}
public class FormRules
{
public FormType Form = FormType.None;
public bool NeedsNight = false;
}
public class AswidRules
{
// Add state 0 properties here
public float BonusHealth = 0f;
public float BonusStamina = 0f;
public bool HasSurtlingForm = false;
}
public static AswidRules GetRules(int state)
{
AswidRules rules = new AswidRules();
// State 0 is the base state, no modifiers yet.
if (state >= 1)
{
// Future modifiers
}
if (state >= 8) // Fader
{
rules.HasSurtlingForm = true;
}
return rules;
}
public static FormRules GetGKeyRules(int state)
{
FormRules rules = new FormRules();
if (state >= 3)
{
rules.Form = FormType.Bat;
rules.NeedsNight = false; // The Elder: always
}
else if (state >= 2)
{
rules.Form = FormType.Bat;
rules.NeedsNight = true; // Eikthyr: night only
}
return rules.Form != FormType.None ? rules : null;
}
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,145 @@
using Jotunn.Managers;
using Jotunn.Entities;
using System;
using UnityEngine;
namespace RacesOfValheim
{
public class SE_AswidStats : SE_Stats
{
public override void Setup(Character character)
{
base.Setup(character);
name = "SE_AswidStats";
m_name = "Benedictus et Afflictus";
m_tooltip = "Vampiric senses and life drain.";
}
public void UpdateStats(int state)
{
m_fallDamageModifier = -1f; // No fall damage
float multiplier = (EnvMan.instance != null && EnvMan.IsNight()) ? 2f : 1f;
m_speedModifier = 0.01f * state * multiplier; // +3% speed per stage (*2 at night)
// For jump, Valheim SE_Stats typically adds the y value to 1
m_jumpModifier = new Vector3(0f, 0.01f * state * multiplier, 0f);
if (state >= 5)
{
if (m_mods == null) m_mods = new System.Collections.Generic.List<HitData.DamageModPair>();
m_mods.Clear(); // Refresh to avoid duplicates
m_mods.Add(new HitData.DamageModPair() { m_type = HitData.DamageType.Poison, m_modifier = HitData.DamageModifier.Immune });
}
else
{
if (m_mods != null) m_mods.Clear();
}
}
public override void ModifyAttack(Skills.SkillType skill, ref HitData hitData)
{
base.ModifyAttack(skill, ref hitData);
if (m_character is Player p && p.GetComponent<ZNetView>() != null && p.GetComponent<ZNetView>().GetZDO() != null)
{
int state = BossProgressionManager.GetCurrentProgressionState();
var rules = AswidProgression.GetRules(state);
if (rules != null && rules.HasSurtlingForm)
{
hitData.m_damage.m_damage += 30f;
}
}
}
}
public class SE_BatForm : SE_Stats
{
public override void Setup(Character character)
{
base.Setup(character);
name = "SE_BatForm";
m_name = "Like a Bat out of Hell";
m_tooltip = "You have taken the form of a Bat. You can fly, but cannot attack.";
m_fallDamageModifier = -1f; // Immune to fall damage just in case
}
}
public class SE_MistForm : SE_Stats
{
public override void Setup(Character character)
{
base.Setup(character);
name = "SE_MistForm";
m_name = "Weight of Shadows";
m_tooltip = "You are mist. Immune to physical damage and poison. Cannot attack or run.";
m_fallDamageModifier = -1f;
m_mods = new System.Collections.Generic.List<HitData.DamageModPair>
{
new HitData.DamageModPair { m_type = HitData.DamageType.Blunt, m_modifier = HitData.DamageModifier.Immune },
new HitData.DamageModPair { m_type = HitData.DamageType.Slash, m_modifier = HitData.DamageModifier.Immune },
new HitData.DamageModPair { m_type = HitData.DamageType.Pierce, m_modifier = HitData.DamageModifier.Immune },
new HitData.DamageModPair { m_type = HitData.DamageType.Poison, m_modifier = HitData.DamageModifier.Immune }
};
}
}
public class SE_AswidSensesMark : SE_Stats
{
public override void Setup(Character character)
{
base.Setup(character);
name = "SE_AswidSensesMark";
m_name = "Sensed";
m_tooltip = "";
m_ttl = 2f;
m_icon = null; // No icon needed for mobs
}
}
public class SE_SuperhumanSenses : SE_Stats
{
public override void Setup(Character character)
{
base.Setup(character);
name = "SE_SuperhumanSenses";
m_name = "Auspex";
m_tooltip = "Sensing life force of nearby creatures.";
}
}
public class AswidStatusEffects
{
public static void RegisterStatusEffects()
{
var aswidStats = ScriptableObject.CreateInstance<SE_AswidStats>();
aswidStats.name = "SE_AswidStats";
aswidStats.m_icon = PrefabManager.Cache.GetPrefab<ItemDrop>("TrophyBat")?.m_itemData.m_shared.m_icons[0];
ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(aswidStats, fixReference: false));
var batForm = ScriptableObject.CreateInstance<SE_BatForm>();
batForm.name = "SE_BatForm";
batForm.m_icon = PrefabManager.Cache.GetPrefab<ItemDrop>("TrophyBat")?.m_itemData.m_shared.m_icons[0];
ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(batForm, fixReference: false));
var mistForm = ScriptableObject.CreateInstance<SE_MistForm>();
mistForm.name = "SE_MistForm";
mistForm.m_icon = PrefabManager.Cache.GetPrefab<ItemDrop>("TrophyWraith")?.m_itemData.m_shared.m_icons[0];
ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(mistForm, fixReference: false));
var sensesMark = ScriptableObject.CreateInstance<SE_AswidSensesMark>();
sensesMark.name = "SE_AswidSensesMark";
sensesMark.m_name = "Sensed";
sensesMark.m_ttl = 2f;
ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(sensesMark, fixReference: false));
var senses = ScriptableObject.CreateInstance<SE_SuperhumanSenses>();
senses.name = "SE_SuperhumanSenses";
senses.m_icon = PrefabManager.Cache.GetPrefab<ItemDrop>("TrophyWolf")?.m_itemData.m_shared.m_icons[0];
ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(senses, fixReference: false));
}
}
}

View file

@ -0,0 +1,159 @@
using UnityEngine;
using System;
namespace RacesOfValheim
{
public class AswidThrall : MonoBehaviour, Interactable, Hoverable
{
private Character m_character;
private MonsterAI m_ai;
private ZNetView m_nview;
private bool m_wasEnslaved = false;
private bool m_wasConsumed = false;
private void Awake()
{
m_character = GetComponent<Character>();
m_ai = GetComponent<MonsterAI>();
m_nview = GetComponent<ZNetView>();
}
private void Update()
{
if (m_nview == null || !m_nview.IsValid()) return;
bool isEnslaved = m_nview.GetZDO().GetBool("AswidEnslaved", false);
if (isEnslaved)
{
if (!m_wasEnslaved)
{
m_wasEnslaved = true;
m_character.SetTamed(true); // Ensure tamed is true on client side if it missed the RPC
if (m_ai != null)
{
// Custom AI behaviors can be set here if needed
}
}
// If it dies, the local player who owns it tries to consume it
if (m_character.IsDead() && !m_wasConsumed)
{
m_wasConsumed = true;
if (m_nview.IsOwner() && AswidRace.IsAswid())
{
AswidRace.TryConsumeMob(m_character, m_character.GetMaxHealth());
}
}
// Only the ZDO owner should track lifetime to kill it
if (m_nview.IsOwner())
{
long enslaveTime = m_nview.GetZDO().GetLong("AswidEnslaveTime", 0);
if (enslaveTime > 0)
{
DateTime time = new DateTime(enslaveTime);
if ((DateTime.Now - time).TotalSeconds >= 60.0)
{
// Time's up! Kill the thrall.
HitData hit = new HitData();
hit.m_damage.m_damage = 99999f;
hit.m_hitType = HitData.HitType.Undefined;
m_character.ApplyDamage(hit, true, false);
}
}
}
}
}
public bool Interact(Humanoid user, bool hold, bool alt)
{
if (hold || alt) return false;
if (m_nview == null || !m_nview.IsValid()) return false;
if (user != Player.m_localPlayer || !AswidRace.IsAswid()) return false;
bool isEnslaved = m_nview.GetZDO().GetBool("AswidEnslaved", false);
if (isEnslaved)
{
// Toggle follow/stay
if (m_ai != null)
{
if (m_ai.GetFollowTarget() == user.gameObject)
{
m_ai.SetFollowTarget(null);
user.Message(MessageHud.MessageType.Center, $"{m_character.m_name} is staying.");
}
else
{
m_ai.SetFollowTarget(user.gameObject);
user.Message(MessageHud.MessageType.Center, $"{m_character.m_name} is following.");
}
}
return true;
}
// Enslave action
if (BossProgressionManager.GetCurrentProgressionState() < 6) return false;
float cooldown = AswidRace.GetEnslaveCooldown();
if (cooldown > 0)
{
user.Message(MessageHud.MessageType.Center, $"Dominate on cooldown ({Mathf.CeilToInt(cooldown / 60f)}m {Mathf.CeilToInt(cooldown % 60f)}s)");
return false;
}
// Enslave it!
AswidRace.StartEnslaveCooldown();
// Take ownership to set ZDO vars reliably
m_nview.ClaimOwnership();
m_nview.GetZDO().Set("AswidEnslaved", true);
m_nview.GetZDO().Set("AswidEnslaveTime", DateTime.Now.Ticks);
m_character.SetTamed(true);
if (m_ai != null)
{
m_ai.SetFollowTarget(user.gameObject);
}
GameObject vfx = ZNetScene.instance.GetPrefab("vfx_surtling_death");
if (vfx) Instantiate(vfx, m_character.transform.position, Quaternion.identity);
user.Message(MessageHud.MessageType.Center, $"{m_character.m_name} dominated!");
return true;
}
public bool UseItem(Humanoid user, ItemDrop.ItemData item)
{
return false;
}
public string GetHoverText()
{
if (m_nview == null || !m_nview.IsValid()) return "";
if (Player.m_localPlayer == null || !AswidRace.IsAswid()) return "";
bool isEnslaved = m_nview.GetZDO().GetBool("AswidEnslaved", false);
if (isEnslaved)
{
bool following = m_ai != null && m_ai.GetFollowTarget() != null;
return following ? "[<color=yellow><b>E</b></color>] Stay" : "[<color=yellow><b>E</b></color>] Follow";
}
else
{
if (BossProgressionManager.GetCurrentProgressionState() < 6) return "";
float cd = AswidRace.GetEnslaveCooldown();
if (cd > 0) return $"[<color=red>E</color>] Dominate (Cooldown: {Mathf.CeilToInt(cd / 60f)}m)";
return "[<color=yellow><b>E</b></color>] Dominate";
}
}
public string GetHoverName()
{
return ""; // Character component already provides the name
}
}
}

View file

@ -0,0 +1,54 @@
using UnityEngine;
using Jotunn.Managers;
namespace RacesOfValheim
{
public class BatFormBehavior : MonoBehaviour
{
private Animator anim;
private AswidProgression.FormRules formRules;
public void Initialize(AswidProgression.FormRules rules)
{
this.formRules = rules;
}
private void Start()
{
anim = GetComponentInChildren<Animator>();
if (Player.m_localPlayer != null)
{
HarmonyLib.Traverse.Create(Player.m_localPlayer).Field("m_debugFly").SetValue(true);
}
}
private void Update()
{
if (Player.m_localPlayer == null || Player.m_localPlayer.IsDead()) return;
// Ensure flight remains on continuously
HarmonyLib.Traverse.Create(Player.m_localPlayer).Field("m_debugFly").SetValue(true);
// Sync Animator
if (anim != null)
{
Vector3 vel = Player.m_localPlayer.GetVelocity();
vel.y = 0f;
float speed = vel.magnitude;
// Bats don't necessarily have a complex animator like players,
// but if they do have a speed or flying parameter, we set it here.
anim.SetFloat("forward_speed", speed);
anim.SetBool("flying", true);
}
}
private void OnDestroy()
{
if (Player.m_localPlayer != null)
{
HarmonyLib.Traverse.Create(Player.m_localPlayer).Field("m_debugFly").SetValue(false);
}
}
}
}

View file

@ -0,0 +1,51 @@
using Jotunn.Managers;
using System.Collections.Generic;
namespace RacesOfValheim
{
public static class BossProgressionManager
{
public static int DebugState = -1; // [DEBUG] Da rimuovere in seguito
// Valheim Global Keys for bosses
public const string Eikthyr = "defeated_eikthyr";
public const string TheElder = "defeated_gdking";
public const string Bonemass = "defeated_bonemass";
public const string Moder = "defeated_dragon";
public const string Yagluth = "defeated_goblinking";
public const string TheQueen = "defeated_queen";
public const string Fader = "defeated_fader";
/// <summary>
/// Returns the current progression state of the world based on defeated bosses.
/// 1 = No bosses defeated
/// 2 = Eikthyr defeated
/// 3 = The Elder defeated
/// 4 = Bonemass defeated
/// 5 = Moder defeated
/// 6 = Yagluth defeated
/// 7 = The Queen defeated
/// 8 = Fader defeated
/// </summary>
public static int GetCurrentProgressionState()
{
if (DebugState != -1) return DebugState; // [DEBUG]
if (ZoneSystem.instance == null)
{
return 1; // Default to 1 if ZoneSystem isn't ready
}
// We check in reverse order (highest tier first)
if (ZoneSystem.instance.GetGlobalKey(Fader)) return 8;
if (ZoneSystem.instance.GetGlobalKey(TheQueen)) return 7;
if (ZoneSystem.instance.GetGlobalKey(Yagluth)) return 6;
if (ZoneSystem.instance.GetGlobalKey(Moder)) return 5;
if (ZoneSystem.instance.GetGlobalKey(Bonemass)) return 4;
if (ZoneSystem.instance.GetGlobalKey(TheElder)) return 3;
if (ZoneSystem.instance.GetGlobalKey(Eikthyr)) return 2;
return 1; // No bosses defeated
}
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,97 @@
using System.Collections;
using BepInEx;
using HarmonyLib;
using Jotunn.Configs;
using Jotunn.Entities;
using Jotunn.Managers;
using UnityEngine;
using UnityEngine.UI; // Added for UI
namespace RacesOfValheim
{
[HarmonyPatch(typeof(Character), nameof(Character.StartAttack))]
public static class BlockPlayerLogicAttackPatch
{
public static bool Prefix(Character __instance)
{
if (__instance != null && __instance == Player.m_localPlayer)
{
if (__instance.GetSEMan().HaveStatusEffect("SE_FenrirForm".GetStableHashCode()))
{
return false;
}
}
return true;
}
}
// --- PATCH 2: BLOCCO ANIMAZIONI ED EFFETTI SONORI NATIVI ---
[HarmonyPatch(typeof(ZSyncAnimation), nameof(ZSyncAnimation.SetTrigger))]
public static class BlockPlayerAnimationsPatch
{
public static bool Prefix(ZSyncAnimation __instance, string name)
{
if (Player.m_localPlayer != null && __instance.gameObject == Player.m_localPlayer.gameObject)
{
if (Player.m_localPlayer.GetSEMan().HaveStatusEffect("SE_FenrirForm".GetStableHashCode()))
{
string triggerName = name.ToLower();
if (triggerName.Contains("attack") || triggerName.Contains("swing") || triggerName.Contains("punch"))
{
return false;
}
}
}
return true;
}
}
[HarmonyPatch]
public static class FenrirDamagePatch
{
[HarmonyTargetMethod]
public static System.Reflection.MethodBase TargetMethod()
{
return System.Linq.Enumerable.FirstOrDefault(
HarmonyLib.AccessTools.GetDeclaredMethods(typeof(ItemDrop.ItemData)),
m => m.Name == "GetDamage" && m.ReturnType == typeof(HitData.DamageTypes)
);
}
public static void Postfix(ItemDrop.ItemData __instance, ref HitData.DamageTypes __result)
{
if (Player.m_localPlayer != null &&
Player.m_localPlayer.GetSEMan().HaveStatusEffect("SE_FenrirCurse".GetStableHashCode()) &&
Player.m_localPlayer.GetInventory().ContainsItem(__instance))
{
int state = BossProgressionManager.GetCurrentProgressionState();
if (state > 0)
{
float bonus = FenrirProgression.GetDamageBonus(state);
if (__result.m_slash > 0) __result.m_slash += bonus;
if (__result.m_blunt > 0) __result.m_blunt += bonus;
if (__result.m_pierce > 0) __result.m_pierce += bonus;
if (__result.m_chop > 0) __result.m_chop += bonus;
if (__result.m_pickaxe > 0) __result.m_pickaxe += bonus;
}
}
}
}
[HarmonyPatch(typeof(Player), nameof(Player.GetBodyArmor))]
public static class FenrirArmorPatch
{
public static void Postfix(Player __instance, ref float __result)
{
if (__instance != null && __instance == Player.m_localPlayer)
{
if (__instance.GetSEMan().HaveStatusEffect("SE_FenrirCurse".GetStableHashCode()))
{
int state = BossProgressionManager.GetCurrentProgressionState();
__result += FenrirProgression.GetArmorBonus(state);
}
}
}
}
}

View file

@ -0,0 +1,84 @@
using System;
using UnityEngine;
namespace RacesOfValheim
{
public static class FenrirProgression
{
public enum FormType
{
None,
Wolf,
Ulv,
Fenring,
Cultist
}
public class FormRules
{
public FormType Form;
public bool NeedsNight;
public float DurationMinutes;
public float CooldownMinutes;
public FormRules(FormType form, bool needsNight, float duration, float cooldown)
{
Form = form;
NeedsNight = needsNight;
DurationMinutes = duration;
CooldownMinutes = cooldown;
}
}
public static float GetArmorBonus(int state)
{
return 3f * state;
}
public static float GetDamageBonus(int state)
{
return 5f * state;
}
public static float GetFallDamageModifier(int state)
{
return Mathf.Clamp(-0.1f * state, -1f, 0f);
}
public static float GetSpeedModifier(int state)
{
return 0.03f * state;
}
public static float GetJumpModifier(int state)
{
return 0.03f * state;
}
// --- Transformation Rules for Keys ---
public static FormRules GetGKeyRules(int state)
{
if (state >= 5) return new FormRules(FormType.Ulv, false, 0f, 0f); // Moder: Ulv (Day/Night)
if (state >= 4) return new FormRules(FormType.Wolf, false, 0f, 0f); // Bonemass: Wolf (Day/Night)
if (state >= 3) return new FormRules(FormType.Wolf, true, 0f, 0f); // Elder: Wolf (Night)
return null;
}
public static FormRules GetHKeyRules(int state)
{
if (state >= 7) return new FormRules(FormType.Fenring, false, 0f, 0f); // Queen: Fenrir (Day/Night)
if (state >= 5) return new FormRules(FormType.Fenring, true, 0f, 0f); // Moder: Fenrir (Night)
if (state >= 4) return new FormRules(FormType.Ulv, true, 0f, 0f); // Bonemass: Ulv (Night)
return null;
}
public static FormRules GetJKeyRules(int state)
{
if (state >= 8) return new FormRules(FormType.Cultist, false, 0f, 0f); // Fader: Cultist (Day/Night)
if (state >= 7) return new FormRules(FormType.Cultist, true, 1f, 5f); // Queen: Cultist (Night, 1m dur, 5m cd)
if (state >= 6) return new FormRules(FormType.Cultist, true, 1f, 10f); // Yagluth: Cultist (Night, 1m dur, 10m cd)
return null;
}
}
}

View file

@ -0,0 +1,429 @@
using System;
using System.Collections;
using Jotunn.Configs;
using Jotunn.Entities;
using Jotunn.Managers;
using UnityEngine;
namespace RacesOfValheim {
public class FenrirRace : MonoBehaviour {
public static FenrirRace Instance;
public static SE_FenrirCurse curseSE;
public static SE_Stats formBuffSE;
public static SE_Stats wolfFormBuffSE;
public static SE_Stats cultistFormBuffSE;
public static SE_FormCooldown fenrirCdSE;
public static SE_FormCooldown cultistCdSE;
private GameObject currentTransformation;
private bool isTransformed = false;
private bool isTransformingSequence = false;
private FenrirProgression.FormRules activeRules = null;
private bool wasNight = false;
private float sunSicknessTimer = 0f;
private void Awake()
{
Instance = this;
}
public void CreateModAssets()
{
curseSE = ScriptableObject.CreateInstance<SE_FenrirCurse>();
curseSE.name = "SE_FenrirCurse";
curseSE.m_name = "Fenrir's Blood";
curseSE.m_tooltip = "You are of the Fenrir race.";
curseSE.m_mods = new System.Collections.Generic.List<HitData.DamageModPair>()
{
new HitData.DamageModPair() { m_type = HitData.DamageType.Spirit, m_modifier = HitData.DamageModifier.Weak }
};
GameObject fenringTrophy = PrefabManager.Cache.GetPrefab<ItemDrop>("TrophyFenring")?.gameObject;
Sprite fenringTrophyIcon = null;
if (fenringTrophy != null)
{
ItemDrop trophyDrop = fenringTrophy.GetComponent<ItemDrop>();
if (trophyDrop != null && trophyDrop.m_itemData.m_shared.m_icons.Length > 0)
{
fenringTrophyIcon = trophyDrop.m_itemData.m_shared.m_icons[0];
curseSE.m_icon = fenringTrophyIcon;
}
}
ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(curseSE, fixReference: false));
fenrirCdSE = ScriptableObject.CreateInstance<SE_FormCooldown>();
fenrirCdSE.name = "SE_FenrirCooldown";
fenrirCdSE.m_name = "Fenrir Form Cooldown";
fenrirCdSE.m_icon = fenringTrophyIcon;
ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(fenrirCdSE, fixReference: false));
cultistCdSE = ScriptableObject.CreateInstance<SE_FormCooldown>();
cultistCdSE.name = "SE_CultistCooldown";
cultistCdSE.m_name = "Cultist Form Cooldown";
cultistCdSE.m_icon = fenringTrophyIcon;
ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(cultistCdSE, fixReference: false));
formBuffSE = ScriptableObject.CreateInstance<SE_Stats>();
formBuffSE.name = "SE_FenrirForm";
formBuffSE.m_name = "Bestial Fury";
formBuffSE.m_speedModifier = 1.0f;
formBuffSE.m_jumpModifier = new Vector3(0, 1.0f, 0);
formBuffSE.m_fallDamageModifier = -1f;
formBuffSE.m_staminaRegenMultiplier = 1.3f;
formBuffSE.m_runStaminaDrainModifier = -0.2f;
formBuffSE.m_icon = fenringTrophyIcon;
ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(formBuffSE, fixReference: false));
cultistFormBuffSE = ScriptableObject.CreateInstance<SE_Stats>();
cultistFormBuffSE.name = "SE_CultistForm";
cultistFormBuffSE.m_name = "Cultist Fury";
cultistFormBuffSE.m_speedModifier = 1.0f;
cultistFormBuffSE.m_jumpModifier = new Vector3(0, 1.0f, 0);
cultistFormBuffSE.m_fallDamageModifier = -1f;
cultistFormBuffSE.m_staminaRegenMultiplier = 1.3f;
cultistFormBuffSE.m_runStaminaDrainModifier = -0.2f;
cultistFormBuffSE.m_icon = fenringTrophyIcon;
ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(cultistFormBuffSE, fixReference: false));
wolfFormBuffSE = ScriptableObject.CreateInstance<SE_Stats>();
wolfFormBuffSE.name = "SE_WolfForm";
wolfFormBuffSE.m_name = "Wolf Senses";
wolfFormBuffSE.m_speedModifier = 0.5f;
wolfFormBuffSE.m_fallDamageModifier = -0.5f;
wolfFormBuffSE.m_staminaRegenMultiplier = 1.3f;
wolfFormBuffSE.m_runStaminaDrainModifier = -0.2f;
wolfFormBuffSE.m_icon = fenringTrophyIcon;
ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(wolfFormBuffSE, fixReference: false));
}
private void Update()
{
if (Player.m_localPlayer == null || EnvMan.instance == null) return;
if (isTransformingSequence) return;
if (!Player.m_localPlayer.GetSEMan().HaveStatusEffect("SE_FenrirCurse".GetStableHashCode())) return;
if (sunSicknessTimer > 0f)
{
sunSicknessTimer -= Time.deltaTime;
}
bool isNight = EnvMan.IsNight();
if (isNight && !wasNight)
{
Player.m_localPlayer.GetSEMan().RemoveStatusEffect("SE_FenrirCooldown".GetStableHashCode());
Player.m_localPlayer.GetSEMan().RemoveStatusEffect("SE_CultistCooldown".GetStableHashCode());
var fenrirSE = Player.m_localPlayer.GetSEMan().GetStatusEffect("SE_FenrirForm".GetStableHashCode());
if (fenrirSE != null) fenrirSE.m_ttl = 0f;
var cultistSE = Player.m_localPlayer.GetSEMan().GetStatusEffect("SE_CultistForm".GetStableHashCode());
if (cultistSE != null) cultistSE.m_ttl = 0f;
var wolfSE = Player.m_localPlayer.GetSEMan().GetStatusEffect("SE_WolfForm".GetStableHashCode());
if (wolfSE != null) wolfSE.m_ttl = 0f;
}
else if (!isNight && wasNight)
{
// Sunrise: force revert and block for 60 seconds
sunSicknessTimer = 60f;
ForceRevert();
}
wasNight = isNight;
if (isTransformed)
{
bool hasAnyForm = Player.m_localPlayer.GetSEMan().HaveStatusEffect("SE_FenrirForm".GetStableHashCode()) ||
Player.m_localPlayer.GetSEMan().HaveStatusEffect("SE_CultistForm".GetStableHashCode()) ||
Player.m_localPlayer.GetSEMan().HaveStatusEffect("SE_WolfForm".GetStableHashCode());
if (!hasAnyForm)
{
ForceRevert();
return;
}
}
int state = BossProgressionManager.GetCurrentProgressionState();
if (Input.GetKeyDown(KeyCode.G)) { TryTransformWithRules(FenrirProgression.GetGKeyRules(state)); return; }
if (Input.GetKeyDown(KeyCode.H)) { TryTransformWithRules(FenrirProgression.GetHKeyRules(state)); return; }
if (Input.GetKeyDown(KeyCode.J)) { TryTransformWithRules(FenrirProgression.GetJKeyRules(state)); return; }
}
private void TryTransformWithRules(FenrirProgression.FormRules rules)
{
if (rules == null || rules.Form == FenrirProgression.FormType.None) return;
if (sunSicknessTimer > 0f)
{
Player.m_localPlayer.Message(MessageHud.MessageType.Center, "The beast is tired");
return;
}
if (isTransformed)
{
StartCoroutine(RevertToHumanRoutine());
return;
}
if (rules.NeedsNight && !EnvMan.IsNight())
{
Player.m_localPlayer.Message(MessageHud.MessageType.Center, "The beast rests. You can only transform at night.");
return;
}
if (rules.CooldownMinutes > 0)
{
string cdName = rules.Form == FenrirProgression.FormType.Cultist ? "SE_CultistCooldown" : "SE_FenrirCooldown";
var cdSE = Player.m_localPlayer.GetSEMan().GetStatusEffect(cdName.GetStableHashCode());
if (cdSE != null)
{
float m_time = HarmonyLib.Traverse.Create(cdSE).Field<float>("m_time").Value;
float remaining = cdSE.m_ttl - m_time;
if (remaining < 0) remaining = 0;
int rMin = Mathf.FloorToInt(remaining / 60f);
int rSec = Mathf.FloorToInt(remaining % 60f);
string formName = rules.Form == FenrirProgression.FormType.Cultist ? "Cultist" : "Fenrir";
Player.m_localPlayer.Message(MessageHud.MessageType.Center, $"{formName} form is on cooldown ({rMin}:{rSec:00}).");
return;
}
}
StartCoroutine(TransformIntoWolfRoutine(rules));
}
public void ForceRevert()
{
if (isTransformed && !isTransformingSequence)
{
StartCoroutine(RevertToHumanRoutine());
}
}
private IEnumerator TransformIntoWolfRoutine(FenrirProgression.FormRules rules)
{
isTransformingSequence = true;
activeRules = rules;
ZSyncAnimation zAnim = Player.m_localPlayer.GetComponent<ZSyncAnimation>();
if (zAnim != null) zAnim.SetTrigger("gpower");
yield return new WaitForSeconds(1.1f);
SpawnPoofEffect();
if (ZNetScene.instance != null)
{
GameObject howlPrefab = ZNetScene.instance.GetPrefab("sfx_wolf_howl") ?? ZNetScene.instance.GetPrefab("sfx_fenring_idle");
if (howlPrefab != null) Instantiate(howlPrefab, Player.m_localPlayer.transform.position, Quaternion.identity);
}
yield return new WaitForSeconds(0.1f);
ExecuteTransformation(rules);
if (currentTransformation != null && currentTransformation.GetComponent<WolfFormBehavior>() == null && currentTransformation.GetComponent<UlvFormBehavior>() == null)
{
float elapsed = 0f;
float duration = 0.5f;
float startMultiplier = 0.5f;
Vector3 startScale = Vector3.one * startMultiplier;
Vector3 endScale = Vector3.one;
currentTransformation.transform.localScale = startScale;
while (elapsed < duration)
{
if (currentTransformation == null) break;
currentTransformation.transform.localScale = Vector3.Lerp(startScale, endScale, elapsed / duration);
elapsed += Time.deltaTime;
yield return null;
}
if (currentTransformation != null) currentTransformation.transform.localScale = endScale;
}
isTransformingSequence = false;
}
private IEnumerator RevertToHumanRoutine()
{
isTransformingSequence = true;
if (currentTransformation != null)
{
FenrirFormBehavior fenrirBehavior = currentTransformation.GetComponent<FenrirFormBehavior>();
if (fenrirBehavior != null) fenrirBehavior.enabled = false;
CultistFormBehavior cultistBehavior = currentTransformation.GetComponent<CultistFormBehavior>();
if (cultistBehavior != null) cultistBehavior.enabled = false;
WolfFormBehavior wolfBehavior = currentTransformation.GetComponent<WolfFormBehavior>();
if (wolfBehavior != null) wolfBehavior.enabled = false;
UlvFormBehavior ulvBehavior = currentTransformation.GetComponent<UlvFormBehavior>();
if (ulvBehavior != null) ulvBehavior.enabled = false;
if (wolfBehavior == null && ulvBehavior == null)
{
float elapsed = 0f;
float duration = 0.5f;
Vector3 startScale = currentTransformation.transform.localScale;
float endMultiplier = 0.5f;
Vector3 endScale = startScale * endMultiplier;
while (elapsed < duration)
{
if (currentTransformation == null) break;
currentTransformation.transform.localScale = Vector3.Lerp(startScale, endScale, elapsed / duration);
elapsed += Time.deltaTime;
yield return null;
}
}
}
SpawnPoofEffect();
yield return new WaitForSeconds(0.1f);
ExecuteReversion();
isTransformingSequence = false;
}
private void SpawnPoofEffect()
{
if (Player.m_localPlayer == null) return;
Vector3 pos = Player.m_localPlayer.transform.position + Vector3.up;
GameObject smoke = PrefabManager.Cache.GetPrefab<GameObject>("vfx_corpse_destruction");
if (smoke != null) Instantiate(smoke, pos, Quaternion.identity);
GameObject sparks = PrefabManager.Cache.GetPrefab<GameObject>("vfx_HitSparks");
if (sparks != null) Instantiate(sparks, pos, Quaternion.identity);
}
private void ExecuteTransformation(FenrirProgression.FormRules rules)
{
Transform playerVisual = Player.m_localPlayer.transform.Find("Visual");
string prefabName = "";
switch (rules.Form)
{
case FenrirProgression.FormType.Wolf: prefabName = "Wolf"; break;
case FenrirProgression.FormType.Ulv: prefabName = "Ulv"; break;
case FenrirProgression.FormType.Fenring: prefabName = "Fenring"; break;
case FenrirProgression.FormType.Cultist: prefabName = "Fenring_Cultist"; break;
}
GameObject prefab = PrefabManager.Cache.GetPrefab<GameObject>(prefabName);
// Sync to ZDO
ZNetView nview = Player.m_localPlayer.GetComponent<ZNetView>();
if (nview != null && nview.IsValid())
{
nview.GetZDO().Set("RacesOfValheim_FenrirForm", prefabName);
}
if (prefab != null && playerVisual != null)
{
playerVisual.localScale = Vector3.one * 0.001f;
Transform visual = prefab.transform.Find("Visual");
if (visual != null)
{
currentTransformation = Instantiate(visual.gameObject, Player.m_localPlayer.transform);
currentTransformation.transform.localPosition = Vector3.zero;
currentTransformation.transform.localRotation = Quaternion.identity;
Component animEvent = currentTransformation.GetComponent("AnimEvent");
if (animEvent != null) Destroy(animEvent);
float ttl = rules.DurationMinutes > 0 ? (rules.DurationMinutes * 60f) : 0f;
if (prefabName == "Ulv")
{
currentTransformation.AddComponent<UlvFormBehavior>();
Player.m_localPlayer.GetSEMan().AddStatusEffect("SE_WolfForm".GetStableHashCode(), true);
var se = Player.m_localPlayer.GetSEMan().GetStatusEffect("SE_WolfForm".GetStableHashCode());
if (se != null) se.m_ttl = ttl;
Player.m_localPlayer.Message(MessageHud.MessageType.Center, "You are an Ulv!");
}
else if (prefabName == "Wolf")
{
currentTransformation.AddComponent<WolfFormBehavior>();
Player.m_localPlayer.GetSEMan().AddStatusEffect("SE_WolfForm".GetStableHashCode(), true);
var se = Player.m_localPlayer.GetSEMan().GetStatusEffect("SE_WolfForm".GetStableHashCode());
if (se != null) se.m_ttl = ttl;
Player.m_localPlayer.Message(MessageHud.MessageType.Center, "You are a Wolf!");
}
else if (prefabName == "Fenring_Cultist")
{
currentTransformation.AddComponent<CultistFormBehavior>();
Player.m_localPlayer.GetSEMan().AddStatusEffect("SE_CultistForm".GetStableHashCode(), true);
var se = Player.m_localPlayer.GetSEMan().GetStatusEffect("SE_CultistForm".GetStableHashCode());
if (se != null) se.m_ttl = ttl;
Player.m_localPlayer.Message(MessageHud.MessageType.Center, "You are a Cultist!");
}
else
{
currentTransformation.AddComponent<FenrirFormBehavior>();
Player.m_localPlayer.GetSEMan().AddStatusEffect("SE_FenrirForm".GetStableHashCode(), true);
var se = Player.m_localPlayer.GetSEMan().GetStatusEffect("SE_FenrirForm".GetStableHashCode());
if (se != null) se.m_ttl = ttl;
Player.m_localPlayer.Message(MessageHud.MessageType.Center, "You are a Fenring!");
}
isTransformed = true;
}
}
}
private void DestroyAllForms()
{
if (Player.m_localPlayer == null) return;
var forms1 = Player.m_localPlayer.GetComponentsInChildren<FenrirFormBehavior>(true);
foreach (var f in forms1) Destroy(f.gameObject);
var forms2 = Player.m_localPlayer.GetComponentsInChildren<CultistFormBehavior>(true);
foreach (var f in forms2) Destroy(f.gameObject);
var forms3 = Player.m_localPlayer.GetComponentsInChildren<WolfFormBehavior>(true);
foreach (var f in forms3) Destroy(f.gameObject);
var forms4 = Player.m_localPlayer.GetComponentsInChildren<UlvFormBehavior>(true);
foreach (var f in forms4) Destroy(f.gameObject);
}
private void ExecuteReversion()
{
Transform playerVisual = Player.m_localPlayer.transform.Find("Visual");
if (currentTransformation != null) Destroy(currentTransformation);
DestroyAllForms(); // Safety check to remove any leaked forms
// Sync to ZDO
ZNetView nview = Player.m_localPlayer.GetComponent<ZNetView>();
if (nview != null && nview.IsValid())
{
nview.GetZDO().Set("RacesOfValheim_FenrirForm", "");
}
if (playerVisual != null)
{
playerVisual.localScale = Vector3.one;
playerVisual.gameObject.SetActive(true);
}
Player.m_localPlayer.GetSEMan().RemoveStatusEffect("SE_FenrirForm".GetStableHashCode());
Player.m_localPlayer.GetSEMan().RemoveStatusEffect("SE_CultistForm".GetStableHashCode());
Player.m_localPlayer.GetSEMan().RemoveStatusEffect("SE_WolfForm".GetStableHashCode());
isTransformed = false;
Player.m_localPlayer.Message(MessageHud.MessageType.Center, "You returned to human form.");
if (activeRules != null && activeRules.CooldownMinutes > 0)
{
string cdName = activeRules.Form == FenrirProgression.FormType.Cultist ? "SE_CultistCooldown" : "SE_FenrirCooldown";
Player.m_localPlayer.GetSEMan().AddStatusEffect(cdName.GetStableHashCode(), true);
var cdSE = Player.m_localPlayer.GetSEMan().GetStatusEffect(cdName.GetStableHashCode());
if (cdSE != null) cdSE.m_ttl = activeRules.CooldownMinutes * 60f;
}
activeRules = null;
}
}
}

View file

@ -0,0 +1,46 @@
using System.Collections;
using BepInEx;
using HarmonyLib;
using Jotunn.Configs;
using Jotunn.Entities;
using Jotunn.Managers;
using UnityEngine;
using UnityEngine.UI; // Added for UI
namespace RacesOfValheim
{
public class SE_FormCooldown : StatusEffect
{
public override void Stop()
{
base.Stop();
if (Player.m_localPlayer != null)
{
Player.m_localPlayer.Message(MessageHud.MessageType.Center, $"{m_name} is Ready!");
}
}
}
public class SE_FenrirCurse : SE_Stats
{
public override void Setup(Character character)
{
base.Setup(character);
if (character == Player.m_localPlayer)
{
Player.m_localPlayer.m_customData["FenrirCurse_Active"] = "true";
}
}
public override void UpdateStatusEffect(float dt)
{
base.UpdateStatusEffect(dt);
int state = BossProgressionManager.GetCurrentProgressionState();
m_fallDamageModifier = FenrirProgression.GetFallDamageModifier(state);
m_speedModifier = 1.0f + FenrirProgression.GetSpeedModifier(state);
m_jumpModifier = new Vector3(0, FenrirProgression.GetJumpModifier(state), 0);
}
}
}

View file

@ -0,0 +1,157 @@
using HarmonyLib;
using UnityEngine;
using System.Collections.Generic;
namespace RacesOfValheim
{
/// <summary>
/// "Through Fire and Flames" — unlocks after Fader (state >= 8).
///
/// Effects:
/// 1. Player has SE_Burning applied ONCE (999-min duration), like walking on a bonfire.
/// Reapplied automatically after respawn, load, or state unlock.
/// 2. No fire damage taken (handled in FurlingPatches.Furling_Character_Damage_Patch).
/// 3. The Burning icon is hidden from the HUD.
/// 4. All physical attacks apply SE_Burning to the target.
/// </summary>
public static class FurlingFireAbility
{
private static int _lastState = -1;
private static bool _burningApplied = false;
private static readonly int BurningHash = "Burning".GetStableHashCode();
private const float BURN_DURATION = 999f * 60f; // 999 minutes in seconds
// ─── Called from FurlingRace.Update() — cheap check, no timer ────────
public static void Tick()
{
if (Player.m_localPlayer == null || !FurlingRace.IsFurling())
{
_burningApplied = false;
_lastState = -1;
return;
}
int state = BossProgressionManager.GetCurrentProgressionState();
if (state < 8)
{
_burningApplied = false;
_lastState = state;
return;
}
bool stateJustUnlocked = (_lastState < 8);
bool seMissing = !Player.m_localPlayer.GetSEMan()
.HaveStatusEffect(BurningHash);
// Apply only when: first time, state just reached 8, or SE was lost (respawn/load)
if (!_burningApplied || stateJustUnlocked || seMissing)
{
ApplyPermanentBurning();
_burningApplied = true;
}
_lastState = state;
}
private static void ApplyPermanentBurning()
{
var seman = Player.m_localPlayer.GetSEMan();
// Allow our application through the suppression patch
FurlingFire_SuppressExternalBurning_Patch.AllowNextBurning = true;
seman.AddStatusEffect(BurningHash, true);
// Override the duration to 999 minutes so it never expires naturally
StatusEffect se = seman.GetStatusEffect(BurningHash);
if (se != null)
{
se.m_ttl = BURN_DURATION;
// Reset elapsed time so we start fresh
HarmonyLib.Traverse.Create(se).Field<float>("m_time").Value = 0f;
}
}
// ─── Hide Burning icon from HUD ───────────────────────────────────────
[HarmonyPatch(typeof(SEMan), "GetStatusEffects")]
public static class FurlingFire_HideHUDBurning_Patch
{
public static void Postfix(SEMan __instance, List<StatusEffect> __result)
{
if (__result == null || __result.Count == 0) return;
Character character = HarmonyLib.Traverse.Create(__instance)
.Field<Character>("m_character").Value;
if (character == null || character != Player.m_localPlayer) return;
if (!FurlingRace.IsFurling()) return;
if (BossProgressionManager.GetCurrentProgressionState() < 8) return;
__result.RemoveAll(se => se != null && se.name != null &&
se.name.IndexOf("Burning", System.StringComparison.OrdinalIgnoreCase) >= 0);
}
}
// ─── Block external Burning (fire pits, arrows) from being applied ────
[HarmonyPatch(typeof(SEMan), "AddStatusEffect",
new System.Type[] { typeof(int), typeof(bool), typeof(int), typeof(float) })]
public static class FurlingFire_SuppressExternalBurning_Patch
{
public static bool AllowNextBurning = false;
public static bool Prefix(SEMan __instance, ref int nameHash)
{
if (nameHash != BurningHash) return true;
Character character = HarmonyLib.Traverse.Create(__instance)
.Field<Character>("m_character").Value;
if (character == null || character != Player.m_localPlayer) return true;
if (!FurlingRace.IsFurling()) return true;
if (BossProgressionManager.GetCurrentProgressionState() < 8) return true;
if (AllowNextBurning)
{
AllowNextBurning = false;
return true; // our own application — allow
}
return false; // external source — block (player is immune)
}
}
// ─── Physical attacks set enemies on fire ─────────────────────────────
[HarmonyPatch(typeof(Character), "Damage")]
public static class FurlingFire_IgniteOnHit_Patch
{
public static void Prefix(Character __instance, HitData hit)
{
if (__instance == null || __instance is Player) return;
if (Player.m_localPlayer == null || !FurlingRace.IsFurling()) return;
if (BossProgressionManager.GetCurrentProgressionState() < 8) return;
Character attacker = hit.GetAttacker();
if (attacker == null || attacker != Player.m_localPlayer) return;
if (hit.m_damage.m_blunt > 0 || hit.m_damage.m_slash > 0 ||
hit.m_damage.m_pierce > 0 || hit.m_damage.m_chop > 0 ||
hit.m_damage.m_pickaxe > 0)
{
hit.m_damage.m_fire = Mathf.Max(hit.m_damage.m_fire, 10f);
}
}
public static void Postfix(Character __instance, HitData hit)
{
if (__instance == null || __instance is Player) return;
if (Player.m_localPlayer == null || !FurlingRace.IsFurling()) return;
if (BossProgressionManager.GetCurrentProgressionState() < 8) return;
Character attacker = hit.GetAttacker();
if (attacker == null || attacker != Player.m_localPlayer) return;
if (!__instance.IsDead())
__instance.GetSEMan().AddStatusEffect(BurningHash, true);
}
}
}
}

View file

@ -0,0 +1,149 @@
using HarmonyLib;
using UnityEngine;
using UnityEngine.UI;
using Jotunn.Managers;
namespace RacesOfValheim
{
/// <summary>
/// Displays a small "King / Queen" status indicator in the top-right corner of the HUD
/// when the local Furling player is inside the Plains biome and has unlocked the Yagluth ability (state >= 8).
/// Shows the unmodified Midsummer Crown icon above the gendered title.
/// </summary>
public static class FurlingKingUI
{
private static GameObject _hudRoot; // root panel anchored top-right
private static Image _crownImage; // the crown sprite
private static Text _titleText; // "King" / "Queen"
private const float UPDATE_INTERVAL = 1.0f;
private static float _timer = 0f;
// ─── Harmony patch: hook onto Hud.Update ─────────────────────────────
[HarmonyPatch(typeof(Hud), "Update")]
public static class FurlingKingUI_Hud_Update_Patch
{
public static void Postfix(Hud __instance)
{
_timer += Time.deltaTime;
if (_timer < UPDATE_INTERVAL) return;
_timer = 0f;
Tick(__instance);
}
}
// ─── Core update logic ────────────────────────────────────────────────
private static void Tick(Hud hud)
{
bool shouldShow = ShouldShowKingStatus();
if (!shouldShow)
{
if (_hudRoot != null) _hudRoot.SetActive(false);
return;
}
// Build the UI the first time it's needed
if (_hudRoot == null)
{
BuildUI(hud);
if (_hudRoot == null) return; // build failed (prefab not ready yet)
}
_hudRoot.SetActive(true);
// Update label based on player model (0 = male → King, 1 = female → Queen)
if (_titleText != null && Player.m_localPlayer != null)
{
int modelIndex = HarmonyLib.Traverse.Create(
Player.m_localPlayer.GetComponent<VisEquipment>()
).Field<int>("m_modelIndex").Value;
_titleText.text = (modelIndex == 1) ? "Queen" : "King";
}
}
// ─── Condition check ──────────────────────────────────────────────────
private static bool ShouldShowKingStatus()
{
if (Player.m_localPlayer == null) return false;
if (!FurlingRace.IsFurling()) return false;
if (BossProgressionManager.GetCurrentProgressionState() < 8) return false;
// Check Plains biome
Heightmap.Biome biome = Player.m_localPlayer.GetCurrentBiome();
return biome == Heightmap.Biome.Plains;
}
// ─── Build the HUD panel ──────────────────────────────────────────────
private static void BuildUI(Hud hud)
{
// Fetch the crown item icon
Sprite crownSprite = null;
var crownPrefab = PrefabManager.Cache.GetPrefab<ItemDrop>("HelmetMidsummerCrown");
if (crownPrefab != null)
crownSprite = crownPrefab.m_itemData.m_shared.m_icons.Length > 0
? crownPrefab.m_itemData.m_shared.m_icons[0]
: null;
// Parent to the Hud root canvas
Canvas canvas = hud.GetComponentInChildren<Canvas>();
if (canvas == null) return;
// Root panel
_hudRoot = new GameObject("FurlingKingStatus", typeof(RectTransform));
_hudRoot.transform.SetParent(canvas.transform, false);
RectTransform rt = _hudRoot.GetComponent<RectTransform>();
rt.anchorMin = new Vector2(1f, 1f);
rt.anchorMax = new Vector2(1f, 1f);
rt.pivot = new Vector2(1f, 1f);
rt.sizeDelta = new Vector2(90f, 110f);
rt.anchoredPosition = new Vector2(-10f, -10f); // 10px from top-right edge
// ── Crown icon ──────────────────────────────────────────────────
GameObject iconGO = new GameObject("CrownIcon", typeof(RectTransform), typeof(Image));
iconGO.transform.SetParent(_hudRoot.transform, false);
RectTransform iconRt = iconGO.GetComponent<RectTransform>();
iconRt.anchorMin = new Vector2(0.5f, 1f);
iconRt.anchorMax = new Vector2(0.5f, 1f);
iconRt.pivot = new Vector2(0.5f, 1f);
iconRt.sizeDelta = new Vector2(72f, 72f);
iconRt.anchoredPosition = Vector2.zero;
_crownImage = iconGO.GetComponent<Image>();
_crownImage.preserveAspect = true;
if (crownSprite != null)
_crownImage.sprite = crownSprite;
else
_crownImage.color = new Color(1f, 0.9f, 0.2f, 1f); // gold fallback
// ── Title text ──────────────────────────────────────────────────
GameObject textGO = new GameObject("TitleText", typeof(RectTransform), typeof(Text));
textGO.transform.SetParent(_hudRoot.transform, false);
RectTransform textRt = textGO.GetComponent<RectTransform>();
textRt.anchorMin = new Vector2(0f, 0f);
textRt.anchorMax = new Vector2(1f, 0f);
textRt.pivot = new Vector2(0.5f, 0f);
textRt.sizeDelta = new Vector2(0f, 28f);
textRt.anchoredPosition = Vector2.zero;
_titleText = textGO.GetComponent<Text>();
_titleText.text = "King";
_titleText.alignment = TextAnchor.MiddleCenter;
_titleText.fontSize = 18;
_titleText.fontStyle = FontStyle.Bold;
_titleText.color = new Color(1f, 0.92f, 0.4f, 1f); // gold text
// Try to match Valheim's font
_titleText.font = Resources.GetBuiltinResource<Font>("Arial.ttf");
// ── Subtle dark backing for readability ─────────────────────────
CanvasGroup cg = _hudRoot.AddComponent<CanvasGroup>();
cg.alpha = 0.92f;
}
}
}

View file

@ -0,0 +1,643 @@
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 || __instance != Player.m_localPlayer) return;
if (FurlingRace.IsFurling())
{
// 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;
}
}
[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 (!__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)
{
string name = otherChar.gameObject.name.Replace("(Clone)", "").ToLower();
if (name == "goblin" ||
name == "goblinbrute" ||
name == "goblinshaman" ||
name == "lox" ||
name == "deathsquito" ||
name == "troll")
{
// Exclude minibosses/bosses explicitly if needed, but normally bosses are handled separately (Yagluth is GoblinKing).
if (name != "goblinking")
{
__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)
{
// instantiateInWorldSpace = false per ereditare esattamente la trasformazione base
GameObject trophyVisual = UnityEngine.Object.Instantiate(trophyPrefab, headBone, false);
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.Destroy(comp);
}
if (trophyVisual.GetComponent<Rigidbody>() != null)
UnityEngine.Object.Destroy(trophyVisual.GetComponent<Rigidbody>());
foreach (var col in trophyVisual.GetComponentsInChildren<Collider>())
{
UnityEngine.Object.Destroy(col);
}
// 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 (either by skill or by checking if a bow/ammo was used)
if ((hitData != null && hitData.m_skill == Skills.SkillType.Bows) ||
(ammo != null && ammo.m_shared.m_skillType == Skills.SkillType.Bows))
{
// 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());
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;
}
}
}
}
}
}

View file

@ -0,0 +1,16 @@
using System;
namespace RacesOfValheim
{
public static class FurlingProgression
{
public static void UpdateProgression()
{
if (!FurlingRace.IsFurling()) return;
int state = BossProgressionManager.GetCurrentProgressionState();
// Progression logic based on defeated bosses
}
}
}

View file

@ -0,0 +1,44 @@
using BepInEx;
using HarmonyLib;
using UnityEngine;
using System.Collections.Generic;
namespace RacesOfValheim
{
public class FurlingRace : MonoBehaviour
{
private static FurlingRace _instance;
public static FurlingRace Instance
{
get
{
if (_instance == null)
{
GameObject go = new GameObject("FurlingRace");
_instance = go.AddComponent<FurlingRace>();
DontDestroyOnLoad(go);
}
return _instance;
}
}
public static bool IsFurling()
{
return Player.m_localPlayer != null && Player.m_localPlayer.GetPlayerModel() == 5; // Assumed ID for Furling
}
public void CreateModAssets()
{
Jotunn.Logger.LogInfo("Initializing Furling Race...");
FurlingStatusEffects.RegisterStatusEffects();
}
private void Update()
{
if (!IsFurling()) return;
// Through Fire and Flames (Fader)
FurlingFireAbility.Tick();
}
}
}

View file

@ -0,0 +1,14 @@
using Jotunn.Managers;
using Jotunn.Entities;
using UnityEngine;
namespace RacesOfValheim
{
public static class FurlingStatusEffects
{
public static void RegisterStatusEffects()
{
// Register custom status effects for Furling
}
}
}

View file

@ -0,0 +1,104 @@
# RacesOfValheim
A comprehensive Valheim mod that allows you to play as different unique races, each offering distinct mechanics, visual transformations, and a deep progression system tailored to your journey in Valheim.
## Features
This mod currently introduces 4 custom races:
### 1. Skeleton
- **Stamina-less Combat**: Skeletons do not consume stamina and do not use the stamina bar.
- **Undead Diet**: You cannot eat standard food. Instead, you gain maximum health automatically as you defeat Valheim's bosses to compensate for the lack of food buffs.
### 2. Skadi
- **Ice Affinity**: Gain unique resistance and affinity to the cold.
### 3. Fenrir
- **Beast Form**: Transform into a powerful wolf-like beast.
- **Cultist Form**: Transform into a Cultist to wield fire abilities.
- **Progression**: The beast and cultist forms evolve as you defeat Valheim's bosses, granting new abilities, cooldown reductions, and power scaling. Immune to fall damage in both forms.
### 4. Aswid
- **The Vampire**: A creature of the night with powerful life-draining abilities.
- **Bat Transformation**: Press `G` to transform into a bat, allowing you to fly over obstacles and travel quickly.
- **Blood Magic**: Block to channel a life-draining aura that saps the life of enemies in an area around you (doubled radius at night).
- **Blood Magic Mastery**: You can cast Blood Magic items with infinite Eitr, relying purely on their health costs.
- **Night Prowler**: Your passive speed and jump bonuses double during the night.
- **Undead Vigor**: Like the skeleton, the Aswid has infinite stamina. You consume the lifeforce of fallen foes directly instead of eating standard food.
## Installation (manual)
1. Install BepInExPack Valheim.
2. Install Jotunn.
3. Extract the contents of this mod into your `BepInEx/plugins` folder.
## Changelog
**v1.0.0**
- Initial release with 4 distinct races.
- Added Aswid life-draining and night transformations.
- Complete progression system tied to Valheim's bosses.
**v1.1.0**
- **Aswid**: Passive abilities (Speed and Jump) are now properly doubled during the night.
- **Aswid**: New Enslavement Power (Yagluth tier)! Press E on non-tameable, non-boss enemies to enslave them for 60 seconds (15-min cooldown). Enslaved thralls fight alongside you and drop standard loot.
- **Aswid**: Edible thralls are automatically consumed upon death, granting you their lifeforce (Fader tier).
- **Aswid**: Complete overhaul of the Food system. Added Mistlands and Ashlands creatures to the consumption map. Accurately scaled food stats based on creature health.
- **Aswid**: Excluded undead and inorganic creatures (Skeletons, Draugrs, Golems, etc.) from being edible.
- **Aswid**: Added a dynamic green light effect to all forms (Bonemass tier).
**v1.2.0**
- **Multiplayer Sync**: Fully implemented visual syncing for Aswid forms (Bat, Mist) and Skadi forms (Bear, Wolf, Hatchling, Fader) so other players can see your transformations in multiplayer!
- **Aswid**: Scrapped the Fader (Surtling) visual override; reaching the final progression state now makes the player 10% taller and adds a flat +30 physical damage bonus.
- **Aswid**: Defeating enemies with physical attacks in the final state now automatically consumes them if you have food slots available.
- **General**: Eradicated remaining localizations of the old "Strigoi" name.
**v1.3.0**
- **Progression Fix**: Fixed a massive bug where boss progression states were misaligned. Players no longer receive Eikthyr or higher-tier powers immediately upon starting a new game (State 1). All unlocks now perfectly match the corresponding boss defeat global keys.
- **Furling**: Fine-tuned the custom 3D Goblin Head trophy alignment and scaling. It now fits perfectly inside the player's skull, revealing only the goblin ears!
- **Documentation**: Added complete level-by-level progression lists to the README for all races.
## Race Progressions (Level-by-Level)
### Aswid Progression
- **Base (No Bosses)**: Vampiric Aura (heal 20% on magic AoE damage). Progressive stats (+3 Armor, +5 Damage, +3% Speed, +3% Jump per boss killed). All passive bonuses are doubled at night! You can cast Blood Magic items with infinite Eitr.
- **Eikthyr**: Bat Transformation (Night only).
- **The Elder**: Bat Transformation (Always active).
- **Bonemass**: Superhuman Senses (Aura reveals untamed creatures).
- **Moder**: Freezing Blood (Permanent immunity to Freezing and Poison).
- **Yagluth**: Enslavement Power (E Key - Enslave non-tameable enemies).
- **The Queen**: Mist Form (H Key - Immune to physical/poison, double aura damage, weak to fire/frost/spirit. Breaks at sunrise).
- **Fader**: +10% Size, +30 Physical Damage. Physical kills automatically consume enemies.
### Skadi Progression
- **Base (No Bosses)**: Immune to Cold, Bonus Frost Damage, 50% Frost Resistance.
- **Eikthyr**: +20% Eitr Regen, Freezing to Cold (mountains act as normal cold), Cold Spell.
- **The Elder**: Drake Form (Cannot attack).
- **Bonemass**: Drake Form (Can attack).
- **Moder**: Moder Form (1 min duration, 10 min cooldown).
- **Yagluth**: Improved Cold Spell. Moder Form (1 min duration, 5 min cooldown).
- **The Queen**: Moder Form (Unlimited duration, no cooldown).
- **Fader**: Skeleton Dragon Form.
### Skeleton Progression
- **Base (No Bosses)**: +50 Max Health. Undead Diet (Cannot eat mortal food, no stamina bar).
- **Eikthyr**: Poison Skeleton Model, Poison Immunity, 5% Lifesteal, +80 Max Health.
- **The Elder**: 10% Lifesteal, Auto-Stun on First Hit, +110 Max Health.
- **Bonemass**: 15% Lifesteal, Poison Attacks, +140 Max Health.
- **Moder**: Fire Skeleton Model, 20% Lifesteal, Fire Aura, Enhanced Regen, +170 Max Health.
- **Yagluth**: 25% Lifesteal, Auto Resurrect, +200 Max Health.
- **The Queen**: 30% Lifesteal, Summon on Kill (Max 3 Skeletons), +230 Max Health.
- **Fader**: 35% Lifesteal, Max 5 Summons, +275 Max Health.
### Fenrir Progression
- **Base (No Bosses)**: Progressive stats (+3 Armor, +5 Damage, -10% Fall Damage, +3% Speed, +3% Jump per boss killed).
- **The Elder**: Wolf Form (Night).
- **Bonemass**: Wolf Form (Day/Night). Ulv Form (Night).
- **Moder**: Ulv Form (Day/Night). Fenring Form (Night).
- **Yagluth**: Cultist Form (Night - 1 min duration, 10 min cooldown).
- **The Queen**: Fenring Form (Day/Night). Cultist Form (Night - 1 min duration, 5 min cooldown).
- **Fader**: Cultist Form (Day/Night).
### Furling Progression
- **Eikthyr**: Master of Shadows (Bonus attack damage when in the dark or at night).
- **The Elder**: The Wickerman (-50% Fire and Poison damage, increased to -90% if it's from an arrow).
- **Bonemass**: Dance of the Dead (Ignore certain crafting costs).
- **Moder**: The Man/Woman on the Silver Mountain (Doubles normal enemy trophy drops, yields gold coins based on stars within 25 meters, and doubles mined raw ore yield).
- **Yagluth**: The King is Dead, Hail to the King/Queen (In the Plains biome, the 2x XP multiplier is extended to all non-combat skills).

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.3 KiB

View file

@ -0,0 +1,10 @@
{
"name": "RacesOfValheim",
"description": "A Valheim mod that adds custom playable races (Skeleton, Skadi, Fenrir, Aswid, Furling) each with unique abilities, traits, and a deep boss-driven progression system.",
"version_number": "1.3.2",
"website_url": "",
"dependencies": [
"denikson-BepInExPack_Valheim-5.4.2333",
"ValheimModding-Jotunn-2.26.1"
]
}

View file

@ -0,0 +1,35 @@
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("RacesOfValheim")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("RacesOfValheim")]
[assembly: AssemblyCopyright("Copyright © 2021")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("e3243d22-4307-4008-ba36-9f326008cde5")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
//[assembly: AssemblyVersion(JotunnModStub.JotunnModStub.PluginVersion)]
//[assembly: AssemblyFileVersion(JotunnModStub.JotunnModStub.PluginVersion)]

View file

@ -0,0 +1,17 @@
// Veilheim
// a Valheim mod
//
// File: IgnoreAccessModifiers.cs
// Project: Veilheim
using System.Security.Permissions;
// SecurityPermision set to minimum
// for skipping access modifiers check from the mono JIT
// The same attribute are added to the assembly when ticking
// Unsafe Code in the Project settings
// This is done here to allow an explanation of the trick and
// not in an outside source you could potentially miss.
#pragma warning disable CS0618 // Type or member is obsolete
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]

156
JotunnModStub/README.md Normal file
View file

@ -0,0 +1,156 @@
# RacesOfValheim
A comprehensive Valheim mod that allows you to play as different unique races, each offering distinct mechanics, visual transformations, and a deep progression system tailored to your journey in Valheim.
## Features
This mod currently introduces 6 custom races:
### 1. Skeleton
- **Stamina-less Combat**: Skeletons do not consume stamina and do not use the stamina bar.
- **Undead Diet**: You cannot eat standard food. Instead, you gain maximum health automatically as you defeat Valheim's bosses to compensate for the lack of food buffs.
### 2. Skadi
- **Ice Affinity**: Gain unique resistance and affinity to the cold.
- **Drake Form**: Transform into a frost Drake, taking to the skies and attacking from above.
- **Dragon Form**: Evolve your form into the mighty Moder and, eventually, unleash the terrifying power of the Skeleton Dragon.
### 3. Fenrir
- **Beast Form**: Transform into a powerful wolf-like beast.
- **Cultist Form**: Transform into a Cultist to wield fire abilities.
- **Progression**: The beast and cultist forms evolve as you defeat Valheim's bosses, granting new abilities, cooldown reductions, and power scaling. Immune to fall damage in both forms.
### 4. Aswid
- **The Vampire**: A creature of the night with powerful life-draining abilities.
- **Bat Transformation**: Press G to transform into a bat, allowing you to fly over obstacles and travel quickly.
- **Blood Magic**: Block to channel a life-draining aura that saps the life of enemies in an area around you (doubled radius at night). **Only available while in Bat or Mist form.**
- **Blood Magic Mastery**: You can cast Blood Magic items with infinite Eitr, relying purely on their health costs.
- **Day walker, Night stalker**: Your passive speed and jump bonuses double during the night.
- **Undead Vigor**: Like the skeleton, the Aswid has infinite stamina. You consume the lifeforce of fallen foes directly instead of eating standard food.
### 5. Furling
- **Goblin Heritage**: You play as a Goblin (Fuling). No beard, no hair (for males).
- **Combat Mastery**: All weapon and combat skills gain 2x XP permanently.
- **Boss-Driven Progression**: Each major boss defeat unlocks a new passive ability.
### 6. Trol
- **Trol Heritage**: Play as a massive Trol! You are natively 20% larger than a human.
- **Immense Strength**: Your carry weight is vastly increased and your armor naturally scales as you defeat bosses.
- **Rock Throwing**: You can hurl boulders at your enemies for massive physical damage.
- **Tree Weaponry**: At higher levels, transform into your True Form to rip logs directly out of trees and wield them as devastating weapons or throw them!
## Installation (manual)
1. Install BepInExPack Valheim.
2. Install Jotunn.
3. Extract the contents of this mod into your BepInEx/plugins folder.
## Race Progressions (Level-by-Level)
### Trol Progression
- **Base (No Bosses)**: +20% Size. +200 Max Carry Weight. Gain +3 Armor per boss defeated.
- **Eikthyr**: Increased XP gain for physical labor and blunt combat (Clubs, Unarmed, Axes, Pickaxes, WoodCutting).
- **The Elder**: Unlock Rock Throwing ability. +10% passive health regeneration.
- **Bonemass**: +5% Size. +50 Carry Weight. +10 Damage to Clubs/Unarmed. +10 Rock Throwing Damage. Unlocks a **4th Food Slot**.
- **Moder**: Unlock True Form (Transformation ability).
- **Yagluth**: +5% Size. +50 Carry Weight. +10 Damage to Clubs/Unarmed. +5 Rock Throwing Damage. Unlocks a **5th Food Slot**.
- **The Queen**: Unlock Log Weapon (in True Form, interact with trees to wield them as weapons). True Form size is massively increased (2.5x).
- **Fader**: Your wielded trees can now instantly smash through the toughest materials in the Ashlands.
### Furling Progression
- **Base (No Bosses)**: Goblin head model. All weapon & combat skills gain 2x XP permanently.
- **Eikthyr**: Master of Shadows — sounds ≤15m are suppressed (near-silent movement).
- **The Elder**: The Wickerman — -50% Fire & Poison damage; arrows gain bonus fire damage.
- **Bonemass**: Dance of the Dead — Crafting meads, bombs, and ammo yields double quantity.
- **Moder**: The Man/Woman on the Silver Mountain — doubles trophy drops from normal enemies within 25m, drops bonus gold from starred enemies, doubles ore mining yield.
- **Yagluth**: The King is Dead, Hail to the King/Queen — while in the Plains biome, ALL skills gain 2x XP (including magic). HUD status icon shown.
- **The Queen**: In the Mist He/She Was Standing — blue (Eitr) foods last twice as long.
- **Fader**: Through Fire and Flames — permanently on fire (visual only), immune to fire damage, physical attacks set targets on fire.
### Aswid Progression
- **Base (No Bosses)**: Physical kills automatically consume enemies (if edible). Progressive stats (+1 Armor, +2 Damage, +1% Speed, +1% Jump per boss killed). All passive bonuses are doubled at night! You can cast Blood Magic items with infinite Eitr.
- **Eikthyr**: Bat Transformation (Night only). Vampiric Aura (heal 20% on magic AoE damage).
- **The Elder**: Bat Transformation (Always active).
- **Bonemass**: Superhuman Senses (Aura reveals untamed creatures).
- **Moder**: Freezing Blood (Permanent immunity to Freezing and Poison).
- **Yagluth**: Enslavement Power (E Key — Enslave non-tameable enemies).
- **The Queen**: Mist Form (H Key — Immune to physical/poison, double aura damage, weak to fire/frost/spirit. Breaks at sunrise).
- **Fader**: +10% Size, +30 Physical Damage. Physical kills automatically consume enemies.
### Skadi Progression
- **Base (No Bosses)**: Immune to Cold, Bonus Frost Damage, 50% Frost Resistance.
- **Eikthyr**: +20% Eitr Regen, Freezing to Cold, Cold Spell.
- **The Elder**: Drake Form (Cannot attack).
- **Bonemass**: Drake Form (Can attack).
- **Moder**: Moder Form (1 min duration, 10 min cooldown).
- **Yagluth**: Improved Cold Spell. Moder Form (1 min duration, 5 min cooldown).
- **The Queen**: Moder Form (Unlimited duration, no cooldown).
- **Fader**: Skeleton Dragon Form.
### Skeleton Progression
- **Base (No Bosses)**: +50 Max Health. Undead Diet (Cannot eat mortal food, no stamina bar).
- **Eikthyr**: Poison Skeleton Model, Poison Immunity, 5% Lifesteal, +80 Max Health.
- **The Elder**: 10% Lifesteal, Auto-Stun on First Hit, +110 Max Health.
- **Bonemass**: 15% Lifesteal, Poison Attacks, +140 Max Health.
- **Moder**: Fire Skeleton Model, 20% Lifesteal, Fire Aura, Enhanced Regen, +170 Max Health.
- **Yagluth**: 25% Lifesteal, Auto Resurrect, +200 Max Health.
- **The Queen**: 30% Lifesteal, Summon on Kill (Max 3 Skeletons), +230 Max Health.
- **Fader**: 35% Lifesteal, Max 5 Summons, +275 Max Health.
### Fenrir Progression
- **Base (No Bosses)**: Progressive stats (+3 Armor, +5 Damage, -10% Fall Damage, +3% Speed, +3% Jump per boss killed).
- **The Elder**: Wolf Form (Night).
- **Bonemass**: Wolf Form (Day/Night). Ulv Form (Night).
- **Moder**: Ulv Form (Day/Night). Fenring Form (Night).
- **Yagluth**: Cultist Form (Night — 1 min duration, 10 min cooldown).
- **The Queen**: Fenring Form (Day/Night). Cultist Form (Night — 1 min duration, 5 min cooldown).
- **Fader**: Cultist Form (Day/Night).
## Development & Feedback
This is a stable release of Races of Valheim, but the mod is actively in development! We plan to add more races, gameplay elements, and refine the mechanics in future updates.
Any feedback, bug reports, or suggestions for new features are more than welcome.
Please write to us on my Discord server: **https://discord.gg/gbBEK2VTE**
## Changelog
**v1.3.2**
- **Aswid**: Blood Magic (Vampiric Aura) is now only active when blocking in Bat or Mist form. Base damage reduced by 50%.
- **Aswid**: Added thematic day/night transition messages ("what a horrible night to have a curse").
- **Bugfix**: Fixed an issue where the new automatic food consumption logic for Aswid physical kills failed to find the correct prefabs for basic animals like Deer and Boars.
**v1.3.1**
- **NEW RACE — Trol**: Added the sixth playable race, the Trol. Huge size, immense strength, rock throwing, and the ability to wield trees as weapons!
- **Trol Combat**: The Trol starts with increased size and carry weight, scaling stats as bosses are killed, and unlocking the ability to throw massive rocks at The Elder tier.
- **Trol True Form**: Unlocked at Moder, allowing you to transform. Once you defeat The Queen, you can look at trees while in True Form to rip a log out and use it as a massive 2-handed weapon!
- **Trol Stomachs**: As you progress, you unlock a 4th (Bonemass) and a 5th (Yagluth) stomach slot, allowing you to consume up to 5 foods simultaneously!
- **Bugfixes**: Fixed various item/food duplication bugs and polished the new eating logic to perfectly integrate with the native UI.
**v1.3.0**
- **NEW RACE — Furling**: Added the fifth playable race, the Furling (Goblin). Unique goblin head model, full progression tied to all 7 bosses.
- **Furling — Eikthyr (Master of Shadows)**: Sounds below 15m range are suppressed, making you nearly silent at night or in dungeons.
- **Furling — The Elder (The Wickerman)**: Gain -50% Fire and Poison damage resistance. Arrows gain bonus fire damage.
- **Furling — Bonemass (Dance of the Dead)**: Crafting meads, bombs, and ammo yields double the quantity.
- **Furling — Moder (The Man/Woman on the Silver Mountain)**: Trophy drops from normal enemies are doubled, starred enemies drop bonus coins, and ore mining yields are doubled.
- **Furling — Yagluth (The King is Dead, Hail to the King/Queen)**: In the Plains biome, the 2x XP multiplier extends to ALL skills (including Elemental and Blood Magic). A HUD status icon appears in the top-right when active.
- **Furling — The Queen (In the Mist He/She Was Standing)**: Eitr (blue) foods last twice as long for you.
- **Furling — Fader (Through Fire and Flames)**: You are permanently wreathed in native fire flames (SE_Burning visual, no damage, no HUD warning). Full fire immunity. All physical attacks set targets on fire.
- **Bugfix**: Fixed MineRock.RPC_Damage → MineRock.RPC_Hit Harmony patch after a Valheim update renamed the method.
**v1.2.0**
- **Multiplayer Sync**: Fully implemented visual syncing for Aswid forms (Bat, Mist) and Skadi forms (Bear, Wolf, Hatchling, Fader) so other players can see your transformations in multiplayer!
- **Aswid**: Scrapped the Fader (Surtling) visual override; reaching the final progression state now makes the player 10% taller and adds a flat +30 physical damage bonus.
- **Aswid**: Defeating enemies with physical attacks in the final state now automatically consumes them if you have food slots available.
- **General**: Eradicated remaining localizations of the old "Strigoi" name.
**v1.1.0**
- **Aswid**: Passive abilities (Speed and Jump) are now properly doubled during the night.
- **Aswid**: New Enslavement Power (Yagluth tier)! Press E on non-tameable, non-boss enemies to enslave them for 60 seconds (15-min cooldown). Enslaved thralls fight alongside you and drop standard loot.
- **Aswid**: Edible thralls are automatically consumed upon death, granting you their lifeforce (Fader tier).
- **Aswid**: Complete overhaul of the Food system. Added Mistlands and Ashlands creatures to the consumption map. Accurately scaled food stats based on creature health.
- **Aswid**: Excluded undead and inorganic creatures (Skeletons, Draugrs, Golems, etc.) from being edible.
- **Aswid**: Added a dynamic green light effect to all forms (Bonemass tier).
**v1.0.0**
- Initial release with 4 distinct races.
- Added Aswid life-draining and night transformations.
- Complete progression system tied to Valheim's bosses.

View file

@ -0,0 +1,217 @@
using UnityEngine;
using HarmonyLib;
using System.Text;
using System.Collections.Generic;
namespace RacesOfValheim
{
public static class RaceCompendium
{
private static readonly string[] RaceTitles = new string[]
{
"Aswid Secrets",
"Fenrir Secrets",
"Skadi Secrets",
"Skeleton Secrets",
"Furling Secrets",
"Trol Secrets"
};
public static void UpdateCompendiumText(Player player)
{
if (player == null) return;
var knownTexts = HarmonyLib.Traverse.Create(player).Field("m_knownTexts").GetValue<Dictionary<string, string>>();
if (knownTexts == null) return;
// 1. Remove all old race texts to keep it clean
foreach (var title in RaceTitles)
{
if (knownTexts.ContainsKey(title))
{
knownTexts.Remove(title);
}
}
// 2. Determine current race
ZNetView nview = player.GetComponent<ZNetView>();
if (nview == null || !nview.IsValid()) return;
string currentRace = nview.GetZDO().GetString("RacesOfValheim_Race", "Human");
int state = BossProgressionManager.GetCurrentProgressionState();
if (currentRace == "Aswid")
{
GenerateAswidText(knownTexts, state);
}
else if (currentRace == "Fenrir")
{
GenerateFenrirText(knownTexts, state);
}
else if (currentRace == "Skadi")
{
GenerateSkadiText(knownTexts, state);
}
else if (currentRace == "Skeleton")
{
GenerateSkeletonText(knownTexts, state);
}
else if (currentRace == "Furling")
{
GenerateFurlingText(knownTexts, state, player);
}
else if (currentRace == "Trol")
{
GenerateTrolText(knownTexts, state, player);
}
}
private static void GenerateTrolText(Dictionary<string, string> knownTexts, int state, Player player)
{
StringBuilder sb = new StringBuilder();
sb.AppendLine("The Trol's Heritage\n");
sb.AppendLine($"Base Passive: Physical kills automatically consume enemies (if edible). You are natively 20% larger than a human with immense strength. You have +200 Max Carry Weight and gain +3 Armor per boss defeated.\n");
if (state >= 1)
sb.AppendLine("Eikthyr Defeated: Increased XP gain for physical labor and blunt combat (Clubs, Unarmed, Axes, Pickaxes, WoodCutting).\n");
if (state >= 2)
sb.AppendLine("The Elder Defeated: Unlocked Rock Throwing ability. +10% passive health regeneration.\n");
if (state >= 3)
sb.AppendLine("Bonemass Defeated: +5% Size, +50 Carry Weight, +10 Damage to Clubs/Unarmed, +10 Rock Throwing Damage. Unlocked 4th Food Slot.\n");
if (state >= 4)
sb.AppendLine("Moder Defeated: Unlocked True Form (Transformation ability).\n");
if (state >= 5)
sb.AppendLine("Yagluth Defeated: +5% Size, +50 Carry Weight, +10 Damage to Clubs/Unarmed, +5 Rock Throwing Damage. Unlocked 5th Food Slot.\n");
if (state >= 6)
sb.AppendLine("The Queen Defeated: Unlocked Log Weapon (in True Form, interact with trees to wield them as weapons). True Form size is massively increased.\n");
if (state >= 7)
sb.AppendLine("Fader Defeated: Your wielded trees can now instantly smash through the toughest materials in the Ashlands.\n");
knownTexts["Trol Secrets"] = sb.ToString();
}
private static void GenerateAswidText(Dictionary<string, string> knownTexts, int state)
{
int spd = state * 3;
int jmp = state * 3;
int arm = state * 3;
int dmg = state * 5;
StringBuilder sb = new StringBuilder();
sb.AppendLine("The Aswid's Curse\n");
sb.AppendLine($"[Base Passive] Benedictus et Afflictus:");
sb.AppendLine($"Physical kills automatically consume enemies (Vae Victis) granting Blood Magic XP. Your physical stats scale progressively as you defeat Valheim's Bosses: +{arm} Armor, +{dmg} Damage, +{spd}% Speed, and +{jmp}% Jump. All your passive bonuses are doubled during the night. You can cast Blood Magic items with infinite Eitr, and your Blood Magic skill increases twice as fast.\n");
sb.AppendLine("Vampiric Aura (Like a Bat out of Hell/Weight of Shadows Only): Block with your shield (Mouse 2) while in bat or mist form to channel an AoE magic damage aura against nearby enemies, healing for 20% of the damage dealt and converting them into food when they die.\n");
if (state >= 1)
{
// Eikthyr - Base passives already covered
}
if (state >= 5)
{
sb.AppendLine("[Moder Unlock] Freezing Blood (Passive):");
sb.AppendLine("You gain permanent immunity to the Freezing status (mountains/snowstorms) and Poison damage.\n");
sb.AppendLine("[Moder Unlock] Auspex (Passive):");
sb.AppendLine("You emit a 10-meter aura that reveals the presence of untamed creatures by wreathing them in ethereal flames.\n");
}
if (state >= 6)
{
sb.AppendLine("[Yagluth Unlock] Dominate (E Key):");
sb.AppendLine("Press E on non-tameable, non-boss enemies to dominate them for 60 seconds (15-min cooldown). Dominated thralls fight alongside you and drop standard loot.\n");
}
if (state >= 7)
{
sb.AppendLine("[The Queen Unlock] Weight of Shadows (H Key):");
sb.AppendLine("You transform into an elusive mist. You become immune to physical and poison damage, but weak to fire, frost, and spirit. Your Vampiric Aura deals double damage, but you cannot attack or run. Sunrise breaks the transformation.\n");
}
if (state >= 8)
{
sb.AppendLine("[Fader Unlock] Asmund (Passive):");
sb.AppendLine("Your hair and beard turn as dark as the abyss. You become 10% taller and gain a flat +30 to Physical Damage.\n");
}
knownTexts["Aswid Secrets"] = sb.ToString();
}
private static void GenerateFenrirText(Dictionary<string, string> knownTexts, int state)
{
int spd = state * 3;
int jmp = state * 3;
int arm = state * 3;
int dmg = state * 5;
knownTexts["Fenrir Secrets"] = $"The secrets of the pack will be revealed soon...\n\nBase Passive: Physical kills automatically consume enemies (if edible). Your physical stats scale progressively as you defeat Valheim's Bosses: +{arm} Armor, +{dmg} Damage, +{spd}% Speed, and +{jmp}% Jump.";
}
private static void GenerateSkadiText(Dictionary<string, string> knownTexts, int state)
{
knownTexts["Skadi Secrets"] = "The secrets of winter will be revealed soon...";
}
private static void GenerateSkeletonText(Dictionary<string, string> knownTexts, int state)
{
knownTexts["Skeleton Secrets"] = "The secrets of the crypt will be revealed soon...";
}
private static void GenerateFurlingText(Dictionary<string, string> knownTexts, int state, Player player)
{
StringBuilder sb = new StringBuilder();
sb.AppendLine("The secrets of the hoard will be revealed soon...\n");
sb.AppendLine("[Base Passive] Combat Mastery:");
sb.AppendLine("All weapon and combat skills gain 2x XP permanently. You're short, but very fast — your movement speed is permanently increased by 10%.\n");
if (state >= 5)
{
int modelIndex = Traverse.Create(player.GetComponent<VisEquipment>()).Field<int>("m_modelIndex").Value;
string title = modelIndex == 1 ? "The Woman on the Silver Mountain" : "The Man on the Silver Mountain";
sb.AppendLine($"[Moder Unlock] {title} (Passive):");
sb.AppendLine("Whenever a normal enemy dies within 25 meters, its trophy drops are doubled and it drops guaranteed gold coins based on its stars. Furthermore, whenever you mine raw ore deposits, your yield is doubled.\n");
}
if (state >= 6)
{
int modelIndex = Traverse.Create(player.GetComponent<VisEquipment>()).Field<int>("m_modelIndex").Value;
string title = modelIndex == 1 ? "The King is Dead, Hail to the Queen" : "The King is Dead, Hail to the King";
sb.AppendLine($"[Yagluth Unlock] {title} (Passive):");
sb.AppendLine("While you are in the Plains biome, your 2x XP multiplier is extended to all non-combat skills (including Elemental Magic and Blood Magic).\n");
}
if (state >= 7)
{
int modelIndex = Traverse.Create(player.GetComponent<VisEquipment>()).Field<int>("m_modelIndex").Value;
string title = modelIndex == 1 ? "In the Mist She Was Standing" : "In the Mist He Was Standing";
sb.AppendLine($"[The Queen Unlock] {title} (Passive):");
sb.AppendLine("Blue foods (those that restore Eitr) last twice as long for you compared to normal players.\n");
}
if (state >= 8)
{
sb.AppendLine("[Fader Unlock] Through Fire and Flames (Passive):");
sb.AppendLine("You are permanently wreathed in flames. You are completely immune to fire damage. All your physical attacks (regardless of weapon or unarmed) set the target on fire.\n");
}
knownTexts["Furling Secrets"] = sb.ToString();
}
}
[HarmonyPatch(typeof(TextsDialog), "Setup")]
public static class CompendiumSetup_Patch
{
public static void Prefix(Player player)
{
if (player != null)
{
RaceCompendium.UpdateCompendiumText(player);
}
}
}
}

View file

@ -0,0 +1,56 @@
using HarmonyLib;
using UnityEngine;
namespace RacesOfValheim
{
// --- RACE HOSTILITY MANAGER ---
// This script manages which mobs should not attack the player based on their race.
// For now, it manages wolves, ulvs, fenrings, and cultists for the Fenrir race.
[HarmonyPatch(typeof(BaseAI), nameof(BaseAI.IsEnemy), new System.Type[] { typeof(Character), typeof(Character) })]
public static class RaceHostilityManager
{
public static void Postfix(Character a, Character b, ref bool __result)
{
if (!__result) return; // If already not enemies, skip
if (a == null || b == null) return;
Character playerCharacter = a.IsPlayer() ? a : (b.IsPlayer() ? b : null);
Character monster = a.IsPlayer() ? b : (b.IsPlayer() ? a : null);
if (playerCharacter != null && monster != null)
{
Player p = playerCharacter as Player;
if (p != null)
{
// Fenrir Race Logic
if (p.m_customData.ContainsKey("Race") && p.m_customData["Race"] == "Fenrir")
{
string prefabName = monster.gameObject.name.ToLower();
if (prefabName.Contains("wolf") || prefabName.Contains("fenring") ||
prefabName.Contains("ulv") || prefabName.Contains("cultist"))
{
__result = false;
}
}
// Aswid Race Logic
if (p.m_customData.ContainsKey("Race") && p.m_customData["Race"] == "Aswid")
{
string prefabName = monster.gameObject.name.ToLower();
int state = BossProgressionManager.GetCurrentProgressionState();
if (state >= 2 && prefabName.Contains("boar")) __result = false;
if (state >= 3 && prefabName.Contains("bear")) __result = false;
if (state >= 4 && (prefabName.Contains("leech") || prefabName.Contains("ghost") || prefabName.Contains("wraith"))) __result = false;
if (state >= 5 && prefabName.Contains("wolf")) __result = false;
if (state >= 6 && (prefabName.Contains("lox") || prefabName.Contains("deathsquito"))) __result = false;
if (state >= 7 && (prefabName.Contains("hare") || prefabName.Contains("gjall"))) __result = false;
if (state >= 8 && (prefabName.Contains("asksvin") || prefabName.Contains("volture") || prefabName.Contains("vulture") || prefabName.Contains("valkyrie"))) __result = false;
}
}
}
}
}
}

View file

@ -0,0 +1,685 @@
using System.Collections;
using BepInEx;
using HarmonyLib;
using Jotunn.Configs;
using Jotunn.Entities;
using Jotunn.Managers;
using UnityEngine;
using UnityEngine.UI; // Added for UI
namespace RacesOfValheim
{
[BepInPlugin(PluginGUID, PluginName, PluginVersion)]
[BepInDependency(Jotunn.Main.ModGuid)]
public class RacesOfValheim : BaseUnityPlugin
{
public const string PluginGUID = "com.nandor.racesofvalheim";
public const string PluginName = "Races Of Valheim";
public const string PluginVersion = "1.3.2";
private readonly Harmony harmony = new Harmony(PluginGUID);
public static RacesOfValheim Instance;
private GameObject raceSelectionMenu;
private void Awake() {
Instance = this;
harmony.PatchAll();
gameObject.AddComponent<FenrirRace>();
gameObject.AddComponent<SkadiRace>();
gameObject.AddComponent<SkeletonRace>();
gameObject.AddComponent<AswidRace>();
gameObject.AddComponent<FurlingRace>();
gameObject.AddComponent<TrolRace>();
PrefabManager.OnVanillaPrefabsAvailable += CreateAllModAssets;
CommandManager.Instance.AddConsoleCommand(new ResetRaceCommand());
CommandManager.Instance.AddConsoleCommand(new CheckProgressionCommand());
CommandManager.Instance.AddConsoleCommand(new IncreaseProgressionCommand());
CommandManager.Instance.AddConsoleCommand(new ResetProgressionCommand());
}
private void CreateAllModAssets() {
PrefabManager.OnVanillaPrefabsAvailable -= CreateAllModAssets;
FenrirRace.Instance.CreateModAssets();
SkadiRace.Instance.CreateModAssets();
SkeletonRace.Instance.CreateModAssets();
AswidRace.Instance.CreateModAssets();
FurlingRace.Instance.CreateModAssets();
TrolRace.Instance.CreateModAssets();
}
// --- RACE SELECTION UI ---
public void ShowRaceSelectionMenu()
{
if (raceSelectionMenu != null) return;
if (GUIManager.Instance == null || GUIManager.CustomGUIFront == null)
{
Jotunn.Logger.LogWarning("GUIManager.CustomGUIFront is null, cannot show race menu.");
return;
}
raceSelectionMenu = new GameObject("RaceSelectionMenu");
raceSelectionMenu.transform.SetParent(GUIManager.CustomGUIFront.transform, false);
RectTransform rect = raceSelectionMenu.AddComponent<RectTransform>();
rect.anchorMin = new Vector2(0, 0);
rect.anchorMax = new Vector2(1, 1);
rect.offsetMin = Vector2.zero;
rect.offsetMax = Vector2.zero;
Image bg = raceSelectionMenu.AddComponent<Image>();
bg.color = new Color(0, 0, 0, 0.9f);
GameObject selectionPanel = new GameObject("SelectionPanel");
selectionPanel.transform.SetParent(raceSelectionMenu.transform, false);
RectTransform spRect = selectionPanel.AddComponent<RectTransform>();
spRect.anchorMin = Vector2.zero; spRect.anchorMax = Vector2.one;
spRect.offsetMin = Vector2.zero; spRect.offsetMax = Vector2.zero;
GameObject confirmationPanel = new GameObject("ConfirmationPanel");
confirmationPanel.transform.SetParent(raceSelectionMenu.transform, false);
RectTransform cpRect = confirmationPanel.AddComponent<RectTransform>();
cpRect.anchorMin = Vector2.zero; cpRect.anchorMax = Vector2.one;
cpRect.offsetMin = Vector2.zero; cpRect.offsetMax = Vector2.zero;
confirmationPanel.SetActive(false);
GameObject titleObj = new GameObject("Title");
titleObj.transform.SetParent(selectionPanel.transform, false);
Text titleText = titleObj.AddComponent<Text>();
titleText.font = GUIManager.Instance.AveriaSerifBold;
titleText.text = "Choose your Race";
titleText.fontSize = 50;
titleText.alignment = TextAnchor.MiddleCenter;
titleText.color = Color.white;
RectTransform titleRect = titleObj.GetComponent<RectTransform>();
titleRect.anchoredPosition = new Vector2(0, 200);
titleRect.sizeDelta = new Vector2(600, 100);
GameObject confTitleObj = new GameObject("ConfTitle");
confTitleObj.transform.SetParent(confirmationPanel.transform, false);
Text confTitleText = confTitleObj.AddComponent<Text>();
confTitleText.font = GUIManager.Instance.AveriaSerifBold;
confTitleText.fontSize = 50;
confTitleText.alignment = TextAnchor.MiddleCenter;
confTitleText.color = Color.white;
RectTransform confTitleRect = confTitleObj.GetComponent<RectTransform>();
confTitleRect.anchoredPosition = new Vector2(0, 150);
confTitleRect.sizeDelta = new Vector2(600, 100);
GameObject confDescObj = new GameObject("ConfDesc");
confDescObj.transform.SetParent(confirmationPanel.transform, false);
Text confDescText = confDescObj.AddComponent<Text>();
confDescText.font = GUIManager.Instance.AveriaSerifBold;
confDescText.fontSize = 24;
confDescText.alignment = TextAnchor.MiddleCenter;
confDescText.color = Color.white;
RectTransform confDescRect = confDescObj.GetComponent<RectTransform>();
confDescRect.anchoredPosition = new Vector2(0, 0);
confDescRect.sizeDelta = new Vector2(800, 200);
GameObject btnOkObj = new GameObject("OkButton");
btnOkObj.transform.SetParent(confirmationPanel.transform, false);
RectTransform btnOkRect = btnOkObj.AddComponent<RectTransform>();
btnOkRect.sizeDelta = new Vector2(200, 60);
btnOkRect.anchoredPosition = new Vector2(120, -150);
Image btnOkImg = btnOkObj.AddComponent<Image>();
btnOkImg.color = new Color(0.2f, 0.5f, 0.2f, 1f);
Button btnOk = btnOkObj.AddComponent<Button>();
GameObject btnOkTxtObj = new GameObject("Text");
btnOkTxtObj.transform.SetParent(btnOkObj.transform, false);
Text btnOkTxt = btnOkTxtObj.AddComponent<Text>();
btnOkTxt.font = GUIManager.Instance.AveriaSerifBold;
btnOkTxt.text = "OK";
btnOkTxt.fontSize = 24;
btnOkTxt.alignment = TextAnchor.MiddleCenter;
btnOkTxt.color = Color.white;
RectTransform btnOkTxtRect = btnOkTxtObj.GetComponent<RectTransform>();
btnOkTxtRect.anchorMin = Vector2.zero; btnOkTxtRect.anchorMax = Vector2.one;
btnOkTxtRect.offsetMin = Vector2.zero; btnOkTxtRect.offsetMax = Vector2.zero;
GameObject btnBackObj = new GameObject("BackButton");
btnBackObj.transform.SetParent(confirmationPanel.transform, false);
RectTransform btnBackRect = btnBackObj.AddComponent<RectTransform>();
btnBackRect.sizeDelta = new Vector2(200, 60);
btnBackRect.anchoredPosition = new Vector2(-120, -150);
Image btnBackImg = btnBackObj.AddComponent<Image>();
btnBackImg.color = new Color(0.5f, 0.2f, 0.2f, 1f);
Button btnBack = btnBackObj.AddComponent<Button>();
btnBack.onClick.AddListener(() => {
confirmationPanel.SetActive(false);
selectionPanel.SetActive(true);
});
GameObject btnBackTxtObj = new GameObject("Text");
btnBackTxtObj.transform.SetParent(btnBackObj.transform, false);
Text btnBackTxt = btnBackTxtObj.AddComponent<Text>();
btnBackTxt.font = GUIManager.Instance.AveriaSerifBold;
btnBackTxt.text = "Back";
btnBackTxt.fontSize = 24;
btnBackTxt.alignment = TextAnchor.MiddleCenter;
btnBackTxt.color = Color.white;
RectTransform btnBackTxtRect = btnBackTxtObj.GetComponent<RectTransform>();
btnBackTxtRect.anchorMin = Vector2.zero; btnBackTxtRect.anchorMax = Vector2.one;
btnBackTxtRect.offsetMin = Vector2.zero; btnBackTxtRect.offsetMax = Vector2.zero;
void CreateRaceButtonWithConfirm(string label, Vector2 position, Sprite iconSprite, string description, UnityEngine.Events.UnityAction onConfirm)
{
CreateRaceButton(label, position, iconSprite, selectionPanel.transform, () => {
selectionPanel.SetActive(false);
confirmationPanel.SetActive(true);
confTitleText.text = label;
confDescText.text = description;
btnOk.onClick.RemoveAllListeners();
btnOk.onClick.AddListener(onConfirm);
});
}
// Row 1 (y = 100)
CreateRaceButtonWithConfirm("Human", new Vector2(-300, 100), GetHumanIcon(), "The versatile founders of Midgard. Balanced stats with no specific weaknesses.", SelectHuman);
CreateRaceButtonWithConfirm("Fenrir", new Vector2(0, 100), GetFenrirIcon(), "Cursed by the blood of the wolf. Fast and deadly, but vulnerable to silver.", SelectFenrir);
CreateRaceButtonWithConfirm("Skadi", new Vector2(300, 100), GetSkadiIcon(), "Children of the mountains. Resistant to frost, at home in the freezing cold.", SelectSkadi);
// Row 2 (y = 0)
CreateRaceButtonWithConfirm("Skeleton", new Vector2(-300, 0), GetSkeletonIcon(), "Undead warriors. Immune to poison, but brittle against blunt trauma.", SelectSkeleton);
CreateRaceButtonWithConfirm("Aswid", new Vector2(0, 0), GetAswidIcon(), "Fierce night stalker. Strong and resilient, transforms into a bat.", SelectAswid);
CreateRaceButtonWithConfirm("Furling", new Vector2(300, 0), GetFurlingIcon(), "Cunning goblin-like creatures. Agile and resourceful.", SelectFurling);
// Row 3 (y = -100)
CreateRaceButtonWithConfirm("Trol", new Vector2(0, -100), GetTrolIcon(), "Massive brute strength. Towering over others but slow to react.", SelectTrol);
GUIManager.BlockInput(true);
}
private Sprite GetHumanIcon()
{
GameObject clubPrefab = PrefabManager.Cache.GetPrefab<ItemDrop>("Club")?.gameObject;
if (clubPrefab != null)
{
ItemDrop clubDrop = clubPrefab.GetComponent<ItemDrop>();
if (clubDrop != null && clubDrop.m_itemData.m_shared.m_icons.Length > 0)
{
return clubDrop.m_itemData.m_shared.m_icons[0];
}
}
return null;
}
private Sprite GetFenrirIcon()
{
GameObject fenringTrophy = PrefabManager.Cache.GetPrefab<ItemDrop>("TrophyFenring")?.gameObject;
if (fenringTrophy != null)
{
ItemDrop trophyDrop = fenringTrophy.GetComponent<ItemDrop>();
if (trophyDrop != null && trophyDrop.m_itemData.m_shared.m_icons.Length > 0)
{
return trophyDrop.m_itemData.m_shared.m_icons[0];
}
}
return null;
}
private Sprite GetSkadiIcon()
{
GameObject drakeTrophy = PrefabManager.Cache.GetPrefab<ItemDrop>("TrophyHatchling")?.gameObject;
if (drakeTrophy != null)
{
ItemDrop trophyDrop = drakeTrophy.GetComponent<ItemDrop>();
if (trophyDrop != null && trophyDrop.m_itemData.m_shared.m_icons.Length > 0)
{
return trophyDrop.m_itemData.m_shared.m_icons[0];
}
}
return null;
}
private Sprite GetSkeletonIcon()
{
GameObject skelTrophy = PrefabManager.Cache.GetPrefab<ItemDrop>("TrophySkeleton")?.gameObject;
if (skelTrophy != null)
{
ItemDrop trophyDrop = skelTrophy.GetComponent<ItemDrop>();
if (trophyDrop != null && trophyDrop.m_itemData.m_shared.m_icons.Length > 0)
{
return trophyDrop.m_itemData.m_shared.m_icons[0];
}
}
return null;
}
private Sprite GetAswidIcon()
{
GameObject aswidTrophy = PrefabManager.Cache.GetPrefab<ItemDrop>("TrophyWraith")?.gameObject;
if (aswidTrophy != null)
{
ItemDrop trophyDrop = aswidTrophy.GetComponent<ItemDrop>();
if (trophyDrop != null && trophyDrop.m_itemData.m_shared.m_icons.Length > 0)
{
return trophyDrop.m_itemData.m_shared.m_icons[0];
}
}
return null;
}
private void CreateRaceButton(string label, Vector2 position, Sprite iconSprite, Transform parentTransform, UnityEngine.Events.UnityAction onClick)
{
GameObject btnObj = new GameObject(label + "Button");
btnObj.transform.SetParent(parentTransform, false);
RectTransform btnRect = btnObj.AddComponent<RectTransform>();
btnRect.sizeDelta = new Vector2(250, 80);
btnRect.anchoredPosition = position;
Image btnImg = btnObj.AddComponent<Image>();
btnImg.color = new Color(0.2f, 0.2f, 0.2f, 1f);
Button btn = btnObj.AddComponent<Button>();
btn.onClick.AddListener(onClick);
GameObject txtObj = new GameObject("Text");
txtObj.transform.SetParent(btnObj.transform, false);
Text txt = txtObj.AddComponent<Text>();
txt.font = GUIManager.Instance.AveriaSerifBold;
txt.text = label;
txt.fontSize = 30;
txt.alignment = TextAnchor.MiddleCenter;
txt.color = Color.white;
RectTransform txtRect = txtObj.GetComponent<RectTransform>();
txtRect.anchorMin = Vector2.zero;
txtRect.anchorMax = Vector2.one;
txtRect.offsetMin = Vector2.zero;
txtRect.offsetMax = Vector2.zero;
if (iconSprite != null)
{
GameObject iconObj = new GameObject("Icon");
iconObj.transform.SetParent(btnObj.transform, false);
Image iconImg = iconObj.AddComponent<Image>();
iconImg.sprite = iconSprite;
RectTransform iconRect = iconObj.GetComponent<RectTransform>();
iconRect.sizeDelta = new Vector2(60, 60);
iconRect.anchoredPosition = new Vector2(-70, 0); // shift left
txt.alignment = TextAnchor.MiddleRight;
txtRect.offsetMax = new Vector2(-30, 0);
}
}
private void SelectHuman()
{
if (Player.m_localPlayer != null)
{
Player.m_localPlayer.m_customData["Race"] = "Human";
ZNetView nview = Player.m_localPlayer.GetComponent<ZNetView>();
if (nview != null && nview.IsValid()) nview.GetZDO().Set("RacesOfValheim_Race", "Human");
Player.m_localPlayer.Message(MessageHud.MessageType.Center, "You chose to remain Human.");
}
CloseRaceSelectionMenu();
}
private void SelectFenrir()
{
if (Player.m_localPlayer != null)
{
Player.m_localPlayer.m_customData["Race"] = "Fenrir";
ZNetView nview = Player.m_localPlayer.GetComponent<ZNetView>();
if (nview != null && nview.IsValid()) nview.GetZDO().Set("RacesOfValheim_Race", "Fenrir");
Player.m_localPlayer.m_customData["FenrirCurse_Active"] = "true";
Player.m_localPlayer.GetSEMan().AddStatusEffect("SE_FenrirCurse".GetStableHashCode(), true);
Player.m_localPlayer.Message(MessageHud.MessageType.Center, "You chose the path of the Fenrir.");
}
CloseRaceSelectionMenu();
}
private void SelectSkadi()
{
if (Player.m_localPlayer != null)
{
Player.m_localPlayer.m_customData["Race"] = "Skadi";
ZNetView nview = Player.m_localPlayer.GetComponent<ZNetView>();
if (nview != null && nview.IsValid()) nview.GetZDO().Set("RacesOfValheim_Race", "Skadi");
Player.m_localPlayer.Message(MessageHud.MessageType.Center, "You chose the path of Skadi.");
// Force update skin colors
VisEquipment visEq = Player.m_localPlayer.GetComponent<VisEquipment>();
if (visEq != null)
{
visEq.GetType().GetMethod("UpdateColors", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Public)?.Invoke(visEq, null);
}
}
CloseRaceSelectionMenu();
}
private void SelectSkeleton()
{
if (Player.m_localPlayer != null)
{
Player.m_localPlayer.m_customData["Race"] = "Skeleton";
ZNetView nview = Player.m_localPlayer.GetComponent<ZNetView>();
if (nview != null && nview.IsValid()) nview.GetZDO().Set("RacesOfValheim_Race", "Skeleton");
// Add the stats SE for Skeleton
Player.m_localPlayer.GetSEMan().AddStatusEffect("SE_SkeletonStats".GetStableHashCode(), true);
VisEquipment visEq = Player.m_localPlayer.GetComponent<VisEquipment>();
if (visEq != null)
{
visEq.GetType().GetMethod("UpdateColors", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Public)?.Invoke(visEq, null);
}
Player.m_localPlayer.Message(MessageHud.MessageType.Center, "You chose the path of the Skeleton.");
CloseRaceSelectionMenu();
}
}
private void SelectAswid()
{
if (Player.m_localPlayer != null)
{
Player.m_localPlayer.m_customData["Race"] = "Aswid";
ZNetView nview = Player.m_localPlayer.GetComponent<ZNetView>();
if (nview != null && nview.IsValid()) nview.GetZDO().Set("RacesOfValheim_Race", "Aswid");
VisEquipment visEq = Player.m_localPlayer.GetComponent<VisEquipment>();
if (visEq != null)
{
// Save original skin color
if (!Player.m_localPlayer.m_customData.ContainsKey("OriginalSkinColor_X"))
{
Vector3 currentSkinColor = Traverse.Create(visEq).Field("m_skinColor").GetValue<Vector3>();
Player.m_localPlayer.m_customData["OriginalSkinColor_X"] = currentSkinColor.x.ToString();
Player.m_localPlayer.m_customData["OriginalSkinColor_Y"] = currentSkinColor.y.ToString();
Player.m_localPlayer.m_customData["OriginalSkinColor_Z"] = currentSkinColor.z.ToString();
}
// Force max white
Traverse.Create(visEq).Method("SetSkinColor", new Vector3(1f, 1f, 1f)).GetValue();
visEq.GetType().GetMethod("UpdateColors", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Public)?.Invoke(visEq, null);
}
Player.m_localPlayer.Message(MessageHud.MessageType.Center, "You chose the path of the Aswid.");
CloseRaceSelectionMenu();
}
}
private void SelectFurling()
{
if (Player.m_localPlayer != null)
{
Player.m_localPlayer.m_customData["Race"] = "Furling";
ZNetView nview = Player.m_localPlayer.GetComponent<ZNetView>();
if (nview != null && nview.IsValid()) nview.GetZDO().Set("RacesOfValheim_Race", "Furling");
VisEquipment visEq = Player.m_localPlayer.GetComponent<VisEquipment>();
if (visEq != null)
{
if (!Player.m_localPlayer.m_customData.ContainsKey("OriginalSkinColor_X"))
{
Vector3 currentSkinColor = Traverse.Create(visEq).Field("m_skinColor").GetValue<Vector3>();
Player.m_localPlayer.m_customData["OriginalSkinColor_X"] = currentSkinColor.x.ToString();
Player.m_localPlayer.m_customData["OriginalSkinColor_Y"] = currentSkinColor.y.ToString();
Player.m_localPlayer.m_customData["OriginalSkinColor_Z"] = currentSkinColor.z.ToString();
}
Traverse.Create(visEq).Method("SetSkinColor", new Vector3(0.3f, 0.8f, 0.3f)).GetValue();
visEq.GetType().GetMethod("UpdateColors", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Public)?.Invoke(visEq, null);
}
Player.m_localPlayer.Message(MessageHud.MessageType.Center, "You chose the path of the Furling.");
CloseRaceSelectionMenu();
}
}
private Sprite GetFurlingIcon()
{
GameObject trophyPrefab = PrefabManager.Cache.GetPrefab<ItemDrop>("TrophyGoblin")?.gameObject;
if (trophyPrefab != null)
{
ItemDrop trophyDrop = trophyPrefab.GetComponent<ItemDrop>();
if (trophyDrop != null && trophyDrop.m_itemData.m_shared.m_icons.Length > 0)
{
return trophyDrop.m_itemData.m_shared.m_icons[0];
}
}
return null;
}
private void SelectTrol()
{
if (Player.m_localPlayer != null)
{
Player.m_localPlayer.m_customData["Race"] = "Trol";
ZNetView nview = Player.m_localPlayer.GetComponent<ZNetView>();
if (nview != null && nview.IsValid()) nview.GetZDO().Set("RacesOfValheim_Race", "Trol");
VisEquipment visEq = Player.m_localPlayer.GetComponent<VisEquipment>();
if (visEq != null)
{
if (!Player.m_localPlayer.m_customData.ContainsKey("OriginalSkinColor_X"))
{
Vector3 currentSkinColor = Traverse.Create(visEq).Field("m_skinColor").GetValue<Vector3>();
Player.m_localPlayer.m_customData["OriginalSkinColor_X"] = currentSkinColor.x.ToString();
Player.m_localPlayer.m_customData["OriginalSkinColor_Y"] = currentSkinColor.y.ToString();
Player.m_localPlayer.m_customData["OriginalSkinColor_Z"] = currentSkinColor.z.ToString();
}
Traverse.Create(visEq).Method("SetSkinColor", new Vector3(0.1f, 0.6f, 0.7f)).GetValue();
visEq.GetType().GetMethod("UpdateColors", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Public)?.Invoke(visEq, null);
}
Player.m_localPlayer.Message(MessageHud.MessageType.Center, "You chose the path of the Trol.");
CloseRaceSelectionMenu();
}
}
private Sprite GetTrolIcon()
{
GameObject trophyPrefab = PrefabManager.Cache.GetPrefab<ItemDrop>("TrophyFrostTroll")?.gameObject;
if (trophyPrefab == null) trophyPrefab = PrefabManager.Cache.GetPrefab<ItemDrop>("TrophyTroll")?.gameObject;
if (trophyPrefab != null)
{
ItemDrop trophyDrop = trophyPrefab.GetComponent<ItemDrop>();
if (trophyDrop != null && trophyDrop.m_itemData.m_shared.m_icons.Length > 0)
{
return trophyDrop.m_itemData.m_shared.m_icons[0];
}
}
return null;
}
public void CloseRaceSelectionMenu()
{
if (raceSelectionMenu != null)
{
Destroy(raceSelectionMenu);
raceSelectionMenu = null;
}
GUIManager.BlockInput(false);
}
}
// --- MAIN MENU CHARACTER PREVIEW SKIN PATCH ---
// Forces skin color/visuals refresh on the FejdStartup character preview
// so Aswid/Furling skins are visible before loading into a world.
[HarmonyPatch(typeof(FejdStartup), "SetupCharacterPreview")]
public static class FejdStartup_SetupCharacterPreview_Patch
{
public static void Postfix(FejdStartup __instance) => ForcePreviewRefresh(__instance);
internal static void ForcePreviewRefresh(FejdStartup instance)
{
// GetPreviewPlayer returns the preview Player instance (has m_customData but no ZNetView)
Player preview = instance.GetType()
.GetMethod("GetPreviewPlayer",
System.Reflection.BindingFlags.Instance |
System.Reflection.BindingFlags.NonPublic |
System.Reflection.BindingFlags.Public)
?.Invoke(instance, null) as Player;
if (preview == null) return;
VisEquipment visEq = preview.GetComponent<VisEquipment>();
if (visEq == null) return;
// Fire UpdateVisuals first (goblin head, hair/beard hide), then UpdateColors (skin tint)
var flags = System.Reflection.BindingFlags.Instance |
System.Reflection.BindingFlags.NonPublic |
System.Reflection.BindingFlags.Public;
visEq.GetType().GetMethod("UpdateVisuals", flags)?.Invoke(visEq, null);
visEq.GetType().GetMethod("UpdateColors", flags)?.Invoke(visEq, null);
}
}
[HarmonyPatch(typeof(FejdStartup), "SetSelectedProfile")]
public static class FejdStartup_SetSelectedProfile_Patch
{
public static void Postfix(FejdStartup __instance) =>
FejdStartup_SetupCharacterPreview_Patch.ForcePreviewRefresh(__instance);
}
// --- PLAYER SPAWN PATCH (RACE CHECK) ---
[HarmonyPatch(typeof(Player), "OnSpawned")]
public static class PlayerSpawnPatch
{
public static void Postfix(Player __instance)
{
if (__instance == Player.m_localPlayer)
{
if (__instance.m_customData.ContainsKey("FenrirCurse_Active") && __instance.m_customData["FenrirCurse_Active"] == "true")
{
__instance.GetSEMan().AddStatusEffect("SE_FenrirCurse".GetStableHashCode(), true);
}
// If Skadi, Aswid, Furling or Trol, re-trigger visual update to set skin color
if (__instance.m_customData.ContainsKey("Race") && (__instance.m_customData["Race"] == "Skadi" || __instance.m_customData["Race"] == "Aswid" || __instance.m_customData["Race"] == "Furling" || __instance.m_customData["Race"] == "Trol"))
{
VisEquipment visEq = __instance.GetComponent<VisEquipment>();
if (visEq != null) visEq.GetType().GetMethod("UpdateColors", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Public)?.Invoke(visEq, null);
}
// Check for Race Selection
if (!__instance.m_customData.ContainsKey("Race"))
{
if (RacesOfValheim.Instance != null)
{
RacesOfValheim.Instance.ShowRaceSelectionMenu();
}
}
}
}
}
// --- CONSOLE COMMANDS ---
public class ResetRaceCommand : ConsoleCommand
{
public override string Name => "resetrace";
public override string Help => "Resets the player's race and reopens the race selection menu for debugging";
public override void Run(string[] args)
{
if (Player.m_localPlayer != null)
{
Player.m_localPlayer.m_customData.Remove("Race");
Player.m_localPlayer.m_customData.Remove("FenrirCurse_Active");
// Restore original skin color if it exists
if (Player.m_localPlayer.m_customData.ContainsKey("OriginalSkinColor_X"))
{
float x = float.Parse(Player.m_localPlayer.m_customData["OriginalSkinColor_X"]);
float y = float.Parse(Player.m_localPlayer.m_customData["OriginalSkinColor_Y"]);
float z = float.Parse(Player.m_localPlayer.m_customData["OriginalSkinColor_Z"]);
Vector3 origColor = new Vector3(x, y, z);
VisEquipment visEq = Player.m_localPlayer.GetComponent<VisEquipment>();
if (visEq != null)
{
Traverse.Create(visEq).Method("SetSkinColor", origColor).GetValue();
visEq.GetType().GetMethod("UpdateColors", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Public)?.Invoke(visEq, null);
}
}
Player.m_localPlayer.GetSEMan().RemoveStatusEffect("SE_FenrirCurse".GetStableHashCode());
Player.m_localPlayer.GetSEMan().RemoveStatusEffect("SE_AswidStats".GetStableHashCode());
Player.m_localPlayer.GetSEMan().RemoveStatusEffect("SE_SkeletonStats".GetStableHashCode());
ZNetView nview = Player.m_localPlayer.GetComponent<ZNetView>();
if (nview != null && nview.IsValid()) nview.GetZDO().Set("RacesOfValheim_Race", "Human");
if (RacesOfValheim.Instance != null)
{
if (FenrirRace.Instance != null) FenrirRace.Instance.ForceRevert();
RacesOfValheim.Instance.ShowRaceSelectionMenu();
}
Console.instance.Print("Race has been reset. The selection menu should now appear.");
}
else
{
Console.instance.Print("You must be in-game to reset your race.");
}
}
}
public class CheckProgressionCommand : ConsoleCommand
{
public override string Name => "checkprogression";
public override string Help => "Checks the current boss progression state (1-8)";
public override void Run(string[] args)
{
int state = BossProgressionManager.GetCurrentProgressionState();
Console.instance.Print($"Current World Boss Progression State: {state}");
if (Player.m_localPlayer != null)
{
Player.m_localPlayer.Message(MessageHud.MessageType.Center, $"World Progression State: {state}");
}
}
}
public class IncreaseProgressionCommand : ConsoleCommand
{
public override string Name => "increaseprogression";
public override string Help => "[DEBUG] Increases the current boss progression state by 1 (max 8)";
public override void Run(string[] args)
{
if (BossProgressionManager.DebugState == -1)
{
BossProgressionManager.DebugState = BossProgressionManager.GetCurrentProgressionState();
}
if (BossProgressionManager.DebugState < 8)
{
BossProgressionManager.DebugState++;
Console.instance.Print($"[DEBUG] Progression state increased to: {BossProgressionManager.DebugState}");
if (Player.m_localPlayer != null)
{
Player.m_localPlayer.Message(MessageHud.MessageType.Center, $"Progression State: {BossProgressionManager.DebugState}");
Traverse.Create(Player.m_localPlayer).Method("SetupEquipment").GetValue();
}
}
else
{
Console.instance.Print("[DEBUG] Progression state is already at maximum (8).");
}
}
}
public class ResetProgressionCommand : ConsoleCommand
{
public override string Name => "resetprogression";
public override string Help => "[DEBUG] Resets the progression state to natural world state";
public override void Run(string[] args)
{
BossProgressionManager.DebugState = -1;
int state = BossProgressionManager.GetCurrentProgressionState();
Console.instance.Print($"[DEBUG] Progression state reset to natural world state: {state}");
if (Player.m_localPlayer != null)
{
Player.m_localPlayer.Message(MessageHud.MessageType.Center, $"Progression reset to: {state}");
Traverse.Create(Player.m_localPlayer).Method("SetupEquipment").GetValue();
}
}
}
}

View file

@ -0,0 +1,107 @@
<?xml version="1.0" encoding="utf-8"?>
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Library</OutputType>
<TargetFramework>net48</TargetFramework>
<RootNamespace>RacesOfValheim</RootNamespace>
<AssemblyName>RacesOfValheim</AssemblyName>
<FileAlignment>512</FileAlignment>
<Deterministic>true</Deterministic>
<LangVersion>10</LangVersion>
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'Debug' ">
<DefineConstants>DEBUG;TRACE</DefineConstants>
<Optimize>false</Optimize>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<WarningLevel>4</WarningLevel>
<AllowUnsafeBlocks>false</AllowUnsafeBlocks>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)' == 'Release' ">
<Optimize>true</Optimize>
<DebugType>pdbonly</DebugType>
<WarningLevel>4</WarningLevel>
<AllowUnsafeBlocks>false</AllowUnsafeBlocks>
</PropertyGroup>
<ItemGroup>
<Reference Include="assembly_utils">
<HintPath>..\..\..\..\..\..\Program Files (x86)\Steam\steamapps\common\Valheim\valheim_Data\Managed\assembly_utils.dll</HintPath>
</Reference>
<Reference Include="assembly_valheim">
<HintPath>..\..\..\..\..\..\Program Files (x86)\Steam\steamapps\common\Valheim\valheim_Data\Managed\assembly_valheim.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<None Include="app.config" />
<None Include="packages.config" />
<None Include="README.md" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="BepInEx.Core" Version="5.4.21" />
<PackageReference Include="JotunnLib" Version="2.29.2" />
</ItemGroup>
<PropertyGroup>
<VALHEIM_MANAGED>$(VALHEIM_INSTALL)/valheim_Data/Managed</VALHEIM_MANAGED>
<UNITY_FOLDER>$(SolutionDir)JotunnModStubUnity</UNITY_FOLDER>
</PropertyGroup>
<Target Name="CopyToUnity">
<Message Text="Copy assemblies to Unity" Importance="high" />
<Copy SourceFiles="$(BEPINEX_PATH)/core/BepInEx.dll" DestinationFolder="$(UNITY_FOLDER)/Assets/Assemblies" />
<Copy SourceFiles="$(BEPINEX_PATH)/core/0Harmony.dll" DestinationFolder="$(UNITY_FOLDER)/Assets/Assemblies" />
<Copy SourceFiles="$(BEPINEX_PATH)/core/Mono.Cecil.dll" DestinationFolder="$(UNITY_FOLDER)/Assets/Assemblies" />
<Copy SourceFiles="$(BEPINEX_PATH)/core/MonoMod.Utils.dll" DestinationFolder="$(UNITY_FOLDER)/Assets/Assemblies" />
<Copy SourceFiles="$(BEPINEX_PATH)/core/MonoMod.RuntimeDetour.dll" DestinationFolder="$(UNITY_FOLDER)/Assets/Assemblies" />
<Copy SourceFiles="$(TargetDir)Jotunn.dll" DestinationFolder="$(UNITY_FOLDER)/Assets/Assemblies" />
<Copy SourceFiles="$(TargetDir)$(TargetName).dll" DestinationFolder="$(UNITY_FOLDER)/Assets/Assemblies" />
<Copy SourceFiles="$(TargetDir)$(TargetName).pdb" DestinationFolder="$(UNITY_FOLDER)/Assets/Assemblies" />
<!-- mdb generation doesn't work from portable pdbs, which are the only kind supported under Linux -->
<Copy Condition="Exists('$(TargetDir)$(TargetName).dll.mdb')" SourceFiles="$(TargetDir)$(TargetName).dll.mdb" DestinationFolder="$(UNITY_FOLDER)/Assets/Assemblies" />
<Copy SourceFiles="$(VALHEIM_MANAGED)/Assembly-CSharp.dll" DestinationFolder="$(UNITY_FOLDER)/Assets/Assemblies" />
<Copy SourceFiles="$(VALHEIM_MANAGED)/assembly_valheim.dll" DestinationFolder="$(UNITY_FOLDER)/Assets/Assemblies" />
<Copy SourceFiles="$(VALHEIM_MANAGED)/assembly_utils.dll" DestinationFolder="$(UNITY_FOLDER)/Assets/Assemblies" />
<Copy SourceFiles="$(VALHEIM_MANAGED)/assembly_postprocessing.dll" DestinationFolder="$(UNITY_FOLDER)/Assets/Assemblies" />
<Copy SourceFiles="$(VALHEIM_MANAGED)/assembly_sunshafts.dll" DestinationFolder="$(UNITY_FOLDER)/Assets/Assemblies" />
<Copy SourceFiles="$(VALHEIM_MANAGED)/assembly_guiutils.dll" DestinationFolder="$(UNITY_FOLDER)/Assets/Assemblies" />
<Copy SourceFiles="$(VALHEIM_MANAGED)/assembly_lux.dll" DestinationFolder="$(UNITY_FOLDER)/Assets/Assemblies" />
<Copy SourceFiles="$(VALHEIM_MANAGED)/assembly_simplemeshcombine.dll" DestinationFolder="$(UNITY_FOLDER)/Assets/Assemblies" />
<Copy SourceFiles="$(VALHEIM_MANAGED)/assembly_googleanalytics.dll" DestinationFolder="$(UNITY_FOLDER)/Assets/Assemblies" />
<Copy SourceFiles="$(VALHEIM_MANAGED)/PlayFab.dll" DestinationFolder="$(UNITY_FOLDER)/Assets/Assemblies" />
<Copy SourceFiles="$(VALHEIM_MANAGED)/PlayFabParty.dll" DestinationFolder="$(UNITY_FOLDER)/Assets/Assemblies" />
<Copy SourceFiles="$(VALHEIM_MANAGED)/Splatform.dll" DestinationFolder="$(UNITY_FOLDER)/Assets/Assemblies" />
<Copy SourceFiles="$(VALHEIM_MANAGED)/Splatform.Steam.dll" DestinationFolder="$(UNITY_FOLDER)/Assets/Assemblies" />
<Copy SourceFiles="$(VALHEIM_MANAGED)/gui_framework.dll" DestinationFolder="$(UNITY_FOLDER)/Assets/Assemblies" />
<Copy SourceFiles="$(VALHEIM_MANAGED)/com.rlabrecque.steamworks.net.dll" DestinationFolder="$(UNITY_FOLDER)/Assets/Assemblies" />
<Copy SourceFiles="$(VALHEIM_MANAGED)/SoftReferenceableAssets.dll" DestinationFolder="$(UNITY_FOLDER)/Assets/Assemblies" />
</Target>
<Target Name="JotunnPostBuildTask" AfterTargets="Build">
<CallTarget Targets="CopyToUnity" Condition="Exists('$(UNITY_FOLDER)')" />
</Target>
<Target Name="PackageThunderstore" AfterTargets="Build">
<Message Text="Packaging Thunderstore and Nexus Zips..." Importance="high" />
<Exec Command="powershell -Command &quot;if (!(Test-Path 'C:\Users\FERDINANDO\Desktop\Pacchetto_Rame\racesofvalheim')) { New-Item -ItemType Directory -Force -Path 'C:\Users\FERDINANDO\Desktop\Pacchetto_Rame\racesofvalheim' }; Compress-Archive -Path '$(TargetDir)$(TargetName).dll', '$(ProjectDir)..\manifest.json', '$(ProjectDir)..\README.md', 'C:\Users\FERDINANDO\Desktop\Pacchetto_Rame\racesofvalheim\icon.png' -DestinationPath 'C:\Users\FERDINANDO\Desktop\Pacchetto_Rame\racesofvalheim\RacesOfValheim_Thunderstore.zip' -Force; Compress-Archive -Path '$(TargetDir)$(TargetName).dll' -DestinationPath 'C:\Users\FERDINANDO\Desktop\Pacchetto_Rame\racesofvalheim\RacesOfValheim_Nexus.zip' -Force&quot;" />
<Message Text="Copying DLL to Valheim BepInEx plugins..." Importance="high" />
<Copy SourceFiles="$(TargetDir)$(TargetName).dll" DestinationFolder="C:\Program Files (x86)\Steam\steamapps\common\Valheim\BepInEx\plugins\" />
</Target>
<Target Name="JotunnPostBuildTaskUnix" AfterTargets="Build" Condition=" '$(OS)' == 'Unix' ">
<Exec Command="sh &quot;$(SolutionDir)scripts/publish.sh&quot; --target &quot;$(ConfigurationName)&quot; --target-path &quot;$(TargetDir)&quot; --target-assembly &quot;$(TargetFileName)&quot; --valheim-path &quot;$(VALHEIM_INSTALL)&quot; --deploy-path &quot;$(MOD_DEPLOYPATH)&quot; --project-path &quot;$(ProjectDir)&quot;" />
</Target>
</Project>

View file

@ -0,0 +1,25 @@
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.14.37502.11 d17.14
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "RacesOfValheim", "RacesOfValheim.csproj", "{4BC9C85D-6D61-5CA6-D031-E76B8F1059A3}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{4BC9C85D-6D61-5CA6-D031-E76B8F1059A3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{4BC9C85D-6D61-5CA6-D031-E76B8F1059A3}.Debug|Any CPU.Build.0 = Debug|Any CPU
{4BC9C85D-6D61-5CA6-D031-E76B8F1059A3}.Release|Any CPU.ActiveCfg = Release|Any CPU
{4BC9C85D-6D61-5CA6-D031-E76B8F1059A3}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {70AFA5D0-F1FA-4F08-8D74-5EAB86FFEFC2}
EndGlobalSection
EndGlobal

View file

@ -0,0 +1,354 @@
using UnityEngine;
using System.Collections;
using Jotunn.Managers;
namespace RacesOfValheim
{
public class DrakeFormBehavior : MonoBehaviour
{
private Animator anim;
private bool isFlying = false;
private bool isLanding = false;
private float lastAttackTime = 0f;
private SkadiProgression.FormRules formRules;
public void Initialize(SkadiProgression.FormRules rules)
{
this.formRules = rules;
}
private const float ATTACK_COST = 20f;
private const float ATTACK_COOLDOWN = 3f;
private void Start()
{
anim = GetComponentInChildren<Animator>();
if (Player.m_localPlayer != null)
{
HarmonyLib.Traverse.Create(Player.m_localPlayer).Field("m_debugFly").SetValue(false);
}
}
private void Update()
{
if (Player.m_localPlayer == null || Player.m_localPlayer.IsDead()) return;
// Handle Flight Toggle (RMB) - Disabled for Fader
if (Input.GetMouseButtonDown(1) && formRules != null && formRules.Form != SkadiProgression.FormType.SkeletonDragon)
{
if (!isFlying && !isLanding)
{
isFlying = true;
HarmonyLib.Traverse.Create(Player.m_localPlayer).Field("m_debugFly").SetValue(true);
}
else if (isFlying && !isLanding)
{
isLanding = true;
isFlying = false;
HarmonyLib.Traverse.Create(Player.m_localPlayer).Field("m_debugFly").SetValue(false);
}
else if (isLanding)
{
// Cancel landing, resume flight
isLanding = false;
isFlying = true;
HarmonyLib.Traverse.Create(Player.m_localPlayer).Field("m_debugFly").SetValue(true);
}
}
if (isLanding)
{
// Prevent fall damage by keeping maxAirAltitude equal to current height
var altitudeField = HarmonyLib.Traverse.Create(Player.m_localPlayer).Field("m_maxAirAltitude");
if (altitudeField.FieldExists())
{
altitudeField.SetValue(Player.m_localPlayer.transform.position.y);
}
if (Player.m_localPlayer.IsOnGround())
{
isLanding = false;
}
}
// Sync Animator
if (anim != null)
{
bool grounded = !isFlying && !isLanding && Player.m_localPlayer.IsOnGround();
// Use standard Valheim monster animator parameters
anim.SetBool("onGround", grounded);
anim.SetBool("flying", isFlying || isLanding);
Vector3 vel = Player.m_localPlayer.GetVelocity();
vel.y = 0f;
float speed = vel.magnitude;
anim.SetFloat("forward_speed", speed);
}
// Handle Attack
if (formRules != null && formRules.CanAttackInForm)
{
if (Input.GetMouseButtonDown(0))
{
if (Time.time - lastAttackTime >= ATTACK_COOLDOWN)
{
StartCoroutine(PerformAttackCoroutine(0));
}
}
else if (Input.GetMouseButtonDown(2)) // MMB
{
if (Time.time - lastAttackTime >= ATTACK_COOLDOWN)
{
StartCoroutine(PerformAttackCoroutine(2));
}
}
else if (Input.GetMouseButtonDown(1) && formRules.Form == SkadiProgression.FormType.SkeletonDragon) // RMB for Fader Spin
{
if (Time.time - lastAttackTime >= ATTACK_COOLDOWN)
{
StartCoroutine(PerformAttackCoroutine(1));
}
}
}
}
private IEnumerator PerformAttackCoroutine(int button)
{
lastAttackTime = Time.time;
if (formRules.Form == SkadiProgression.FormType.Drake)
{
if (button == 2) yield break; // Drake only uses LMB
Player.m_localPlayer.UseEitr(ATTACK_COST);
if (anim != null) anim.SetTrigger("attack");
// Delay to match animation spit timing
yield return new WaitForSeconds(0.3f);
GameObject projPrefab = PrefabManager.Cache.GetPrefab<GameObject>("hatchling_cold_projectile");
if (projPrefab == null) yield break;
ItemDrop staffDrop = PrefabManager.Cache.GetPrefab<GameObject>("StaffIceShards")?.GetComponent<ItemDrop>();
if (staffDrop == null) yield break;
float vel = staffDrop.m_itemData.m_shared.m_attack.m_projectileVel;
for (int i = 0; i < 3; i++)
{
Vector3 spawnPos = Player.m_localPlayer.GetEyePoint() + Player.m_localPlayer.GetLookDir() * 1.5f;
Vector3 targetDir = Player.m_localPlayer.GetLookDir();
Vector3 right = Vector3.Cross(Vector3.up, targetDir);
targetDir += right * UnityEngine.Random.Range(-0.1f, 0.1f) + Vector3.up * UnityEngine.Random.Range(-0.1f, 0.1f);
targetDir.Normalize();
GameObject projInstance = Instantiate(projPrefab, spawnPos, Quaternion.LookRotation(targetDir));
Projectile proj = projInstance.GetComponent<Projectile>();
if (proj != null)
{
HitData hitData = new HitData();
hitData.m_damage = staffDrop.m_itemData.m_shared.m_damages;
hitData.SetAttacker(Player.m_localPlayer);
proj.Setup(Player.m_localPlayer, targetDir * vel, -1f, hitData, staffDrop.m_itemData, null);
}
yield return new WaitForSeconds(0.2f);
}
}
else if (formRules.Form == SkadiProgression.FormType.Moder)
{
string attackTrigger = "attack_bite";
string projName = null;
int projCount = 1;
float projDelay = 0.5f;
bool isMelee = true;
if (isFlying || isLanding)
{
// Air attack (Ice Barrage)
attackTrigger = "attack_iceball";
projName = "dragon_ice_projectile";
projCount = 16;
projDelay = 0.8f;
isMelee = false;
}
else
{
if (button == 2)
{
// Ground MMB (Breath)
attackTrigger = "attack_breath";
projName = "hatchling_cold_projectile"; // Use cold explosion projectiles for a breath stream
projCount = 20;
projDelay = 0.5f; // Wait for the head to lower before breathing
isMelee = false;
}
else
{
// Ground LMB (Bite/Claw)
attackTrigger = UnityEngine.Random.value > 0.5f ? "attack_bite" : (UnityEngine.Random.value > 0.5f ? "attack_claw_left" : "attack_claw_right");
isMelee = true;
projDelay = 0.5f;
}
}
Player.m_localPlayer.UseEitr(ATTACK_COST);
if (anim != null) anim.SetTrigger(attackTrigger);
yield return new WaitForSeconds(projDelay);
if (!isMelee && projName != null)
{
GameObject projPrefab = PrefabManager.Cache.GetPrefab<GameObject>(projName);
if (projPrefab == null) yield break;
ItemDrop staffDrop = PrefabManager.Cache.GetPrefab<GameObject>("StaffIceShards")?.GetComponent<ItemDrop>();
if (staffDrop == null) yield break;
float vel = staffDrop.m_itemData.m_shared.m_attack.m_projectileVel;
for (int i = 0; i < projCount; i++)
{
Vector3 spawnPos = Player.m_localPlayer.GetEyePoint() + Player.m_localPlayer.GetLookDir() * 3.0f;
Vector3 targetDir = Player.m_localPlayer.GetLookDir();
if (projCount > 1)
{
Vector3 right = Vector3.Cross(Vector3.up, targetDir);
targetDir += right * UnityEngine.Random.Range(-0.3f, 0.3f) + Vector3.up * UnityEngine.Random.Range(-0.3f, 0.3f);
targetDir.Normalize();
}
GameObject projInstance = Instantiate(projPrefab, spawnPos, Quaternion.LookRotation(targetDir));
Projectile proj = projInstance.GetComponent<Projectile>();
if (proj != null)
{
HitData hitData = new HitData();
hitData.m_damage = staffDrop.m_itemData.m_shared.m_damages;
hitData.SetAttacker(Player.m_localPlayer);
proj.Setup(Player.m_localPlayer, targetDir * vel, -1f, hitData, staffDrop.m_itemData, null);
}
if (projCount > 1) yield return new WaitForSeconds(0.05f);
}
}
}
else if (formRules.Form == SkadiProgression.FormType.SkeletonDragon)
{
string attackTrigger = "attack_bite";
string projName = null;
int projCount = 1;
float projDelay = 0.5f;
bool isMelee = true;
if (isFlying || isLanding)
{
// Air attack (Meteors replacement -> Ice Barrage)
attackTrigger = "attack_roar"; // taunt animation has issues in air
projName = "dragon_ice_projectile"; // spawn_fader_meteors is buggy without Fader boss script
projCount = 16;
projDelay = 1.0f;
isMelee = false;
}
else
{
if (button == 2)
{
// Ground MMB (Frost Breath stream)
attackTrigger = "attack_flamebreath";
projName = "hatchling_cold_projectile";
projCount = 60; // Tripled!
projDelay = 0.5f;
isMelee = false;
}
else if (button == 1)
{
// Ground RMB (Spin)
attackTrigger = "attack_Spin";
isMelee = true;
projDelay = 0.5f;
}
else
{
// Ground LMB (Melee mix - bite/claws)
float rand = UnityEngine.Random.value;
if (rand < 0.33f) attackTrigger = "attack_bite";
else if (rand < 0.66f) attackTrigger = "attack_ClawL";
else attackTrigger = "attack_ClawR";
isMelee = true;
projDelay = 0.5f;
}
}
Player.m_localPlayer.UseEitr(ATTACK_COST);
if (anim != null) anim.SetTrigger(attackTrigger);
yield return new WaitForSeconds(projDelay);
if (!isMelee && projName != null)
{
GameObject projPrefab = PrefabManager.Cache.GetPrefab<GameObject>(projName);
if (projPrefab == null) yield break;
ItemDrop staffDrop = PrefabManager.Cache.GetPrefab<GameObject>("StaffIceShards")?.GetComponent<ItemDrop>();
if (staffDrop == null) yield break;
float vel = staffDrop.m_itemData.m_shared.m_attack.m_projectileVel;
for (int i = 0; i < projCount; i++)
{
Vector3 spawnPos = Player.m_localPlayer.GetEyePoint() + Player.m_localPlayer.GetLookDir() * 4.0f;
Vector3 targetDir = Player.m_localPlayer.GetLookDir();
if (projCount > 1)
{
Vector3 right = Vector3.Cross(Vector3.up, targetDir);
targetDir += right * UnityEngine.Random.Range(-0.2f, 0.2f) + Vector3.up * UnityEngine.Random.Range(-0.2f, 0.2f);
targetDir.Normalize();
}
GameObject projInstance = Instantiate(projPrefab, spawnPos, Quaternion.LookRotation(targetDir));
Projectile proj = projInstance.GetComponent<Projectile>();
HitData hitData = new HitData();
hitData.m_damage = staffDrop.m_itemData.m_shared.m_damages;
// Convert Fire to Frost
hitData.m_damage.m_frost += hitData.m_damage.m_fire;
hitData.m_damage.m_fire = 0f;
hitData.SetAttacker(Player.m_localPlayer);
if (proj != null)
{
proj.Setup(Player.m_localPlayer, targetDir * vel, -1f, hitData, staffDrop.m_itemData, null);
}
// Turn fire VFX to blue/frost
foreach (ParticleSystem ps in projInstance.GetComponentsInChildren<ParticleSystem>())
{
var main = ps.main;
main.startColor = new Color(0.4f, 0.8f, 1f, 1f); // Ice blue
}
foreach (Light l in projInstance.GetComponentsInChildren<Light>())
{
l.color = new Color(0.4f, 0.8f, 1f, 1f);
}
if (projCount > 1) yield return new WaitForSeconds(0.05f);
}
}
}
}
private void OnDestroy()
{
if (Player.m_localPlayer != null)
{
HarmonyLib.Traverse.Create(Player.m_localPlayer).Field("m_debugFly").SetValue(false);
}
}
}
}

View file

@ -0,0 +1,144 @@
using HarmonyLib;
using UnityEngine;
namespace RacesOfValheim
{
[HarmonyPatch(typeof(VisEquipment), "UpdateColors")]
public static class SkadiSkinColorPatch
{
public static void Postfix(VisEquipment __instance)
{
if (!__instance.m_isPlayer) return;
Player player = __instance.GetComponent<Player>();
if (player == null) return;
ZNetView nview = player.GetComponent<ZNetView>();
if (nview != null && nview.IsValid() && nview.GetZDO().GetString("RacesOfValheim_Race", "Human") == "Skadi")
{
if (__instance.m_bodyModel != null && __instance.m_bodyModel.material != null)
{
// Azzurro molto chiaro
Color skadiColor = new Color(0.6f, 0.8f, 1f, 1f);
__instance.m_bodyModel.material.SetColor("_SkinColor", skadiColor);
}
}
}
}
[HarmonyPatch(typeof(VisEquipment), "UpdateVisuals")]
public static class Skadi_MultiplayerVisuals_Patch
{
public static void Postfix(VisEquipment __instance)
{
if (!__instance.m_isPlayer) return;
Player player = __instance.GetComponent<Player>();
if (player == null || player.IsOwner()) return; // Only process remote players
ZNetView nview = player.GetComponent<ZNetView>();
if (nview != null && nview.IsValid() && nview.GetZDO().GetString("RacesOfValheim_Race", "Human") == "Skadi")
{
string formName = nview.GetZDO().GetString("RacesOfValheim_SkadiForm", "");
Transform playerVisual = player.transform.Find("Visual");
Transform formBody = player.transform.Find("SkadiBody_Form");
if (!string.IsNullOrEmpty(formName)) {
if (formBody != null && formBody.gameObject.name != formName + "_multiplayer") {
UnityEngine.Object.Destroy(formBody.gameObject);
formBody = null;
}
if (formBody == null) {
GameObject prefab = Jotunn.Managers.PrefabManager.Cache.GetPrefab<GameObject>(formName);
if (prefab != null) {
Transform visual = prefab.transform.Find("Visual");
if (visual != null) {
GameObject formInstance = UnityEngine.Object.Instantiate(visual.gameObject, player.transform);
formInstance.name = formName + "_multiplayer";
if (formName == "Hatchling") formInstance.transform.localPosition = new Vector3(0f, -1.0f, 0f);
else formInstance.transform.localPosition = Vector3.zero;
formInstance.transform.localRotation = Quaternion.identity;
}
}
}
if (playerVisual != null) playerVisual.gameObject.SetActive(false);
} else {
if (formBody != null) UnityEngine.Object.Destroy(formBody.gameObject);
// Fader form has a different name? "SkadiBody_Form" was used earlier, we just find all children and destroy them if they have "_multiplayer"
foreach (Transform child in player.transform) {
if (child.name.EndsWith("_multiplayer")) {
UnityEngine.Object.Destroy(child.gameObject);
}
}
if (playerVisual != null) playerVisual.gameObject.SetActive(true);
}
}
}
}
[HarmonyPatch(typeof(SEMan), "AddStatusEffect", new System.Type[] { typeof(int), typeof(bool), typeof(int), typeof(float) })]
public static class SkadiSEManPatch
{
public static bool Prefix(SEMan __instance, ref int nameHash)
{
Character character = Traverse.Create(__instance).Field<Character>("m_character").Value;
if (character == Player.m_localPlayer && SkadiRace.Instance != null && SkadiRace.Instance.IsSkadi())
{
var rules = SkadiProgression.GetRules(BossProgressionManager.GetCurrentProgressionState());
if (nameHash == "Cold".GetStableHashCode() && rules.ImmuneToCold)
{
return false;
}
if (nameHash == "Freezing".GetStableHashCode())
{
if (rules.ImmuneToFreezing) return false;
if (rules.FreezingToCold)
{
nameHash = "Cold".GetStableHashCode();
}
}
}
return true;
}
}
[HarmonyPatch(typeof(Character), "ApplyDamage")]
public static class SkadiDamagePatch
{
public static void Prefix(Character __instance, ref HitData hit)
{
if (hit.GetAttacker() != null && hit.GetAttacker() == Player.m_localPlayer)
{
if (SkadiRace.Instance != null && SkadiRace.Instance.IsSkadi())
{
var rules = SkadiProgression.GetRules(BossProgressionManager.GetCurrentProgressionState());
if (rules.BonusFrostDamage)
{
hit.m_damage.m_frost += 2f * BossProgressionManager.GetCurrentProgressionState();
}
}
}
}
}
[HarmonyPatch(typeof(Humanoid), "StartAttack")]
public static class SkadiAttackPatch
{
public static bool Prefix(Humanoid __instance)
{
if (__instance == Player.m_localPlayer && __instance.GetComponentInChildren<DrakeFormBehavior>() != null)
{
return false;
}
return true;
}
}
}

View file

@ -0,0 +1,128 @@
using System;
using UnityEngine;
namespace RacesOfValheim
{
public static class SkadiProgression
{
public class FormRules
{
public bool ImmuneToCold = false;
public bool ImmuneToFreezing = false;
public bool FreezingToCold = false;
public bool BonusFrostDamage = false;
public bool FrostAura = false;
public float FrostResistance = 0f;
public float EitrRegenMultiplier = 1f;
public bool ColdSpell = false;
public bool ImprovedColdSpell = false;
public FormType Form = FormType.None;
public float DurationMinutes = 0f;
public float CooldownMinutes = 0f;
public bool CanAttackInForm = false;
}
public enum FormType
{
None,
Drake,
Moder,
SkeletonDragon
}
public static FormRules GetRules(int state)
{
FormRules rules = new FormRules();
if (state >= 1)
{
rules.ImmuneToCold = true;
rules.BonusFrostDamage = true;
rules.FrostResistance = 0.5f; // 50% resistance? Valheim uses DamageModifiers.
// Wait, FrostResistance isn't a percentage, it's a category.
// We'll map this to DamageModifier.Resistant (which is 50% reduction).
}
if (state >= 2)
{
rules.EitrRegenMultiplier = 1.20f;
rules.FreezingToCold = true;
rules.ColdSpell = true;
}
if (state >= 6)
{
rules.EitrRegenMultiplier = 1.50f;
rules.ImmuneToFreezing = true;
rules.FreezingToCold = false; // Immunity overrides conversion
rules.ImprovedColdSpell = true;
}
if (state >= 7)
{
// Immunity to frost damage => DamageModifier.Immune
rules.FrostResistance = 1f; // 1 means Immune in our logic
rules.FrostAura = true;
}
return rules;
}
public static FormRules GetGKeyRules(int state)
{
FormRules rules = new FormRules();
if (state >= 4) // Bonemass
{
rules.Form = FormType.Drake;
rules.CanAttackInForm = true;
}
else if (state >= 3) // Elder
{
rules.Form = FormType.Drake;
rules.CanAttackInForm = false;
}
return rules.Form != FormType.None ? rules : null;
}
public static FormRules GetHKeyRules(int state)
{
FormRules rules = new FormRules();
if (state >= 7) // Queen
{
rules.Form = FormType.Moder;
rules.DurationMinutes = 0f;
rules.CooldownMinutes = 0f;
rules.CanAttackInForm = true;
}
else if (state >= 6) // Yagluth
{
rules.Form = FormType.Moder;
rules.DurationMinutes = 1f;
rules.CooldownMinutes = 5f;
rules.CanAttackInForm = true;
}
else if (state >= 5) // Moder
{
rules.Form = FormType.Moder;
rules.DurationMinutes = 1f;
rules.CooldownMinutes = 10f;
rules.CanAttackInForm = true;
}
return rules.Form != FormType.None ? rules : null;
}
public static FormRules GetJKeyRules(int state)
{
FormRules rules = new FormRules();
if (state >= 8) // Fader
{
rules.Form = FormType.SkeletonDragon;
rules.DurationMinutes = 0f; // Assuming unlimited
rules.CooldownMinutes = 0f;
rules.CanAttackInForm = true;
}
return rules.Form != FormType.None ? rules : null;
}
}
}

View file

@ -0,0 +1,628 @@
using System;
using System.Collections;
using UnityEngine;
using Jotunn.Managers;
using Jotunn.Entities;
namespace RacesOfValheim
{
public class SkadiRace : MonoBehaviour
{
public static SkadiRace Instance;
public static SE_SkadiStats skadiCurseSE;
public static SE_FormCooldown skadiCdSE;
private float auraTimer = 0f;
private float lastSpellTime = 0f;
private GameObject currentTransformation;
private bool isTransformed = false;
private bool isTransformingSequence = false;
private SkadiProgression.FormRules activeRules = null;
private float lastAuraTime = 0f;
private GameObject frostAuraVFX = null;
private void Awake()
{
Instance = this;
}
public void CreateModAssets()
{
var se = ScriptableObject.CreateInstance<SE_SkadiStats>();
se.name = "SE_SkadiStats";
se.m_name = "Skadi's Blessing";
// Icon
GameObject drakeTrophy = PrefabManager.Cache.GetPrefab<ItemDrop>("TrophyHatchling")?.gameObject;
if (drakeTrophy != null)
{
ItemDrop trophyDrop = drakeTrophy.GetComponent<ItemDrop>();
if (trophyDrop != null && trophyDrop.m_itemData.m_shared.m_icons.Length > 0)
{
se.m_icon = trophyDrop.m_itemData.m_shared.m_icons[0];
}
}
CustomStatusEffect skadiStats = new CustomStatusEffect(se, fixReference: false);
ItemManager.Instance.AddStatusEffect(skadiStats);
skadiCurseSE = skadiStats.StatusEffect as SE_SkadiStats;
skadiCdSE = ScriptableObject.CreateInstance<SE_FormCooldown>();
skadiCdSE.name = "SE_SkadiCooldown";
skadiCdSE.m_name = "Dragon Form Cooldown";
if (drakeTrophy != null)
{
ItemDrop trophyDrop = drakeTrophy.GetComponent<ItemDrop>();
if (trophyDrop != null && trophyDrop.m_itemData.m_shared.m_icons.Length > 0)
{
skadiCdSE.m_icon = trophyDrop.m_itemData.m_shared.m_icons[0];
}
}
ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(skadiCdSE, fixReference: false));
}
public bool IsSkadi()
{
return Player.m_localPlayer != null &&
Player.m_localPlayer.m_customData.ContainsKey("Race") &&
Player.m_localPlayer.m_customData["Race"] == "Skadi";
}
private void Update()
{
if (!IsSkadi()) return;
if (Player.m_localPlayer.IsDead() && isTransformed)
{
ExecuteReversion();
}
var rules = SkadiProgression.GetRules(BossProgressionManager.GetCurrentProgressionState());
// Update the stats SE
if (skadiCurseSE != null)
{
skadiCurseSE.UpdateStats(rules);
if (!Player.m_localPlayer.GetSEMan().HaveStatusEffect(skadiCurseSE.name.GetStableHashCode()))
{
Player.m_localPlayer.GetSEMan().AddStatusEffect(skadiCurseSE.name.GetStableHashCode(), true);
}
}
if (rules.FrostAura)
{
EnsureFrostAuraVFX(true);
if (Time.time - lastAuraTime >= 1f)
{
ApplyColdAura();
lastAuraTime = Time.time;
}
}
else
{
EnsureFrostAuraVFX(false);
}
if (rules.EitrRegenMultiplier > 1f && !Player.m_localPlayer.IsDead())
{
try
{
var eitrTimerField = HarmonyLib.Traverse.Create(Player.m_localPlayer).Field("m_eitrRegenTimer");
if (eitrTimerField.FieldExists())
{
float currentTimer = eitrTimerField.GetValue<float>();
if (currentTimer > 0f)
{
float bonus = rules.EitrRegenMultiplier - 1f;
if (bonus > 0f && bonus < 1f)
{
float targetTime = 1f - bonus;
float requiredSpeed = 1f / targetTime;
float additionalSpeed = requiredSpeed - 1f;
eitrTimerField.SetValue(currentTimer - (additionalSpeed * Time.deltaTime));
}
}
}
}
catch (Exception e)
{
// Ignore, to prevent breaking the rest of the Update loop
}
}
if (rules.ColdSpell)
{
HandleColdSpell(rules);
}
if (isTransformingSequence) return;
int state = BossProgressionManager.GetCurrentProgressionState();
if (Input.GetKeyDown(KeyCode.G)) { TryTransformWithRules(SkadiProgression.GetGKeyRules(state)); return; }
if (Input.GetKeyDown(KeyCode.H)) { TryTransformWithRules(SkadiProgression.GetHKeyRules(state)); return; }
if (Input.GetKeyDown(KeyCode.J)) { TryTransformWithRules(SkadiProgression.GetJKeyRules(state)); return; }
// Debug Dump
if (Input.GetKeyDown(KeyCode.F8))
{
DumpPrefabDebugInfo("Dragon");
DumpPrefabDebugInfo("Hatchling");
DumpPrefabDebugInfo("Fader");
if (Player.m_localPlayer != null) Player.m_localPlayer.Message(MessageHud.MessageType.Center, "Dumped Dragon/Drake/Fader debug info to console!");
}
}
private void DumpPrefabDebugInfo(string prefabName)
{
GameObject prefab = Jotunn.Managers.PrefabManager.Cache.GetPrefab<GameObject>(prefabName);
if (prefab == null)
{
Jotunn.Logger.LogWarning($"{prefabName} prefab not found!");
return;
}
Jotunn.Logger.LogInfo($"=== {prefabName.ToUpper()} DEBUG INFO ===");
Animator anim = prefab.GetComponentInChildren<Animator>();
if (anim != null)
{
Jotunn.Logger.LogInfo("--- Animator Parameters ---");
foreach (UnityEngine.AnimatorControllerParameter param in anim.parameters)
{
Jotunn.Logger.LogInfo($"Param: {param.name} (Type: {param.type})");
}
}
Humanoid humanoid = prefab.GetComponent<Humanoid>();
if (humanoid != null)
{
Jotunn.Logger.LogInfo("--- Weapons (Default Items) ---");
if (humanoid.m_defaultItems != null)
{
foreach (GameObject item in humanoid.m_defaultItems)
{
if (item == null) continue;
ItemDrop drop = item.GetComponent<ItemDrop>();
if (drop != null)
{
var attack = drop.m_itemData.m_shared.m_attack;
Jotunn.Logger.LogInfo($"Weapon Prefab: {item.name}");
Jotunn.Logger.LogInfo($" - Attack Anim: {attack.m_attackAnimation}");
if (attack.m_attackProjectile != null)
Jotunn.Logger.LogInfo($" - Projectile: {attack.m_attackProjectile.name}");
}
}
}
Jotunn.Logger.LogInfo("--- Random Weapons ---");
if (humanoid.m_randomWeapon != null)
{
foreach (var item in humanoid.m_randomWeapon)
{
if (item == null) continue;
ItemDrop drop = item.GetComponent<ItemDrop>();
if (drop != null)
{
var attack = drop.m_itemData.m_shared.m_attack;
Jotunn.Logger.LogInfo($"Random Weapon Prefab: {item.name}");
Jotunn.Logger.LogInfo($" - Attack Anim: {attack.m_attackAnimation}");
if (attack.m_attackProjectile != null)
Jotunn.Logger.LogInfo($" - Projectile: {attack.m_attackProjectile.name}");
}
}
}
}
ZSFX[] sfxs = prefab.GetComponentsInChildren<ZSFX>(true);
Jotunn.Logger.LogInfo("--- Sounds (ZSFX) ---");
foreach (ZSFX sfx in sfxs)
{
Jotunn.Logger.LogInfo($"Sound: {sfx.gameObject.name}");
}
Jotunn.Logger.LogInfo($"=== END {prefabName.ToUpper()} DEBUG INFO ===");
}
private void HandleColdSpell(SkadiProgression.FormRules rules)
{
if (Player.m_localPlayer == null || Player.m_localPlayer.IsDead()) return;
if (isTransformed) return; // Do not cast human spell while in dragon form
// Middle Mouse Button to cast (Kick)
if (Input.GetMouseButtonDown(2))
{
float cooldown = rules.ImprovedColdSpell ? 2.0f : 1.5f;
if (Time.time - lastSpellTime < cooldown) return;
if (!Player.m_localPlayer.HaveEitr(10f))
{
Player.m_localPlayer.Message(MessageHud.MessageType.Center, "Not enough Eitr");
return;
}
Player.m_localPlayer.UseEitr(10f);
lastSpellTime = Time.time;
var zanim = HarmonyLib.Traverse.Create(Player.m_localPlayer).Field<ZSyncAnimation>("m_zanim").Value;
if (zanim != null)
{
// Forcing secondary attack trigger, which is kick when unarmed
zanim.SetTrigger("secondary");
}
StartCoroutine(ColdSpellKickCoroutine(rules));
}
}
private IEnumerator ColdSpellKickCoroutine(SkadiProgression.FormRules rules)
{
// Wait for the kick animation to reach the extension point
yield return new WaitForSeconds(0.4f);
if (Player.m_localPlayer == null || Player.m_localPlayer.IsDead()) yield break;
GameObject staffPrefab = PrefabManager.Cache.GetPrefab<GameObject>("StaffIceShards");
if (staffPrefab == null) yield break;
ItemDrop staffDrop = staffPrefab.GetComponent<ItemDrop>();
if (staffDrop == null) yield break;
string projName = rules.ImprovedColdSpell ? "hatchling_cold_projectile" : null;
GameObject projPrefab = null;
if (projName != null)
{
projPrefab = PrefabManager.Cache.GetPrefab<GameObject>(projName);
}
if (projPrefab == null)
{
projPrefab = staffDrop.m_itemData.m_shared.m_attack.m_attackProjectile; // Default Staff of Frost projectile
}
if (projPrefab == null) yield break;
int count = rules.ImprovedColdSpell ? 10 : 1;
for (int i = 0; i < count; i++)
{
if (Player.m_localPlayer == null || Player.m_localPlayer.IsDead()) break;
// Spawn from the foot (low position, forward)
Vector3 lookDir = Player.m_localPlayer.GetLookDir();
// Add a small spread for the improved blast
if (rules.ImprovedColdSpell && i > 0)
{
lookDir = Quaternion.Euler(UnityEngine.Random.Range(-5f, 5f), UnityEngine.Random.Range(-5f, 5f), 0f) * lookDir;
}
Vector3 spawnPos = Player.m_localPlayer.transform.position + Vector3.up * 0.4f + lookDir * 0.6f;
GameObject projInstance = Instantiate(projPrefab, spawnPos, Quaternion.LookRotation(lookDir));
Projectile proj = projInstance.GetComponent<Projectile>();
if (proj != null)
{
HitData hitData = new HitData();
hitData.m_damage = staffDrop.m_itemData.m_shared.m_damages;
hitData.SetAttacker(Player.m_localPlayer);
proj.Setup(Player.m_localPlayer, lookDir * staffDrop.m_itemData.m_shared.m_attack.m_projectileVel, -1f, hitData, staffDrop.m_itemData, null);
}
if (count > 1) yield return new WaitForSeconds(0.05f);
}
}
private void EnsureFrostAuraVFX(bool enable)
{
if (Player.m_localPlayer == null) return;
if (enable)
{
if (frostAuraVFX == null)
{
frostAuraVFX = new GameObject("SkadiFrostAuraVFX");
frostAuraVFX.transform.SetParent(Player.m_localPlayer.transform, false);
frostAuraVFX.transform.localPosition = new Vector3(0, 1f, 0); // Center of player
ParticleSystem ps = frostAuraVFX.AddComponent<ParticleSystem>();
var main = ps.main;
main.duration = 5f;
main.loop = true;
main.startLifetime = 3f;
main.startSpeed = 0.2f; // Slow moving
main.startSize = new ParticleSystem.MinMaxCurve(0.005f, 0.01f); // 1cm max
main.startColor = new Color(0.7f, 0.9f, 1f, 0.4f); // Light blue, semi-transparent
main.maxParticles = 300;
main.simulationSpace = ParticleSystemSimulationSpace.World; // Leaves a trail when walking
var emission = ps.emission;
emission.rateOverTime = 90; // Dense mist
var shape = ps.shape;
shape.shapeType = ParticleSystemShapeType.Sphere;
shape.radius = 3f; // 3 meters radius
var colorOverLifetime = ps.colorOverLifetime;
colorOverLifetime.enabled = true;
Gradient grad = new Gradient();
grad.SetKeys(
new GradientColorKey[] { new GradientColorKey(Color.white, 0.0f), new GradientColorKey(Color.white, 1.0f) },
new GradientAlphaKey[] { new GradientAlphaKey(0.0f, 0.0f), new GradientAlphaKey(1.0f, 0.2f), new GradientAlphaKey(1.0f, 0.8f), new GradientAlphaKey(0.0f, 1.0f) }
);
colorOverLifetime.color = grad;
var renderer = frostAuraVFX.GetComponent<ParticleSystemRenderer>();
// Steal material from an existing Valheim effect
GameObject freezingVfx = Jotunn.Managers.PrefabManager.Cache.GetPrefab<GameObject>("vfx_Freezing");
if (freezingVfx != null)
{
ParticleSystemRenderer origRenderer = freezingVfx.GetComponentInChildren<ParticleSystemRenderer>();
if (origRenderer != null)
{
renderer.material = origRenderer.material;
}
}
}
if (!frostAuraVFX.activeSelf)
{
frostAuraVFX.SetActive(true);
}
}
else
{
if (frostAuraVFX != null && frostAuraVFX.activeSelf)
{
frostAuraVFX.SetActive(false);
}
}
}
private void ApplyColdAura()
{
if (Player.m_localPlayer == null) return;
Vector3 center = Player.m_localPlayer.transform.position;
foreach (Character c in Character.GetAllCharacters())
{
if (c == Player.m_localPlayer) continue;
if (c.IsTamed() || c.IsPlayer()) continue;
if (Vector3.Distance(center, c.transform.position) <= 3f)
{
HitData hit = new HitData();
hit.m_damage.m_frost = 10f;
hit.m_point = c.transform.position;
hit.m_dir = (c.transform.position - center).normalized;
hit.SetAttacker(Player.m_localPlayer);
c.ApplyDamage(hit, true, false);
}
}
}
private void TryTransformWithRules(SkadiProgression.FormRules rules)
{
if (rules == null || rules.Form == SkadiProgression.FormType.None) return;
if (isTransformed)
{
StartCoroutine(RevertToHumanRoutine());
return;
}
if (rules.CooldownMinutes > 0)
{
var cdSE = Player.m_localPlayer.GetSEMan().GetStatusEffect("SE_SkadiCooldown".GetStableHashCode());
if (cdSE != null)
{
float m_time = HarmonyLib.Traverse.Create(cdSE).Field<float>("m_time").Value;
float remaining = cdSE.m_ttl - m_time;
if (remaining < 0) remaining = 0;
int rMin = Mathf.FloorToInt(remaining / 60f);
int rSec = Mathf.FloorToInt(remaining % 60f);
Player.m_localPlayer.Message(MessageHud.MessageType.Center, $"Dragon Form is on cooldown ({rMin}:{rSec:00}).");
return;
}
}
activeRules = rules;
StartCoroutine(TransformRoutine(rules));
}
private Vector3 GetFormScale(SkadiProgression.FormType form)
{
if (form == SkadiProgression.FormType.Moder) return Vector3.one * 0.5f; // Increased to 50%
if (form == SkadiProgression.FormType.SkeletonDragon) return Vector3.one * 0.55f; // 10% larger than Moder
return Vector3.one * 0.9f; // Drake (reduced by 10%)
}
private IEnumerator TransformRoutine(SkadiProgression.FormRules rules)
{
isTransformingSequence = true;
ZSyncAnimation zAnim = Player.m_localPlayer.GetComponent<ZSyncAnimation>();
if (zAnim != null) zAnim.SetTrigger("gpower");
yield return new WaitForSeconds(1.1f);
SpawnPoofEffect();
ExecuteTransformation(rules);
if (currentTransformation != null)
{
float elapsed = 0f;
float duration = 0.5f;
Vector3 endScale = GetFormScale(rules.Form);
Vector3 startScale = endScale * 0.5f;
currentTransformation.transform.localScale = startScale;
while (elapsed < duration)
{
if (currentTransformation == null) break;
currentTransformation.transform.localScale = Vector3.Lerp(startScale, endScale, elapsed / duration);
elapsed += Time.deltaTime;
yield return null;
}
if (currentTransformation != null) currentTransformation.transform.localScale = endScale;
}
isTransformingSequence = false;
}
private System.Collections.IEnumerator RevertToHumanRoutine()
{
isTransformingSequence = true;
if (Player.m_localPlayer.GetComponent<ZNetView>() != null) {
Player.m_localPlayer.GetComponent<ZNetView>().GetZDO().Set("Skadi_Form", "");
}
if (currentTransformation != null)
{
DrakeFormBehavior drakeBehavior = currentTransformation.GetComponent<DrakeFormBehavior>();
if (drakeBehavior != null) drakeBehavior.enabled = false;
float elapsed = 0f;
float duration = 0.5f;
Vector3 startScale = currentTransformation.transform.localScale;
float endMultiplier = 0.5f;
Vector3 endScale = startScale * endMultiplier;
while (elapsed < duration)
{
if (currentTransformation == null) break;
currentTransformation.transform.localScale = Vector3.Lerp(startScale, endScale, elapsed / duration);
elapsed += Time.deltaTime;
yield return null;
}
}
SpawnPoofEffect();
yield return new WaitForSeconds(0.1f);
ExecuteReversion();
isTransformingSequence = false;
}
private void SpawnPoofEffect()
{
if (Player.m_localPlayer == null) return;
Vector3 pos = Player.m_localPlayer.transform.position + Vector3.up;
GameObject smoke = PrefabManager.Cache.GetPrefab<GameObject>("vfx_corpse_destruction");
if (smoke != null) Instantiate(smoke, pos, Quaternion.identity);
GameObject sparks = PrefabManager.Cache.GetPrefab<GameObject>("vfx_HitSparks");
if (sparks != null) Instantiate(sparks, pos, Quaternion.identity);
}
private void ExecuteTransformation(SkadiProgression.FormRules rules)
{
Transform playerVisual = Player.m_localPlayer.transform.Find("Visual");
string prefabName = "";
switch (rules.Form)
{
case SkadiProgression.FormType.Drake: prefabName = "Hatchling"; break;
case SkadiProgression.FormType.Moder: prefabName = "Dragon"; break;
case SkadiProgression.FormType.SkeletonDragon: prefabName = "Fader"; break;
}
if (Player.m_localPlayer.GetComponent<ZNetView>() != null) {
Player.m_localPlayer.GetComponent<ZNetView>().GetZDO().Set("Skadi_Form", prefabName);
}
GameObject prefab = PrefabManager.Cache.GetPrefab<GameObject>(prefabName);
// Sync to ZDO
ZNetView nview = Player.m_localPlayer.GetComponent<ZNetView>();
if (nview != null && nview.IsValid())
{
nview.GetZDO().Set("RacesOfValheim_SkadiForm", prefabName);
}
if (prefab != null && playerVisual != null)
{
playerVisual.localScale = Vector3.one * 0.001f;
Transform visual = prefab.transform.Find("Visual");
if (visual != null)
{
currentTransformation = Instantiate(visual.gameObject, Player.m_localPlayer.transform);
if (prefabName == "Hatchling")
{
currentTransformation.transform.localPosition = new Vector3(0f, -1.0f, 0f);
}
else if (prefabName == "Fader")
{
// Turn Fader into a Frost Skeleton Dragon
foreach (Renderer r in currentTransformation.GetComponentsInChildren<Renderer>())
{
if (r.material != null)
{
r.material.SetColor("_Color", new Color(0.6f, 0.8f, 1f, 1f));
if (r.material.HasProperty("_EmissionColor"))
{
r.material.SetColor("_EmissionColor", new Color(0f, 0.5f, 1f, 1f));
}
}
}
}
else
{
currentTransformation.transform.localPosition = Vector3.zero;
}
currentTransformation.transform.localRotation = Quaternion.identity;
// Keep AnimEvent so native sounds (footsteps, attack shouts) play correctly!
DrakeFormBehavior behavior = currentTransformation.AddComponent<DrakeFormBehavior>();
behavior.Initialize(rules);
if (prefabName == "Hatchling") Player.m_localPlayer.Message(MessageHud.MessageType.Center, "You are a Drake!");
else if (prefabName == "Dragon") Player.m_localPlayer.Message(MessageHud.MessageType.Center, "You are Moder!");
else if (prefabName == "Fader") Player.m_localPlayer.Message(MessageHud.MessageType.Center, "You are Fader!");
isTransformed = true;
}
}
}
private void ExecuteReversion()
{
Transform playerVisual = Player.m_localPlayer.transform.Find("Visual");
if (currentTransformation != null) Destroy(currentTransformation);
// Sync to ZDO
ZNetView nview = Player.m_localPlayer.GetComponent<ZNetView>();
if (nview != null && nview.IsValid())
{
nview.GetZDO().Set("RacesOfValheim_SkadiForm", "");
}
var forms1 = Player.m_localPlayer.GetComponentsInChildren<DrakeFormBehavior>(true);
foreach (var f in forms1) Destroy(f.gameObject);
if (playerVisual != null)
{
playerVisual.localScale = Vector3.one;
playerVisual.gameObject.SetActive(true);
}
isTransformed = false;
Player.m_localPlayer.Message(MessageHud.MessageType.Center, "You returned to human form.");
if (activeRules != null && activeRules.CooldownMinutes > 0)
{
Player.m_localPlayer.GetSEMan().AddStatusEffect("SE_SkadiCooldown".GetStableHashCode(), true);
var cdSE = Player.m_localPlayer.GetSEMan().GetStatusEffect("SE_SkadiCooldown".GetStableHashCode());
if (cdSE != null) cdSE.m_ttl = activeRules.CooldownMinutes * 60f;
}
activeRules = null;
}
}
}

View file

@ -0,0 +1,32 @@
using System;
using System.Collections.Generic;
using UnityEngine;
namespace RacesOfValheim
{
public class SE_SkadiStats : SE_Stats
{
public override void Setup(Character character)
{
base.Setup(character);
name = "SE_SkadiStats";
m_name = "Skadi's Aura";
m_tooltip = "Empowered by the frost.";
}
public void UpdateStats(SkadiProgression.FormRules rules)
{
m_mods = new List<HitData.DamageModPair>();
if (rules.FrostResistance >= 1f)
{
m_mods.Add(new HitData.DamageModPair() { m_type = HitData.DamageType.Frost, m_modifier = HitData.DamageModifier.Immune });
}
else if (rules.FrostResistance >= 0.5f)
{
m_mods.Add(new HitData.DamageModPair() { m_type = HitData.DamageType.Frost, m_modifier = HitData.DamageModifier.Resistant });
}
m_eitrRegenMultiplier = rules.EitrRegenMultiplier;
}
}
}

View file

@ -0,0 +1 @@
// Add logic to SkadiRace.cs using powershell

View file

@ -0,0 +1,480 @@
using HarmonyLib;
using UnityEngine;
using Jotunn.Managers;
using System.Linq;
namespace RacesOfValheim
{
public static class SkeletonPatches
{
// Cache the skeleton mesh and materials for performance
private static Mesh skeletonMesh = null;
private static Material[] skeletonMaterials = null;
[HarmonyPatch(typeof(Player), "UseStamina")]
public static class Player_UseStamina_Patch
{
public static bool Prefix(Player __instance)
{
if ((SkeletonRace.IsSkeleton() || AswidRace.IsAswid()) && __instance == Player.m_localPlayer)
{
// Infinite stamina: skip the original UseStamina method
return false;
}
return true;
}
}
[HarmonyPatch(typeof(Player), "ConsumeItem")]
public static class Player_ConsumeItem_Patch
{
public static bool Prefix(Player __instance, ItemDrop.ItemData item, ref bool __result)
{
if (__instance == Player.m_localPlayer)
{
if (SkeletonRace.IsSkeleton() && item.m_shared.m_itemType == ItemDrop.ItemData.ItemType.Consumable && (item.m_shared.m_food > 0 || item.m_shared.m_foodStamina > 0 || item.m_shared.m_foodEitr > 0))
{
__instance.Message(MessageHud.MessageType.Center, "Skeletons do not need to eat.");
__result = false;
return false;
}
else if (AswidRace.IsAswid() && !AswidRace.BypassAswidFoodCheck && item.m_shared.m_itemType == ItemDrop.ItemData.ItemType.Consumable && (item.m_shared.m_food > 0 || item.m_shared.m_foodStamina > 0 || item.m_shared.m_foodEitr > 0))
{
__instance.Message(MessageHud.MessageType.Center, "Mortal food disgusts you.");
__result = false;
return false;
}
}
return true;
}
}
[HarmonyPatch(typeof(Player), "Message")]
public static class Player_Message_Patch
{
public static bool Prefix(Player __instance, MessageHud.MessageType type, string msg)
{
if (__instance == Player.m_localPlayer)
{
if (msg == "$msg_eatanother" || msg.ToLower().Contains("eat") || msg.ToLower().Contains("mangiare") || msg.ToLower().Contains("boccone"))
{
if (AswidRace.IsAswid())
{
return false;
}
}
}
return true;
}
}
[HarmonyPatch(typeof(Hud), "UpdateFood")]
public static class Hud_UpdateFood_Patch
{
private static readonly string[] foodElements = new string[]
{
"hudroot/healthpanel/foodicon",
"hudroot/healthpanel/foodicon (1)",
"hudroot/healthpanel/food0",
"hudroot/healthpanel/food1",
"hudroot/healthpanel/food2",
"hudroot/healthpanel/FoodText",
"hudroot/healthpanel/Food"
};
public static bool Prefix(Hud __instance, Player player)
{
try
{
if (player == Player.m_localPlayer && SkeletonRace.IsSkeleton())
{
if (__instance.m_foodBarRoot != null && __instance.m_foodBarRoot.gameObject.activeSelf)
{
__instance.m_foodBarRoot.gameObject.SetActive(false);
}
foreach (string path in foodElements)
{
Transform t = __instance.transform.Find(path);
if (t != null && t.gameObject.activeSelf)
{
t.gameObject.SetActive(false);
}
}
return false; // Safely skip original Valheim Hud.UpdateFood
}
else
{
if (__instance.m_foodBarRoot != null && !__instance.m_foodBarRoot.gameObject.activeSelf)
{
__instance.m_foodBarRoot.gameObject.SetActive(true);
}
foreach (string path in foodElements)
{
Transform t = __instance.transform.Find(path);
if (t != null && !t.gameObject.activeSelf)
{
t.gameObject.SetActive(true);
}
}
return true;
}
}
catch (System.Exception e)
{
if (player == Player.m_localPlayer && SkeletonRace.IsSkeleton()) return false;
return true;
}
}
}
[HarmonyPatch(typeof(VisEquipment), "UpdateVisuals")]
public static class VisEquipment_UpdateVisuals_Patch
{
public static void Postfix(VisEquipment __instance)
{
if (!__instance.m_isPlayer) return;
Player p = __instance.GetComponent<Player>();
if (p == null) return;
ZNetView nview = p.GetComponent<ZNetView>();
if (nview == null || !nview.IsValid()) return;
string race = nview.GetZDO().GetString("RacesOfValheim_Race", "Human");
if (race == "Skeleton")
{
if (__instance.m_bodyModel != null)
{
// Ensure the base model is hidden
__instance.m_bodyModel.enabled = false;
int state = nview.GetZDO().GetInt("RacesOfValheim_SkeletonState", 0);
SkeletonProgression.SkeletonRules rules = SkeletonProgression.GetRules(state);
string targetBodyName = $"SkeletonBody_{rules.ModelPrefab}";
// Check if we already created the Skeleton body for this VisEquipment
Transform parentTransform = __instance.m_bodyModel.transform.parent;
// Destroy old bodies if state changed
for (int i = parentTransform.childCount - 1; i >= 0; i--)
{
Transform child = parentTransform.GetChild(i);
if (child.name.StartsWith("SkeletonBody") && child.name != targetBodyName)
{
UnityEngine.Object.Destroy(child.gameObject);
}
}
Transform skeletonBodyTransform = parentTransform.Find(targetBodyName);
if (skeletonBodyTransform == null)
{
GameObject skelPrefab = PrefabManager.Cache.GetPrefab<GameObject>(rules.ModelPrefab);
if (skelPrefab != null)
{
GameObject skelObj = new GameObject(targetBodyName);
skelObj.transform.SetParent(parentTransform, false);
SkinnedMeshRenderer[] smrs = skelPrefab.GetComponentsInChildren<SkinnedMeshRenderer>(true);
foreach (SkinnedMeshRenderer smr in smrs)
{
GameObject partObj = UnityEngine.Object.Instantiate(smr.gameObject, skelObj.transform);
partObj.name = smr.gameObject.name;
SkinnedMeshRenderer newSmr = partObj.GetComponent<SkinnedMeshRenderer>();
// Map bones by name
Transform[] playerBones = __instance.m_bodyModel.bones;
Transform[] newBones = new Transform[newSmr.bones.Length];
for (int i = 0; i < newSmr.bones.Length; i++)
{
Transform matchedBone = FindBoneByName(playerBones, newSmr.bones[i].name);
newBones[i] = matchedBone != null ? matchedBone : playerBones[0];
}
newSmr.bones = newBones;
if (newSmr.rootBone != null)
{
newSmr.rootBone = FindBoneByName(playerBones, newSmr.rootBone.name) ?? playerBones[0];
}
}
skeletonBodyTransform = skelObj.transform;
}
}
if (skeletonBodyTransform != null)
{
skeletonBodyTransform.gameObject.SetActive(true);
}
// Prevent Animator from freezing when body is disabled
Animator anim = __instance.GetComponentInChildren<Animator>();
if (anim != null)
{
anim.cullingMode = AnimatorCullingMode.AlwaysAnimate;
}
HideItemInstances(__instance, "m_hairItemInstances");
HideItemInstances(__instance, "m_beardItemInstances");
}
}
else
{
// Not a skeleton, ensure human body is visible and skeleton is hidden
if (__instance.m_bodyModel != null)
{
__instance.m_bodyModel.enabled = true;
Transform parentTransform = __instance.m_bodyModel.transform.parent;
if (parentTransform != null)
{
for (int i = 0; i < parentTransform.childCount; i++)
{
Transform child = parentTransform.GetChild(i);
if (child.name.StartsWith("SkeletonBody"))
{
child.gameObject.SetActive(false);
}
}
}
ShowItemInstances(__instance, "m_hairItemInstances");
ShowItemInstances(__instance, "m_beardItemInstances");
}
}
}
private static void HideItemInstances(VisEquipment visEq, string fieldName)
{
try
{
var field = typeof(VisEquipment).GetField(fieldName, System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
if (field != null)
{
var list = field.GetValue(visEq) as System.Collections.Generic.List<GameObject>;
if (list != null)
{
foreach (GameObject go in list)
{
if (go != null) go.SetActive(false);
}
}
}
}
catch (System.Exception e)
{
Jotunn.Logger.LogWarning($"Failed to hide {fieldName}: {e.Message}");
}
}
private static void ShowItemInstances(VisEquipment visEq, string fieldName)
{
try
{
var field = typeof(VisEquipment).GetField(fieldName, System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
if (field != null)
{
var list = field.GetValue(visEq) as System.Collections.Generic.List<GameObject>;
if (list != null)
{
foreach (GameObject go in list)
{
if (go != null) go.SetActive(true);
}
}
}
}
catch (System.Exception e) { }
}
private static Transform FindBoneByName(Transform[] bones, string skelBoneName)
{
// Exact match first
foreach (Transform b in bones)
{
if (b != null && b.name == skelBoneName) return b;
}
// Fuzzy match
string sName = skelBoneName.ToLower().Replace("skeleton_", "").Replace("skel_", "").Replace(" skeleton", "");
// Some specific Valheim mappings if needed
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(Character), "Damage")]
public static class Character_Damage_Patch
{
private static float lastStunTime = 0f;
public static bool Prefix(Character __instance, HitData hit)
{
if (Player.m_localPlayer == null) return true;
int state = BossProgressionManager.GetCurrentProgressionState();
var rules = SkeletonProgression.GetRules(state);
// Auto-Resurrect check
if (__instance == Player.m_localPlayer && SkeletonRace.IsSkeleton() && rules.AutoResurrect)
{
if (hit.GetTotalDamage() >= __instance.GetHealth())
{
if (!Player.m_localPlayer.GetSEMan().HaveStatusEffect("SE_SkeletonResurrectCooldown".GetStableHashCode()))
{
// Cancel death!
Player.m_localPlayer.Heal(Player.m_localPlayer.GetMaxHealth(), true);
Player.m_localPlayer.GetSEMan().AddStatusEffect("SE_SkeletonResurrectCooldown".GetStableHashCode(), true);
// Spawn VFX
GameObject vfx = PrefabManager.Cache.GetPrefab<GameObject>("vfx_skeleton_spawn") ??
PrefabManager.Cache.GetPrefab<GameObject>("vfx_bloodmagic_aoe");
if (vfx != null)
{
UnityEngine.Object.Instantiate(vfx, Player.m_localPlayer.transform.position, Quaternion.identity);
}
Player.m_localPlayer.Message(MessageHud.MessageType.Center, "You have been resurrected by dark magic!");
return false; // Skip applying this lethal damage
}
}
}
// Outgoing damage (Lifesteal, Poison, Stun)
Character attacker = hit.GetAttacker();
if (attacker != null && attacker == Player.m_localPlayer && SkeletonRace.IsSkeleton())
{
// Auto Stun
if (rules.AutoStunFirstHit && Time.time - lastStunTime > 5f)
{
hit.m_staggerMultiplier = 100f; // Force stagger
lastStunTime = Time.time;
}
// Poison Attacks
if (rules.PoisonAttacks)
{
hit.m_damage.m_poison += 20f; // Add flat 20 poison damage
}
// Lifesteal
if (rules.LifestealPercent > 0f)
{
float physDamage = hit.m_damage.m_blunt + hit.m_damage.m_slash + hit.m_damage.m_pierce;
if (physDamage > 0)
{
float healAmount = physDamage * rules.LifestealPercent;
Player.m_localPlayer.Heal(healAmount, true);
}
}
}
return true;
}
}
[HarmonyPatch(typeof(Character), "OnDeath")]
public static class Character_OnDeath_Patch
{
public static System.Collections.Generic.List<Character> activeMinions = new System.Collections.Generic.List<Character>();
public static void Prefix(Character __instance)
{
if (Player.m_localPlayer == null || !SkeletonRace.IsSkeleton()) return;
HitData lastHit = HarmonyLib.Traverse.Create(__instance).Field("m_lastHit").GetValue<HitData>();
if (lastHit != null && lastHit.GetAttacker() == Player.m_localPlayer)
{
int state = BossProgressionManager.GetCurrentProgressionState();
var rules = SkeletonProgression.GetRules(state);
if (rules.SummonOnKill && !string.IsNullOrEmpty(rules.SummonPrefab))
{
// Clean up dead minions
activeMinions.RemoveAll(m => m == null || m.IsDead());
if (activeMinions.Count < rules.MaxSummons)
{
GameObject minionPrefab = PrefabManager.Cache.GetPrefab<GameObject>(rules.SummonPrefab);
if (minionPrefab != null)
{
GameObject minion = UnityEngine.Object.Instantiate(minionPrefab, __instance.transform.position, Quaternion.identity);
Character minionChar = minion.GetComponent<Character>();
if (minionChar != null)
{
// Make it friendly
minionChar.m_faction = Character.Faction.Players;
BaseAI ai = minion.GetComponent<BaseAI>();
if (ai != null)
{
MonsterAI monsterAI = minion.GetComponent<MonsterAI>();
if (monsterAI != null)
{
monsterAI.SetFollowTarget(Player.m_localPlayer.gameObject);
}
}
activeMinions.Add(minionChar);
}
}
}
}
}
}
}
[HarmonyPatch(typeof(BaseAI), "IsEnemy", typeof(Character), typeof(Character))]
public static class BaseAI_IsEnemy_Patch
{
public static void Postfix(Character a, Character b, ref bool __result)
{
if (!__result || !SkeletonRace.IsSkeleton() || 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)
{
string name = otherChar.gameObject.name.Replace("(Clone)", "").ToLower();
if (name == "skeleton" ||
name == "skeleton_noarcher" ||
name == "skeleton_poison" ||
name == "skeleton_friendly" ||
name.StartsWith("draugr") ||
name == "ghost" ||
name == "wraith")
{
__result = false;
}
}
}
}
}
}

View file

@ -0,0 +1,98 @@
using System;
namespace RacesOfValheim
{
public static class SkeletonProgression
{
public static float GetMaxHealthBonus(int state)
{
if (state == 0) return 0f;
if (state == 1) return 50f;
if (state == 2) return 80f;
if (state == 3) return 110f;
if (state == 4) return 140f;
if (state == 5) return 170f;
if (state == 6) return 200f;
if (state == 7) return 230f;
if (state >= 8) return 275f;
return 50f;
}
public struct SkeletonRules
{
public float LifestealPercent;
public bool EnhancedRegen;
public bool PoisonImmunity;
public bool PoisonAttacks;
public bool AutoResurrect;
public bool SummonOnKill;
public int MaxSummons;
public string SummonPrefab;
public bool AutoStunFirstHit;
public bool FireAura;
public string ModelPrefab;
public UnityEngine.Vector3 ScaleMultiplier;
}
public static SkeletonRules GetRules(int state)
{
SkeletonRules rules = new SkeletonRules
{
LifestealPercent = 0f,
EnhancedRegen = false,
PoisonImmunity = false,
PoisonAttacks = false,
AutoResurrect = false,
SummonOnKill = false,
MaxSummons = 0,
SummonPrefab = "",
AutoStunFirstHit = false,
FireAura = false,
ModelPrefab = "Skeleton",
ScaleMultiplier = UnityEngine.Vector3.one
};
if (state >= 2)
{
rules.ModelPrefab = "Skeleton_Poison";
rules.LifestealPercent = 0.20f;
}
if (state >= 3)
{
rules.EnhancedRegen = true;
}
if (state >= 4)
{
rules.PoisonImmunity = true;
rules.PoisonAttacks = true;
}
if (state >= 5)
{
rules.AutoResurrect = true;
}
if (state >= 6)
{
rules.ModelPrefab = "Skeleton_Poison";
rules.LifestealPercent = 0.30f;
rules.SummonOnKill = true;
rules.MaxSummons = 2;
rules.SummonPrefab = "Skeleton_friendly";
rules.ScaleMultiplier = UnityEngine.Vector3.one * 1.1f;
}
if (state >= 7)
{
rules.AutoStunFirstHit = true;
rules.LifestealPercent = 0.40f;
}
if (state >= 8)
{
rules.ModelPrefab = "Charred_Twitcher";
rules.SummonPrefab = "Charred_Twitcher";
rules.FireAura = true;
rules.ScaleMultiplier = new UnityEngine.Vector3(0.85f, 1.20f, 0.85f);
}
return rules;
}
}
}

View file

@ -0,0 +1,466 @@
using UnityEngine;
using Jotunn.Managers;
using Jotunn.Entities;
using System.Collections.Generic;
namespace RacesOfValheim
{
public class SkeletonRace : MonoBehaviour
{
public static SkeletonRace Instance;
public static SE_SkeletonStats skeletonStatsSE;
private void Awake()
{
Instance = this;
}
public void CreateModAssets()
{
var se = ScriptableObject.CreateInstance<SE_SkeletonStats>();
se.name = "SE_SkeletonStats";
se.m_name = "Undead Fortitude";
// Icon
GameObject skelTrophy = PrefabManager.Cache.GetPrefab<ItemDrop>("TrophySkeleton")?.gameObject;
if (skelTrophy != null)
{
ItemDrop trophyDrop = skelTrophy.GetComponent<ItemDrop>();
if (trophyDrop != null && trophyDrop.m_itemData.m_shared.m_icons.Length > 0)
{
se.m_icon = trophyDrop.m_itemData.m_shared.m_icons[0];
}
}
CustomStatusEffect skeletonStats = new CustomStatusEffect(se, fixReference: false);
ItemManager.Instance.AddStatusEffect(skeletonStats);
skeletonStatsSE = skeletonStats.StatusEffect as SE_SkeletonStats;
var resurrectSE = ScriptableObject.CreateInstance<SE_SkeletonResurrectCooldown>();
resurrectSE.name = "SE_SkeletonResurrectCooldown";
CustomStatusEffect customResurrectSE = new CustomStatusEffect(resurrectSE, fixReference: false);
ItemManager.Instance.AddStatusEffect(customResurrectSE);
}
public static bool IsSkeleton()
{
return Player.m_localPlayer != null &&
Player.m_localPlayer.m_customData.ContainsKey("Race") &&
Player.m_localPlayer.m_customData["Race"] == "Skeleton";
}
private float lastAuraTime = 0f;
private GameObject fireAuraVFX = null;
private static List<ItemDrop.ItemData>[] cachedRealFoods = new List<ItemDrop.ItemData>[9];
private List<ItemDrop.ItemData> GetBestRealFoods(int state)
{
if (state < 1) state = 1;
if (state > 8) state = 8;
if (cachedRealFoods[state] != null) return cachedRealFoods[state];
if (ObjectDB.instance == null || ObjectDB.instance.m_items == null) return null;
float targetHealth = SkeletonProgression.GetMaxHealthBonus(state);
List<ItemDrop.ItemData> allFoods = new List<ItemDrop.ItemData>();
foreach (GameObject obj in ObjectDB.instance.m_items)
{
ItemDrop drop = obj.GetComponent<ItemDrop>();
if (drop != null && drop.m_itemData != null && drop.m_itemData.m_shared.m_itemType == ItemDrop.ItemData.ItemType.Consumable && drop.m_itemData.m_shared.m_food > 0)
{
allFoods.Add(drop.m_itemData);
}
}
if (allFoods.Count < 3) return null;
float bestDiff = float.MaxValue;
float bestRegen = -1f;
List<ItemDrop.ItemData> bestCombo = null;
if (state == 8)
{
ItemDrop.ItemData f1 = null, f2 = null, f3 = null;
foreach(var drop in allFoods)
{
string n = drop.m_shared.m_name.ToLower();
string p = drop.m_dropPrefab != null ? drop.m_dropPrefab.name.ToLower() : "";
if (f1 == null && ((n.Contains("asksvin") && n.Contains("tail")) || (p.Contains("asksvin") && p.Contains("tail")))) f1 = drop;
else if (f2 == null && ((n.Contains("mashed") && n.Contains("meat")) || (p.Contains("mashed") && p.Contains("meat")))) f2 = drop;
else if (f3 == null && ((n.Contains("piquant") && n.Contains("pie")) || (p.Contains("piquant") && p.Contains("pie")))) f3 = drop;
}
if (f1 != null && f2 != null && f3 != null)
{
bestCombo = new List<ItemDrop.ItemData> { f1.Clone(), f2.Clone(), f3.Clone() };
}
}
if (bestCombo == null)
{
for (int i = 0; i < allFoods.Count; i++)
{
for (int j = i; j < allFoods.Count; j++)
{
for (int k = j; k < allFoods.Count; k++)
{
var f1 = allFoods[i];
var f2 = allFoods[j];
var f3 = allFoods[k];
float hpSum = f1.m_shared.m_food + f2.m_shared.m_food + f3.m_shared.m_food;
float regenSum = f1.m_shared.m_foodRegen + f2.m_shared.m_foodRegen + f3.m_shared.m_foodRegen;
float diff = Mathf.Abs(hpSum - targetHealth);
if (diff < bestDiff || (Mathf.Abs(diff - bestDiff) < 0.1f && regenSum > bestRegen))
{
bestDiff = diff;
bestRegen = regenSum;
bestCombo = new List<ItemDrop.ItemData> { f1.Clone(), f2.Clone(), f3.Clone() };
}
}
}
}
}
if (bestCombo != null)
{
float actualSum = 0f;
foreach(var c in bestCombo) actualSum += c.m_shared.m_food;
float scale = actualSum > 0f ? (targetHealth / actualSum) : 1f;
foreach(var c in bestCombo)
{
c.m_shared = (ItemDrop.ItemData.SharedData)typeof(object).GetMethod("MemberwiseClone", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic).Invoke(c.m_shared, null);
// Modificatore per scalare perfettamente gli HP
c.m_shared.m_food = c.m_shared.m_food * scale;
// Azzerare completamente l'Eitr e la Stamina
c.m_shared.m_foodEitr = 0f;
c.m_shared.m_foodStamina = 0f;
c.m_shared.m_foodBurnTime = 999999f;
}
}
cachedRealFoods[state] = bestCombo;
return bestCombo;
}
private void DumpTransformHierarchy(Transform t, string indent)
{
if (t == null) return;
Jotunn.Logger.LogInfo(indent + t.name + " (Active: " + t.gameObject.activeSelf + ")");
for(int i = 0; i < t.childCount; i++)
{
DumpTransformHierarchy(t.GetChild(i), indent + " ");
}
}
private void Update()
{
if (Input.GetKeyDown(KeyCode.F8))
{
if (Hud.instance != null)
{
Jotunn.Logger.LogInfo("--- HUD HIERARCHY DUMP ---");
DumpTransformHierarchy(Hud.instance.transform, "");
Jotunn.Logger.LogInfo("--------------------------");
}
}
if (Player.m_localPlayer == null) return;
if (!IsSkeleton() || Player.m_localPlayer.IsDead())
{
EnsureFireAuraVFX(false);
if (Player.m_localPlayer.transform.localScale != Vector3.one)
{
Player.m_localPlayer.transform.localScale = Vector3.one;
}
return;
}
// Force hide hair and beard
var profile = Game.instance?.GetPlayerProfile();
if (profile != null)
{
var hair = HarmonyLib.Traverse.Create(profile).Field<string>("m_hairItem");
var beard = HarmonyLib.Traverse.Create(profile).Field<string>("m_beardItem");
if (!string.IsNullOrEmpty(hair.Value) || !string.IsNullOrEmpty(beard.Value))
{
hair.Value = "";
beard.Value = "";
HarmonyLib.Traverse.Create(Player.m_localPlayer).Field("m_hairItem").SetValue("");
HarmonyLib.Traverse.Create(Player.m_localPlayer).Field("m_beardItem").SetValue("");
VisEquipment vis = Player.m_localPlayer.GetComponent<VisEquipment>();
if (vis != null)
{
vis.SetHairItem("");
vis.SetBeardItem("");
}
}
}
int state = BossProgressionManager.GetCurrentProgressionState();
var rules = SkeletonProgression.GetRules(state);
// Continuously adjust equipment
VisEquipment currentVis = Player.m_localPlayer.GetComponent<VisEquipment>();
if (currentVis != null)
{
// Hide Helmets (Valheim uses singular GameObject for helmet)
var helmetObj = HarmonyLib.Traverse.Create(currentVis).Field<GameObject>("m_helmetItemInstance").Value;
if (helmetObj != null && helmetObj.transform.localScale != Vector3.zero)
{
helmetObj.transform.localScale = Vector3.zero;
}
// Scale Body Armor (Chest, Legs, Shoulder) by 5%
string[] armorFields = { "m_chestItemInstances", "m_legItemInstances", "m_shoulderItemInstances" };
foreach (string field in armorFields)
{
var armorList = HarmonyLib.Traverse.Create(currentVis).Field<System.Collections.Generic.List<GameObject>>(field).Value;
if (armorList != null)
{
foreach (GameObject armor in armorList)
{
if (armor != null && Mathf.Abs(armor.transform.localScale.x - 1.05f) > 0.01f)
{
armor.transform.localScale = new Vector3(1.05f, 1.05f, 1.05f);
}
}
}
}
}
// Hide Charred Twitcher Jaw
if (currentVis != null && currentVis.m_bodyModel != null && currentVis.m_bodyModel.bones != null)
{
foreach (Transform bone in currentVis.m_bodyModel.bones)
{
if (bone != null && bone.name.ToLower().Contains("jaw"))
{
if (state >= 8)
{
if (bone.localScale != Vector3.zero) bone.localScale = Vector3.zero;
}
else
{
if (bone.localScale == Vector3.zero) bone.localScale = Vector3.one;
}
break;
}
}
}
// Apply Scale
Vector3 targetScale = rules.ScaleMultiplier;
if (Player.m_localPlayer.transform.localScale != targetScale)
{
Player.m_localPlayer.transform.localScale = targetScale;
}
// Ensure ZDO is synced for visuals
ZNetView nview = Player.m_localPlayer.GetComponent<ZNetView>();
if (nview != null && nview.IsValid())
{
nview.GetZDO().Set("RacesOfValheim_SkeletonState", state);
}
// Manage Fake Foods
var foods = Player.m_localPlayer.GetFoods();
bool needsFood = false;
if (foods.Count != 3)
{
needsFood = true;
}
else
{
foreach(var food in foods)
{
food.m_time = 0f; // Always reset time so they never degrade!
}
float expectedHp = 0f;
var expectedFoods = GetBestRealFoods(state);
if (expectedFoods != null)
{
foreach(var f in expectedFoods) expectedHp += f.m_shared.m_food;
}
float currentHp = 0f;
foreach(var food in foods)
{
if (food.m_item != null && food.m_item.m_shared != null)
currentHp += food.m_item.m_shared.m_food;
}
if (Mathf.Abs(currentHp - expectedHp) > 1f)
{
needsFood = true;
}
}
if (needsFood)
{
Player.m_localPlayer.ClearFood();
var newDiet = GetBestRealFoods(state);
if (newDiet != null)
{
foreach (var dietItem in newDiet)
{
Player.Food newFood = new Player.Food();
newFood.m_name = dietItem.m_dropPrefab != null ? dietItem.m_dropPrefab.name : "";
newFood.m_item = dietItem;
newFood.m_health = dietItem.m_shared.m_food;
newFood.m_stamina = dietItem.m_shared.m_foodStamina;
newFood.m_eitr = dietItem.m_shared.m_foodEitr;
newFood.m_time = 0f;
foods.Add(newFood);
}
}
}
// Enhanced Health Regeneration
if (rules.EnhancedRegen)
{
if (skeletonStatsSE != null)
{
skeletonStatsSE.m_healthRegenMultiplier = 1.5f;
}
// Speed up regen ticks by 20% (1.25x faster timer accumulation)
float currentTimer = HarmonyLib.Traverse.Create(Player.m_localPlayer).Field<float>("m_foodRegenTimer").Value;
HarmonyLib.Traverse.Create(Player.m_localPlayer).Field("m_foodRegenTimer").SetValue(currentTimer + Time.deltaTime * 0.25f);
}
else
{
if (skeletonStatsSE != null)
{
skeletonStatsSE.m_healthRegenMultiplier = 1.0f;
}
}
if (rules.FireAura)
{
EnsureFireAuraVFX(true);
if (Time.time - lastAuraTime >= 1f)
{
ApplyFireAura();
lastAuraTime = Time.time;
}
}
else
{
EnsureFireAuraVFX(false);
}
}
private void EnsureFireAuraVFX(bool enable)
{
if (enable && Player.m_localPlayer != null)
{
if (fireAuraVFX == null)
{
// Look for a smoke or fog effect to tint as fire fog
GameObject sourceVFX = PrefabManager.Cache.GetPrefab<GameObject>("vfx_smoke") ??
PrefabManager.Cache.GetPrefab<GameObject>("vfx_surtling_death");
fireAuraVFX = new GameObject("SkeletonFireAuraVFX");
fireAuraVFX.transform.SetParent(Player.m_localPlayer.transform, false);
fireAuraVFX.transform.localPosition = new Vector3(0, 1f, 0);
if (sourceVFX != null)
{
ParticleSystem[] pss = sourceVFX.GetComponentsInChildren<ParticleSystem>();
if (pss.Length > 0)
{
ParticleSystem ps = fireAuraVFX.AddComponent<ParticleSystem>();
var main = ps.main;
main.loop = true;
main.duration = 1f;
main.startLifetime = 1.5f;
main.startSize = new ParticleSystem.MinMaxCurve(1.5f, 3f);
main.startSpeed = 0f;
main.simulationSpace = ParticleSystemSimulationSpace.World;
var renderer = fireAuraVFX.GetComponent<ParticleSystemRenderer>();
renderer.material = pss[0].GetComponent<ParticleSystemRenderer>().material;
var shape = ps.shape;
shape.shapeType = ParticleSystemShapeType.Sphere;
shape.radius = 4.5f; // Similar to the damage radius
var emission = ps.emission;
emission.rateOverTime = 40f;
// Add a fire-like color gradient
var colorOverLifetime = ps.colorOverLifetime;
colorOverLifetime.enabled = true;
Gradient grad = new Gradient();
grad.SetKeys(
new GradientColorKey[] {
new GradientColorKey(new Color(1f, 0.8f, 0.2f), 0.0f), // Yellow
new GradientColorKey(new Color(1f, 0.3f, 0.0f), 0.5f), // Orange/Red
new GradientColorKey(new Color(0.2f, 0.0f, 0.0f), 1.0f) // Dark red/smoke
},
new GradientAlphaKey[] {
new GradientAlphaKey(0.0f, 0.0f),
new GradientAlphaKey(0.6f, 0.2f),
new GradientAlphaKey(0.6f, 0.8f),
new GradientAlphaKey(0.0f, 1.0f)
}
);
colorOverLifetime.color = grad;
}
}
}
if (!fireAuraVFX.activeSelf)
{
fireAuraVFX.SetActive(true);
}
}
else
{
if (fireAuraVFX != null && fireAuraVFX.activeSelf)
{
fireAuraVFX.SetActive(false);
}
}
}
private void ApplyFireAura()
{
if (Player.m_localPlayer == null) return;
Vector3 center = Player.m_localPlayer.transform.position;
float radius = 5f;
HitData hitData = new HitData();
hitData.m_damage.m_fire = 30f; // 30 fire damage per second
hitData.SetAttacker(Player.m_localPlayer);
hitData.m_dir = Vector3.zero;
int hits = 0;
foreach (Collider collider in Physics.OverlapSphere(center, radius))
{
Character character = collider.GetComponentInParent<Character>();
if (character != null && character != Player.m_localPlayer && BaseAI.IsEnemy(Player.m_localPlayer, character))
{
character.Damage(hitData);
hits++;
}
}
}
}
}

View file

@ -0,0 +1,46 @@
using UnityEngine;
using System.Collections.Generic;
namespace RacesOfValheim
{
public class SE_SkeletonStats : SE_Stats
{
public override void Setup(Character character)
{
base.Setup(character);
// Apply Damage Modifiers
int state = BossProgressionManager.GetCurrentProgressionState();
SkeletonProgression.SkeletonRules rules = SkeletonProgression.GetRules(state);
m_mods = new List<HitData.DamageModPair>();
m_mods.Add(new HitData.DamageModPair { m_type = HitData.DamageType.Pierce, m_modifier = HitData.DamageModifier.Resistant });
m_mods.Add(new HitData.DamageModPair { m_type = HitData.DamageType.Slash, m_modifier = HitData.DamageModifier.Resistant });
m_mods.Add(new HitData.DamageModPair { m_type = HitData.DamageType.Blunt, m_modifier = HitData.DamageModifier.Weak });
if (rules.PoisonImmunity)
{
m_mods.Add(new HitData.DamageModPair { m_type = HitData.DamageType.Poison, m_modifier = HitData.DamageModifier.Immune });
}
}
public override void UpdateStatusEffect(float dt)
{
base.UpdateStatusEffect(dt);
// Health is handled in SkeletonPatches.Player_GetMaxHealth_Patch
}
}
public class SE_SkeletonResurrectCooldown : StatusEffect
{
public override void Setup(Character character)
{
base.Setup(character);
m_name = "Resurrection Cooldown";
m_tooltip = "Your skeletal body is too weak to resurrect again right now.";
m_icon = Jotunn.Managers.PrefabManager.Cache.GetPrefab<GameObject>("TrophySkeletonPoison")?.GetComponent<ItemDrop>()?.m_itemData.GetIcon()
?? Jotunn.Managers.PrefabManager.Cache.GetPrefab<GameObject>("TrophySkeleton")?.GetComponent<ItemDrop>()?.m_itemData.GetIcon();
m_ttl = 300f; // 5 minutes
}
}
}

View file

@ -0,0 +1,28 @@
using HarmonyLib;
using UnityEngine;
using UnityEngine.UI;
namespace RacesOfValheim
{
[HarmonyPatch]
public static class TMPDebug
{
[HarmonyPatch(typeof(Hud), "Awake")]
[HarmonyPostfix]
public static void Awake_Postfix(Hud __instance)
{
Transform food2 = __instance.transform.Find("hudroot/healthpanel/food2");
if (food2 != null)
{
Transform time = food2.Find("time");
if (time != null)
{
Component[] comps = time.GetComponents<Component>();
foreach(var c in comps) {
Jotunn.Logger.LogInfo("Time component: " + c.GetType().Name);
}
}
}
}
}
}

View file

@ -0,0 +1,11 @@
using HarmonyLib;
namespace RacesOfValheim {
[HarmonyPatch(typeof(Player), "ClearFood")]
public static class Trol_ClearFood_Patch {
public static void Postfix(Player __instance) {
if (__instance == Player.m_localPlayer && TrolRace.IsTrol()) {
TrolFoodManager.ClearFood(__instance);
}
}
}
}

View file

@ -0,0 +1,60 @@
using HarmonyLib;
using UnityEngine;
namespace RacesOfValheim
{
[HarmonyPatch(typeof(Character), "ApplyDamage")]
public static class Trol_Character_ApplyDamage_Patch
{
public static void Prefix(Character __instance, ref HitData hit)
{
if (__instance == Player.m_localPlayer && TrolRace.IsTrol())
{
// Trols are weak to fire (take 50% more damage)
if (hit.m_damage.m_fire > 0f)
{
hit.m_damage.m_fire *= 1.5f;
}
}
if (hit.GetAttacker() == Player.m_localPlayer && TrolRace.IsTrol())
{
if (BossProgressionManager.GetCurrentProgressionState() >= 4) // Bonemass
{
if (hit.m_skill == Skills.SkillType.Clubs || hit.m_skill == Skills.SkillType.Unarmed)
{
hit.m_damage.m_blunt += 10f;
}
else if (hit.m_skill == Skills.SkillType.Axes)
{
hit.m_damage.m_slash += 10f;
}
}
if (BossProgressionManager.GetCurrentProgressionState() >= 6) // Yagluth
{
if (hit.m_skill == Skills.SkillType.Clubs || hit.m_skill == Skills.SkillType.Unarmed)
{
hit.m_damage.m_blunt += 5f;
}
else if (hit.m_skill == Skills.SkillType.Axes)
{
hit.m_damage.m_slash += 5f;
}
}
if (Player.m_localPlayer.GetSEMan().HaveStatusEffect("SE_TrolTrueForm".GetStableHashCode()))
{
if (hit.m_skill == Skills.SkillType.Clubs || hit.m_skill == Skills.SkillType.Unarmed)
{
hit.m_damage.m_blunt += 40f;
}
else if (hit.m_skill == Skills.SkillType.Axes)
{
hit.m_damage.m_slash += 40f;
}
}
}
}
}
}

View file

@ -0,0 +1,133 @@
using HarmonyLib;
using UnityEngine;
using UnityEngine.UI;
namespace RacesOfValheim
{
[HarmonyPatch]
public static class TrolExtraFoodUI
{
private static GameObject TrolFoodUIBase;
private static Image TrolFoodIcon;
private static GameObject TrolFoodTimeObj;
private static GameObject TrolFoodUIBase5;
private static Image TrolFoodIcon5;
private static GameObject TrolFoodTimeObj5;
[HarmonyPatch(typeof(Hud), "Awake")]
[HarmonyPostfix]
public static void Awake_Postfix(Hud __instance)
{
Transform healthPanel = __instance.transform.Find("hudroot/healthpanel");
if (healthPanel == null) return;
Transform food1 = healthPanel.Find("food1");
Transform food2 = healthPanel.Find("food2");
if (food1 == null || food2 == null) return;
// Clone food2
GameObject food3 = UnityEngine.Object.Instantiate(food2.gameObject, healthPanel);
food3.name = "TrolExtraFoodSlot";
// Calculate vertical offset (distance between slot 1 and 2)
float offset = food2.localPosition.y - food1.localPosition.y;
food3.transform.localPosition = food2.localPosition + new Vector3(0, offset, 0);
TrolFoodUIBase = food3;
TrolFoodIcon = food3.transform.Find("foodicon2")?.GetComponent<Image>();
if (TrolFoodIcon == null) TrolFoodIcon = food3.transform.Find("icon")?.GetComponent<Image>(); // Fallback
TrolFoodTimeObj = food3.transform.Find("time")?.gameObject;
TrolFoodUIBase.SetActive(false);
// Clone food3 for 5th slot
GameObject food4 = UnityEngine.Object.Instantiate(food3.gameObject, healthPanel);
food4.name = "TrolExtraFoodSlot5";
food4.transform.localPosition = food3.transform.localPosition + new Vector3(0, offset, 0);
TrolFoodUIBase5 = food4;
TrolFoodIcon5 = food4.transform.Find("foodicon2")?.GetComponent<Image>();
if (TrolFoodIcon5 == null) TrolFoodIcon5 = food4.transform.Find("icon")?.GetComponent<Image>();
TrolFoodTimeObj5 = food4.transform.Find("time")?.gameObject;
TrolFoodUIBase5.SetActive(false);
}
[HarmonyPatch(typeof(Hud), "UpdateFood")]
[HarmonyPostfix]
public static void UpdateFood_Postfix(Hud __instance)
{
if (TrolFoodUIBase == null) return;
if (Player.m_localPlayer == null || !TrolRace.IsTrol())
{
TrolFoodUIBase.SetActive(false);
if (TrolFoodUIBase5 != null) TrolFoodUIBase5.SetActive(false);
return;
}
TrolFoodUIBase.SetActive(true);
bool show5th = BossProgressionManager.GetCurrentProgressionState() >= 6;
if (TrolFoodUIBase5 != null) TrolFoodUIBase5.SetActive(show5th);
UpdateSlotUI(Player.m_localPlayer, TrolFoodManager.ExtraFoods, TrolFoodIcon, TrolFoodTimeObj);
if (show5th)
{
UpdateSlotUI(Player.m_localPlayer, TrolFoodManager.ExtraFoods5, TrolFoodIcon5, TrolFoodTimeObj5);
}
}
private static void UpdateSlotUI(Player player, System.Collections.Generic.Dictionary<Player, Player.Food> dict, Image icon, GameObject timeObj)
{
if (dict.TryGetValue(player, out Player.Food extraFood) && extraFood != null)
{
if (icon != null)
{
icon.sprite = extraFood.m_item.GetIcon();
icon.gameObject.SetActive(true);
bool canEat = extraFood.m_time >= (extraFood.m_item.m_shared.m_foodBurnTime * 0.5f);
if (canEat) icon.color = new Color(1f, 1f, 1f, Mathf.Sin(Time.time * 10f) * 0.5f + 0.5f);
else icon.color = Color.white;
}
if (timeObj != null)
{
timeObj.SetActive(true);
float remaining = extraFood.m_item.m_shared.m_foodBurnTime - extraFood.m_time;
if (remaining < 0) remaining = 0;
string timeStr = remaining < 60f ? Mathf.CeilToInt(remaining).ToString() + "s" : Mathf.CeilToInt(remaining / 60f).ToString() + "m";
bool canEat = extraFood.m_time >= (extraFood.m_item.m_shared.m_foodBurnTime * 0.5f);
Color timeCol = canEat ? new Color(1f, 0.5f, 0.5f, Mathf.Sin(Time.time * 10f) * 0.5f + 0.5f) : Color.white;
UpdateTextComponent(timeObj, timeStr, timeCol);
}
}
else
{
if (icon != null) icon.gameObject.SetActive(false);
if (timeObj != null) timeObj.SetActive(false);
}
}
private static void UpdateTextComponent(GameObject obj, string text, Color color)
{
var unityText = obj.GetComponent<UnityEngine.UI.Text>();
if (unityText != null)
{
unityText.text = text;
unityText.color = color;
}
var tmpText = obj.GetComponent("TMPro.TMP_Text");
if (tmpText != null)
{
var textProp = tmpText.GetType().GetProperty("text");
if (textProp != null) textProp.SetValue(tmpText, text, null);
var colorProp = tmpText.GetType().GetProperty("color");
if (colorProp != null) colorProp.SetValue(tmpText, color, null);
}
}
}
}

View file

@ -0,0 +1,101 @@
using HarmonyLib;
using UnityEngine;
namespace RacesOfValheim
{
public static class TrolFarmingHelper
{
public static void ApplyTrolUnarmedToolBuff(HitData hit, bool isTree)
{
if (hit == null) return;
Character attacker = hit.GetAttacker();
if (attacker != null && attacker == Player.m_localPlayer && TrolRace.IsTrol())
{
ItemDrop.ItemData rightItem = HarmonyLib.Traverse.Create(Player.m_localPlayer).Field<ItemDrop.ItemData>("m_rightItem").Value;
bool isHoldingLog = rightItem != null && rightItem.m_dropPrefab != null && rightItem.m_dropPrefab.name.StartsWith("TrolWeapon_");
if (isHoldingLog && isTree)
{
hit.m_toolTier = 10;
hit.m_damage.m_chop = 9999f;
return;
}
if (hit.m_skill == Skills.SkillType.Unarmed)
{
int state = BossProgressionManager.GetCurrentProgressionState();
if (state >= 8) hit.m_toolTier = 5; // Fader (Fire Metal)
else if (state >= 6) hit.m_toolTier = 4; // Yagluth (Black Metal)
else if (state >= 5) hit.m_toolTier = 3; // Moder (Silver)
else if (state >= 4) hit.m_toolTier = 2; // Bonemass (Iron)
else if (state >= 3) hit.m_toolTier = 1; // Elder (Bronze)
else if (state >= 2) hit.m_toolTier = 1; // Eikthyr (Flint/Antler)
float damageBonus = state * 3f;
// Convert blunt damage to chop or pickaxe damage, plus progression bonus
if (isTree)
{
hit.m_damage.m_chop = hit.m_damage.m_blunt + damageBonus;
Player.m_localPlayer.RaiseSkill(Skills.SkillType.WoodCutting, 1f);
}
else
{
hit.m_damage.m_pickaxe = hit.m_damage.m_blunt + damageBonus;
Player.m_localPlayer.RaiseSkill(Skills.SkillType.Pickaxes, 1f);
}
}
}
}
}
[HarmonyPatch(typeof(TreeBase), "RPC_Damage")]
public static class Trol_TreeBase_RPC_Damage_Patch
{
public static void Prefix(HitData hit)
{
TrolFarmingHelper.ApplyTrolUnarmedToolBuff(hit, true);
}
}
[HarmonyPatch(typeof(TreeLog), "RPC_Damage")]
public static class Trol_TreeLog_RPC_Damage_Patch
{
public static void Prefix(HitData hit)
{
TrolFarmingHelper.ApplyTrolUnarmedToolBuff(hit, true);
}
}
[HarmonyPatch(typeof(Destructible), "RPC_Damage")]
public static class Trol_Destructible_RPC_Damage_Patch
{
public static void Prefix(HitData hit, Destructible __instance)
{
// Some destructibles are trees (stumps), some are rocks.
// We can check the destructible type.
bool isTree = __instance.m_destructibleType == DestructibleType.Tree;
TrolFarmingHelper.ApplyTrolUnarmedToolBuff(hit, isTree);
}
}
[HarmonyPatch(typeof(MineRock), "RPC_Hit")]
public static class Trol_MineRock_RPC_Hit_Patch
{
public static void Prefix(HitData hit)
{
TrolFarmingHelper.ApplyTrolUnarmedToolBuff(hit, false);
}
}
[HarmonyPatch(typeof(MineRock5), "DamageArea")]
public static class Trol_MineRock5_DamageArea_Patch
{
public static void Prefix(HitData hit)
{
TrolFarmingHelper.ApplyTrolUnarmedToolBuff(hit, false);
}
}
}

View file

@ -0,0 +1,74 @@
using HarmonyLib;
using UnityEngine;
namespace RacesOfValheim
{
[HarmonyPatch]
public static class TrolFoodDebug
{
[HarmonyPatch(typeof(Player), "Update")]
[HarmonyPostfix]
public static void Update_Postfix(Player __instance)
{
if (__instance != Player.m_localPlayer) return;
if (Input.GetKeyDown(KeyCode.F8))
{
Jotunn.Logger.LogInfo("=== F8 TROL FOOD DEBUG ===");
Jotunn.Logger.LogInfo($"IsTrol: {TrolRace.IsTrol()}");
var foods = Traverse.Create(__instance).Field("m_foods").GetValue<System.Collections.Generic.List<Player.Food>>();
Jotunn.Logger.LogInfo($"Native m_foods Count: {foods?.Count ?? 0}");
if (foods != null)
{
for (int i = 0; i < foods.Count; i++)
{
var f = foods[i];
Jotunn.Logger.LogInfo($" [{i}] {f.m_item?.m_shared?.m_name} | Time: {f.m_time} / {f.m_item?.m_shared?.m_foodBurnTime}");
}
}
if (TrolFoodManager.ExtraFoods.TryGetValue(__instance, out Player.Food extraFood))
{
Jotunn.Logger.LogInfo($"ExtraFoods Dictionary has entry:");
Jotunn.Logger.LogInfo($" Name: {extraFood?.m_item?.m_shared?.m_name}");
Jotunn.Logger.LogInfo($" Time: {extraFood?.m_time} / {extraFood?.m_item?.m_shared?.m_foodBurnTime}");
}
else
{
Jotunn.Logger.LogInfo($"ExtraFoods Dictionary is EMPTY for this player.");
}
if (__instance.m_customData.TryGetValue("TrolFood_Prefab", out string prefab))
{
Jotunn.Logger.LogInfo($"m_customData TrolFood_Prefab: {prefab}");
}
if (__instance.m_customData.TryGetValue("TrolFood_Time", out string time))
{
Jotunn.Logger.LogInfo($"m_customData TrolFood_Time: {time}");
}
Jotunn.Logger.LogInfo("==========================");
}
}
[HarmonyPatch(typeof(Humanoid), "ConsumeItem")]
[HarmonyPrefix]
public static void ConsumeItem_Prefix(Humanoid __instance, Inventory inventory, ItemDrop.ItemData item)
{
if (__instance == Player.m_localPlayer && item != null && item.m_shared.m_name == "$item_bukeperry")
{
Jotunn.Logger.LogInfo("=== BUKEPERRY CONSUMED ===");
Jotunn.Logger.LogInfo($"IsTrol: {TrolRace.IsTrol()}");
if (TrolFoodManager.ExtraFoods.ContainsKey((Player)__instance))
{
Jotunn.Logger.LogInfo("ExtraFoods HAS entry. Will it clear?");
}
else
{
Jotunn.Logger.LogInfo("ExtraFoods DOES NOT HAVE entry before clear.");
}
Jotunn.Logger.LogInfo("==========================");
}
}
}
}

View file

@ -0,0 +1,67 @@
using HarmonyLib;
using UnityEngine;
using UnityEngine.UI;
namespace RacesOfValheim
{
[HarmonyPatch]
public static class TrolFoodDebugUI
{
[HarmonyPatch(typeof(Player), "Update")]
[HarmonyPostfix]
public static void Update_Postfix(Player __instance)
{
if (__instance != Player.m_localPlayer) return;
if (Input.GetKeyDown(KeyCode.F8))
{
Jotunn.Logger.LogInfo("=== F8 TROL FOOD UI DEBUG ===");
Transform healthPanel = Hud.instance?.transform.Find("hudroot/healthpanel");
if (healthPanel != null)
{
Transform food3 = healthPanel.Find("TrolExtraFoodSlot");
if (food3 != null)
{
Transform timeT = food3.Find("time");
Jotunn.Logger.LogInfo($"Found TrolExtraFoodSlot! time transform found: {timeT != null}");
if (timeT != null)
{
Component[] comps = timeT.GetComponents<Component>();
Jotunn.Logger.LogInfo("Components on 'time' object:");
foreach(var c in comps) {
Jotunn.Logger.LogInfo(" - " + c.GetType().FullName);
}
Text timeText = timeT.GetComponent<Text>();
Jotunn.Logger.LogInfo($"UnityEngine.UI.Text component: {timeText != null}");
if (timeText != null) Jotunn.Logger.LogInfo($"Text value: '{timeText.text}'");
var tmpComp = timeT.GetComponent("TMPro.TMP_Text");
Jotunn.Logger.LogInfo($"TMPro.TMP_Text component: {tmpComp != null}");
if (tmpComp != null) {
var prop = tmpComp.GetType().GetProperty("text");
if (prop != null) {
Jotunn.Logger.LogInfo($"TMP value: '{prop.GetValue(tmpComp, null)}'");
}
}
}
}
else
{
Jotunn.Logger.LogInfo("TrolExtraFoodSlot NOT FOUND! (Did Awake_Postfix run?)");
}
}
if (TrolFoodManager.ExtraFoods.TryGetValue(__instance, out Player.Food extraFood) && extraFood != null)
{
Jotunn.Logger.LogInfo($"ExtraFoods Dictionary:");
Jotunn.Logger.LogInfo($" Name: {extraFood.m_item?.m_shared?.m_name}");
Jotunn.Logger.LogInfo($" Time: {extraFood.m_time} / {extraFood.m_item?.m_shared?.m_foodBurnTime}");
}
Jotunn.Logger.LogInfo("=============================");
}
}
}
}

View file

@ -0,0 +1,140 @@
using System.Collections.Generic;
using UnityEngine;
namespace RacesOfValheim
{
public static class TrolFoodManager
{
// Runtime dictionary holding the 4th food slot per player
public static Dictionary<Player, Player.Food> ExtraFoods = new Dictionary<Player, Player.Food>();
public static Dictionary<Player, Player.Food> ExtraFoods5 = new Dictionary<Player, Player.Food>();
// Called when player spawns to load the 4th and 5th food from custom data
public static void LoadFood(Player player)
{
if (player == null) return;
// If they are no longer a Trol, clear it out
if (!TrolRace.IsTrol())
{
ClearFood(player);
return;
}
if (!player.m_customData.ContainsKey("TrolFood_Prefab")) return;
string prefabName = player.m_customData["TrolFood_Prefab"];
GameObject prefab = ObjectDB.instance.GetItemPrefab(prefabName);
if (prefab == null) return;
ItemDrop itemDrop = prefab.GetComponent<ItemDrop>();
if (itemDrop == null) return;
// Build food object
Player.Food food = new Player.Food();
food.m_item = itemDrop.m_itemData.Clone(); // Clone to be safe
// Try parse remaining time
if (player.m_customData.TryGetValue("TrolFood_Time", out string timeStr) && float.TryParse(timeStr, System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out float time))
{
food.m_time = time;
}
food.m_health = itemDrop.m_itemData.m_shared.m_food;
food.m_stamina = itemDrop.m_itemData.m_shared.m_foodStamina;
food.m_eitr = itemDrop.m_itemData.m_shared.m_foodEitr;
ExtraFoods[player] = food;
if (player.m_customData.ContainsKey("TrolFood5_Prefab"))
{
string prefabName5 = player.m_customData["TrolFood5_Prefab"];
GameObject prefab5 = ObjectDB.instance.GetItemPrefab(prefabName5);
if (prefab5 != null)
{
ItemDrop itemDrop5 = prefab5.GetComponent<ItemDrop>();
if (itemDrop5 != null)
{
Player.Food food5 = new Player.Food();
food5.m_item = itemDrop5.m_itemData.Clone();
if (player.m_customData.TryGetValue("TrolFood5_Time", out string timeStr5) && float.TryParse(timeStr5, System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out float time5))
{
food5.m_time = time5;
}
food5.m_health = itemDrop5.m_itemData.m_shared.m_food;
food5.m_stamina = itemDrop5.m_itemData.m_shared.m_foodStamina;
food5.m_eitr = itemDrop5.m_itemData.m_shared.m_foodEitr;
ExtraFoods5[player] = food5;
}
}
}
}
// Called to save the current runtime 4th food to custom data for persistence
public static void SaveFood(Player player)
{
if (player == null) return;
if (ExtraFoods.TryGetValue(player, out Player.Food food) && food != null && food.m_item != null)
{
player.m_customData["TrolFood_Prefab"] = food.m_item.m_dropPrefab.name;
player.m_customData["TrolFood_Time"] = food.m_time.ToString(System.Globalization.CultureInfo.InvariantCulture);
}
else
{
player.m_customData.Remove("TrolFood_Prefab");
player.m_customData.Remove("TrolFood_Time");
}
if (ExtraFoods5.TryGetValue(player, out Player.Food food5) && food5 != null && food5.m_item != null)
{
player.m_customData["TrolFood5_Prefab"] = food5.m_item.m_dropPrefab.name;
player.m_customData["TrolFood5_Time"] = food5.m_time.ToString(System.Globalization.CultureInfo.InvariantCulture);
}
else
{
player.m_customData.Remove("TrolFood5_Prefab");
player.m_customData.Remove("TrolFood5_Time");
}
}
public static void SetExtraFood(Player player, ItemDrop.ItemData item)
{
Player.Food food = new Player.Food();
food.m_item = item.Clone();
food.m_item.m_stack = 1; // Only eat 1
food.m_time = 0f;
food.m_health = item.m_shared.m_food;
food.m_stamina = item.m_shared.m_foodStamina;
food.m_eitr = item.m_shared.m_foodEitr;
ExtraFoods[player] = food;
SaveFood(player);
}
public static void SetExtraFood5(Player player, ItemDrop.ItemData item)
{
Player.Food food = new Player.Food();
food.m_item = item.Clone();
food.m_item.m_stack = 1;
food.m_time = 0f;
food.m_health = item.m_shared.m_food;
food.m_stamina = item.m_shared.m_foodStamina;
food.m_eitr = item.m_shared.m_foodEitr;
ExtraFoods5[player] = food;
SaveFood(player);
}
public static void ClearFood(Player player)
{
if (player == null) return;
ExtraFoods.Remove(player);
ExtraFoods5.Remove(player);
player.m_customData.Remove("TrolFood_Prefab");
player.m_customData.Remove("TrolFood_Time");
player.m_customData.Remove("TrolFood5_Prefab");
player.m_customData.Remove("TrolFood5_Time");
}
}
}

View file

@ -0,0 +1,255 @@
using HarmonyLib;
using UnityEngine;
using System.Collections.Generic;
namespace RacesOfValheim
{
[HarmonyPatch(typeof(Player), "OnSpawned")]
public static class Trol_PlayerOnSpawned_Patch
{
public static void Postfix(Player __instance)
{
if (__instance == Player.m_localPlayer)
{
TrolFoodManager.LoadFood(__instance);
}
}
}
[HarmonyPatch(typeof(Player), "CanConsumeItem")]
public static class Trol_PlayerCanConsumeItem_Patch
{
public static bool CanTrolEat(Player player, ItemDrop.ItemData item)
{
var foods = Traverse.Create(player).Field("m_foods").GetValue<System.Collections.Generic.List<Player.Food>>();
if (foods != null)
{
foreach (Player.Food f in foods)
{
if (f.m_item.m_shared.m_name == item.m_shared.m_name)
{
return f.CanEatAgain();
}
}
if (foods.Count < 3) return true;
}
bool state5 = BossProgressionManager.GetCurrentProgressionState() >= 6;
bool has4 = TrolFoodManager.ExtraFoods.TryGetValue(player, out Player.Food food4) && food4 != null;
bool canEat4 = has4 && food4.m_time >= (food4.m_item.m_shared.m_foodBurnTime * 0.5f);
bool has5 = TrolFoodManager.ExtraFoods5.TryGetValue(player, out Player.Food food5) && food5 != null;
bool canEat5 = has5 && food5.m_time >= (food5.m_item.m_shared.m_foodBurnTime * 0.5f);
if (has4 && food4.m_item.m_shared.m_name == item.m_shared.m_name) return canEat4;
if (state5 && has5 && food5.m_item.m_shared.m_name == item.m_shared.m_name) return canEat5;
if (!has4 || canEat4) return true;
if (state5 && (!has5 || canEat5)) return true;
return false;
}
public static bool Prefix(Player __instance, ItemDrop.ItemData item, ref bool __result)
{
if (__instance == Player.m_localPlayer && TrolRace.IsTrol())
{
if (item != null && item.m_shared != null && item.m_shared.m_itemType == ItemDrop.ItemData.ItemType.Consumable)
{
__result = CanTrolEat(__instance, item);
return false;
}
}
return true;
}
}
[HarmonyPatch(typeof(Player), "EatFood")]
public static class Trol_PlayerEatFood_Patch
{
private static bool CanEatNative(Player player, ItemDrop.ItemData item)
{
var foods = Traverse.Create(player).Field("m_foods").GetValue<List<Player.Food>>();
if (foods != null)
{
foreach (Player.Food food in foods)
{
if (food.m_item.m_shared.m_name == item.m_shared.m_name)
{
return food.CanEatAgain();
}
}
if (foods.Count < 3) return true;
}
return false;
}
public static bool Prefix(Player __instance, ItemDrop.ItemData item, ref bool __result)
{
if (__instance != Player.m_localPlayer || !TrolRace.IsTrol()) return true;
// If Valheim's native system can eat it (meaning it's either going to fill one of the first 3 slots,
// or replace an already eaten flashing food), let the native system handle it completely!
if (CanEatNative(__instance, item))
{
return true;
}
bool state5 = BossProgressionManager.GetCurrentProgressionState() >= 6;
bool has4 = TrolFoodManager.ExtraFoods.TryGetValue(__instance, out Player.Food food4) && food4 != null;
bool canEat4 = has4 && food4.m_time >= (food4.m_item.m_shared.m_foodBurnTime * 0.5f);
bool has5 = TrolFoodManager.ExtraFoods5.TryGetValue(__instance, out Player.Food food5) && food5 != null;
bool canEat5 = has5 && food5.m_time >= (food5.m_item.m_shared.m_foodBurnTime * 0.5f);
// 1. Is it already in native slots but NOT flashing? (If flashing, CanEatNative would have caught it)
var foods = Traverse.Create(__instance).Field("m_foods").GetValue<System.Collections.Generic.List<Player.Food>>();
if (foods != null)
{
foreach (Player.Food f in foods)
{
if (f.m_item.m_shared.m_name == item.m_shared.m_name)
{
__instance.Message(MessageHud.MessageType.Center, "$msg_eatanother");
__result = false;
return false;
}
}
}
// 2. Is it already in slot 4 or 5?
if (has4 && food4.m_item.m_shared.m_name == item.m_shared.m_name)
{
if (canEat4) { TrolFoodManager.SetExtraFood(__instance, item); ConsumeItemEffect(__instance, item); __result = true; return false; }
else { __instance.Message(MessageHud.MessageType.Center, "$msg_eatanother"); __result = false; return false; }
}
if (state5 && has5 && food5.m_item.m_shared.m_name == item.m_shared.m_name)
{
if (canEat5) { TrolFoodManager.SetExtraFood5(__instance, item); ConsumeItemEffect(__instance, item); __result = true; return false; }
else { __instance.Message(MessageHud.MessageType.Center, "$msg_eatanother"); __result = false; return false; }
}
// 3. Not in any slots. Try to fill an empty slot or replace a flashing one
if (!has4 || canEat4)
{
TrolFoodManager.SetExtraFood(__instance, item);
ConsumeItemEffect(__instance, item);
__result = true;
return false;
}
else if (state5 && (!has5 || canEat5))
{
TrolFoodManager.SetExtraFood5(__instance, item);
ConsumeItemEffect(__instance, item);
__result = true;
return false;
}
__instance.Message(MessageHud.MessageType.Center, "$msg_canteatanymore");
__result = false;
return false;
}
private static void ConsumeItemEffect(Player player, ItemDrop.ItemData item)
{
var consumeEffects = Traverse.Create(player).Field("m_consumeItemEffects").GetValue<EffectList>();
if (consumeEffects != null)
{
consumeEffects.Create(player.transform.position, Quaternion.identity, player.transform, 1f, -1);
}
var zanim = Traverse.Create(player).Field("m_zanim").GetValue<ZSyncAnimation>();
if (zanim != null)
{
zanim.SetTrigger("eat");
}
if (item.m_shared.m_food > 0f)
{
player.Heal(item.m_shared.m_food, true);
}
}
}
[HarmonyPatch(typeof(Player), "UpdateFood")]
public static class Trol_PlayerUpdateFood_Patch
{
public static void Prefix(Player __instance, float dt, bool forceUpdate)
{
if (__instance != Player.m_localPlayer || !TrolRace.IsTrol()) return;
UpdateExtraFood(__instance, TrolFoodManager.ExtraFoods, dt, 4);
UpdateExtraFood(__instance, TrolFoodManager.ExtraFoods5, dt, 5);
}
private static void UpdateExtraFood(Player player, Dictionary<Player, Player.Food> dict, float dt, int slot)
{
if (dict.TryGetValue(player, out Player.Food extraFood) && extraFood != null)
{
extraFood.m_time += dt;
if (extraFood.m_item != null && extraFood.m_item.m_shared != null)
{
if (extraFood.m_time >= extraFood.m_item.m_shared.m_foodBurnTime)
{
dict.Remove(player);
if (slot == 4)
{
player.m_customData.Remove("TrolFood_Prefab");
player.m_customData.Remove("TrolFood_Time");
}
else
{
player.m_customData.Remove("TrolFood5_Prefab");
player.m_customData.Remove("TrolFood5_Time");
}
}
else
{
float factor = extraFood.m_time / extraFood.m_item.m_shared.m_foodBurnTime;
extraFood.m_health = Mathf.Lerp(extraFood.m_item.m_shared.m_food, extraFood.m_item.m_shared.m_food * 0.2f, factor);
extraFood.m_stamina = Mathf.Lerp(extraFood.m_item.m_shared.m_foodStamina, extraFood.m_item.m_shared.m_foodStamina * 0.2f, factor);
extraFood.m_eitr = Mathf.Lerp(extraFood.m_item.m_shared.m_foodEitr, extraFood.m_item.m_shared.m_foodEitr * 0.2f, factor);
}
}
}
}
}
[HarmonyPatch(typeof(Player), "GetTotalFoodValue")]
public static class Trol_PlayerGetTotalFoodValue_Patch
{
public static void Postfix(Player __instance, ref float hp, ref float stamina, ref float eitr)
{
if (__instance != Player.m_localPlayer || !TrolRace.IsTrol()) return;
if (TrolFoodManager.ExtraFoods.TryGetValue(__instance, out Player.Food extraFood) && extraFood != null)
{
hp += extraFood.m_health;
stamina += extraFood.m_stamina;
eitr += extraFood.m_eitr;
}
if (BossProgressionManager.GetCurrentProgressionState() >= 6)
{
if (TrolFoodManager.ExtraFoods5.TryGetValue(__instance, out Player.Food extraFood5) && extraFood5 != null)
{
hp += extraFood5.m_health;
stamina += extraFood5.m_stamina;
eitr += extraFood5.m_eitr;
}
}
}
}
[HarmonyPatch(typeof(Player), "Message")]
public static class Trol_PlayerMessage_Patch
{
public static bool Prefix(Player __instance, MessageHud.MessageType type, string msg)
{
// We no longer block eat messages so the user knows when they are full.
return true;
}
}
}

View file

@ -0,0 +1,97 @@
using HarmonyLib;
using System.Collections.Generic;
using UnityEngine;
using Jotunn.Managers;
using BepInEx;
namespace RacesOfValheim
{
public static class TrolLogWeapon
{
public static void GrabLog(Humanoid user, TreeLog logTarget)
{
if (user == null || logTarget == null) return;
if (!TrolRace.IsTrol()) return;
if (BossProgressionManager.GetCurrentProgressionState() < 7) return;
var seman = user.GetSEMan();
if (seman == null) return;
if (!seman.HaveStatusEffect("SE_TrolTrueForm".GetStableHashCode()))
{
user.Message(MessageHud.MessageType.Center, "You must be in True Form to lift this!");
return;
}
string logName = Utils.GetPrefabName(logTarget.gameObject);
if (!logName.EndsWith("_half"))
{
logName += "_half";
}
string weaponName = "TrolWeapon_" + logName;
GameObject weaponPrefab = PrefabManager.Cache.GetPrefab<GameObject>(weaponName);
if (weaponPrefab == null)
{
weaponName = "TrolWeapon_beech_log_half"; // Fallback
weaponPrefab = PrefabManager.Cache.GetPrefab<GameObject>(weaponName);
}
if (weaponPrefab == null)
{
Jotunn.Logger.LogWarning("TrolWeapon prefab not found: " + weaponName);
return;
}
// Check if already holding a weapon
ItemDrop.ItemData rightItem = HarmonyLib.Traverse.Create(user).Field<ItemDrop.ItemData>("m_rightItem").Value;
if (rightItem != null && rightItem.m_dropPrefab != null && rightItem.m_dropPrefab.name.StartsWith("TrolWeapon_"))
{
user.Message(MessageHud.MessageType.Center, "You are already holding a log!");
return;
}
// Play pickup animation
var zanim = HarmonyLib.Traverse.Create(user).Field("m_zanim").GetValue<ZSyncAnimation>();
if (zanim != null)
{
zanim.SetTrigger("interact");
}
// Unequip current items for safety
ItemDrop.ItemData currentRight = HarmonyLib.Traverse.Create(user).Field<ItemDrop.ItemData>("m_rightItem").Value;
if (currentRight != null) user.UnequipItem(currentRight);
ItemDrop.ItemData currentLeft = HarmonyLib.Traverse.Create(user).Field<ItemDrop.ItemData>("m_leftItem").Value;
if (currentLeft != null) user.UnequipItem(currentLeft);
// Add the real weapon to inventory in a virtual slot (99, 99) to hide it
ItemDrop wepDrop = weaponPrefab.GetComponent<ItemDrop>();
ItemDrop.ItemData newItem = wepDrop.m_itemData.Clone();
newItem.m_dropPrefab = weaponPrefab;
newItem.m_gridPos = new Vector2i(99, 99);
newItem.m_durability = newItem.GetMaxDurability();
var m_inventory = HarmonyLib.Traverse.Create(user.GetInventory()).Field<List<ItemDrop.ItemData>>("m_inventory").Value;
if (m_inventory != null)
{
m_inventory.Add(newItem);
HarmonyLib.Traverse.Create(user.GetInventory()).Method("Changed").GetValue();
}
// Equip it
user.EquipItem(newItem);
// Destroy the log in the world
ZNetView nview = logTarget.GetComponent<ZNetView>();
if (nview != null && nview.IsValid())
{
nview.ClaimOwnership();
nview.Destroy();
}
else
{
UnityEngine.Object.Destroy(logTarget.gameObject);
}
}
}
}

View file

@ -0,0 +1,172 @@
using HarmonyLib;
using UnityEngine;
namespace RacesOfValheim
{
[HarmonyPatch(typeof(VisEquipment), "UpdateColors")]
public static class TrolSkinColorPatch
{
// Golden blonde hair
private static readonly Color HairColor = new Color(0.9f, 0.8f, 0.4f, 1f);
public static void Postfix(VisEquipment __instance)
{
if (!__instance.m_isPlayer) return;
Player player = __instance.GetComponent<Player>();
if (player == null) return;
// ZDO first (in-game + remote players), then m_customData fallback
// (main menu preview and first spawn frame — Player.m_localPlayer is null there)
// DO NOT check player == Player.m_localPlayer in the fallback.
string race = "Human";
ZNetView nview = player.GetComponent<ZNetView>();
if (nview != null && nview.IsValid())
race = nview.GetZDO().GetString("RacesOfValheim_Race", "Human");
else if (player.m_customData != null &&
player.m_customData.TryGetValue("Race", out string savedRace))
race = savedRace;
if (race != "Trol") return;
// Apply skin, hair, beard colors here...
if (__instance.m_bodyModel != null && __instance.m_bodyModel.material != null)
{
// Peacock blue (deep greenish-blue)
Color trolColor = new Color(0.1f, 0.6f, 0.7f, 1f);
__instance.m_bodyModel.material.SetColor("_SkinColor", trolColor);
}
// Hair
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", HairColor);
// Beard
var beardInst = Traverse.Create(__instance).Field("m_beardItemInstance").GetValue<GameObject>();
if (beardInst != null)
foreach (var r in beardInst.GetComponentsInChildren<Renderer>())
if (r.material != null) r.material.SetColor("_SkinColor", HairColor);
}
}
[HarmonyPatch(typeof(VisEquipment), "UpdateVisuals")]
public static class Trol_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");
// No Player.m_localPlayer check — works for menu preview too
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 == "Trol")
{
// Apply model changes here...
}
else
{
// Revert changes here if needed
}
}
}
[HarmonyPatch(typeof(Player), "Update")]
public static class Trol_PlayerUpdate_Patch
{
public static void Postfix(Player __instance)
{
if (__instance == null) return;
string race = "Human"; ZNetView nview = __instance.GetComponent<ZNetView>(); if (nview != null && nview.IsValid()) race = nview.GetZDO().GetString("RacesOfValheim_Race", "Human"); else if (__instance.m_customData != null && __instance.m_customData.TryGetValue("Race", out string savedRace)) race = savedRace; if (race == "Trol")
{
// Scale player visuals up by 20%
GameObject visual = Traverse.Create(__instance).Field("m_visual").GetValue<GameObject>();
// Prevent overriding scale while transforming or in True Form
bool isTrueFormActive = __instance.GetSEMan() != null && __instance.GetSEMan().HaveStatusEffect("SE_TrolTrueForm".GetStableHashCode());
bool isTransforming = (__instance == Player.m_localPlayer && TrolRace.Instance != null && TrolRace.Instance.isTransforming);
if (!isTrueFormActive && !isTransforming)
{
float targetScale = 1.2f;
int state = BossProgressionManager.GetCurrentProgressionState();
if (state >= 6) targetScale = 1.30f;
else if (state >= 4) targetScale = 1.25f;
if (visual != null && visual.transform.localScale != new Vector3(targetScale, targetScale, targetScale))
{
visual.transform.localScale = new Vector3(targetScale, targetScale, targetScale);
}
}
}
else
{
// Reset scale if not Trol
GameObject visual = Traverse.Create(__instance).Field("m_visual").GetValue<GameObject>();
int state = BossProgressionManager.GetCurrentProgressionState();
float targetScale = 1.2f;
if (state >= 6) targetScale = 1.30f;
else if (state >= 4) targetScale = 1.25f;
if (visual != null && visual.transform.localScale == new Vector3(targetScale, targetScale, targetScale))
{
visual.transform.localScale = Vector3.one;
}
}
}
}
[HarmonyPatch(typeof(Player), "GetMaxCarryWeight")]
public static class Trol_GetMaxCarryWeight_Patch
{
public static void Postfix(Player __instance, ref float __result)
{
if (__instance == null) return;
string race = "Human"; ZNetView nview = __instance.GetComponent<ZNetView>(); if (nview != null && nview.IsValid()) race = nview.GetZDO().GetString("RacesOfValheim_Race", "Human"); else if (__instance.m_customData != null && __instance.m_customData.TryGetValue("Race", out string savedRace)) race = savedRace; if (race == "Trol")
{
// Base carry weight is 300. We add 200 to make it 500.
// If they wear Megingjord, it will become 500 + 150 = 650.
__result += 200f;
int state = BossProgressionManager.GetCurrentProgressionState();
if (state >= 4)
{
__result += 50f; // After Bonemass
}
if (state >= 6)
{
__result += 50f; // After Yagluth
}
}
}
}
[HarmonyPatch(typeof(Player), "GetBodyArmor")]
public static class Trol_GetBodyArmor_Patch
{
public static void Postfix(Player __instance, ref float __result)
{
if (__instance == Player.m_localPlayer && TrolRace.IsTrol())
{
// +3 Armor per progression state (boss defeated)
int state = BossProgressionManager.GetCurrentProgressionState();
__result += 3f * state;
}
}
}
}

View file

@ -0,0 +1,392 @@
using BepInEx;
using HarmonyLib;
using UnityEngine;
using System.Collections.Generic;
using Jotunn.Managers;
using Jotunn.Entities;
namespace RacesOfValheim
{
public class TrolRace : MonoBehaviour
{
private static TrolRace _instance;
public static TrolRace Instance
{
get
{
if (_instance == null)
{
GameObject go = new GameObject("TrolRace");
_instance = go.AddComponent<TrolRace>();
DontDestroyOnLoad(go);
}
return _instance;
}
}
public static bool IsTrol()
{
if (Player.m_localPlayer == null) return false;
ZNetView nview = Player.m_localPlayer.GetComponent<ZNetView>();
if (nview != null && nview.IsValid())
return nview.GetZDO().GetString("RacesOfValheim_Race", "") == "Trol";
return Player.m_localPlayer.m_customData.TryGetValue("Race", out string r) && r == "Trol";
}
public void CreateModAssets()
{
Jotunn.Logger.LogInfo("Initializing Trol Race...");
TrolStatusEffects.RegisterStatusEffects();
// No custom projectile needed anymore
string[] logNames = new string[] {
"beech_log", "beech_log_half",
"pine_log", "pine_log_half",
"birch_log", "birch_log_half",
"oak_log", "oak_log_half",
"FirTree_log", "FirTree_log_half",
"yggdrasil_shoot_log", "yggdrasil_shoot_log_half",
"AshTree_log", "AshTree_log_half",
"DeadTree_log", "DeadTree_log_half",
"SwampTree1_log", "SwampTree1_log_half",
"SwampTree2_log", "SwampTree2_log_half"
};
foreach (string logName in logNames)
{
GameObject logPrefab = PrefabManager.Cache.GetPrefab<GameObject>(logName);
if (logPrefab != null)
{
Jotunn.Configs.ItemConfig config = new Jotunn.Configs.ItemConfig();
config.Name = "Giant's Log";
config.Description = "A massive tree log wielded as a weapon.";
CustomItem customWep = new CustomItem("TrolWeapon_" + logName, "MaceIron", config);
if (customWep != null && customWep.ItemPrefab != null)
{
Transform attach = customWep.ItemPrefab.transform.Find("attach");
if (attach != null)
{
foreach (Transform child in attach)
{
Destroy(child.gameObject);
}
GameObject newVisual = new GameObject("TrolWeaponVisual");
newVisual.transform.SetParent(attach);
newVisual.transform.localScale = new Vector3(0.4f, 0.4f, 0.4f);
// Valheim logs are aligned along Y. Rotate Y to point along Z (forward).
newVisual.transform.localRotation = Quaternion.Euler(90, 0, 0);
// Offset along the local Z axis to grab it by the end instead of the middle
newVisual.transform.localPosition = new Vector3(0, 0, 1.5f);
MeshRenderer[] renderers = logPrefab.GetComponentsInChildren<MeshRenderer>(true);
foreach (var r in renderers)
{
if (r.name.ToLower().Contains("lod")) continue;
GameObject part = new GameObject(r.gameObject.name);
part.transform.SetParent(newVisual.transform);
part.transform.localPosition = r.transform.localPosition;
part.transform.localRotation = r.transform.localRotation;
part.transform.localScale = r.transform.localScale;
var mf = part.AddComponent<MeshFilter>();
var origMf = r.GetComponent<MeshFilter>();
if (origMf != null) mf.sharedMesh = origMf.sharedMesh;
var mr = part.AddComponent<MeshRenderer>();
mr.sharedMaterials = r.sharedMaterials;
}
}
ItemDrop itemDrop = customWep.ItemPrefab.GetComponent<ItemDrop>();
itemDrop.m_itemData.m_shared.m_maxDurability = 6f;
itemDrop.m_itemData.m_shared.m_useDurability = true;
itemDrop.m_itemData.m_shared.m_useDurabilityDrain = 1f;
itemDrop.m_itemData.m_shared.m_destroyBroken = false;
itemDrop.m_itemData.m_shared.m_weight = 0f;
itemDrop.m_itemData.m_shared.m_equipDuration = 0.1f;
// It uses MaceIron base, so its skill is Clubs, which automatically gets our damage buffs!
ItemManager.Instance.AddItem(customWep);
}
}
}
}
public bool isTransforming = false;
private bool wasTrueFormActive = false;
private void Update()
{
if (!IsTrol()) return;
if (Input.GetKeyDown(KeyCode.G))
{
TryThrowRock();
}
if (Input.GetKeyDown(KeyCode.H))
{
TryTrueForm();
}
// Check log durability
ItemDrop.ItemData rightItem = HarmonyLib.Traverse.Create(Player.m_localPlayer).Field<ItemDrop.ItemData>("m_rightItem").Value;
if (rightItem != null && rightItem.m_dropPrefab != null && rightItem.m_dropPrefab.name.StartsWith("TrolWeapon_"))
{
if (rightItem.m_durability <= 0f)
{
string logName = rightItem.m_dropPrefab.name.Substring("TrolWeapon_".Length);
GameObject logPrefab = PrefabManager.Cache.GetPrefab<GameObject>(logName);
if (logPrefab != null)
{
DropOnDestroyed dod = logPrefab.GetComponent<DropOnDestroyed>();
if (dod != null && dod.m_dropWhenDestroyed != null)
{
var drops = dod.m_dropWhenDestroyed.GetDropList();
foreach (var drop in drops)
{
Vector3 offset = UnityEngine.Random.insideUnitSphere * 0.5f;
offset.y = 0.5f;
UnityEngine.Object.Instantiate(drop, Player.m_localPlayer.transform.position + offset, Quaternion.identity);
}
}
}
// Message removed
Player.m_localPlayer.UnequipItem(rightItem);
Player.m_localPlayer.GetInventory().RemoveItem(rightItem);
}
}
// Auto-revert True Form check
bool isTrueFormActive = Player.m_localPlayer.GetSEMan().HaveStatusEffect("SE_TrolTrueForm".GetStableHashCode());
if (wasTrueFormActive && !isTrueFormActive && !isTransforming)
{
StartCoroutine(RevertTrueFormRoutine());
}
wasTrueFormActive = isTrueFormActive;
}
private void TryTrueForm()
{
if (BossProgressionManager.GetCurrentProgressionState() < 5) return; // Requires Moder
if (Player.m_localPlayer.GetSEMan().HaveStatusEffect("SE_TrolTrueForm".GetStableHashCode()))
{
if (BossProgressionManager.GetCurrentProgressionState() >= 7)
{
GameObject hoverObj = Player.m_localPlayer.GetHoverObject();
if (hoverObj != null)
{
TreeLog log = hoverObj.GetComponentInParent<TreeLog>();
if (log != null)
{
TrolLogWeapon.GrabLog(Player.m_localPlayer, log);
}
}
}
return;
}
var cdSE = Player.m_localPlayer.GetSEMan().GetStatusEffect("SE_TrolTrueFormCooldown".GetStableHashCode());
if (cdSE != null)
{
float m_time = HarmonyLib.Traverse.Create(cdSE).Field<float>("m_time").Value;
int remaining = (int)(cdSE.m_ttl - m_time);
return;
}
if (!isTransforming)
{
StartCoroutine(TransformToTrueFormRoutine());
}
}
private System.Collections.IEnumerator TransformToTrueFormRoutine()
{
isTransforming = true;
Player.m_localPlayer.GetSEMan().AddStatusEffect("SE_TrolTrueForm".GetStableHashCode(), true);
Player.m_localPlayer.GetSEMan().RemoveStatusEffect("SE_TrolThrowRockCooldown".GetStableHashCode(), true);
float duration = 1.5f;
float elapsed = 0f;
GameObject visual = HarmonyLib.Traverse.Create(Player.m_localPlayer).Field("m_visual").GetValue<GameObject>();
if (visual != null)
{
Vector3 startScale = visual.transform.localScale;
float trueFormScale = BossProgressionManager.GetCurrentProgressionState() >= 7 ? 2.5f : 2.0f;
Vector3 targetScale = new Vector3(trueFormScale, trueFormScale, trueFormScale);
while (elapsed < duration)
{
visual.transform.localScale = Vector3.Lerp(startScale, targetScale, elapsed / duration);
elapsed += Time.deltaTime;
yield return null;
}
visual.transform.localScale = targetScale;
}
isTransforming = false;
}
private System.Collections.IEnumerator RevertTrueFormRoutine()
{
isTransforming = true;
float duration = 1.5f;
float elapsed = 0f;
GameObject visual = HarmonyLib.Traverse.Create(Player.m_localPlayer).Field("m_visual").GetValue<GameObject>();
if (visual != null)
{
Vector3 startScale = visual.transform.localScale;
float normalScale = 1.2f;
int state = BossProgressionManager.GetCurrentProgressionState();
if (state >= 6) normalScale = 1.30f;
else if (state >= 4) normalScale = 1.25f;
Vector3 targetScale = new Vector3(normalScale, normalScale, normalScale);
while (elapsed < duration)
{
visual.transform.localScale = Vector3.Lerp(startScale, targetScale, elapsed / duration);
elapsed += Time.deltaTime;
yield return null;
}
visual.transform.localScale = targetScale;
}
Player.m_localPlayer.GetSEMan().AddStatusEffect("SE_TrolTrueFormCooldown".GetStableHashCode(), true);
isTransforming = false;
}
private void TryThrowRock()
{
if (BossProgressionManager.GetCurrentProgressionState() < 3) return; // Requires The Elder
var cdSE = Player.m_localPlayer.GetSEMan().GetStatusEffect("SE_TrolThrowRockCooldown".GetStableHashCode());
if (cdSE != null)
{
return;
}
StartCoroutine(ThrowRockRoutine());
}
private System.Collections.IEnumerator ThrowRockRoutine()
{
bool isTrueForm = Player.m_localPlayer.GetSEMan().HaveStatusEffect("SE_TrolTrueForm".GetStableHashCode());
float throwRockCooldown = isTrueForm ? 15f : 60f;
var addedSE = Player.m_localPlayer.GetSEMan().AddStatusEffect("SE_TrolThrowRockCooldown".GetStableHashCode(), true);
if (addedSE != null)
{
addedSE.m_ttl = throwRockCooldown;
}
var zanim = HarmonyLib.Traverse.Create(Player.m_localPlayer).Field("m_zanim").GetValue<ZSyncAnimation>();
if (zanim != null)
{
zanim.SetTrigger("throw_bomb");
}
string logName = "";
ItemDrop.ItemData rightItem = HarmonyLib.Traverse.Create(Player.m_localPlayer).Field<ItemDrop.ItemData>("m_rightItem").Value;
bool isHoldingLog = rightItem != null && rightItem.m_dropPrefab != null && rightItem.m_dropPrefab.name.StartsWith("TrolWeapon_");
if (isHoldingLog)
{
logName = rightItem.m_dropPrefab.name.Substring("TrolWeapon_".Length);
// Remove the weapon from inventory
Player.m_localPlayer.UnequipItem(rightItem);
Player.m_localPlayer.GetInventory().RemoveItem(rightItem);
}
// Wait a moment for the animation to reach the throw point
yield return new WaitForSeconds(0.4f);
Vector3 spawnPos = Player.m_localPlayer.GetEyePoint() + Player.m_localPlayer.GetLookDir() * 1.5f;
if (isHoldingLog && !string.IsNullOrEmpty(logName))
{
// Spawn original log asset further away so it doesn't instantly collide with the player
Vector3 logSpawnPos = Player.m_localPlayer.GetEyePoint() + Player.m_localPlayer.GetLookDir() * 3.5f;
GameObject originalLogPrefab = ZNetScene.instance.GetPrefab(logName);
if (originalLogPrefab != null)
{
GameObject logInstance = UnityEngine.Object.Instantiate(originalLogPrefab, logSpawnPos, Quaternion.LookRotation(Player.m_localPlayer.GetLookDir()));
Rigidbody rb = logInstance.GetComponent<Rigidbody>();
if (rb == null) rb = logInstance.GetComponentInChildren<Rigidbody>();
if (rb != null)
{
// 3x speed to compensate for log weight/drag
rb.velocity = Player.m_localPlayer.GetLookDir() * 60f;
// Add some slight rotation tumbling
rb.angularVelocity = new Vector3(10f, 5f, 0f);
}
logInstance.AddComponent<LogImpactBreaker>();
}
}
else
{
// Default rock throw
GameObject projPrefab = ZNetScene.instance.GetPrefab("troll_throw_projectile");
if (projPrefab != null)
{
GameObject projInstance = UnityEngine.Object.Instantiate(projPrefab, spawnPos, Quaternion.LookRotation(Player.m_localPlayer.GetLookDir()));
Projectile proj = projInstance.GetComponent<Projectile>();
if (proj != null)
{
HitData hitData = new HitData();
hitData.m_damage.m_blunt = 25f; // Base troll rock
if (BossProgressionManager.GetCurrentProgressionState() >= 4)
{
hitData.m_damage.m_blunt += 10f; // Bonemass bonus
}
if (BossProgressionManager.GetCurrentProgressionState() >= 6)
{
hitData.m_damage.m_blunt += 5f; // Yagluth bonus
}
if (isTrueForm)
{
hitData.m_damage.m_blunt += 40f; // True Form bonus
}
hitData.SetAttacker(Player.m_localPlayer);
proj.Setup(Player.m_localPlayer, Player.m_localPlayer.GetLookDir() * 20f, -1f, hitData, null, null);
}
}
}
}
}
public class LogImpactBreaker : MonoBehaviour
{
private bool broken = false;
private float armTime;
private void Awake()
{
armTime = Time.time + 0.2f;
}
private void OnCollisionEnter(Collision collision)
{
if (broken || Time.time < armTime) return;
broken = true;
Destructible destructible = GetComponent<Destructible>();
if (destructible != null)
{
HitData hitData = new HitData();
hitData.m_damage.m_chop = 9999f;
hitData.m_point = collision.contacts.Length > 0 ? collision.contacts[0].point : transform.position;
destructible.Damage(hitData);
}
}
}
}

View file

@ -0,0 +1,20 @@
using HarmonyLib;
namespace RacesOfValheim
{
[HarmonyPatch(typeof(SEMan), "ModifyHealthRegen")]
public static class Trol_SEMan_ModifyHealthRegen_Patch
{
public static void Postfix(SEMan __instance, ref float regenMultiplier)
{
if (__instance == Player.m_localPlayer?.GetSEMan() && TrolRace.IsTrol())
{
// After The Elder (Progression State >= 2)
if (BossProgressionManager.GetCurrentProgressionState() >= 3)
{
regenMultiplier *= 1.10f; // +10% passive health regeneration
}
}
}
}
}

View file

@ -0,0 +1,32 @@
using HarmonyLib;
namespace RacesOfValheim
{
[HarmonyPatch(typeof(Skills), "RaiseSkill")]
public static class Trol_Skills_RaiseSkill_Patch
{
public static void Prefix(Skills __instance, Skills.SkillType skillType, ref float factor)
{
Player player = HarmonyLib.Traverse.Create(__instance).Field("m_player").GetValue<Player>();
if (player != null && player == Player.m_localPlayer && TrolRace.IsTrol())
{
// After Eikthyr (Progression State >= 1)
if (BossProgressionManager.GetCurrentProgressionState() >= 2)
{
bool isTrolSkill = (
skillType == Skills.SkillType.Clubs ||
skillType == Skills.SkillType.Unarmed ||
skillType == Skills.SkillType.Axes ||
skillType == Skills.SkillType.Pickaxes ||
skillType == Skills.SkillType.WoodCutting
);
if (isTrolSkill)
{
factor *= 2f;
}
}
}
}
}
}

View file

@ -0,0 +1,91 @@
using Jotunn.Managers;
using Jotunn.Entities;
using UnityEngine;
namespace RacesOfValheim
{
public class SE_TrolThrowRockCooldown : SE_Stats
{
public override void Setup(Character character)
{
base.Setup(character);
name = "SE_TrolThrowRockCooldown";
m_name = "Throw Rock Cooldown";
m_tooltip = "You must wait before throwing another rock.";
m_ttl = 60f; // 1 minute cooldown
// Try to find a rock-like icon, e.g. Stone
GameObject itemPrefab = PrefabManager.Cache.GetPrefab<GameObject>("Stone");
if (itemPrefab != null)
{
ItemDrop drop = itemPrefab.GetComponent<ItemDrop>();
if (drop != null && drop.m_itemData.m_shared.m_icons.Length > 0)
{
m_icon = drop.m_itemData.m_shared.m_icons[0];
}
}
}
}
public class SE_TrolTrueForm : SE_Stats
{
public override void Setup(Character character)
{
base.Setup(character);
name = "SE_TrolTrueForm";
m_name = "True Form";
m_tooltip = "You have unleashed your inner troll!";
m_ttl = 60f; // 1 minute duration
GameObject itemPrefab = PrefabManager.Cache.GetPrefab<GameObject>("Stone");
if (itemPrefab != null)
{
ItemDrop drop = itemPrefab.GetComponent<ItemDrop>();
if (drop != null && drop.m_itemData.m_shared.m_icons.Length > 0)
{
m_icon = drop.m_itemData.m_shared.m_icons[0];
}
}
}
}
public class SE_TrolTrueFormCooldown : SE_Stats
{
public override void Setup(Character character)
{
base.Setup(character);
name = "SE_TrolTrueFormCooldown";
m_name = "True Form Cooldown";
m_tooltip = "You are exhausted from your True Form.";
m_ttl = 600f; // 10 minutes cooldown
GameObject itemPrefab = PrefabManager.Cache.GetPrefab<GameObject>("Stone");
if (itemPrefab != null)
{
ItemDrop drop = itemPrefab.GetComponent<ItemDrop>();
if (drop != null && drop.m_itemData.m_shared.m_icons.Length > 0)
{
m_icon = drop.m_itemData.m_shared.m_icons[0];
}
}
}
}
public static class TrolStatusEffects
{
public static void RegisterStatusEffects()
{
var cdSE = ScriptableObject.CreateInstance<SE_TrolThrowRockCooldown>();
cdSE.name = "SE_TrolThrowRockCooldown";
ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(cdSE, fixReference: false));
var tfSE = ScriptableObject.CreateInstance<SE_TrolTrueForm>();
tfSE.name = "SE_TrolTrueForm";
ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(tfSE, fixReference: false));
var tfCdSE = ScriptableObject.CreateInstance<SE_TrolTrueFormCooldown>();
tfCdSE.name = "SE_TrolTrueFormCooldown";
ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(tfCdSE, fixReference: false));
}
}
}

View file

@ -0,0 +1,341 @@
using HarmonyLib;
using UnityEngine;
using System.Collections.Generic;
namespace RacesOfValheim
{
[HarmonyPatch(typeof(Player), "Awake")]
public static class Player_Awake_VisualSync_Patch
{
public static void Postfix(Player __instance)
{
if (__instance.gameObject.GetComponent<RacesVisualController>() == null)
{
__instance.gameObject.AddComponent<RacesVisualController>();
}
}
}
[HarmonyPatch(typeof(Player), "OnSpawned")]
public static class Player_OnSpawned_Sync_Patch
{
public static void Postfix(Player __instance)
{
ZNetView nview = __instance.GetComponent<ZNetView>();
if (__instance == Player.m_localPlayer && nview != null && nview.IsValid())
{
if (__instance.m_customData.TryGetValue("Race", out string race))
{
nview.GetZDO().Set("RacesOfValheim_Race", race);
}
}
}
}
public class RacesVisualController : MonoBehaviour
{
private Player m_player;
private string m_lastFenrirForm = "";
private string m_lastSkadiForm = "";
private GameObject m_currentFormInstance = null;
private GameObject m_fireAuraVFX = null;
private void Awake()
{
m_player = GetComponent<Player>();
}
private void Update()
{
if (m_player == null) return;
ZNetView nview = m_player.GetComponent<ZNetView>();
if (nview == null || !nview.IsValid()) return;
if (m_player == Player.m_localPlayer) return; // Local player handles their own visuals in Race scripts
if (m_player.IsDead())
{
RevertAllVisuals();
return;
}
string race = nview.GetZDO().GetString("RacesOfValheim_Race", "Human");
if (race == "Skeleton")
{
UpdateSkeletonVisuals();
}
else if (race == "Fenrir")
{
UpdateFenrirVisuals();
}
else if (race == "Skadi")
{
UpdateSkadiVisuals();
}
else if (race == "Aswid")
{
UpdateAswidVisuals();
}
else
{
RevertAllVisuals();
}
}
private void UpdateAswidVisuals()
{
// Empty for now, relying on VisEquipment patch
}
private void UpdateSkeletonVisuals()
{
ZNetView nview = m_player.GetComponent<ZNetView>();
int state = nview.GetZDO().GetInt("RacesOfValheim_SkeletonState", 0);
var rules = SkeletonProgression.GetRules(state);
// Hide hair and beard
VisEquipment vis = m_player.GetComponent<VisEquipment>();
if (vis != null)
{
vis.SetHairItem("");
vis.SetBeardItem("");
// Hide Helmet
var helmetObj = HarmonyLib.Traverse.Create(vis).Field<GameObject>("m_helmetItemInstance").Value;
if (helmetObj != null && helmetObj.transform.localScale != Vector3.zero)
{
helmetObj.transform.localScale = Vector3.zero;
}
// Scale Body Armor
string[] armorFields = { "m_chestItemInstances", "m_legItemInstances", "m_shoulderItemInstances" };
foreach (string field in armorFields)
{
var armorList = HarmonyLib.Traverse.Create(vis).Field<List<GameObject>>(field).Value;
if (armorList != null)
{
foreach (GameObject armor in armorList)
{
if (armor != null && Mathf.Abs(armor.transform.localScale.x - 1.05f) > 0.01f)
{
armor.transform.localScale = new Vector3(1.05f, 1.05f, 1.05f);
}
}
}
}
// Hide Jaw for Charred Twitcher
if (vis.m_bodyModel != null && vis.m_bodyModel.bones != null)
{
foreach (Transform bone in vis.m_bodyModel.bones)
{
if (bone != null && bone.name.ToLower().Contains("jaw"))
{
if (state >= 8)
{
if (bone.localScale != Vector3.zero) bone.localScale = Vector3.zero;
}
else
{
if (bone.localScale == Vector3.zero) bone.localScale = Vector3.one;
}
break;
}
}
}
}
// Apply Scale
Vector3 targetScale = rules.ScaleMultiplier;
if (m_player.transform.localScale != targetScale)
{
m_player.transform.localScale = targetScale;
}
// Fire Aura VFX
EnsureFireAuraVFX(rules.FireAura);
}
private void UpdateFenrirVisuals()
{
ZNetView nview = m_player.GetComponent<ZNetView>();
string currentForm = nview.GetZDO().GetString("RacesOfValheim_FenrirForm", "");
if (currentForm != m_lastFenrirForm)
{
// Form changed
if (m_currentFormInstance != null) Destroy(m_currentFormInstance);
Transform playerVisual = m_player.transform.Find("Visual");
if (playerVisual != null)
{
if (string.IsNullOrEmpty(currentForm))
{
playerVisual.localScale = Vector3.one;
}
else
{
playerVisual.localScale = Vector3.one * 0.001f;
GameObject prefab = Jotunn.Managers.PrefabManager.Cache.GetPrefab<GameObject>(currentForm);
if (prefab != null)
{
Transform visual = prefab.transform.Find("Visual");
if (visual != null)
{
m_currentFormInstance = Instantiate(visual.gameObject, m_player.transform);
m_currentFormInstance.transform.localPosition = Vector3.zero;
m_currentFormInstance.transform.localRotation = Quaternion.identity;
Component animEvent = m_currentFormInstance.GetComponent("AnimEvent");
if (animEvent != null) Destroy(animEvent);
// Clean up colliders on remote visuals
foreach (var col in m_currentFormInstance.GetComponentsInChildren<Collider>())
{
Destroy(col);
}
}
}
}
}
m_lastFenrirForm = currentForm;
}
}
private void UpdateSkadiVisuals()
{
ZNetView nview = m_player.GetComponent<ZNetView>();
string currentForm = nview.GetZDO().GetString("RacesOfValheim_SkadiForm", "");
if (currentForm != m_lastSkadiForm)
{
// Form changed
if (m_currentFormInstance != null) Destroy(m_currentFormInstance);
Transform playerVisual = m_player.transform.Find("Visual");
if (playerVisual != null)
{
if (string.IsNullOrEmpty(currentForm))
{
playerVisual.localScale = Vector3.one;
}
else
{
playerVisual.localScale = Vector3.one * 0.001f;
GameObject prefab = Jotunn.Managers.PrefabManager.Cache.GetPrefab<GameObject>(currentForm);
if (prefab != null)
{
Transform visual = prefab.transform.Find("Visual");
if (visual != null)
{
m_currentFormInstance = Instantiate(visual.gameObject, m_player.transform);
m_currentFormInstance.transform.localPosition = Vector3.zero;
m_currentFormInstance.transform.localRotation = Quaternion.identity;
Component animEvent = m_currentFormInstance.GetComponent("AnimEvent");
if (animEvent != null) Destroy(animEvent);
foreach (var col in m_currentFormInstance.GetComponentsInChildren<Collider>())
{
Destroy(col);
}
}
}
}
}
m_lastSkadiForm = currentForm;
}
}
private void RevertAllVisuals()
{
if (m_player.transform.localScale != Vector3.one) m_player.transform.localScale = Vector3.one;
Transform playerVisual = m_player.transform.Find("Visual");
if (playerVisual != null && playerVisual.localScale != Vector3.one)
{
playerVisual.localScale = Vector3.one;
}
if (m_currentFormInstance != null) Destroy(m_currentFormInstance);
EnsureFireAuraVFX(false);
Animator anim = m_player.GetComponentInChildren<Animator>();
if (anim != null)
{
Transform headBone = anim.GetBoneTransform(HumanBodyBones.Head);
if (headBone != null)
{
Transform eyes = headBone.Find("AswidEyes");
if (eyes != null) Destroy(eyes.gameObject);
}
}
m_lastFenrirForm = "";
m_lastSkadiForm = "";
}
private void EnsureFireAuraVFX(bool enable)
{
if (enable)
{
if (m_fireAuraVFX == null)
{
GameObject sourceVFX = Jotunn.Managers.PrefabManager.Cache.GetPrefab<GameObject>("vfx_smoke") ??
Jotunn.Managers.PrefabManager.Cache.GetPrefab<GameObject>("vfx_surtling_death");
m_fireAuraVFX = new GameObject("SkeletonFireAuraVFX");
m_fireAuraVFX.transform.SetParent(m_player.transform, false);
m_fireAuraVFX.transform.localPosition = new Vector3(0, 1f, 0);
if (sourceVFX != null)
{
ParticleSystem[] pss = sourceVFX.GetComponentsInChildren<ParticleSystem>();
if (pss.Length > 0)
{
ParticleSystem ps = m_fireAuraVFX.AddComponent<ParticleSystem>();
var main = ps.main;
main.loop = true;
main.duration = 1f;
main.startLifetime = 1.5f;
main.startSize = new ParticleSystem.MinMaxCurve(1.5f, 3f);
main.startSpeed = 0f;
main.simulationSpace = ParticleSystemSimulationSpace.World;
var renderer = m_fireAuraVFX.GetComponent<ParticleSystemRenderer>();
renderer.material = pss[0].GetComponent<ParticleSystemRenderer>().material;
var shape = ps.shape;
shape.shapeType = ParticleSystemShapeType.Sphere;
shape.radius = 4.5f;
var emission = ps.emission;
emission.rateOverTime = 40f;
var colorOverLifetime = ps.colorOverLifetime;
colorOverLifetime.enabled = true;
Gradient grad = new Gradient();
grad.SetKeys(
new GradientColorKey[] {
new GradientColorKey(new Color(1f, 0.8f, 0.2f), 0.0f),
new GradientColorKey(new Color(1f, 0.3f, 0.0f), 0.5f),
new GradientColorKey(new Color(0.2f, 0.0f, 0.0f), 1.0f)
},
new GradientAlphaKey[] {
new GradientAlphaKey(0.0f, 0.0f),
new GradientAlphaKey(0.6f, 0.2f),
new GradientAlphaKey(0.6f, 0.8f),
new GradientAlphaKey(0.0f, 1.0f)
}
);
colorOverLifetime.color = grad;
}
}
}
if (!m_fireAuraVFX.activeSelf) m_fireAuraVFX.SetActive(true);
}
else
{
if (m_fireAuraVFX != null && m_fireAuraVFX.activeSelf) m_fireAuraVFX.SetActive(false);
}
}
}
}

5
JotunnModStub/app.config Normal file
View file

@ -0,0 +1,5 @@
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<runtime>
</runtime>
</configuration>

View file

@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="JotunnLib" version="2.26.1" targetFramework="net48" />
</packages>