RacesOfValheim/JotunnModStub/Skeleton/SkeletonPatches.cs
2026-10-07 17:31:29 +02:00

867 lines
44 KiB
C#

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;
// Model names already reported as missing. The body swap runs from a visual refresh, so
// without this a mistyped prefab id would log every time equipment changes.
private static readonly System.Collections.Generic.HashSet<string> warnedMissingModels =
new System.Collections.Generic.HashSet<string>();
// Model parts whose bone mapping has already been reported this session.
private static readonly System.Collections.Generic.HashSet<string> loggedBoneMaps =
new System.Collections.Generic.HashSet<string>();
private static void WarnMissingModelOnce(string prefabName)
{
if (!warnedMissingModels.Add(prefabName)) return;
Jotunn.Logger.LogWarning(
$"[Skeleton] Body model prefab '{prefabName}' not found - the race has no mesh at this tier. " +
"Check the id in SkeletonProgression.");
}
/// <summary>
/// Makes the Skeleton's max health exactly what its progression promises.
///
/// A Skeleton cannot eat, so SkeletonRace fakes three permanent foods whose values are
/// scaled to add up to the tier's bonus. That is a good way to keep food-based health
/// regeneration working - Valheim regenerates from the food list, so a Skeleton with no
/// food would never heal - but a bad way to land an exact number: the value the game reads
/// is Food.m_health, which UpdateFood recomputes every second as
/// Pow(remaining/burnTime, 0.3) * m_food, and anything that leaves those three foods
/// partly burnt, partly rebuilt or one short quietly costs health. A Bonemass-tier
/// Skeleton reported 95 max health where the table promises 25 + 140.
///
/// So the foods stay, for regeneration, and the total they feed into is overwritten here.
/// GetTotalFoodValue has exactly one caller, Player.UpdateFood, which passes the result
/// straight to SetMaxHealth - so this is the single point where the number is decided, and
/// it now comes from the progression table rather than from three scaled sausages.
/// </summary>
[HarmonyPatch(typeof(Player), "GetTotalFoodValue")]
public static class Player_GetTotalFoodValue_SkeletonHealth_Patch
{
public static void Postfix(Player __instance, ref float hp)
{
if (__instance != Player.m_localPlayer || !SkeletonRace.IsSkeleton()) return;
int state = BossProgressionManager.GetCurrentProgressionState();
hp = __instance.m_baseHP + SkeletonProgression.GetMaxHealthBonus(state);
}
}
[HarmonyPatch(typeof(Player), "UseStamina")]
public static class Player_UseStamina_Patch
{
public static bool Prefix(Player __instance)
{
if ((SkeletonRace.IsSkeleton() || AswidRace.IsAswid() || DraughRace.IsDraugh()) && __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, ModText.Get("rov_msg_skeleton_skeletons_do_not_need_eat"));
__result = false;
return false;
}
// Blood Essence is the one real food an Aswid can still chew, so it has to
// survive this blanket refusal - everything else mortal still bounces.
else if (AswidRace.IsAswid() && !AswidRace.BypassAswidFoodCheck && !AswidBloodRefinery.IsAswidMeal(item) && 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, ModText.Get("rov_msg_skeleton_mortal_food_disgusts"));
__result = false;
return false;
}
}
return true;
}
}
[HarmonyPatch(typeof(MessageHud), "ShowMessage")]
public static class MessageHud_ShowMessage_Patch
{
private static System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<float>> messageTimestamps = new System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<float>>();
private static System.Collections.Generic.Dictionary<string, float> messageBans = new System.Collections.Generic.Dictionary<string, float>();
public static bool Prefix(MessageHud __instance, MessageHud.MessageType type, string text)
{
if (Player.m_localPlayer != null && SkeletonRace.IsSkeleton())
{
if (string.IsNullOrEmpty(text)) return true;
// Exception for resting messages to never be filtered
string lowerText = text.ToLower();
if (text == "$se_resting_name" || text == "$se_resting" || lowerText.Contains("resting") || lowerText.Contains("riposo"))
{
return true;
}
float currentTime = Time.time;
// Check if message is currently banned (4 hours = 14400 seconds)
if (messageBans.TryGetValue(text, out float banTime))
{
if (currentTime - banTime < 14400f)
{
return false; // Still banned
}
else
{
messageBans.Remove(text); // Ban expired
if (messageTimestamps.ContainsKey(text))
{
messageTimestamps[text].Clear(); // Reset spam count
}
}
}
if (!messageTimestamps.ContainsKey(text))
{
messageTimestamps[text] = new System.Collections.Generic.List<float>();
}
// Remove timestamps older than 5 seconds
messageTimestamps[text].RemoveAll(t => currentTime - t > 5f);
if (messageTimestamps[text].Count >= 2)
{
// Trigger a 4-hour ban
messageBans[text] = currentTime;
return false;
}
messageTimestamps[text].Add(currentTime);
}
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;
// Race and tier both come through SkeletonVisuals, which falls back to
// m_customData when there is no ZNetView. That is the whole of what was keeping
// the race off the main-menu character preview: the preview player carries its
// saved custom data but has no network view, so an unconditional ZDO read gave up
// before it could find out it was looking at a Skeleton.
string race = SkeletonVisuals.GetPlayerRace(p);
if (race == SkeletonVisuals.RaceId)
{
if (__instance.m_bodyModel != null)
{
// Ensure the base model is hidden
__instance.m_bodyModel.enabled = false;
int state = SkeletonVisuals.GetProgressionState(p);
SkeletonProgression.SkeletonRules rules = SkeletonProgression.GetRules(state);
// The look chosen at the barber, when it is still unlocked; the tier's own
// body otherwise. Cosmetic: rules keeps driving every ability.
string modelPrefab = SkeletonVisuals.GetModel(p, state);
string targetBodyName = $"SkeletonBody_{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>(modelPrefab);
// The cache answers by name alone, and every magic mod named in the
// purple-smoke report carries an object of its own called "Skeleton" -
// which is this race's own tier-0 model name. So far the vanilla
// creature has always won; the log is here to say so, or to say which
// mod's object took its place. See SkeletonVisuals.EnsureFireAura.
SkeletonVisuals.LogResolvedPrefabOnce("model " + modelPrefab, skelPrefab);
if (skelPrefab == null)
{
// The human body was switched off two lines up, so an unresolved
// model leaves an invisible player rather than an obvious error.
// Say so once per tier instead of failing silently.
WarnMissingModelOnce(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;
LogBoneMapping(modelPrefab, newSmr, playerBones);
Transform[] newBones = new Transform[newSmr.bones.Length];
for (int i = 0; i < newSmr.bones.Length; i++)
{
newBones[i] = ResolveBone(playerBones, newSmr.bones[i]);
}
newSmr.bones = newBones;
if (newSmr.rootBone != null)
{
newSmr.rootBone = ResolveBone(playerBones, newSmr.rootBone);
}
}
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_hairItemInstance");
HideItemInstances(__instance, "m_beardItemInstance");
SetHelmetVisible(__instance, false);
// Poses the mandible, once per frame, after the animation. Attached from
// here rather than from SkeletonRace because this postfix is the one path
// every skeleton reaches - local, remote and the menu preview - and the
// jaw is a rig bone, so whoever is looking sees the same face.
if (p.GetComponent<SkeletonJawFix>() == null)
{
p.gameObject.AddComponent<SkeletonJawFix>();
}
// The /evillaugh pose; same reasoning as the jaw, so remote players laugh too.
if (p.GetComponent<SkeletonEvilLaugh>() == null)
{
p.gameObject.AddComponent<SkeletonEvilLaugh>();
}
// The lights in the eye sockets, cloned out of this tier's own creature so
// that each one arrives its own colour. Outside the build block above on
// purpose: they hang off the player's rig bones rather than off the body
// container, so they outlive it and have to be checked every refresh.
SkeletonEyeGlow.Apply(__instance, modelPrefab);
}
}
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_hairItemInstance");
ShowItemInstances(__instance, "m_beardItemInstance");
SetHelmetVisible(__instance, true);
// Parented to rig bones, not to the body container that was just switched
// off above - so without this a human keeps the skeleton's lit sockets.
SkeletonEyeGlow.Clear(__instance);
}
}
}
/// <summary>
/// A helmet on a skull looks like a helmet floating in a skull, so the race hides it.
///
/// SkeletonRace does this every frame in a world, but it only ever runs for the local
/// player - which is why the helmet came back on the main-menu preview once the body
/// swap started working there. Doing it here covers the menu, remote players and the
/// first frame after a race change, all of which reach this postfix and none of which
/// reach SkeletonRace.
///
/// Delegates to SkeletonVisuals.SetEquipmentPieceHidden, which scales the wrapper to
/// zero and disables its renderers - scale alone leaves a skinned piece (bound to the
/// player's own bones rather than its own transform) still drawing, which is what a
/// helmet with a skinned cloth or chain part looked like.
/// </summary>
private static void SetHelmetVisible(VisEquipment visEq, bool visible)
{
GameObject helmet = Traverse.Create(visEq).Field<GameObject>("m_helmetItemInstance").Value;
SkeletonVisuals.SetEquipmentPieceHidden(helmet, !visible);
}
private static void HideItemInstances(VisEquipment visEq, string fieldName)
{
SetItemInstanceActive(visEq, fieldName, false);
}
private static void ShowItemInstances(VisEquipment visEq, string fieldName)
{
SetItemInstanceActive(visEq, fieldName, true);
}
/// <summary>
/// Hair and beard live in VisEquipment as a single GameObject (m_hairItemInstance /
/// m_beardItemInstance), the same as the helmet - not a list. A previous version of
/// this looked for "m_hairItemInstances" / "m_beardItemInstances" (plural), which do
/// not exist on VisEquipment, so the reflection lookup silently found nothing and the
/// beard never got the SetActive(false) this was supposed to give it. Handling both
/// shapes here matches the defensive pattern the Furling race already uses.
/// </summary>
private static void SetItemInstanceActive(VisEquipment visEq, string fieldName, bool active)
{
try
{
var field = typeof(VisEquipment).GetField(fieldName, System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
if (field == null) return;
object value = field.GetValue(visEq);
if (value is GameObject go)
{
if (go != null) go.SetActive(active);
}
else if (value is System.Collections.Generic.List<GameObject> list)
{
foreach (GameObject item in list)
{
if (item != null) item.SetActive(active);
}
}
}
catch (System.Exception e)
{
Jotunn.Logger.LogWarning($"Failed to set {fieldName} active={active}: {e.Message}");
}
}
// Bones worth reporting on. Not remapped - the player rig has a real 'Jaw' bone and the
// name match lands on it correctly, which is exactly why the plain and poison skeletons
// always looked right. An earlier attempt pinned this group to the head instead and
// deformed all three models; the log is what settled it.
private static readonly string[] SkullParts = { "jaw", "teeth", "tooth", "tongue", "chin", "mandible" };
/// <summary>
/// Finds the player bone a creature bone should be skinned to.
/// </summary>
private static Transform ResolveBone(Transform[] playerBones, Transform sourceBone)
{
if (sourceBone == null) return playerBones[0];
Transform direct = FindBoneByName(playerBones, sourceBone.name);
if (direct != null) return direct;
// Nothing by that name. Follow the creature's own hierarchy upward until something
// matches, so an unmapped part rides its nearest real parent rather than being
// dumped on bones[0], which is the root.
for (Transform parent = sourceBone.parent; parent != null; parent = parent.parent)
{
Transform match = FindBoneByName(playerBones, parent.name);
if (match != null) return match;
}
return playerBones[0];
}
/// <summary>
/// Reports how a model's bones landed on the player rig, once per model per session.
/// The mandible problem is not diagnosable from a screenshot - it matters whether the
/// jaw has a bone at all, whether it matched something, and what it matched - and this
/// answers all three in one line each.
/// </summary>
private static void LogBoneMapping(string modelName, SkinnedMeshRenderer smr, Transform[] playerBones)
{
if (!loggedBoneMaps.Add($"{modelName}/{smr.name}")) return;
Jotunn.Logger.LogInfo($"[Skeleton] '{modelName}' part '{smr.name}': {smr.bones.Length} bones.");
foreach (Transform bone in smr.bones)
{
if (bone == null) continue;
string lower = bone.name.ToLower();
bool interesting = false;
foreach (string part in SkullParts)
{
if (lower.Contains(part)) { interesting = true; break; }
}
Transform resolved = ResolveBone(playerBones, bone);
bool isRootFallback = resolved == playerBones[0] &&
FindBoneByName(playerBones, bone.name) == null;
if (!interesting && !isRootFallback) continue;
// The rest pose comes with it. Three models share this rig bone for bone, yet
// only one of them wears its jaw wrongly - so the difference is in how that
// jaw is posed or bound, not in where it is mapped. Printing the source
// transform next to the player's own gives the exact correction to apply
// rather than another guess at it.
Transform playerEquivalent = FindBoneByName(playerBones, bone.name);
Jotunn.Logger.LogInfo(
$"[Skeleton] '{bone.name}' -> '{(resolved != null ? resolved.name : "null")}'" +
(isRootFallback ? " (ROOT FALLBACK)" : "") +
(interesting ? " (skull part)" : ""));
if (!interesting) continue;
Jotunn.Logger.LogInfo(
$"[Skeleton] source rest: pos={bone.localPosition:F4} " +
$"rot={bone.localRotation.eulerAngles:F2} scale={bone.localScale:F3}");
if (playerEquivalent != null)
{
Jotunn.Logger.LogInfo(
$"[Skeleton] player rest: pos={playerEquivalent.localPosition:F4} " +
$"rot={playerEquivalent.localRotation.eulerAngles:F2} scale={playerEquivalent.localScale:F3}");
}
}
}
/// <summary>
/// The player bone a creature's bone maps onto. Internal because the eye glow hangs
/// its clones off the same mapping the body is skinned through - one answer to
/// "which bone is this", not two that can drift apart.
/// </summary>
internal 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;
// SummonOnKill needs to know "did the local Skeleton player damage this creature
// recently", not just "who threw the exact hit that zeroed its health" - a poison
// DOT tick (SE_Poison.UpdateStatusEffect) builds its own HitData every second with no
// attacker set at all, and Character.ApplyDamage overwrites m_lastHit on every one of
// those ticks. Since PoisonAttacks bakes bonus poison onto every Skeleton hit from
// Bonemass on, a large share of kills finish on an attacker-less poison tick rather
// than the swing itself - Character_OnDeath_Patch falls back to this map when that
// happens. Keyed by ZDOID rather than Character, since the character can already be
// gone by the time OnDeath's Prefix runs.
public static readonly System.Collections.Generic.Dictionary<ZDOID, float> RecentSkeletonHits =
new System.Collections.Generic.Dictionary<ZDOID, float>();
public static bool Prefix(Character __instance, HitData hit)
{
if (Player.m_localPlayer == null) return true;
int state = BossProgressionManager.GetCurrentProgressionState();
var rules = SkeletonProgression.GetRules(state);
// Half in the ground: nothing lands on a Skeleton while it climbs back out.
if (__instance == Player.m_localPlayer && SkeletonRise.IsRising(Player.m_localPlayer)) return false;
// 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 - confirmed real via 'listprefabs'; see SummonOnKill below
// for how the previous two guesses here were caught and replaced.
GameObject vfx = PrefabManager.Cache.GetPrefab<GameObject>("fx_summon_skeleton_spawn") ??
PrefabManager.Cache.GetPrefab<GameObject>("fx_summon_skeleton");
if (vfx != null)
{
UnityEngine.Object.Instantiate(vfx, Player.m_localPlayer.transform.position, Quaternion.identity);
}
// The body climbs out of the ground the way a crypt skeleton does.
SkeletonRise.Begin(Player.m_localPlayer);
Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_skeleton_have_been_resurrected_by_dark"));
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())
{
RecentSkeletonHits[__instance.GetZDOID()] = Time.time;
// Auto Stun
if (rules.AutoStunFirstHit && Time.time - lastStunTime > SkeletonConfig.AutoStunCooldown.Value)
{
hit.m_staggerMultiplier = SkeletonConfig.AutoStunStaggerMultiplier.Value; // Force stagger
lastStunTime = Time.time;
}
// Poison Attacks
if (rules.PoisonAttacks)
{
hit.m_damage.m_poison += SkeletonConfig.PoisonAttackBonus.Value;
}
// 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>();
// How long a recent Skeleton hit still counts toward a kill once the actual death
// blow turns out to be an attacker-less poison tick. Poison's own TTL (SE_Poison,
// vanilla) can run well past 10s on a heavy stack, so this errs generous - the only
// cost of a false positive here is one extra friendly skeleton, not anything unsafe.
private const float KillAttributionWindow = 20f;
// How long a SummonOnKill skeleton lasts before it withers on its own. These are never
// bound to a pile, so RaisedThrall's normal anchor/wither pair has nothing to key off -
// this is the hard, station-independent cap added for exactly that case (see
// RaisedThrall.SetExpiry).
private const float SummonLifetimeSeconds = 120f;
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>();
bool killedByPlayer = lastHit != null && lastHit.GetAttacker() == Player.m_localPlayer;
ZDOID zdoid = __instance.GetZDOID();
if (!killedByPlayer &&
Character_Damage_Patch.RecentSkeletonHits.TryGetValue(zdoid, out float hitTime) &&
Time.time - hitTime <= KillAttributionWindow)
{
// The death blow was very likely an attacker-less poison DOT tick - see the
// comment on RecentSkeletonHits. Credit the kill anyway.
killedByPlayer = true;
}
// The map only needs to remember live targets; drop this one and anything else
// that's aged out, so it can't grow across a long play session.
Character_Damage_Patch.RecentSkeletonHits.Remove(zdoid);
if (Character_Damage_Patch.RecentSkeletonHits.Count > 0)
{
var stale = new System.Collections.Generic.List<ZDOID>();
foreach (var kv in Character_Damage_Patch.RecentSkeletonHits)
{
if (Time.time - kv.Value > KillAttributionWindow) stale.Add(kv.Key);
}
foreach (var key in stale) Character_Damage_Patch.RecentSkeletonHits.Remove(key);
}
if (killedByPlayer)
{
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)
{
Jotunn.Logger.LogWarning($"[Skeleton] SummonOnKill: no '{rules.SummonPrefab}' prefab in the cache; nothing raised from {__instance.m_name}.");
}
else
{
GameObject minion = UnityEngine.Object.Instantiate(minionPrefab, __instance.transform.position, Quaternion.identity);
Character minionChar = minion.GetComponent<Character>();
if (minionChar == null)
{
Jotunn.Logger.LogWarning($"[Skeleton] SummonOnKill: '{rules.SummonPrefab}' has no Character component; destroying the spawned instance.");
UnityEngine.Object.Destroy(minion);
}
else
{
// Confirmed against the live ZNetScene registry via
// 'listprefabs' - "vfx_skeleton_spawn" and "vfx_bloodmagic_aoe"
// (used below by Auto-Resurrect too) were both guesses that
// never actually existed. fx_summon_skeleton_spawn is the real
// vanilla effect for exactly this moment.
GameObject riseVfx = PrefabManager.Cache.GetPrefab<GameObject>("fx_summon_skeleton_spawn") ??
PrefabManager.Cache.GetPrefab<GameObject>("fx_summon_skeleton");
if (riseVfx != null)
{
UnityEngine.Object.Instantiate(riseVfx, minion.transform.position, Quaternion.identity);
}
else
{
Jotunn.Logger.LogWarning("[Skeleton] SummonOnKill: neither 'fx_summon_skeleton_spawn' nor 'fx_summon_skeleton' resolved to a prefab; no rise effect played.");
}
// The particles above are dressing; the actual "climbing out of
// the ground" motion is the creature's own Animator, played by
// setting this bool - the exact call vanilla's CreatureSpawner
// makes (see Spawner_Skeleton_rise) when m_wakeUpAnimation is
// set. Without it the model is simply active from frame one.
ZSyncAnimation zAnim = minion.GetComponent<ZSyncAnimation>();
if (zAnim != null)
{
zAnim.SetBool("wakeup", true);
}
else
{
Jotunn.Logger.LogWarning($"[Skeleton] SummonOnKill: '{rules.SummonPrefab}' has no ZSyncAnimation; cannot play the wakeup animation.");
}
// Make it friendly - same as RaisedThrall.Bind(), minus the
// station anchor, since this one wasn't raised at a pile.
minionChar.m_faction = Character.Faction.Players;
BaseAI ai = minion.GetComponent<BaseAI>();
if (ai == null)
{
Jotunn.Logger.LogWarning($"[Skeleton] SummonOnKill: '{rules.SummonPrefab}' has no BaseAI; it will stand where it spawned and never follow.");
}
else
{
MonsterAI monsterAI = minion.GetComponent<MonsterAI>();
if (monsterAI == null)
{
Jotunn.Logger.LogWarning($"[Skeleton] SummonOnKill: '{rules.SummonPrefab}' has a BaseAI but no MonsterAI; cannot set a follow target.");
}
else
{
monsterAI.MakeTame();
monsterAI.SetFollowTarget(Player.m_localPlayer.gameObject);
}
}
RaisedThrall raised = minion.GetComponent<RaisedThrall>();
if (raised == null)
{
Jotunn.Logger.LogWarning($"[Skeleton] SummonOnKill: '{rules.SummonPrefab}' has no RaisedThrall; it will never wither on its own.");
}
else
{
raised.SetExpiry(SummonLifetimeSeconds);
}
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 (!FactionsConfig.Hostility) return;
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;
}
}
}
}
}
}