From 834d6647fd676cb96e42b1efc192a06a6a33aad9 Mon Sep 17 00:00:00 2001 From: Ferdinando Date: Sun, 20 Sep 2026 08:26:22 +0200 Subject: [PATCH] chore(release): v1.4.19 - eye height, remote forms, food refresh, faction retaliation Race body scale moved the model and not the camera: Character.m_eye hangs off the unscaled root, so a Trol or a Dvergar changed height for everyone but themselves. RaceEyeHeight moves the eye by whatever scale the Visual is wearing, for every player, so aim rays follow too. Remote copies of a Fenrir form had no one writing to their Animator and stood in the controller's default state, sliding. RemoteFenrirAnimator mirrors the four local behaviours off the player's own replicated animator, the way RemoteSkadiAnimator already did for Skadi. Player.Food.m_time is time remaining, not time elapsed: the Aswid, Trenta and Draugh repeat-meal branches all set it to 0 and expired the slot they meant to renew, and left the nutrition values stale. RaceFoodRefresh does what vanilla's own branch does, in one place instead of three. The Trenta prefix now reports __result, or a working refresh would have renewed the slot without consuming the seed. Aswid devour was gated by one timestamp shared by every corpse, so a pack killed at once fed the player once; it is now per corpse, floored at a second, and a refused meal says $msg_nomore. MonsterAI.UpdateTarget discards any target IsEnemy refuses, so a truced mob could not retaliate at all - it stood still or fled. RaceGrudge records the hit on the AI owner's client and both truce postfixes stand down for that pair. The Aswid drain and the Skadi frost aura now skip kin, as the Skeleton's fire aura already did, or an always-on aura would hold every truce permanently broken. Faction sets matched exact prefab names with families half-listed: added Skeleton_NoArcher and Draugr_Ranged to the Swamp, Greyling to the Black Forest. Co-Authored-By: Claude Opus 5 --- JotunnModStub/Aswid/AswidConfig.cs | 2 +- JotunnModStub/Aswid/AswidPatches.cs | 16 +-- JotunnModStub/Aswid/AswidRace.cs | 87 ++++++++++-- JotunnModStub/Draugh/DraughFoodPatches.cs | 16 +-- .../Factions/FactionHostilityPatch.cs | 29 +++- JotunnModStub/Factions/FactionsConfig.cs | 16 ++- JotunnModStub/Fenrir/FenrirBehaviors.cs | 62 +++++++++ JotunnModStub/Package/manifest.json | 2 +- JotunnModStub/RaceEyeHeight.cs | 93 +++++++++++++ JotunnModStub/RaceFoodRefresh.cs | 63 +++++++++ JotunnModStub/RaceGrudge.cs | 127 ++++++++++++++++++ JotunnModStub/RaceHostilityManager.cs | 11 +- JotunnModStub/RacesOfValheim.cs | 2 +- JotunnModStub/Skadi/SkadiRace.cs | 5 + JotunnModStub/Trenta/TrentaFoodPatches.cs | 29 ++-- JotunnModStub/ZdoVisualSync.cs | 7 + README.md | 10 ++ manifest.json | 2 +- 18 files changed, 524 insertions(+), 55 deletions(-) create mode 100644 JotunnModStub/RaceEyeHeight.cs create mode 100644 JotunnModStub/RaceFoodRefresh.cs create mode 100644 JotunnModStub/RaceGrudge.cs diff --git a/JotunnModStub/Aswid/AswidConfig.cs b/JotunnModStub/Aswid/AswidConfig.cs index 498f63e..da24f9d 100644 --- a/JotunnModStub/Aswid/AswidConfig.cs +++ b/JotunnModStub/Aswid/AswidConfig.cs @@ -172,7 +172,7 @@ namespace RacesOfValheim const string devour = "Aswid - Devour"; DevourCooldown = config.Bind(devour, "Consume Cooldown", 5f, - new ConfigDescription("Minimum seconds between devouring a corpse, outside of an execute (which bypasses this).", new AcceptableValueRange(0f, 60f))); + new ConfigDescription("How long one body stays drunk-dry, in seconds. A single death is reported to the devour more than once - by two damage patches, by the aura's execute, by a thrall's kill - and this is the window that keeps those from feeding you twice off the same corpse. It is per body, not per player: killing a whole pack at once devours every one of them. One second is used as the floor, so no corpse feeds you twice even at 0.", new AcceptableValueRange(0f, 60f))); const string domination = "Aswid - Domination"; EnslaveCooldown = config.Bind(domination, "Enslave Cooldown", 900f, diff --git a/JotunnModStub/Aswid/AswidPatches.cs b/JotunnModStub/Aswid/AswidPatches.cs index 5375aad..400e4a4 100644 --- a/JotunnModStub/Aswid/AswidPatches.cs +++ b/JotunnModStub/Aswid/AswidPatches.cs @@ -383,17 +383,11 @@ namespace RacesOfValheim Player.Food f = foodObj as Player.Food; if (f != null && f.m_item.m_shared.m_name == item.m_shared.m_name && f.CanEatAgain()) { - f.m_time = 0f; - f.m_item = item; - - var consumeEffects = HarmonyLib.Traverse.Create(__instance).Field("m_consumeItemEffects").GetValue(); - if (consumeEffects != null) consumeEffects.Create(__instance.transform.position, Quaternion.identity, __instance.transform, 1f, -1); - - var zanim = HarmonyLib.Traverse.Create(__instance).Field("m_zanim").GetValue(); - if (zanim != null) zanim.SetTrigger("eat"); - - if (item.m_shared.m_food > 0f) __instance.Heal(item.m_shared.m_food, true); - + // Was `f.m_time = 0f`, which expired the meal instead of renewing + // it - see RaceFoodRefresh for the whole story. The fourth slot + // above genuinely does count up from zero; this list does not. + RaceFoodRefresh.Refresh(__instance, f, item); + refreshed = true; break; } diff --git a/JotunnModStub/Aswid/AswidRace.cs b/JotunnModStub/Aswid/AswidRace.cs index 4fe1d7e..3078f06 100644 --- a/JotunnModStub/Aswid/AswidRace.cs +++ b/JotunnModStub/Aswid/AswidRace.cs @@ -949,6 +949,20 @@ namespace RacesOfValheim continue; } + // The truce holds here too, or it holds nowhere. This aura is always on + // and asks nothing of the player, so before RaceGrudge it quietly drained + // and executed the race's own kin while they stood there and took it; + // after RaceGrudge that same drain would have kept every leech, draugr and + // blob in the swamp permanently angry at an Aswid who never raised a hand. + // Asking BaseAI.IsEnemy is what the Skeleton's fire aura already does, and + // it is the one question both truce patches answer, so the aura now agrees + // with everything else by construction. The execute is untouched: it still + // fires, on anything the Aswid is actually at war with. + if (!c.IsPlayer() && !BaseAI.IsEnemy(Player.m_localPlayer, c)) + { + continue; + } + float maxHp = c.GetMaxHealth(); float currentHp = c.GetHealth(); @@ -960,7 +974,7 @@ namespace RacesOfValheim if (currentHp > 0 && currentHp <= maxHp * AswidConfig.AuraExecuteThreshold.Value && !c.IsBoss()) { totalDamage = currentHp * 2f; // Lethal damage for execute - TryConsumeMob(c, maxHp, true); // Automatically devour when executed, bypassing cooldown + TryConsumeMob(c, maxHp); // Automatically devour when executed } HitData hd = new HitData(); @@ -987,17 +1001,40 @@ namespace RacesOfValheim public static bool DevourEnabled = true; public static bool AuraEnabled = true; - private static float lastConsumeTime = 0f; - public static void TryConsumeMob(Character c, float maxHp, bool bypassCooldown = false) + /// + /// When each corpse was last drunk from, so one body is never devoured twice. + /// + /// This used to be a single timestamp shared by every corpse in the world, which is what + /// testers hit as "killing with the claws or the aura sometimes adds nothing at all": + /// clear a pack with one blast and the first body ate the cooldown for all of them, the + /// rest dying unnoticed inside the window. The guard was never about pacing kills - it is + /// there because a single death reaches TryConsumeMob from more than one place (two + /// Character.Damage postfixes, the aura's own execute, a thrall's kill), and without it + /// one corpse could feed the player twice. Keyed per corpse it does that job exactly and + /// stops taxing the kills that follow. + /// + private static readonly Dictionary lastConsumedCorpse = new Dictionary(); + private static float lastCorpseSweep = 0f; + + public static void TryConsumeMob(Character c, float maxHp) { if (!DevourEnabled) return; + if (c == null) return; - if (!bypassCooldown && Time.time - lastConsumeTime < AswidConfig.DevourCooldown.Value) + // The window is the config's own "Consume Cooldown", scoped to the body it is about. + // Floored at a second even when that is set to zero: the paths that report one death + // all arrive within the same frame or two, and letting a corpse feed the player twice + // is a bug rather than a setting. + float window = Mathf.Max(AswidConfig.DevourCooldown != null ? AswidConfig.DevourCooldown.Value : 5f, 1f); + ZDOID corpse = c.GetZDOID(); + if (lastConsumedCorpse.TryGetValue(corpse, out float drunkAt) && Time.time - drunkAt < window) { - return; // Cooldown active + return; // This body has already been drunk from. } + SweepConsumedCorpses(window); + string cleanName = c.name.Replace("(Clone)", "").Trim(); string customFoodName = "AswidFood_" + cleanName; @@ -1012,6 +1049,11 @@ namespace RacesOfValheim // Fallback to RawMeat if no specific custom item was generated (e.g. mob not in trophy map) if (foodPrefab == null) { + // Logged rather than shown: a creature with no blood food of its own is a whole + // category, not an event, and a message on every such kill would be noise. It is + // here at all because from the player's chair this looks exactly like a devour + // that failed, and the log is the only way to tell the two apart. + Jotunn.Logger.LogDebug($"[Aswid] '{cleanName}' has no '{customFoodName}' to drink - not edible."); return; // Mob is not edible } @@ -1030,7 +1072,7 @@ namespace RacesOfValheim if (addedItem != null) { - lastConsumeTime = Time.time; + lastConsumedCorpse[corpse] = Time.time; // UseItem natively plays animation and consumes it. // If stomach is full, EatFood fails, UseItem does not consume the item, and virtualInv is destroyed (disintegrated) @@ -1047,8 +1089,15 @@ namespace RacesOfValheim // Vae Victis XP logic - similar to Dead Raiser Player.m_localPlayer.RaiseSkill(Skills.SkillType.BloodMagic, 1f); } - // If it was not eaten the stomach was full: the item disintegrates with - // the virtual inventory, so there is nothing to clean up. + else + { + // The stomach was full and had nothing worth refreshing, so the food + // disintegrates with the virtual inventory - there is nothing to clean + // up, but there used to be nothing to see either. Silence is what made + // a refused meal indistinguishable from a devour that never fired: + // vanilla's own "can't eat more" line, localized for free. + Player.m_localPlayer.Message(MessageHud.MessageType.TopLeft, "$msg_nomore"); + } } else { @@ -1058,6 +1107,28 @@ namespace RacesOfValheim } } + /// + /// Drops corpses the window has passed, so a long session does not carry a growing list of + /// bodies nobody will ever drink from again. Once every window at most - this runs off + /// kills, and a pack dying together should not walk the list once per body. + /// + private static void SweepConsumedCorpses(float window) + { + if (Time.time - lastCorpseSweep < window) return; + lastCorpseSweep = Time.time; + if (lastConsumedCorpse.Count == 0) return; + + List stale = null; + foreach (var entry in lastConsumedCorpse) + { + if (Time.time - entry.Value < window) continue; + if (stale == null) stale = new List(); + stale.Add(entry.Key); + } + if (stale == null) return; + foreach (ZDOID id in stale) lastConsumedCorpse.Remove(id); + } + private static void SpawnBloodVFX(Character target) { try diff --git a/JotunnModStub/Draugh/DraughFoodPatches.cs b/JotunnModStub/Draugh/DraughFoodPatches.cs index 7e2e1af..847a615 100644 --- a/JotunnModStub/Draugh/DraughFoodPatches.cs +++ b/JotunnModStub/Draugh/DraughFoodPatches.cs @@ -134,17 +134,11 @@ namespace RacesOfValheim Player.Food f = foodObj as Player.Food; if (f != null && f.m_item.m_shared.m_name == item.m_shared.m_name && f.CanEatAgain()) { - f.m_time = 0f; - f.m_item = item.Clone(); - - var consumeEffects = Traverse.Create(__instance).Field("m_consumeItemEffects").GetValue(); - if (consumeEffects != null) consumeEffects.Create(__instance.transform.position, Quaternion.identity, __instance.transform, 1f, -1); - - var zanim = Traverse.Create(__instance).Field("m_zanim").GetValue(); - if (zanim != null) zanim.SetTrigger("eat"); - - if (item.m_shared.m_food > 0f) __instance.Heal(item.m_shared.m_food, true); - + // Was `f.m_time = 0f`, which expired the flesh instead of renewing + // it. This is the original of the copy the Aswid and the Trenta + // both inherited - see RaceFoodRefresh. + RaceFoodRefresh.Refresh(__instance, f, item); + refreshed = true; break; } diff --git a/JotunnModStub/Factions/FactionHostilityPatch.cs b/JotunnModStub/Factions/FactionHostilityPatch.cs index a9743c4..2ba265b 100644 --- a/JotunnModStub/Factions/FactionHostilityPatch.cs +++ b/JotunnModStub/Factions/FactionHostilityPatch.cs @@ -24,8 +24,15 @@ namespace RacesOfValheim // is the same as no truce at all - the unexempted Fulings open fire, the player defends // themselves, and every Berserker in earshot joins in through damage retaliation, which // IsEnemy has no say over. Verified against the asset manifest, not the wiki's display names. + // Matching is by exact prefab name, so every variant of a creature has to be named here in + // its own right - a family left half-listed is what made the truce look random by biome + // (see PaludeMobs below for the report that turned this up). "Greyling" is the Meadows + // greydwarf and was missing outright: a Trol or a Furling was at peace with the whole + // Black Forest and still fought the smallest thing in it. The Trenta never noticed, + // because its own list in RaceHostilityManager matches on substrings instead. private static readonly HashSet NeraForestaMobs = new HashSet { + "Greyling", "Greydwarf", "Greydwarf_Elite", "Greydwarf_Shaman", "Goblin", "GoblinArcher", "GoblinBrute", "GoblinShaman", "Troll", @@ -38,10 +45,19 @@ namespace RacesOfValheim "Dverger", "DvergerMageFire", "DvergerMageIce", "DvergerMageSupport", "DvergerAshlands", }; + // Skeleton_NoArcher and Draugr_Ranged are the two that were missing, and they are why an + // Aswid reported skeletons that were peaceful in one biome and hostile in another: it was + // never the biome, it was which variant that particular spawner places. Skeleton_NoArcher + // is vanilla's guaranteed-melee skeleton (the same one SkeletonBonePile borrows), so a + // spawner using it produced hostile skeletons standing next to peaceful ones. Draugr_Ranged + // is the bow draugr, left out while the melee and elite ones were exempt. + // + // Skeleton_Hildir stays out deliberately, on the same rule that keeps GoblinKing and the + // Hildir brothers out of the Black Forest set: a quest boss is not somebody's kin. private static readonly HashSet PaludeMobs = new HashSet { - "Ghost", "Skeleton", "Skeleton_Poison", // Skeleton, Rancid remains - "Draugr", "Draugr_Elite", + "Ghost", "Skeleton", "Skeleton_NoArcher", "Skeleton_Poison", // Skeleton, Rancid remains + "Draugr", "Draugr_Elite", "Draugr_Ranged", "Wraith", "Leech", "Abomination", "Blob", "BlobElite", "BlobTar", // Blob, Oozer, Growth }; @@ -107,6 +123,10 @@ namespace RacesOfValheim Character monster = a.IsPlayer() ? b : (b.IsPlayer() ? a : null); if (!(playerCharacter is Player p) || monster == null) return; + // Same stand-down as the per-race truces get: hit your own faction and it hits back + // until the grudge runs out. See RaceGrudge. + if (RaceGrudge.Holds(monster, p)) return; + if (IsSameFaction(p, monster)) { __result = false; @@ -170,8 +190,9 @@ namespace RacesOfValheim // Filtering the RESULT rather than restating the rule keeps one source of truth: the public // instance IsEnemy(Character) calls the static overload both postfixes above hook, so this // honours whatever the faction sets and RaceHostilityManager's per-race lists already agree - // on. Retaliation is untouched - a mob the player hits is targeted through - // BaseAI.OnDamaged/SetTarget, which never goes near FindEnemy. + // on. Retaliation does not come through here either way - a mob the player hits is targeted + // through BaseAI.OnDamaged/SetTarget, which never goes near FindEnemy. That target only + // SURVIVES because of RaceGrudge, though: UpdateTarget drops anything IsEnemy refuses. [HarmonyPatch(typeof(BaseAI), "FindEnemy")] public static class FactionHuntPlayerPatch { diff --git a/JotunnModStub/Factions/FactionsConfig.cs b/JotunnModStub/Factions/FactionsConfig.cs index 2898c7a..91edfe6 100644 --- a/JotunnModStub/Factions/FactionsConfig.cs +++ b/JotunnModStub/Factions/FactionsConfig.cs @@ -20,12 +20,14 @@ namespace RacesOfValheim { public static ConfigEntry HostilityEnabled; public static ConfigEntry MerchantsEnabled; + public static ConfigEntry GrudgeDuration; // Null-safe, defaulting to ON, for the same reason WarVultureConfig guards its own reads: // a patch that somehow runs before Bind() should behave like the shipped default rather // than throw. Awake() binds before harmony.PatchAll(), so this should never fire. public static bool Hostility => HostilityEnabled?.Value ?? true; public static bool Merchants => MerchantsEnabled?.Value ?? true; + public static float GrudgeSeconds => GrudgeDuration?.Value ?? 60f; public static void Bind(ConfigFile config) { @@ -44,8 +46,18 @@ namespace RacesOfValheim "per-race passives in RaceHostilityManager - Fenrir's wolves, Aswid's " + "progression list, the Draugh's undead, the Trenta's Black Forest, the Sverm's " + "invertebrates. Switching this off gives those five races up along with the " + - "faction truce. Hitting a mob still starts a fight either way: retaliation runs " + - "through BaseAI.OnDamaged, which no truce has a say over.")); + "faction truce. Hitting a mob still starts a fight: see Faction grudge below, " + + "which is what makes that true.")); + + GrudgeDuration = config.Bind(factions, "Faction grudge", 60f, + new ConfigDescription("Seconds a creature stays angry at a player of its own faction who hit it. " + + "Without this the truce is absolute in both directions: MonsterAI.UpdateTarget " + + "throws away any target BaseAI.IsEnemy calls a non-enemy, so a truced mob could " + + "not fight back even after being struck - it stood still, or fled because it " + + "was hurt and had no enemy it was allowed to have. The grudge is per attacker " + + "and per creature, on whichever machine runs that creature's AI. 0 restores the " + + "old absolute truce.", + new AcceptableValueRange(0f, 600f))); MerchantsEnabled = config.Bind(factions, "Faction merchants", true, new ConfigDescription("Certain mobs of your own faction can be traded with - 'E - Talk' opens a shop " + diff --git a/JotunnModStub/Fenrir/FenrirBehaviors.cs b/JotunnModStub/Fenrir/FenrirBehaviors.cs index 20c7157..19e880a 100644 --- a/JotunnModStub/Fenrir/FenrirBehaviors.cs +++ b/JotunnModStub/Fenrir/FenrirBehaviors.cs @@ -39,6 +39,68 @@ namespace RacesOfValheim } } + /// + /// The animation half of somebody else's form. + /// + /// The four behaviours below drive their model's Animator from the player's own, and every + /// one of them runs on the transformed player's client only: FenrirRace.ExecuteTransformation + /// is what adds them, and they read Player.m_localPlayer throughout. RacesVisualController + /// spawns the same model on every other client from the ZDO, and used to spawn nothing else - + /// no parameter was ever written to that copy's Animator, so it sat in its controller's + /// default state and slid across the terrain. The wolf's owner saw a wolf running; everyone + /// else saw a statue on rails. + /// + /// This is the piece that was missing, and it is the arrangement Skadi already uses for its + /// remote dragons (RemoteSkadiAnimator). The parameters come from the remote player's own + /// Visual Animator, which ZSyncAnimation keeps fed over the network for every character a + /// client can see - hiding the body hides renderers, not the animation - so the form walks, + /// runs, jumps and creeps exactly when the real player does. + /// + /// Kept next to the four local behaviours on purpose: this mirrors the movement half of their + /// Update, and the two have to be changed together. + /// + /// Attacks are not mirrored. Those are triggers fired from input on the owner's client and + /// nothing replicates them, so a remote form still bites in silence - that needs a counter of + /// its own on the ZDO and is a separate job. + /// + public class RemoteFenrirAnimator : MonoBehaviour + { + private Player player; + private Animator playerAnim; + private Animator formAnim; + + private void Update() + { + // Resolved here rather than in Start: the model is instantiated under a player who may + // still be assembling their own rig on the frame it arrives. + if (player == null) player = GetComponentInParent(); + if (player == null) return; + + if (formAnim == null) formAnim = GetComponent() ?? GetComponentInChildren(); + if (playerAnim == null) + { + Transform visual = player.transform.Find("Visual"); + if (visual != null) playerAnim = visual.GetComponent(); + } + if (formAnim == null || playerAnim == null) return; + + bool grounded = playerAnim.GetBool("onGround"); + + // All four borrowed creatures answer to these, and they are still written through + // try/catch the way the local behaviours do it: a controller missing one of them would + // otherwise throw once per frame, for every onlooker. + try { formAnim.SetBool("onGround", grounded); } catch {} + try { formAnim.SetBool("inWater", playerAnim.GetBool("inWater")); } catch {} + + // The same three cases the local behaviours use, so both views of the same wolf agree: + // airborne and crouching each read as standing still. Player.IsCrouching answers off + // the animator's current state, which is replicated, so it is true here too. + bool still = !grounded || player.IsCrouching(); + try { formAnim.SetFloat("forward_speed", still ? 0f : playerAnim.GetFloat("forward_speed")); } catch {} + try { formAnim.SetFloat("sideway_speed", still ? 0f : playerAnim.GetFloat("sideway_speed")); } catch {} + } + } + public class FenrirFormBehavior : MonoBehaviour { private Animator playerAnim; diff --git a/JotunnModStub/Package/manifest.json b/JotunnModStub/Package/manifest.json index fe12525..e88f106 100644 --- a/JotunnModStub/Package/manifest.json +++ b/JotunnModStub/Package/manifest.json @@ -1,7 +1,7 @@ { "name": "RacesOfValheim", "description": "A Valheim mod that adds ten custom playable races (Aswid, Draugh, Dvergar, Fenrir, Furling, Skadi, Skeleton, Sverm, Trenta, Trol) each with unique abilities, traits, race stations and a deep boss-driven progression system.", - "version_number": "1.4.18", + "version_number": "1.4.19", "website_url": "", "dependencies": [ "denikson-BepInExPack_Valheim-5.4.2333", diff --git a/JotunnModStub/RaceEyeHeight.cs b/JotunnModStub/RaceEyeHeight.cs new file mode 100644 index 0000000..7195861 --- /dev/null +++ b/JotunnModStub/RaceEyeHeight.cs @@ -0,0 +1,93 @@ +using HarmonyLib; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// Puts the camera at the height of the body the player is actually wearing. + /// + /// Every race that resizes a player does it on the "Visual" child and never on the root: the + /// root carries the collider and the camera pivot, and scaling that drops the player through + /// the ground they are standing on. The cost of that - which is what testers reported - is + /// that Character.m_eye hangs off the same unscaled root. GameCamera.GetCameraBaseOffset takes + /// the camera from m_eye.position minus the root's, and aim raycasts start there too, so a + /// Trol grew a head taller for everyone else while still seeing the world from human eye + /// level, and a Dvergar shrank without ever having to look up at anything. The height was + /// real, and only the other players could see it. + /// + /// The eye is moved by whatever factor the Visual is wearing at that instant, rather than by a + /// per-race number: that way it follows the Trol's transformation lerp for free, costs nothing + /// for a race that is not sizing anybody (the factor is 1), and returns to the measured + /// original the moment a player stops being of that race. + /// + /// Races that scale the player root instead - the Skeleton is the one - are already carrying + /// their eye with them, and read as a factor of 1 here, so they are left alone by + /// construction. So is a player inside a borrowed form (wolf, drake, bat): those hide the + /// body's renderers and leave its scale at 1, and the form's own camera handling is its + /// business. + /// + /// Applied to every player, not just the one at the keyboard. m_eye is also what a mob aims + /// at, so a Dvergar's head being where the Dvergar's head is matters on every client. + /// + public static class RaceEyeHeight + { + // Below this the body is not small, it is being hidden - an old scale-to-zero trick, or a + // transformation caught mid-lerp. Dividing the player's viewpoint down with it would put + // the camera inside the ground, so the eye is left where it last was. + private const float MinScale = 0.05f; + + /// + /// Remembers where the eye sat before any race touched it, on the eye itself, so it dies + /// with the player object and can never be read back as an already-scaled value. + /// + private class EyeRest : MonoBehaviour + { + public Vector3 LocalPosition; + } + + public static void Apply(Player player) + { + if (player == null) return; + + Transform eye = Traverse.Create(player).Field("m_eye").GetValue(); + if (eye == null) return; + + GameObject visual = Traverse.Create(player).Field("m_visual").GetValue(); + if (visual == null) return; + + // If this build ever parents the eye inside the rig, the body scale already carries + // it and doing the same thing here would apply it twice. + if (eye.IsChildOf(visual.transform)) return; + + EyeRest rest = eye.GetComponent(); + if (rest == null) + { + rest = eye.gameObject.AddComponent(); + rest.LocalPosition = eye.localPosition; + } + + float scale = visual.transform.localScale.y; + if (scale < MinScale) return; + + Vector3 wanted = rest.LocalPosition * scale; + if ((eye.localPosition - wanted).sqrMagnitude > 0.000001f) + { + eye.localPosition = wanted; + } + } + + /// + /// Driven from Player.Update, the same place the scales themselves are applied from. The + /// order the postfixes run in does not matter: this reads whatever scale is on the Visual + /// now, so the worst a late scale can cost is one frame. + /// + [HarmonyPatch(typeof(Player), "Update")] + public static class Player_Update_EyeHeight_Patch + { + public static void Postfix(Player __instance) + { + Apply(__instance); + } + } + } +} diff --git a/JotunnModStub/RaceFoodRefresh.cs b/JotunnModStub/RaceFoodRefresh.cs new file mode 100644 index 0000000..daa2a66 --- /dev/null +++ b/JotunnModStub/RaceFoodRefresh.cs @@ -0,0 +1,63 @@ +using HarmonyLib; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// Eating something you are already digesting, for the three races that hand their own food + /// straight to Player.EatFood instead of going through the native right-click path. + /// + /// WHAT WAS WRONG. All three wrote `food.m_time = 0f` to mean "this meal is fresh again". + /// Player.Food.m_time is the opposite: it is the time LEFT. Read out of assembly_valheim - + /// Player.EatFood refreshes a repeat meal with + /// + /// food.m_time = item.m_shared.m_foodBurnTime; + /// + /// and Player.UpdateFood counts it down with `m_time -= dt` and drops the entry the moment it + /// reaches zero. So the line meant to restart the timer was expiring the food on the spot, and + /// the stomach slot vanished instead. + /// + /// The inversion came in honestly: the Aswid's fourth slot and the Trol's fifth are run by + /// this mod rather than by Valheim, and those DO count up from zero (see + /// Aswid_PlayerUpdateFood_Patch). Two opposite conventions, one field name, three copies of + /// the same code - which is why this now lives in one place instead of three. + /// + /// Only a food that answers Player.Food.CanEatAgain() may be refreshed, which is vanilla's own + /// rule (`m_time < m_foodBurnTime / 2`): you cannot top up a meal you have barely started. + /// The callers check it; this does the refreshing. + /// + public static class RaceFoodRefresh + { + /// + /// Puts a slot back to a full meal and plays the eating feedback, exactly as vanilla's own + /// repeat-meal branch does - the three nutrition values included. Leaving those stale was + /// the second half of the bug: a refreshed meal kept whatever health, stamina and eitr the + /// old one had decayed to, so even a correct timer handed back a worn-out slot. + /// + /// Whoever is eating; the one being fed the effects and the heal. + /// The slot already holding this meal. + /// What is being eaten now. Cloned, so the caller's copy - which for the + /// Aswid is a virtual inventory that is thrown away on the next line - can go. + public static void Refresh(Player player, Player.Food food, ItemDrop.ItemData item) + { + if (player == null || food == null || item == null || item.m_shared == null) return; + + food.m_item = item.Clone(); + food.m_time = item.m_shared.m_foodBurnTime; + food.m_health = item.m_shared.m_food; + food.m_stamina = item.m_shared.m_foodStamina; + food.m_eitr = item.m_shared.m_foodEitr; + + EffectList consumeEffects = Traverse.Create(player).Field("m_consumeItemEffects").GetValue(); + if (consumeEffects != null) + { + consumeEffects.Create(player.transform.position, Quaternion.identity, player.transform, 1f, -1); + } + + ZSyncAnimation zanim = Traverse.Create(player).Field("m_zanim").GetValue(); + if (zanim != null) zanim.SetTrigger("eat"); + + if (item.m_shared.m_food > 0f) player.Heal(item.m_shared.m_food, true); + } + } +} diff --git a/JotunnModStub/RaceGrudge.cs b/JotunnModStub/RaceGrudge.cs new file mode 100644 index 0000000..927f4b5 --- /dev/null +++ b/JotunnModStub/RaceGrudge.cs @@ -0,0 +1,127 @@ +using System.Collections.Generic; +using HarmonyLib; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// Hit something that is at peace with you and it hits back. + /// + /// WHY THIS HAS TO EXIST. Both truce patches answer BaseAI.IsEnemy with false, and the comment + /// they each carried - that retaliation runs through BaseAI.OnDamaged and no truce has a say + /// over it - is wrong. Read out of assembly_valheim: + /// + /// MonsterAI.OnDamaged calls SetTarget(attacker), so the mob does take the hit + /// personally, exactly as those comments said, and then + /// MonsterAI.UpdateTarget on its very next tick does + /// if (!IsEnemy(m_targetCreature)) m_targetCreature = null; + /// + /// so the target is thrown away a frame later. A truced mob could not fight back at all: it + /// stood there being hit, or - hurt, with no enemy it was allowed to have - fell into + /// UpdateAI's flee branches and ran away. That is what testers saw and reported. + /// + /// WHAT THIS DOES. It remembers who hit whom, for a while, and both truce postfixes stand down + /// for that one pair while the memory lasts. The mob is an enemy again by vanilla's own rules, + /// which means everything downstream - acquiring, chasing, retaliating, giving up - is vanilla + /// behaviour rather than anything reimplemented here. + /// + /// WHERE IT RUNS. On the client that owns the mob's AI, which is the only one whose UpdateTarget + /// matters and the only one that runs Character.ApplyDamage for it. BaseAI.OnDamaged is reached + /// through the character's damage callback on exactly that machine, so the record is made where + /// it will be read. Nothing is replicated and nothing needs to be: another client's copy of the + /// same mob is not the one deciding who it chases. + /// + /// Vanilla has its own version of this idea in BaseAI.SetAggravated, and it is not usable here: + /// it does nothing unless the prefab sets m_aggravatable, which only the dvergr and the seekers + /// do. + /// + public static class RaceGrudge + { + private struct Grudge + { + public ZDOID Attacker; + public float Until; + } + + // One grudge per mob, against the last thing that hit it. A creature can only chase one + // target anyway, and if two players of the same race are both poking it, the one it wants + // is whoever hit it last. + private static readonly Dictionary grudges = new Dictionary(); + private static float lastSweep = 0f; + + private static float Duration => FactionsConfig.GrudgeSeconds; + + /// + /// True while is owed a hit by . Both + /// truce postfixes ask this first and leave IsEnemy alone when it answers yes. + /// + public static bool Holds(Character monster, Character player) + { + if (monster == null || player == null) return false; + if (Duration <= 0f) return false; + + if (!grudges.TryGetValue(monster.GetZDOID(), out Grudge grudge)) return false; + if (Time.time >= grudge.Until) return false; + + return grudge.Attacker == player.GetZDOID(); + } + + public static void Remember(Character monster, Character attacker) + { + if (monster == null || attacker == null) return; + if (Duration <= 0f) return; + + grudges[monster.GetZDOID()] = new Grudge + { + Attacker = attacker.GetZDOID(), + Until = Time.time + Duration + }; + + Sweep(); + } + + /// + /// Drops grudges nobody is owed any more. At most once per duration: a fight is a burst of + /// damage events and the list should not be walked on each one. + /// + private static void Sweep() + { + if (Time.time - lastSweep < Duration) return; + lastSweep = Time.time; + + List expired = null; + foreach (var entry in grudges) + { + if (Time.time < entry.Value.Until) continue; + if (expired == null) expired = new List(); + expired.Add(entry.Key); + } + if (expired == null) return; + foreach (ZDOID id in expired) grudges.Remove(id); + } + + /// + /// The one place a grudge is born. BaseAI.OnDamaged is the base every AI's own override + /// calls first, so patching it here covers MonsterAI and AnimalAI both, and it lands before + /// MonsterAI.OnDamaged's SetTarget on the same hit - the grudge is on the books by the time + /// UpdateTarget next asks whether that target is allowed. + /// + /// Only a player's hit counts. A greydwarf caught in another greydwarf's swing has vanilla's + /// own rules for that and no truce of ours in the way. + /// + [HarmonyPatch(typeof(BaseAI), "OnDamaged")] + public static class BaseAI_OnDamaged_Grudge_Patch + { + public static void Postfix(BaseAI __instance, Character attacker) + { + if (!FactionsConfig.Hostility) return; + if (attacker == null || !attacker.IsPlayer()) return; + + Character monster = Traverse.Create(__instance).Field("m_character").Value; + if (monster == null || monster.IsPlayer()) return; + + Remember(monster, attacker); + } + } + } +} diff --git a/JotunnModStub/RaceHostilityManager.cs b/JotunnModStub/RaceHostilityManager.cs index ae99bc0..e182951 100644 --- a/JotunnModStub/RaceHostilityManager.cs +++ b/JotunnModStub/RaceHostilityManager.cs @@ -25,6 +25,11 @@ namespace RacesOfValheim Character playerCharacter = a.IsPlayer() ? a : (b.IsPlayer() ? b : null); Character monster = a.IsPlayer() ? b : (b.IsPlayer() ? a : null); + // A truce the player has just broken is not a truce. Without this the mob cannot + // retaliate at all - not because it does not try, but because MonsterAI.UpdateTarget + // throws away any target this method calls a non-enemy. See RaceGrudge. + if (RaceGrudge.Holds(monster, playerCharacter)) return; + if (playerCharacter != null && monster != null) { Player p = playerCharacter as Player; @@ -80,8 +85,10 @@ namespace RacesOfValheim // only in flavour text - Greyling/Greydwarf/Leech/Deathsquito "don't see" a // Trenta as prey (root-kin, or simply nothing with blood to sense), while // Fuling/Troll "choose" not to fight one - but there is no third state to code - // for: vanilla's own damage-response AI already makes any of them retaliate if - // the Trenta strikes first, same as it does for Fenrir's wolves above. + // for. Striking first is handled, though not by the AI on its own as this + // comment used to claim: MonsterAI.UpdateTarget discards any target IsEnemy + // calls a non-enemy, so retaliation needed RaceGrudge, checked at the top of + // this method. if (playerRace == TrentaConfig.RaceId) { string prefabName = monster.gameObject.name.ToLower(); diff --git a/JotunnModStub/RacesOfValheim.cs b/JotunnModStub/RacesOfValheim.cs index 2cf0c9f..78db93b 100644 --- a/JotunnModStub/RacesOfValheim.cs +++ b/JotunnModStub/RacesOfValheim.cs @@ -15,7 +15,7 @@ namespace RacesOfValheim { public const string PluginGUID = "com.nandor.racesofvalheim"; public const string PluginName = "Races Of Valheim"; - public const string PluginVersion = "1.4.18"; + public const string PluginVersion = "1.4.19"; private readonly Harmony harmony = new Harmony(PluginGUID); diff --git a/JotunnModStub/Skadi/SkadiRace.cs b/JotunnModStub/Skadi/SkadiRace.cs index aa141fa..fe7a3ef 100644 --- a/JotunnModStub/Skadi/SkadiRace.cs +++ b/JotunnModStub/Skadi/SkadiRace.cs @@ -522,6 +522,11 @@ namespace RacesOfValheim if (c == Player.m_localPlayer) continue; if (c.IsTamed() || c.IsPlayer()) continue; + // Same guard as the Skeleton's fire aura and the Aswid's drain: an always-on aura + // that burns the race's own kin would, with RaceGrudge in place, keep every wolf, + // drake and dverger permanently angry at a Skadi who never attacked anything. + if (!BaseAI.IsEnemy(Player.m_localPlayer, c)) continue; + if (Vector3.Distance(center, c.transform.position) <= SkadiConfig.AuraRadius.Value) { HitData hit = new HitData(); diff --git a/JotunnModStub/Trenta/TrentaFoodPatches.cs b/JotunnModStub/Trenta/TrentaFoodPatches.cs index c20b87f..f083369 100644 --- a/JotunnModStub/Trenta/TrentaFoodPatches.cs +++ b/JotunnModStub/Trenta/TrentaFoodPatches.cs @@ -137,7 +137,14 @@ namespace RacesOfValheim [HarmonyPatch(typeof(Player), "EatFood")] public static class Trenta_Player_EatFood_DuplicateGuard_Patch { - public static bool Prefix(Player __instance, ItemDrop.ItemData item) + // __result matters here, unlike in a prefix that only ever falls through to vanilla: + // the caller above is TrentaFoodPatches' own UseItem prefix, and it removes the seed + // from the bag only when EatFood answers true. Without this the refresh below would + // renew the slot and leave the seed in the inventory to be eaten again, forever. It + // went unnoticed while the refresh was broken: the old code destroyed the slot instead + // of renewing it, so the free seed had nothing to show for it. The Aswid and the + // Draugh versions of this patch already took __result. + public static bool Prefix(Player __instance, ItemDrop.ItemData item, ref bool __result) { hiddenFoods.Clear(); @@ -155,22 +162,18 @@ namespace RacesOfValheim Player.Food f = foodObj as Player.Food; if (f != null && f.m_item.m_shared.m_name == item.m_shared.m_name && f.CanEatAgain()) { - f.m_time = 0f; - f.m_item = item.Clone(); + // Was `f.m_time = 0f`, which expired the seed instead of renewing it - + // this is the "eating a second seed deletes the first" report. See + // RaceFoodRefresh. + RaceFoodRefresh.Refresh(__instance, f, item); - var consumeEffects = Traverse.Create(__instance).Field("m_consumeItemEffects").GetValue(); - if (consumeEffects != null) consumeEffects.Create(__instance.transform.position, Quaternion.identity, __instance.transform, 1f, -1); - - var zanim = Traverse.Create(__instance).Field("m_zanim").GetValue(); - if (zanim != null) zanim.SetTrigger("eat"); - - if (item.m_shared.m_food > 0f) __instance.Heal(item.m_shared.m_food, true); - - return false; // Refreshed ourselves - skip native EatFood + __result = true; // Eaten: the caller consumes the seed. + return false; // Refreshed ourselves - skip native EatFood } } - return false; // Full, and nothing to refresh + __result = false; // Full, and nothing in it worth topping up: the seed stays. + return false; } // Temporarily hide any existing slot with the same name to force native EatFood diff --git a/JotunnModStub/ZdoVisualSync.cs b/JotunnModStub/ZdoVisualSync.cs index c7d2f2f..ecff680 100644 --- a/JotunnModStub/ZdoVisualSync.cs +++ b/JotunnModStub/ZdoVisualSync.cs @@ -217,6 +217,13 @@ namespace RacesOfValheim { Destroy(col); } + + // Without this the model arrives with nobody writing to its + // Animator and stands in its default pose, sliding wherever the + // player walks. The local form has four behaviours doing this job; + // none of them can run here, because all of them are built around + // Player.m_localPlayer. + m_currentFormInstance.AddComponent(); } } } diff --git a/README.md b/README.md index 11e2bba..1db8120 100644 --- a/README.md +++ b/README.md @@ -404,12 +404,22 @@ Aswid, Draugh, Skeleton / at peace with Ghost, Skeleton, Draugr, Wraith, Leech, The **Sverm** belongs to no faction. Its Hive Pheromones make every invertebrate in the game ignore it instead — leeches, ticks, deathsquitos, seekers and bees — with no boss gate and no trading. +A truce is not a shield: hit one of your own and it hits back, for **Faction grudge** seconds (60 by default), then forgets about it. Your always-on auras — the Aswid's drain, the Skadi's frost — leave your own kin alone, so they never start that fight for you. + Both halves have an off switch under `Factions` in Configuration Manager: **Faction truce** for whether your faction's mobs leave you alone, **Faction merchants** for whether they will trade. Both are on by default and both take effect without a restart. Be aware that turning the truce off also gives up every race's own peace — Fenrir's wolves, the Aswid's list, the Draugh's undead, the Trenta's Black Forest, the Sverm's invertebrates, the Furling's Plains roster and the Skeleton's undead — because they are all the same question asked of the same vanilla method. --- ## Changelog +### v1.4.19 +- **Fix - You could not see your own height:** the Trol stood a head taller and the Dvergar came up short for everyone except themselves — the body was resized, but the camera stayed at human eye level, so from your own chair nothing had changed. Your eyes now sit where your head is, and your shots start from there too. Every race that resizes its body is covered, at whatever size it happens to be wearing: the Trol's True Form lifts the view as it grows and lowers it again on the way back. Thanks to the testers who noticed it only worked on other people. +- **Fix - Other players saw a Fenrir's wolf standing still and sliding:** the form's animations were only ever driven on the transformed player's own screen. Everyone else got the model in its default pose, gliding across the ground. Wolf, Ulv, Fenring and Cultist now walk, run, jump and creep for every player who can see them. Their attacks are still silent to onlookers — that needs its own fix and is not in this build. +- **Fix - Eating the same creature or seed again destroyed that food instead of refreshing it:** the timer was being set to "expired" rather than "full", so a repeat meal deleted the slot it was meant to renew — and it only happened once the food was under half, which is exactly when it starts flashing. Above half, nothing happened at all. The Aswid's devoured creatures, the Trenta's awakened seeds and the Draugh's raw flesh all had it; all three now renew the slot the way any vanilla food does, nourishment included. Thanks to the tester who worked out that it was the flashing ones. +- **Fix - Devouring only ever caught the first kill:** the Aswid's devour was on a five-second timer shared by every corpse in the world, so clearing a group with the claws or the aura fed you once and let the rest die unnoticed. It is now per body: kill a pack and you drink from all of them. A refused meal also says so instead of failing silently. +- **Fix - Mobs of your own faction would not fight back:** attacking one of your own kin did nothing — it stood there, or ran away — because the truce was absolute in both directions and the game threw away any target it was not allowed to have. Now hitting one starts a real fight for **Faction grudge** seconds (60 by default, configurable, 0 for the old behaviour), per creature and per attacker. The Aswid's drain and the Skadi's frost aura no longer touch their own kin, so an always-on aura can no longer pick that fight on your behalf. Thanks to the tester who reported the Trenta and the Aswid. +- **Fix - Friendly skeletons in one biome, hostile ones in the next:** the faction truce matched creatures by exact name and several families were only half-listed, so an Aswid was at peace with one kind of skeleton and at war with another standing next to it. Added the melee-only skeleton and the bow draugr to the Swamp, and the greyling to the Black Forest — a Trol or a Furling was at peace with the whole forest and still fought the smallest thing in it. Thanks to the tester who mapped it out biome by biome. + ### v1.4.18 - **Fix - Drake flight stopped working after the latest Valheim hotfix:** the hotfix changed how the game reads the gamepad's left stick, and the drake's flight still asked for it the old way. Every frame in the air threw a `MissingMethodException` into the log and the drake could not fly. Flight now works on both the new and the old version of the game. - **Fix - Faction merchants would not open their shop:** Valheim 1.0 added a name, tooltip, buy effects and unlock keys to every shop item, and the shop window reads some of them without checking they are there. The merchants' goods were missing them, so pressing E threw a `NullReferenceException` and nothing opened. Buying is covered too — it would have hit the same wall on the buy effects. Thanks to the tester who tracked this down. diff --git a/manifest.json b/manifest.json index fe12525..e88f106 100644 --- a/manifest.json +++ b/manifest.json @@ -1,7 +1,7 @@ { "name": "RacesOfValheim", "description": "A Valheim mod that adds ten custom playable races (Aswid, Draugh, Dvergar, Fenrir, Furling, Skadi, Skeleton, Sverm, Trenta, Trol) each with unique abilities, traits, race stations and a deep boss-driven progression system.", - "version_number": "1.4.18", + "version_number": "1.4.19", "website_url": "", "dependencies": [ "denikson-BepInExPack_Valheim-5.4.2333",