RacesOfValheim/JotunnModStub/Skeleton/SkeletonRace.cs
kanym 59c250b4f8 fix(skeleton): reattach the mandible, light the skull for real, and grow at Fader
The jaw hung off the side of the skull because a creature rig carries bones a
human rig has no answer for. Unmatched bones fell back to bones[0] - the root -
so the mandible was skinned to the hips and followed them. The remap now walks
the creature'''s own hierarchy upward until something matches, which lands a jaw on
the head. It no longer opens, which no player will notice, and it is attached,
which every player did. Teeth and any other facial part the model carries are
fixed by the same walk.

The head flame never appeared. It was built by hand out of the smoke material
with a hand-rolled fire gradient, which at best would have read as a wisp rather
than a burning skull, and at worst never resolved a source at all and returned in
silence. It now clones real fire particles off a vanilla prefab - the torch
first, ground torches and the fire pit behind it - and says in the log which one
it took, or warns if none of them resolved. The torch light comes with it, at
half range and reduced intensity, since a light tuned to fill a corridor from
waist height blows out a face at point-blank range.

Fader now stands 15% taller. That scale goes on the player root, which is how
this race has always sized itself, so the collider, the camera pivot and every
equipment attachment scale with the mesh rather than leaving the model to drift
away from them.
2026-08-05 17:30:15 +02:00

600 lines
26 KiB
C#

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 static readonly int StatsEffectHash = "SE_SkeletonStats".GetStableHashCode();
private float lastAuraTime = 0f;
private GameObject fireAuraVFX = null;
// Flames on the skull. Purely cosmetic, and deliberately not parented to the head bone:
// the player rig is authored at roughly 100x, which would blow the particle sizes up with
// it. Kept under the player and moved onto the bone each frame instead.
private GameObject headFlameVFX = null;
private Transform headFlameBone = null;
// Above the head bone's own origin, which sits at the base of the skull.
private const float HeadFlameHeight = 0.18f;
// Torch flames are authored for a fist-sized fire on a stick. This is the two knobs to
// turn if the skull ends up wearing a bonfire or a birthday candle.
private const float HeadFlameScale = 1.8f;
// Fire sources in preference order. The torch is an item every world has; the ground
// torch and the fire pit are the building pieces to fall back on.
private static readonly string[] FlameSourcePrefabs =
{
"Torch", "piece_groundtorch_wood", "piece_groundtorch", "fire_pit"
};
private static GameObject cachedFlameSource;
private static bool flameSourceResolved;
/// <summary>
/// Finds a vanilla prefab that carries real fire particles. Resolved once per session,
/// failure included, so a miss cannot turn into a per-frame log.
/// </summary>
private static GameObject ResolveFlameSource()
{
if (flameSourceResolved) return cachedFlameSource;
flameSourceResolved = true;
foreach (string name in FlameSourcePrefabs)
{
GameObject prefab = PrefabManager.Cache.GetPrefab<GameObject>(name);
if (prefab == null) continue;
if (prefab.GetComponentsInChildren<ParticleSystem>(true).Length == 0) continue;
Jotunn.Logger.LogInfo($"[Skeleton] Head flame source resolved to '{name}'.");
cachedFlameSource = prefab;
return cachedFlameSource;
}
Jotunn.Logger.LogWarning(
"[Skeleton] No fire prefab resolved (" + string.Join(", ", FlameSourcePrefabs) +
"); the skull stays unlit.");
return 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("");
}
}
}
// Undead Fortitude carries every one of the race's damage modifiers - the pierce and
// slash resistance, the weakness to blunt, and the poison immunity. It was applied in
// exactly one place: the moment the player clicked "Skeleton" in the race menu. Status
// effects are not saved with a character and do not survive death, so from the next
// respawn or the next login onward a Skeleton had none of them, which is why poison
// still landed at tiers that grant immunity. Put it back whenever it is missing.
if (!Player.m_localPlayer.GetSEMan().HaveStatusEffect(StatsEffectHash))
{
Player.m_localPlayer.GetSEMan().AddStatusEffect(StatsEffectHash, true);
}
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. The multiplier itself now lives on the status effect,
// which sets it on the live instance - writing it here only ever reached the template
// SEMan clones from, so it changed nothing for the player. What stays here is the tick
// rate, which is the player's own field.
if (rules.EnhancedRegen)
{
// 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);
}
// Flames on the skull, worn with the fire-tier model and nothing else.
EnsureHeadFlameVFX(rules.ModelPrefab == SkeletonProgression.FireModel);
if (rules.FireAura)
{
EnsureFireAuraVFX(true);
if (Time.time - lastAuraTime >= 1f)
{
ApplyFireAura();
lastAuraTime = Time.time;
}
}
else
{
EnsureFireAuraVFX(false);
}
}
/// <summary>
/// Flames burning on the skull. Cosmetic only - it deals nothing and blocks nothing.
///
/// Built from the same particle source as the fire aura, small and tight rather than a
/// cloud, and left in world simulation space so the flames trail behind a running player
/// instead of riding rigidly on the bone. The object is parented to the player and moved
/// onto the head each frame rather than being parented to the head bone itself: the
/// player's rig is authored at roughly 100x, and a particle system inheriting that scale
/// would put a bonfire where a candle belongs.
/// </summary>
private void EnsureHeadFlameVFX(bool enable)
{
if (!enable)
{
if (headFlameVFX != null && headFlameVFX.activeSelf) headFlameVFX.SetActive(false);
return;
}
if (Player.m_localPlayer == null) return;
if (headFlameVFX == null)
{
Animator anim = Player.m_localPlayer.GetComponentInChildren<Animator>();
headFlameBone = anim != null ? anim.GetBoneTransform(HumanBodyBones.Head) : null;
if (headFlameBone == null) return; // rig not up yet; try again next frame
GameObject source = ResolveFlameSource();
if (source == null) return; // already logged once by the resolver
headFlameVFX = new GameObject("SkeletonHeadFlameVFX");
headFlameVFX.transform.SetParent(Player.m_localPlayer.transform, false);
headFlameVFX.transform.localScale = Vector3.one * HeadFlameScale;
// Real fire is cloned rather than built by hand. The first attempt at this made a
// particle system from scratch on the smoke material, and a hand-rolled gradient
// over a smoke sprite reads as a wisp, not a burning skull.
foreach (ParticleSystem ps in source.GetComponentsInChildren<ParticleSystem>(true))
{
GameObject copy = Instantiate(ps.gameObject, headFlameVFX.transform);
copy.name = ps.gameObject.name;
copy.transform.localPosition = Vector3.zero;
copy.transform.localRotation = Quaternion.identity;
copy.SetActive(true);
// So the holder's scale actually enlarges the fire rather than just spreading
// out where the particles spawn.
ParticleSystem.MainModule main = copy.GetComponent<ParticleSystem>().main;
main.scalingMode = ParticleSystemScalingMode.Hierarchy;
}
// A torch's own light is tuned to light a corridor from waist height; on a head it
// blows out the whole face. Keep the glow, lose the floodlight.
foreach (Light light in headFlameVFX.GetComponentsInChildren<Light>(true))
{
light.range *= 0.5f;
light.intensity *= 0.6f;
}
// Anything that made the source a torch rather than a fire.
foreach (MonoBehaviour comp in headFlameVFX.GetComponentsInChildren<MonoBehaviour>(true))
{
Destroy(comp);
}
foreach (Collider col in headFlameVFX.GetComponentsInChildren<Collider>(true))
{
Destroy(col);
}
}
if (!headFlameVFX.activeSelf) headFlameVFX.SetActive(true);
// Follows the skull without inheriting its scale.
if (headFlameBone != null)
{
headFlameVFX.transform.position = headFlameBone.position + Vector3.up * HeadFlameHeight;
}
}
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++;
}
}
}
}
}