diff --git a/JotunnModStub/Factions/FactionHostilityPatch.cs b/JotunnModStub/Factions/FactionHostilityPatch.cs index dffbcdc..91542f2 100644 --- a/JotunnModStub/Factions/FactionHostilityPatch.cs +++ b/JotunnModStub/Factions/FactionHostilityPatch.cs @@ -111,4 +111,31 @@ namespace RacesOfValheim } } } + + // IsEnemy is not the only way a mob picks the player, and the other way ignores it + // completely. BaseAI.FindEnemy() walks every character asking IsEnemy - which both truce + // patches above answer - but when that walk comes up empty and the creature HuntPlayer()s, + // it falls through to Player.GetClosestPlayer(transform.position, 200f) and returns whoever + // it finds, without asking anything about factions. + // + // That fall-through is why the Black Forest truce looked broken to the Trol's testers: + // MonsterAI.UpdateAI turns hunting on for every IsEventCreature() while an event is running, + // and the events that reach a Trol are "the forest is moving" (Greydwarves), "you are being + // hunted" (Trolls) and the Fuling army - the exact three they named. Anything a SpawnSystem + // entry or a TriggerSpawner flags with huntPlayer arrives by the same door. + // + // 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. + [HarmonyPatch(typeof(BaseAI), "FindEnemy")] + public static class FactionHuntPlayerPatch + { + public static void Postfix(BaseAI __instance, ref Character __result) + { + if (__result == null || !__result.IsPlayer()) return; + if (!__instance.IsEnemy(__result)) __result = null; + } + } } diff --git a/JotunnModStub/Package/manifest.json b/JotunnModStub/Package/manifest.json index 91e2556..47fbce3 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.6", + "version_number": "1.4.8", "website_url": "", "dependencies": [ "denikson-BepInExPack_Valheim-5.4.2333", diff --git a/JotunnModStub/RaceCompendium.cs b/JotunnModStub/RaceCompendium.cs index f18caec..63752ed 100644 --- a/JotunnModStub/RaceCompendium.cs +++ b/JotunnModStub/RaceCompendium.cs @@ -292,25 +292,37 @@ namespace RacesOfValheim sb.AppendLine($"Base Passive: Physical kills automatically consume enemies (if edible). You are natively 20% larger than a human with immense strength. You have +200 Max Carry Weight and gain +3 Armor per boss defeated.\n"); - if (state >= 1) + // Written from the config so a retuned multiplier can't leave the compendium lying. + // It was missing outright, which made the Trol the only race whose one drawback was + // nowhere in its own entry - the Sverm and the Skeleton both name theirs. + sb.AppendLine($"Base Weakness - Kindling: Fire finds you where nothing else does. Every burn you take lands for {(TrolConfig.FireWeaknessMultiplier.Value - 1f) * 100f:0}% more than it would on anyone else, and no armor or resistance changes that.\n"); + + sb.AppendLine("Base Passive: Black Forest kin. Greydwarves, Fulings and Trolls have no quarrel with you and will not open a fight - though hitting one still buys you the answer you asked for.\n"); + + // These gates were each one tier early: BossProgressionManager starts at MinState = 1 + // with NO boss down, so state 2 is Eikthyr and state 8 is Fader - which is what every + // other race's entry in this file uses, and what the Trol's own patches check. A fresh + // Trol was being promised the Eikthyr XP bonus before killing anything, then finding + // TrolSkillPatches (state >= 2) refusing it, and the same slip ran the whole ladder. + if (state >= 2) sb.AppendLine("Eikthyr Defeated: Increased XP gain for physical labor and blunt combat (Clubs, Unarmed, Axes, Pickaxes, WoodCutting).\n"); - if (state >= 2) + if (state >= 3) sb.AppendLine("The Elder Defeated: Unlocked Rock Throwing ability. +10% passive health regeneration.\n"); - if (state >= 3) + if (state >= 4) sb.AppendLine("Bonemass Defeated: +5% Size, +50 Carry Weight, +10 Damage to Clubs/Unarmed, +10 Rock Throwing Damage. Unlocked 4th Food Slot.\n"); - if (state >= 4) + if (state >= 5) sb.AppendLine("Moder Defeated: Unlocked True Form (Transformation ability).\n"); - if (state >= 5) + if (state >= 6) sb.AppendLine("Yagluth Defeated: +5% Size, +50 Carry Weight, +10 Damage to Clubs/Unarmed, +5 Rock Throwing Damage. Unlocked 5th Food Slot.\n"); - if (state >= 6) + if (state >= 7) sb.AppendLine("The Queen Defeated: Unlocked Log Weapon (in True Form, interact with trees to wield them as weapons). True Form size is massively increased.\n"); - if (state >= 7) + if (state >= 8) sb.AppendLine("Fader Defeated: Your wielded trees can now instantly smash through the toughest materials in the Ashlands.\n"); knownTexts["Trol Secrets"] = sb.ToString(); diff --git a/JotunnModStub/RacesOfValheim.cs b/JotunnModStub/RacesOfValheim.cs index f74d342..ca31287 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.6"; + public const string PluginVersion = "1.4.8"; private readonly Harmony harmony = new Harmony(PluginGUID); @@ -319,7 +319,7 @@ namespace RacesOfValheim // Row 2 (y = -20) CreateRaceButtonWithConfirm("Aswid", new Vector2(-450, -20), GetAswidIcon(), "Fierce night stalker. Strong and resilient, transforms into a bat.", SelectAswid); CreateRaceButtonWithConfirm("Furling", new Vector2(-150, -20), GetFurlingIcon(), "Cunning goblin-like creatures. Agile and resourceful.", SelectFurling); - CreateRaceButtonWithConfirm("Trol", new Vector2(150, -20), GetTrolIcon(), "Massive brute strength. Towering over others but slow to react.", SelectTrol); + CreateRaceButtonWithConfirm("Trol", new Vector2(150, -20), GetTrolIcon(), $"Massive brute strength. Towering over others, at peace with the Black Forest - but fire burns a Trol {(TrolConfig.FireWeaknessMultiplier.Value - 1f) * 100f:0}% harder than anyone else.", SelectTrol); CreateRaceButtonWithConfirm("Draugh", new Vector2(450, -20), GetDraughIcon(), "A decaying undead warrior fueled by dark magic and extreme metal.", SelectDraugh); // Row 3 (y = -140) diff --git a/JotunnModStub/Sverm/SvermBrood.cs b/JotunnModStub/Sverm/SvermBrood.cs index 1d52a0e..df9514e 100644 --- a/JotunnModStub/Sverm/SvermBrood.cs +++ b/JotunnModStub/Sverm/SvermBrood.cs @@ -36,6 +36,7 @@ namespace RacesOfValheim public float Price; public int Stage; // the nest stage it becomes available at public float Cooldown; // seconds between two of these + public float SpawnHeight = 0.5f; // how far above the nest it is put down public string PrefabName => PrefabPrefix + Source; public int Cap => CapOf(Id); @@ -53,7 +54,7 @@ namespace RacesOfValheim new Kind { Id = "brood", Display = "Brood", Source = "SeekerBrood", Icon = "TrophySeeker", Price = 100f, Stage = 1, Cooldown = 60f }, new Kind { Id = "seeker", Display = "Seeker", Source = "Seeker", Icon = "TrophySeeker", Price = 250f, Stage = 2, Cooldown = 150f }, new Kind { Id = "soldier", Display = "Soldier", Source = "SeekerBrute", Icon = "TrophySeekerBrute", Price = 500f, Stage = 3, Cooldown = 300f }, - new Kind { Id = "gjall", Display = "Gjall", Source = "Gjall", Icon = "TrophyGjall", Price = 1000f, Stage = 4, Cooldown = 600f }, + new Kind { Id = "gjall", Display = "Gjall", Source = "Gjall", Icon = "TrophyGjall", Price = 1000f, Stage = 4, Cooldown = 600f, SpawnHeight = 10f }, }; private static int CapOf(string id) @@ -141,7 +142,7 @@ namespace RacesOfValheim } /// - /// Puts one on the ground beside the nest, bound to it and born at whatever star the colony + /// Puts one down beside the nest, bound to it and born at whatever star the colony /// has bought. /// public static bool Hatch(SvermHiveBehaviour hive, Kind kind) @@ -156,9 +157,7 @@ namespace RacesOfValheim return false; } - Vector3 offset = Random.insideUnitSphere * 2f; - offset.y = 0f; - Vector3 where = hive.transform.position + offset + Vector3.up * 0.5f; + Vector3 where = SpawnSpot(hive, kind); GameObject spawned = Object.Instantiate(prefab, where, Quaternion.Euler(0f, Random.Range(0, 360), 0f)); if (spawned == null) return false; @@ -179,6 +178,73 @@ namespace RacesOfValheim return true; } + + /// How much open ground is left between the nest's own skirt and a newborn. + private const float SpawnClearance = 2.5f; + + /// + /// Where the newborn is put down: on a ring OUTSIDE the nest, never in the middle of it. + /// + /// Troops were hatching at the nest's own position and half a metre up, which is inside a + /// building several metres wide - so they came out wedged in its collider. This walks a ring + /// from a random angle, takes the first spot with nothing standing on it, and drops the + /// creature on the TERRAIN height there, so a nest on a slope does not bury anyone either. + /// The per-kind height goes on top, which is what keeps the Gjall in the air. + /// + private static Vector3 SpawnSpot(SvermHiveBehaviour hive, Kind kind) + { + Vector3 centre = hive.transform.position; + float radius = RingRadius(hive); + int obstacleMask = LayerMask.GetMask("Default", "static_solid", "Default_small", "piece", "vehicle"); + float start = Random.Range(0f, 360f); + + for (int i = 0; i < 12; i++) + { + float angle = (start + i * (360f / 12f)) * Mathf.Deg2Rad; + Vector3 candidate = centre + new Vector3(Mathf.Cos(angle), 0f, Mathf.Sin(angle)) * radius; + if (ZoneSystem.instance != null) candidate.y = ZoneSystem.instance.GetGroundHeight(candidate); + + if (Physics.CheckSphere(candidate + Vector3.up * 1.5f, 1f, obstacleMask)) continue; + + return candidate + Vector3.up * kind.SpawnHeight; + } + + // Twelve tries and everything is built up: due south on the ring anyway. Still outside + // the nest, which is the thing this is here to guarantee. + Vector3 fallback = centre + new Vector3(0f, 0f, -radius); + if (ZoneSystem.instance != null) fallback.y = ZoneSystem.instance.GetGroundHeight(fallback); + return fallback + Vector3.up * kind.SpawnHeight; + } + + /// + /// How wide the ring is: the nest's own footprint plus a couple of metres. + /// + /// MEASURED and not a number, because the nest grows with its stage - a stage four nest is + /// several times the width of the one that was placed, so any fixed radius that clears the + /// small one hatches troops inside the big one. Only solid meshes are measured; the hive's + /// particle effects have bounds of their own and would report a ring the size of a field. + /// + private static float RingRadius(SvermHiveBehaviour hive) + { + Vector3 centre = hive.transform.position; + float widest = 0f; + + foreach (Renderer renderer in hive.GetComponentsInChildren(true)) + { + if (renderer == null) continue; + if (!(renderer is MeshRenderer) && !(renderer is SkinnedMeshRenderer)) continue; + + Bounds bounds = renderer.bounds; // world space, so the stage's growth is already in it + float reach = Mathf.Max(Mathf.Abs(bounds.center.x - centre.x) + bounds.extents.x, + Mathf.Abs(bounds.center.z - centre.z) + bounds.extents.z); + if (reach > widest) widest = reach; + } + + // Nothing readable means nothing to be stuck in either, but the floor keeps a newborn off + // the nest's own doorstep, and the ceiling stops one measuring mistake spawning troops + // half a zone away. + return Mathf.Clamp(widest, 2f, 20f) + SpawnClearance; + } } /// diff --git a/JotunnModStub/Sverm/SvermHive.cs b/JotunnModStub/Sverm/SvermHive.cs index f5ed0ca..59a3b89 100644 --- a/JotunnModStub/Sverm/SvermHive.cs +++ b/JotunnModStub/Sverm/SvermHive.cs @@ -111,7 +111,25 @@ namespace RacesOfValheim wear.m_hitEffect = new EffectList(); } - if (prefab.GetComponent() == null) prefab.AddComponent(); + // PERSISTENT, EXPLICITLY, and this is the whole reason a nest could vanish at world + // load. Every other station in the mod is cloned from a real building - a workbench, a + // barrel, a cartography table - and inherits a ZNetView that is already persistent. The + // nest is the one piece built out of SCENERY, and a CreepProp is not saved with the + // world: it belongs to the location that placed it and is put back by the location, so + // its ZNetView (or the bare one added here, which defaults to false) marks the ZDO as + // throwaway. The hive stood, worked, took biomass - and was not written to the save. + // Next load, no ZDO, no nest. + // + // m_syncInitialScale stays OFF on purpose. It looks like the obvious partner to this + // line and it would be a bug: the stage growth is applied to the transform at runtime, + // so a ZNetView that stored the scale would restore the GROWN size, Awake would read it + // back as builtScale, and the nest would multiply itself by its stage again every + // reload. The size is derived from the stage on the ZDO instead, by every client. + ZNetView view = prefab.GetComponent() ?? prefab.AddComponent(); + view.m_persistent = true; + view.m_distant = false; + view.m_type = ZDO.ObjectType.Default; + prefab.AddComponent(); MountMouths(prefab); diff --git a/JotunnModStub/Sverm/SvermHiveStore.cs b/JotunnModStub/Sverm/SvermHiveStore.cs index d813ee3..c4fd0d1 100644 --- a/JotunnModStub/Sverm/SvermHiveStore.cs +++ b/JotunnModStub/Sverm/SvermHiveStore.cs @@ -336,7 +336,13 @@ namespace RacesOfValheim wear.m_hitEffect = new EffectList(); } - if (prefab.GetComponent() == null) prefab.AddComponent(); + // The workbench this is cloned from brings a persistent ZNetView with it, so this is + // belt as well as braces - but it is the line the NEST turned out to need after players + // reported hives gone at world load, and a counter that saves only because of what + // it was copied from is one refactor away from not saving at all. + ZNetView view = prefab.GetComponent() ?? prefab.AddComponent(); + view.m_persistent = true; + prefab.AddComponent(); Jotunn.Managers.PieceManager.Instance.AddPiece(new Jotunn.Entities.CustomPiece(prefab, fixReference: false, diff --git a/JotunnModStub/Trol/TrolFoodManager.cs b/JotunnModStub/Trol/TrolFoodManager.cs index 727533e..6476d9e 100644 --- a/JotunnModStub/Trol/TrolFoodManager.cs +++ b/JotunnModStub/Trol/TrolFoodManager.cs @@ -1,100 +1,163 @@ using System.Collections.Generic; +using System.Globalization; using UnityEngine; namespace RacesOfValheim { + /// + /// The Trol's 4th and 5th stomach. The runtime side is two dictionaries; the persistent side + /// is four keys in Player.m_customData, which is the only per-character store Valheim writes + /// to disk (Player.Save/Player.Load pack it into the profile). + /// + /// Two rules hold this file together, and both exist because breaking them ate people's food: + /// + /// 1. Never write to m_customData from a path that cannot prove what it is looking at. + /// Removing a key here is not "failing to load" - it is a deletion from the save file. + /// 2. The two slots are independent. Slot 5 is not a continuation of slot 4 and must never + /// be gated behind slot 4 having something in it. + /// public static class TrolFoodManager { - // Runtime dictionary holding the 4th food slot per player + // Runtime dictionaries holding the 4th and 5th food slot per player public static Dictionary ExtraFoods = new Dictionary(); public static Dictionary ExtraFoods5 = new Dictionary(); - // Called when player spawns to load the 4th and 5th food from custom data + private const string Slot4Prefab = "TrolFood_Prefab"; + private const string Slot4Time = "TrolFood_Time"; + private const string Slot5Prefab = "TrolFood5_Prefab"; + private const string Slot5Time = "TrolFood5_Time"; + + // Called when the player spawns, to restore both extra stomachs from custom data. public static void LoadFood(Player player) { if (player == null) return; - - // If they are no longer a Trol, clear it out - if (!TrolRace.IsTrol()) + + // GetPlayerRace returns null when the race cannot be read at all - ZDO empty AND no + // m_customData entry - and that is the case this method used to get catastrophically + // wrong. It asked TrolRace.IsTrol(), which answered a flat "no" during the spawn frame + // (see IsTrol's comment for why), and then called ClearFood on that "no", deleting all + // four keys. Every reload dropped the Trol's 4th and 5th stomach on the floor. + // + // Now only a race we actually READ, and that is not ours, may touch the save file. + // "I cannot tell yet" drops the runtime entries and leaves the disk alone. + string race = FactionHostilityPatch.GetPlayerRace(player); + if (race != "Trol") { - ClearFood(player); + ExtraFoods.Remove(player); + ExtraFoods5.Remove(player); + if (race != null) ClearFood(player); return; } - if (!player.m_customData.ContainsKey("TrolFood_Prefab")) return; + LoadSlot(player, ExtraFoods, Slot4Prefab, Slot4Time); + LoadSlot(player, ExtraFoods5, Slot5Prefab, Slot5Time); + } + + /// + /// Restores one slot. Called once per slot rather than once for both: slot 5 used to sit + /// inside slot 4's early return, so a Trol carrying food in the 5th stomach and nothing in + /// the 4th lost the 5th on every load, independently of everything else wrong here. + /// + private static void LoadSlot(Player player, Dictionary dict, string prefabKey, string timeKey) + { + dict.Remove(player); + + if (!player.m_customData.TryGetValue(prefabKey, out string prefabName)) return; + if (ObjectDB.instance == null) return; - string prefabName = player.m_customData["TrolFood_Prefab"]; GameObject prefab = ObjectDB.instance.GetItemPrefab(prefabName); if (prefab == null) return; ItemDrop itemDrop = prefab.GetComponent(); if (itemDrop == null) return; - // Build food object - Player.Food food = new Player.Food(); - food.m_item = itemDrop.m_itemData.Clone(); // Clone to be safe - - // Try parse remaining time - if (player.m_customData.TryGetValue("TrolFood_Time", out string timeStr) && float.TryParse(timeStr, System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out float time)) + float time = 0f; + if (player.m_customData.TryGetValue(timeKey, out string timeStr)) { - food.m_time = time; + float.TryParse(timeStr, NumberStyles.Float, CultureInfo.InvariantCulture, out time); } - - food.m_health = itemDrop.m_itemData.m_shared.m_food; - food.m_stamina = itemDrop.m_itemData.m_shared.m_foodStamina; - food.m_eitr = itemDrop.m_itemData.m_shared.m_foodEitr; - - ExtraFoods[player] = food; - if (player.m_customData.ContainsKey("TrolFood5_Prefab")) + ItemDrop.ItemData.SharedData shared = itemDrop.m_itemData.m_shared; + + // A meal that finished digesting is not restored, and its keys go with it - otherwise + // a stale pair could sit in the save forever, since UpdateFood only prunes what it can + // already see in the dictionaries. + if (shared.m_foodBurnTime > 0f && time >= shared.m_foodBurnTime) { - string prefabName5 = player.m_customData["TrolFood5_Prefab"]; - GameObject prefab5 = ObjectDB.instance.GetItemPrefab(prefabName5); - if (prefab5 != null) - { - ItemDrop itemDrop5 = prefab5.GetComponent(); - if (itemDrop5 != null) - { - Player.Food food5 = new Player.Food(); - food5.m_item = itemDrop5.m_itemData.Clone(); - if (player.m_customData.TryGetValue("TrolFood5_Time", out string timeStr5) && float.TryParse(timeStr5, System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out float time5)) - { - food5.m_time = time5; - } - food5.m_health = itemDrop5.m_itemData.m_shared.m_food; - food5.m_stamina = itemDrop5.m_itemData.m_shared.m_foodStamina; - food5.m_eitr = itemDrop5.m_itemData.m_shared.m_foodEitr; - ExtraFoods5[player] = food5; - } - } + player.m_customData.Remove(prefabKey); + player.m_customData.Remove(timeKey); + return; } + + Player.Food food = new Player.Food(); + food.m_item = itemDrop.m_itemData.Clone(); + food.m_item.m_stack = 1; + food.m_time = time; + + // Restore the values the stomach actually had, not a fresh meal's. Same lerp + // Trol_PlayerUpdateFood_Patch runs every frame; without it a reload handed back full + // nourishment until the next tick corrected it. + float factor = shared.m_foodBurnTime > 0f ? Mathf.Clamp01(time / shared.m_foodBurnTime) : 0f; + food.m_health = Mathf.Lerp(shared.m_food, shared.m_food * 0.2f, factor); + food.m_stamina = Mathf.Lerp(shared.m_foodStamina, shared.m_foodStamina * 0.2f, factor); + food.m_eitr = Mathf.Lerp(shared.m_foodEitr, shared.m_foodEitr * 0.2f, factor); + + dict[player] = food; } - // Called to save the current runtime 4th food to custom data for persistence + // Saves the current runtime state of both extra stomachs. Authoritative: it is called from + // SetExtraFood/SetExtraFood5, where the dictionaries are known to be current, and it + // removes the keys of an empty slot on purpose. Do NOT call it from anywhere that could + // run before LoadFood has populated the dictionaries - use SaveFoodTimes there. public static void SaveFood(Player player) { if (player == null) return; if (ExtraFoods.TryGetValue(player, out Player.Food food) && food != null && food.m_item != null) { - player.m_customData["TrolFood_Prefab"] = food.m_item.m_dropPrefab.name; - player.m_customData["TrolFood_Time"] = food.m_time.ToString(System.Globalization.CultureInfo.InvariantCulture); + player.m_customData[Slot4Prefab] = food.m_item.m_dropPrefab.name; + player.m_customData[Slot4Time] = food.m_time.ToString(CultureInfo.InvariantCulture); } else { - player.m_customData.Remove("TrolFood_Prefab"); - player.m_customData.Remove("TrolFood_Time"); + player.m_customData.Remove(Slot4Prefab); + player.m_customData.Remove(Slot4Time); } if (ExtraFoods5.TryGetValue(player, out Player.Food food5) && food5 != null && food5.m_item != null) { - player.m_customData["TrolFood5_Prefab"] = food5.m_item.m_dropPrefab.name; - player.m_customData["TrolFood5_Time"] = food5.m_time.ToString(System.Globalization.CultureInfo.InvariantCulture); + player.m_customData[Slot5Prefab] = food5.m_item.m_dropPrefab.name; + player.m_customData[Slot5Time] = food5.m_time.ToString(CultureInfo.InvariantCulture); } else { - player.m_customData.Remove("TrolFood5_Prefab"); - player.m_customData.Remove("TrolFood5_Time"); + player.m_customData.Remove(Slot5Prefab); + player.m_customData.Remove(Slot5Time); + } + } + + /// + /// Writes how far each stomach has digested, and nothing else. Called from a Player.Save + /// prefix, because the time was previously only ever written at the moment of eating - + /// always as 0 - so both extra stomachs came back from a reload at full duration while the + /// three vanilla slots kept their remaining time. + /// + /// This updates existing entries and never removes a key. Player.Save can run at any + /// moment, including before OnSpawned has restored the dictionaries, and a save hook able + /// to empty the save file is the exact bug this file is recovering from. + /// + public static void SaveFoodTimes(Player player) + { + if (player == null) return; + WriteTime(player, ExtraFoods, Slot4Time); + WriteTime(player, ExtraFoods5, Slot5Time); + } + + private static void WriteTime(Player player, Dictionary dict, string timeKey) + { + if (dict.TryGetValue(player, out Player.Food food) && food != null && food.m_item != null) + { + player.m_customData[timeKey] = food.m_time.ToString(CultureInfo.InvariantCulture); } } @@ -131,10 +194,10 @@ namespace RacesOfValheim if (player == null) return; ExtraFoods.Remove(player); ExtraFoods5.Remove(player); - player.m_customData.Remove("TrolFood_Prefab"); - player.m_customData.Remove("TrolFood_Time"); - player.m_customData.Remove("TrolFood5_Prefab"); - player.m_customData.Remove("TrolFood5_Time"); + player.m_customData.Remove(Slot4Prefab); + player.m_customData.Remove(Slot4Time); + player.m_customData.Remove(Slot5Prefab); + player.m_customData.Remove(Slot5Time); } } } diff --git a/JotunnModStub/Trol/TrolFoodPatches.cs b/JotunnModStub/Trol/TrolFoodPatches.cs index 7dc0770..7ff2255 100644 --- a/JotunnModStub/Trol/TrolFoodPatches.cs +++ b/JotunnModStub/Trol/TrolFoodPatches.cs @@ -252,4 +252,22 @@ namespace RacesOfValheim return true; } } + + // m_customData only reaches the disk through Player.Save, and TrolFood_Time / TrolFood5_Time + // were only ever written at the moment of eating - always as 0. Both extra stomachs therefore + // came back from every reload with a full burn time ahead of them, digesting from scratch, + // while the three vanilla slots kept whatever they had left. Refreshing the two timestamps + // just before the package is packed puts all five on the same footing. + // + // A prefix, so the two keys are already in m_customData when Save packs it. SaveFoodTimes only + // updates keys that already exist and never removes one - see its comment for why that + // distinction matters here. + [HarmonyPatch(typeof(Player), nameof(Player.Save))] + public static class Trol_PlayerSave_Patch + { + public static void Prefix(Player __instance) + { + TrolFoodManager.SaveFoodTimes(__instance); + } + } } diff --git a/JotunnModStub/Trol/TrolRace.cs b/JotunnModStub/Trol/TrolRace.cs index ec5376e..36b6936 100644 --- a/JotunnModStub/Trol/TrolRace.cs +++ b/JotunnModStub/Trol/TrolRace.cs @@ -24,12 +24,26 @@ namespace RacesOfValheim } } + // The ZDO copy is authoritative once it has been written - but it is written by a + // Player.OnSpawned postfix in ZdoVisualSync that Harmony registers AFTER this race's own + // OnSpawned postfix (type 363 against type 319 in the built assembly), and the player's + // ZDO is a brand new empty one every session. So on every single load there is a window + // where m_customData is the only place the race exists, and returning out of the ZDO + // branch unconditionally made that window answer "not a Trol" - which is what had + // TrolFoodManager.LoadFood wiping the 4th and 5th stomach out of the save file on reload. + // + // Same fix, same reason, as FactionHostilityPatch.GetPlayerRace: only trust the ZDO + // string when it is non-empty. An explicit "Human" written by resetrace IS non-empty and + // still wins over a stale m_customData, which is the behaviour that fix was added for. public static bool IsTrol() { if (Player.m_localPlayer == null) return false; ZNetView nview = Player.m_localPlayer.GetComponent(); if (nview != null && nview.IsValid()) - return nview.GetZDO().GetString("RacesOfValheim_Race", "") == "Trol"; + { + string zdoRace = nview.GetZDO().GetString("RacesOfValheim_Race", ""); + if (!string.IsNullOrEmpty(zdoRace)) return zdoRace == "Trol"; + } return Player.m_localPlayer.m_customData.TryGetValue("Race", out string r) && r == "Trol"; } diff --git a/README.md b/README.md index e39985e..89d3109 100644 --- a/README.md +++ b/README.md @@ -67,6 +67,7 @@ Full details under [Sverm](#10-sverm) and [Sverm Progression](#race-progressions ### 6. Trol - **Trol Heritage:** 20% larger than a human. +- **Kindling:** the one drawback — fire lands 50% harder on a Trol than on anyone else, and no armour or resistance changes that. - **Immense Strength:** Increased carry weight; armor scales up as you defeat bosses. - **Rock Throwing:** Hurl huge boulders at enemies. - **Tree Weaponry:** At higher tiers, True Form lets you rip logs and wield them as weapons or throw them. @@ -259,7 +260,7 @@ Build a **Brood Mound** with the hammer — no more than two within its density
Trol Progression -- **Base:** +20% size, +200 carry weight, +3 armor per boss. +- **Base:** +20% size, +200 carry weight, +3 armor per boss. Fire hits 50% harder — the race's only weakness. - **Eikthyr:** Increased XP for physical labor and blunt combat. - **Elder:** Rock Throwing unlocked, +10% passive regen. - **Bonemass:** +5% size, +50 carry, +10 club/unarmed damage, +10 rock throw, unlocks 4th food slot. @@ -375,10 +376,12 @@ The size is a slider in Configuration Manager under `Trols Hammer`. Turning the - Build (2 Wood, Hammer/Misc, no crafting station). First placed near Sacrificial Stones in every new world. -Interact to reset race, or switch between: +Interact to reset your race, reset your progression, or switch between: - **World progression:** tier follows world’s bosses. - **Personal progression:** tier saved to character (server independent). +**Reset Progression** drops any tier override you've claimed and falls back to what the world has actually killed — the same thing the `resetprogression` console command does, without the console. + In personal mode, offer boss’s secondary drop to the Ward (Hard Antler, Crypt Key, Wishbone, Dragon Tear, Yagluth’s thing, Queen’s carapace, Fader’s relic) to claim boss tier. --- @@ -404,8 +407,19 @@ The **Sverm** belongs to no faction. Its Hive Pheromones make every invertebrate ## Changelog -### v1.4.6 +### v1.4.8 +- **Fix - Trol losing the 4th and 5th stomach on every reload:** the food was being saved correctly and then deleted while loading. `TrolRace.IsTrol()` read the race from the ZDO and returned that answer even when the ZDO was empty — and the player's ZDO is a brand new empty one every session, written a fraction of a second later by a different `Player.OnSpawned` postfix that Harmony happens to register after the Trol's own. So the loader asked "am I a Trol?" during the one window where the honest answer lives in the save file instead, got told no, and wiped all four keys out of the character. `IsTrol()` now falls back to the saved race when the ZDO has nothing to say (the same fix the hostility patches got in v1.4.6), and the loader is no longer allowed to delete anything on a race it could not read. Food already lost is gone; from this build on it stays. +- **Fix - Trol 5th stomach lost even when the 4th was empty:** a separate bug in the same loader — slot 5 was restored inside slot 4's early return, so a Trol who had eaten into the fifth and let the fourth run out lost the fifth. The two slots are now loaded independently. +- **Fix - Trol extra stomachs restarting full after a reload:** the remaining burn time was only ever written the moment you ate, always as zero, so both extra slots came back from a reload with a whole meal ahead of them while the three vanilla slots kept their leftovers. The time is now written into the character as the game saves, and restored with the right nourishment left in it — the extra stomachs digest across sessions like every other one. +- **Fix - Faction truces vs. raids:** a mob that hunts players never asked about factions at all. `BaseAI.FindEnemy` checks `IsEnemy` while it scans the creatures around it, but when that scan finds nobody it falls through to "grab the nearest player within 200 m" — and every creature spawned by an event hunts players for as long as the event runs. So the Black Forest truce held right up until *the forest is moving*, *you are being hunted* or a Fuling army arrived, at which point the exact three creatures a Trol is supposed to be at peace with — Greydwarves, Trolls and Fulings — came straight for them. That fall-through now respects the same truce as everything else, for every faction. Raiders still tear into your buildings; they just no longer single you out. +- **Fix - Trol compendium was a tier ahead of itself:** every line in the Trol's entry was gated one boss early, so a Trol with nothing killed yet was already being promised the Eikthyr XP bonus that the code only grants after Eikthyr, and True Form was advertised at Bonemass instead of Moder. The whole ladder now matches what the race actually does. +- **Fix - Trol fire weakness was undocumented:** the Trol takes 50% more fire damage and always has, but neither the race-selection blurb nor the compendium ever said so. Both now do, reading the number out of the config so a retuned multiplier can't leave the text lying. + +### v1.4.7 - **NEW - Root of the Elder (Trenta):** one of the Elder's own summoned roots, planted for good instead of fading. Built with the hammer for 5 Guck and 10 Fine Wood once the Elder is down, race locked to the Trenta. It knits its own wounds shut when left alone, and once a minute it repairs **every player-built thing within five meters** — anyone's buildings, not just its owner's. No damage, no armor: the Trenta defends what it has built rather than fighting for it. +- **NEW - Reset Progression on the Race Menu Ward:** the Ward now carries a **Reset Progression** button beside Reset Race, so dropping a claimed tier override and falling back to the world's real boss state no longer needs the console. The button and the `resetprogression` command run the same code, so the two can't drift apart. + +### v1.4.6 - **Fix - Race truces in multiplayer:** every race's mob-truce check (Fenrir/wolves, Aswid, Draugh, Trenta, Sverm, and Skadi/Fenrir/Dvergar's Montagna set including the Drake) read the player's race from a local-only field that is never populated for anyone but your own client. On a dedicated server, or whenever another player ended up owning a mob's AI, the check silently failed and the "neutral" mob stayed hostile — this is why Skadi players were seeing Drakes attack them. Both hostility patches now read the race from the ZDO copy that actually replicates over the network, falling back to the local field only when the ZDO isn't available yet. ### v1.4.5 diff --git a/manifest.json b/manifest.json index 91e2556..47fbce3 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.6", + "version_number": "1.4.8", "website_url": "", "dependencies": [ "denikson-BepInExPack_Valheim-5.4.2333",