From fa0e2cbb062485865229f378a44e9de0d36e978a Mon Sep 17 00:00:00 2001 From: kanym Date: Wed, 30 Sep 2026 22:43:44 +0200 Subject: [PATCH 001/176] chore(release): v1.5.2 Version bumped in manifest.json, the packaging manifest and PluginVersion. The one change is the Thunderstore package keeping the mod under plugins/, so mod managers no longer take the Translations folders apart. The changelog explains why 1.5.1's zip fix was not enough, and the README leads with it. --- JotunnModStub/Package/manifest.json | 2 +- JotunnModStub/RacesOfValheim.cs | 2 +- README.md | 7 +++++++ manifest.json | 2 +- 4 files changed, 10 insertions(+), 3 deletions(-) diff --git a/JotunnModStub/Package/manifest.json b/JotunnModStub/Package/manifest.json index f04acf9..574ca9b 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.5.1", + "version_number": "1.5.2", "website_url": "", "dependencies": [ "denikson-BepInExPack_Valheim-5.4.2333", diff --git a/JotunnModStub/RacesOfValheim.cs b/JotunnModStub/RacesOfValheim.cs index 2073767..4dc2aab 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.5.1"; + public const string PluginVersion = "1.5.2"; private readonly Harmony harmony = new Harmony(PluginGUID); diff --git a/README.md b/README.md index ae58187..3c75e74 100644 --- a/README.md +++ b/README.md @@ -13,6 +13,10 @@ Support the mod: [Patreon — NandorTheModder](https://www.patreon.com/c/NandorT --- +## New in v1.5.2 + +The mod's texts finally show for everyone who installs through a mod manager (r2modman, the Thunderstore Mod Manager, Gale). Those managers were taking the translation folders apart on install, so every name and message read like `[rov_...]`. Update, and the texts are back. Full details in the [changelog](#v152). + ## New in v1.5.1 A fix release for v1.5.0. The mod's texts show properly again for players whose install turned them into [rov_...] keys, mod managers included. Weapons and shields now match a resized player instead of shrinking after you put them away, and a True Form Trol can reach the log at its feet. The Sverm's Hive Market sells again, because the nest lays its brood eggs while you stand by it. The Trenta's Muspell looks out from its own head and keeps idling, a Furling no longer carries its fire onto another race, and raids made only of your allies no longer come for you. @@ -427,6 +431,9 @@ Both halves have an off switch under `Factions` in Configuration Manager: **Fact ## Changelog +### v1.5.2 +- **Fix - Every text still showed as [rov_...] when installed through a mod manager:** 1.5.1 fixed the zip, but that was not the whole story. r2modman, the Thunderstore Mod Manager and Gale flatten any folder in a package they do not recognise, so the `Translations/English` and `Translations/Italian` folders came out as loose files next to the mod, the Italian copy of each file overwrote the English one, and the game found no translations at all. The package now keeps the mod inside the folder mod managers preserve, and the texts come through with their folders. Thanks to the players who kept reporting it and trying clean installs. + ### v1.5.1 - **New - Raids made only of your allies no longer come for you:** an Aswid got raided by the swamp - skeletons and draugr that ignored the player, as the truce says, and then spent the whole event running around the base smashing it, with no way to stop them short of console commands. A raid whose every creature is at peace with your race is now left out of the raids you can receive, so an Aswid no longer gets the skeleton, blob or Bonemass raids. This counts your faction and your race's own list, the Aswid's boss-by-boss one included. Mixed raids still come. With player-based raids (the world modifier) it works on any server; with world-based raids a dedicated server needs the mod installed as well. Thanks to the player who reported it. - **Fix - Allied creatures smashed buildings when you were not standing right next to them:** the truce only kept them off your structures while you were within 20 m of the creature, and some creatures pick a building from further away than that. Now, while any player they are at peace with is within 100 m, they leave every structure in the area alone, whoever built it. Hit one and its grudge lifts that protection for you, as it does for the truce. diff --git a/manifest.json b/manifest.json index f04acf9..574ca9b 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.5.1", + "version_number": "1.5.2", "website_url": "", "dependencies": [ "denikson-BepInExPack_Valheim-5.4.2333", From b9ac02fe5041381808bff0a6fde49d77f4b170e7 Mon Sep 17 00:00:00 2001 From: Ferdinando Date: Thu, 1 Oct 2026 08:19:36 +0200 Subject: [PATCH 002/176] chore(release): v1.5.3 Version bumped in manifest.json, the packaging manifest and PluginVersion. Valheim 1.0's new creatures for the Aswid and the Draugh (seal, moose, Elaking, Jotun, Barka, Deep North Goblin and every Dvergr), the Elaking Hair Bundle in the blood refinery, and the Skeleton choosing its look at the barber. Co-Authored-By: Claude Sonnet 5.5 --- JotunnModStub/Aswid/AswidBloodRefinery.cs | 1 + JotunnModStub/Aswid/AswidRace.cs | 48 ++++++- JotunnModStub/Draugh/DraughFoodPatches.cs | 6 +- JotunnModStub/Package/manifest.json | 2 +- JotunnModStub/RacesOfValheim.cs | 2 +- JotunnModStub/Skeleton/SkeletonBarber.cs | 124 ++++++++++++++++++ JotunnModStub/Skeleton/SkeletonPatches.cs | 15 ++- JotunnModStub/Skeleton/SkeletonProgression.cs | 22 ++++ JotunnModStub/Skeleton/SkeletonRace.cs | 10 +- JotunnModStub/Skeleton/SkeletonVisuals.cs | 31 +++++ .../Translations/English/messages.json | 3 + .../Translations/Italian/messages.json | 3 + JotunnModStub/ZdoVisualSync.cs | 2 +- README.md | 11 ++ manifest.json | 2 +- 15 files changed, 267 insertions(+), 15 deletions(-) create mode 100644 JotunnModStub/Skeleton/SkeletonBarber.cs diff --git a/JotunnModStub/Aswid/AswidBloodRefinery.cs b/JotunnModStub/Aswid/AswidBloodRefinery.cs index 78a9867..c119d53 100644 --- a/JotunnModStub/Aswid/AswidBloodRefinery.cs +++ b/JotunnModStub/Aswid/AswidBloodRefinery.cs @@ -68,6 +68,7 @@ namespace RacesOfValheim { "AsksvinCarrionRibcage", 3 }, { "AsksvinCarrionSkull", 3 }, { "UndeadBjornRibcage", 3 }, // Deep North + { "ElakingHairBundle", 20 }, // Deep North, dropped by the Elaking }; // Vanilla grills. Anything they cook counts as raw flesh, which keeps modded meat working. diff --git a/JotunnModStub/Aswid/AswidRace.cs b/JotunnModStub/Aswid/AswidRace.cs index edfbdc5..e8bb4c7 100644 --- a/JotunnModStub/Aswid/AswidRace.cs +++ b/JotunnModStub/Aswid/AswidRace.cs @@ -44,7 +44,32 @@ namespace RacesOfValheim { "Ulv", "TrophyUlv" }, { "Fenring_Cultist", "TrophyCultist" }, // the prefab is Fenring_Cultist, not "Cultist" { "Asksvin", "TrophyAsksvin" }, - { "Volture", "TrophyVolture" } + { "Volture", "TrophyVolture" }, + // Valheim 1.0's seals. The baby is Seal_Pup in the prefab list - "baby" is only its + // display token ($enemy_seal_baby). Both wear the one TrophySeal icon. + // The frozen Greydwarfs have no trophy of their own; they borrow the regular one's icon. + { "Greydwarf_Frozen", "TrophyGreydwarf" }, + { "Greydwarf_Shaman_Frozen", "TrophyGreydwarfShaman" }, + { "Elaking", "TrophyElaking" }, + { "ElakingLantern", "TrophyElaking" }, + { "Moose", "TrophyMoose" }, + { "Moose_calf", "TrophyMoose" }, + { "Barka", "TrophyBarka" }, + { "JotunWarrior", "TrophyJotunWarrior" }, + { "JotunWarriorDualWield", "TrophyJotunWarrior" }, + { "JotunWitch", "TrophyJotunWitch" }, + { "ElakingMole", "TrophyMole" }, + { "GoblinDeepNorth", "TrophyGoblin" }, + { "DvergerDeepNorth", "TrophyDvergr" }, + // The Dvergr from before the Deep North, all of them: 90 HP for 25 minutes. + { "Dverger", "TrophyDvergr" }, + { "DvergerMage", "TrophyDvergr" }, + { "DvergerMageFire", "TrophyDvergr" }, + { "DvergerMageIce", "TrophyDvergr" }, + { "DvergerMageSupport", "TrophyDvergr" }, + { "DvergerAshlands", "TrophyDvergr" }, + { "Seal", "TrophySeal" }, + { "Seal_Pup", "TrophySeal" } }; private static Dictionary mobToFoodMap = new Dictionary @@ -65,7 +90,18 @@ namespace RacesOfValheim { "SeekerBrute", "CookedBugMeat" }, { "SeekerBrood", "CookedBugMeat" }, { "Surtling", "BloodPudding" }, - { "Bear", "CookedBearMeat" } + { "Bear", "CookedBearMeat" }, + // Same meal as the Draugh's raw Seal Blubber: vanilla's Seal Meat Soup, so a seal is + // worth exactly what the soup is, adult or pup. + { "Greydwarf_Frozen", "SealSoup" }, + { "Greydwarf_Shaman_Frozen", "SealSoup" }, + // The Cooked Asksvin Tail (prefab CookedAsksvinMeat), the same meal the Asksvin gives. + { "Elaking", "CookedAsksvinMeat" }, + { "ElakingLantern", "CookedAsksvinMeat" }, + { "Moose", "CookedMooseMeat" }, + { "Moose_calf", "CookedMooseMeat" }, + { "Seal", "SealSoup" }, + { "Seal_Pup", "SealSoup" } }; public static bool BypassAswidFoodCheck = false; @@ -155,7 +191,9 @@ namespace RacesOfValheim if (c != null) { float foodHp = Mathf.Min(c.m_health / 2f, 150f); - float burnTime = c.m_health * 2f; + // Capped at 50 minutes: a tough creature like the Barka would otherwise + // feed for over an hour. + float burnTime = Mathf.Min(c.m_health * 2f, 3000f); // StartsWith("Fenring") already covers Fenring_Cultist. "Fuling" was // never a prefab prefix - the family is Goblin* - so that arm of the // test matched nothing until now. @@ -163,6 +201,10 @@ namespace RacesOfValheim { burnTime = 1200f; // 20 minutes } + else if (mobName == "JotunWitch") { foodHp = 120f; burnTime = 3600f; } // 60 minutes + else if (mobName == "ElakingMole") { foodHp = 100f; burnTime = 1800f; } // 30 minutes + else if (mobName.StartsWith("Dverger") && mobName != "DvergerDeepNorth") { foodHp = 90f; burnTime = 1500f; } // 25 minutes + else if (mobName == "DvergerDeepNorth") { foodHp = 100f; burnTime = 1800f; } // 30 minutes else if (mobName == "Greyling") { foodHp = 20f; burnTime = 1200f; } else if (mobName == "Greydwarf") { foodHp = 25f; burnTime = 1200f; } else if (mobName == "Greydwarf_Shaman") { foodHp = 30f; burnTime = 1200f; } diff --git a/JotunnModStub/Draugh/DraughFoodPatches.cs b/JotunnModStub/Draugh/DraughFoodPatches.cs index f6d7fe7..f4a9ce2 100644 --- a/JotunnModStub/Draugh/DraughFoodPatches.cs +++ b/JotunnModStub/Draugh/DraughFoodPatches.cs @@ -27,7 +27,11 @@ namespace RacesOfValheim { "VoltureMeat", "RoastedVoltureMeat" }, { "GreydwarfEye", "DeerStew" }, { "Entrails", "Sausages" }, - { "Bloodbag", "BloodPudding" } + { "Bloodbag", "BloodPudding" }, + { "MooseMeat", "CookedMooseMeat" }, + // Raw blubber keeps its own name and icon (EdibleUncooked_ copies them from the raw + // item) and gives the stats of Seal Meat Soup. + { "SealBlubber", "SealSoup" } }; [HarmonyPatch(typeof(Humanoid), "UseItem")] diff --git a/JotunnModStub/Package/manifest.json b/JotunnModStub/Package/manifest.json index 574ca9b..ac2c5e8 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.5.2", + "version_number": "1.5.3", "website_url": "", "dependencies": [ "denikson-BepInExPack_Valheim-5.4.2333", diff --git a/JotunnModStub/RacesOfValheim.cs b/JotunnModStub/RacesOfValheim.cs index 4dc2aab..79703b3 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.5.2"; + public const string PluginVersion = "1.5.3"; private readonly Harmony harmony = new Harmony(PluginGUID); diff --git a/JotunnModStub/Skeleton/SkeletonBarber.cs b/JotunnModStub/Skeleton/SkeletonBarber.cs new file mode 100644 index 0000000..9419cca --- /dev/null +++ b/JotunnModStub/Skeleton/SkeletonBarber.cs @@ -0,0 +1,124 @@ +using HarmonyLib; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// The barber's own window, put to work for the Skeleton. Hair and beard are hidden on this + /// race, so the two hair arrows would change nothing anyone can see; for a Skeleton they step + /// through the bodies this tier has unlocked instead (normal, green, flames), the label + /// between them names the one worn, Apply keeps it and Cancel puts the old one back. + /// + /// The look is cosmetic - see SkeletonProgression.ResolveModel - and lives in m_customData, + /// which SkeletonRace copies to the ZDO so everyone else sees it too. + /// + public static class SkeletonBarber + { + // What was worn when the chair was sat in, for Cancel. + private static string lookOnOpen = ""; + + private static bool Active => + Player.m_localPlayer != null && SkeletonRace.IsSkeleton(); + + private static void Step(int direction) + { + Player player = Player.m_localPlayer; + int state = BossProgressionManager.GetCurrentProgressionState(); + var models = SkeletonProgression.UnlockedModels(state); + int at = models.IndexOf(SkeletonVisuals.GetModel(player, state)); + int next = (at + direction + models.Count) % models.Count; + SetLook(player, models[next]); + } + + private static void SetLook(Player player, string look) + { + player.m_customData[SkeletonVisuals.LookDataKey] = look; + + // Rebuild the body now, so the mirror-less barber still shows the result. + VisEquipment vis = player.GetComponent(); + if (vis != null) Traverse.Create(vis).Method("UpdateVisuals").GetValue(); + } + + private static string LabelFor(string model) + { + return ModText.Get(model == SkeletonProgression.FireModel ? "rov_msg_skeleton_look_flames" + : model == SkeletonProgression.PoisonModel ? "rov_msg_skeleton_look_green" + : "rov_msg_skeleton_look_normal"); + } + + [HarmonyPatch(typeof(PlayerCustomizaton), nameof(PlayerCustomizaton.ShowBarberGui))] + public static class ShowBarberGui_Patch + { + public static void Postfix() + { + if (!Active) return; + lookOnOpen = SkeletonVisuals.GetModel(Player.m_localPlayer, BossProgressionManager.GetCurrentProgressionState()); + } + } + + [HarmonyPatch(typeof(PlayerCustomizaton), "OnHairLeft")] + public static class OnHairLeft_Patch + { + public static bool Prefix() + { + if (!Active) return true; + Step(-1); + return false; + } + } + + [HarmonyPatch(typeof(PlayerCustomizaton), "OnHairRight")] + public static class OnHairRight_Patch + { + public static bool Prefix() + { + if (!Active) return true; + Step(1); + return false; + } + } + + // The beard arrows have nothing to do for a Skeleton. + [HarmonyPatch(typeof(PlayerCustomizaton), "OnBeardLeft")] + public static class OnBeardLeft_Patch + { + public static bool Prefix() => !Active; + } + + [HarmonyPatch(typeof(PlayerCustomizaton), "OnBeardRight")] + public static class OnBeardRight_Patch + { + public static bool Prefix() => !Active; + } + + [HarmonyPatch(typeof(PlayerCustomizaton), "OnCancel")] + public static class OnCancel_Patch + { + public static void Prefix() + { + if (!Active) return; + SetLook(Player.m_localPlayer, lookOnOpen); + } + } + + // The window refreshes its labels every frame, so the name is written after it. + [HarmonyPatch(typeof(PlayerCustomizaton), "Update")] + public static class Update_Patch + { + public static void Postfix(PlayerCustomizaton __instance) + { + if (!Active || !PlayerCustomizaton.IsBarberGuiVisible()) return; + + if (__instance.m_selectedHair != null) + { + __instance.m_selectedHair.text = LabelFor( + SkeletonVisuals.GetModel(Player.m_localPlayer, BossProgressionManager.GetCurrentProgressionState())); + } + if (__instance.m_beardPanel != null && __instance.m_beardPanel.gameObject.activeSelf) + { + __instance.m_beardPanel.gameObject.SetActive(false); + } + } + } + } +} diff --git a/JotunnModStub/Skeleton/SkeletonPatches.cs b/JotunnModStub/Skeleton/SkeletonPatches.cs index 6ffb291..e28239a 100644 --- a/JotunnModStub/Skeleton/SkeletonPatches.cs +++ b/JotunnModStub/Skeleton/SkeletonPatches.cs @@ -263,7 +263,10 @@ namespace RacesOfValheim int state = SkeletonVisuals.GetProgressionState(p); SkeletonProgression.SkeletonRules rules = SkeletonProgression.GetRules(state); - string targetBodyName = $"SkeletonBody_{rules.ModelPrefab}"; + // 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; @@ -282,21 +285,21 @@ namespace RacesOfValheim if (skeletonBodyTransform == null) { - GameObject skelPrefab = PrefabManager.Cache.GetPrefab(rules.ModelPrefab); + GameObject skelPrefab = PrefabManager.Cache.GetPrefab(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 " + rules.ModelPrefab, skelPrefab); + 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(rules.ModelPrefab); + WarnMissingModelOnce(modelPrefab); } if (skelPrefab != null) { @@ -312,7 +315,7 @@ namespace RacesOfValheim // Map bones by name Transform[] playerBones = __instance.m_bodyModel.bones; - LogBoneMapping(rules.ModelPrefab, newSmr, playerBones); + LogBoneMapping(modelPrefab, newSmr, playerBones); Transform[] newBones = new Transform[newSmr.bones.Length]; for (int i = 0; i < newSmr.bones.Length; i++) @@ -360,7 +363,7 @@ namespace RacesOfValheim // 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, rules.ModelPrefab); + SkeletonEyeGlow.Apply(__instance, modelPrefab); } } else diff --git a/JotunnModStub/Skeleton/SkeletonProgression.cs b/JotunnModStub/Skeleton/SkeletonProgression.cs index b8f4fb7..0045033 100644 --- a/JotunnModStub/Skeleton/SkeletonProgression.cs +++ b/JotunnModStub/Skeleton/SkeletonProgression.cs @@ -67,6 +67,28 @@ namespace RacesOfValheim /// /// The blocks are cumulative: each one only states what its boss adds or replaces. /// + /// + /// The bodies this tier has earned, plainest first. These are the same thresholds + /// GetRules switches the model at, so a look can never be worn before its boss is down. + /// + public static System.Collections.Generic.List UnlockedModels(int state) + { + var models = new System.Collections.Generic.List { BaseModel }; + if (state >= 2) models.Add(PoisonModel); // Eikthyr + if (state >= 5) models.Add(FireModel); // Moder + return models; + } + + /// + /// The body to build: the one chosen at the barber when it is still unlocked, otherwise + /// the tier's own. Cosmetic only - every rule in GetRules keeps following the tier. + /// + public static string ResolveModel(int state, string look) + { + if (!string.IsNullOrEmpty(look) && UnlockedModels(state).Contains(look)) return look; + return GetRules(state).ModelPrefab; + } + public static SkeletonRules GetRules(int state) { SkeletonRules rules = new SkeletonRules diff --git a/JotunnModStub/Skeleton/SkeletonRace.cs b/JotunnModStub/Skeleton/SkeletonRace.cs index 22bc3ec..94912d1 100644 --- a/JotunnModStub/Skeleton/SkeletonRace.cs +++ b/JotunnModStub/Skeleton/SkeletonRace.cs @@ -374,6 +374,14 @@ namespace RacesOfValheim if (nview != null && nview.IsValid()) { nview.GetZDO().Set("RacesOfValheim_SkeletonState", state); + + // The saved look goes on the ZDO so everyone else sees the same body. + Player.m_localPlayer.m_customData.TryGetValue(SkeletonVisuals.LookDataKey, out string savedLook); + savedLook = savedLook ?? ""; + if (nview.GetZDO().GetString(SkeletonVisuals.LookZdoKey, "") != savedLook) + { + nview.GetZDO().Set(SkeletonVisuals.LookZdoKey, savedLook); + } } // Manage Fake Foods @@ -442,7 +450,7 @@ namespace RacesOfValheim } // Flames on the skull, worn with the fire-tier model and nothing else. - headFlame.Apply(Player.m_localPlayer, SkeletonConfig.HeadFireVFXEnabled.Value && rules.ModelPrefab == SkeletonProgression.FireModel); + headFlame.Apply(Player.m_localPlayer, SkeletonConfig.HeadFireVFXEnabled.Value && SkeletonVisuals.GetModel(Player.m_localPlayer, state) == SkeletonProgression.FireModel); if (rules.FireAura) { diff --git a/JotunnModStub/Skeleton/SkeletonVisuals.cs b/JotunnModStub/Skeleton/SkeletonVisuals.cs index 5f82dbc..18ada8b 100644 --- a/JotunnModStub/Skeleton/SkeletonVisuals.cs +++ b/JotunnModStub/Skeleton/SkeletonVisuals.cs @@ -97,6 +97,37 @@ namespace RacesOfValheim return BossProgressionManager.GetCurrentProgressionState(); } + public const string LookZdoKey = "RacesOfValheim_SkeletonLook"; + public const string LookDataKey = "SkeletonLook"; + + /// + /// The body this player chose at the barber, "" if they never did. Read the same way as + /// the race: the ZDO for anyone on the network, m_customData for the menu preview. + /// + public static string GetLook(Player player) + { + if (player == null) return ""; + + ZNetView nview = player.GetComponent(); + if (nview != null && nview.IsValid()) + { + return nview.GetZDO().GetString(LookZdoKey, ""); + } + + if (player.m_customData != null && player.m_customData.TryGetValue(LookDataKey, out string look)) + { + return look; + } + + return ""; + } + + /// The model prefab to wear for this player at this tier, look applied. + public static string GetModel(Player player, int state) + { + return SkeletonProgression.ResolveModel(state, GetLook(player)); + } + /// /// Fire sources in preference order. BUILDING PIECES ONLY, and that is the bug fix. /// diff --git a/JotunnModStub/Translations/English/messages.json b/JotunnModStub/Translations/English/messages.json index d10effc..15c0c64 100644 --- a/JotunnModStub/Translations/English/messages.json +++ b/JotunnModStub/Translations/English/messages.json @@ -122,6 +122,9 @@ "rov_msg_skadi_there_are_already_these_within": "There are already $1 of these within a day's walk. The stone is spent.", "rov_msg_skeleton_has_already_had_one": "It has already had one.", "rov_msg_skeleton_have_been_resurrected_by_dark": "You have been resurrected by dark magic!", + "rov_msg_skeleton_look_normal": "Look: normal bones", + "rov_msg_skeleton_look_green": "Look: green bones", + "rov_msg_skeleton_look_flames": "Look: burning bones", "rov_msg_skeleton_mortal_food_disgusts": "Mortal food disgusts you.", "rov_msg_skeleton_nothing_standing_yet_wants_bone": "Nothing is standing yet. It wants bone.", "rov_msg_skeleton_pile_broken_fall_where_they": "The pile is broken. $1 fall where they stand.", diff --git a/JotunnModStub/Translations/Italian/messages.json b/JotunnModStub/Translations/Italian/messages.json index b3eedcc..a5e7084 100644 --- a/JotunnModStub/Translations/Italian/messages.json +++ b/JotunnModStub/Translations/Italian/messages.json @@ -122,6 +122,9 @@ "rov_msg_skadi_there_are_already_these_within": "Ce ne sono già $1 a una giornata di cammino. La pietra è esaurita.", "rov_msg_skeleton_has_already_had_one": "Ne ha già avuto uno.", "rov_msg_skeleton_have_been_resurrected_by_dark": "Sei stato resuscitato dalla magia oscura!", + "rov_msg_skeleton_look_normal": "Aspetto: ossa normali", + "rov_msg_skeleton_look_green": "Aspetto: ossa verdi", + "rov_msg_skeleton_look_flames": "Aspetto: ossa in fiamme", "rov_msg_skeleton_mortal_food_disgusts": "Il cibo dei mortali ti disgusta.", "rov_msg_skeleton_nothing_standing_yet_wants_bone": "Non c'è ancora niente in piedi. Vuole ossa.", "rov_msg_skeleton_pile_broken_fall_where_they": "Il mucchio è distrutto. $1 cadono dove si trovano.", diff --git a/JotunnModStub/ZdoVisualSync.cs b/JotunnModStub/ZdoVisualSync.cs index 93422ed..15fd55a 100644 --- a/JotunnModStub/ZdoVisualSync.cs +++ b/JotunnModStub/ZdoVisualSync.cs @@ -164,7 +164,7 @@ namespace RacesOfValheim // The burning skull, grown locally for whoever we are looking at. The tier is on the // ZDO, so this client can work out for itself whether they should be alight. - m_skeletonHeadFlame.Apply(m_player, SkeletonConfig.HeadFireVFXEnabled.Value && rules.ModelPrefab == SkeletonProgression.FireModel); + m_skeletonHeadFlame.Apply(m_player, SkeletonConfig.HeadFireVFXEnabled.Value && SkeletonVisuals.GetModel(m_player, state) == SkeletonProgression.FireModel); // Apply Scale Vector3 targetScale = rules.ScaleMultiplier; diff --git a/README.md b/README.md index 3c75e74..9f0c992 100644 --- a/README.md +++ b/README.md @@ -13,6 +13,10 @@ Support the mod: [Patreon — NandorTheModder](https://www.patreon.com/c/NandorT --- +## New in v1.5.3 + +Valheim 1.0's new creatures are on the menu. The Aswid can drink the seals, the moose, the Elaking and its Lantern, the Elaking Mole, the frozen Greydwarfs, the Jotun Warriors and Witch, the Barka, the Deep North Goblin and every Dvergr, and the Draugh can eat raw Seal Blubber and Moose Meat. The Aswid blood refinery takes the Elaking Hair Bundle as bone, and a Skeleton can now pick which of its unlocked looks to wear from the barber's chair. Full details in the [changelog](#v153). + ## New in v1.5.2 The mod's texts finally show for everyone who installs through a mod manager (r2modman, the Thunderstore Mod Manager, Gale). Those managers were taking the translation folders apart on install, so every name and message read like `[rov_...]`. Update, and the texts are back. Full details in the [changelog](#v152). @@ -431,6 +435,13 @@ Both halves have an off switch under `Factions` in Configuration Manager: **Fact ## Changelog +### v1.5.3 +- **New - Valheim 1.0's creatures for the Aswid:** killing and devouring any of these now feeds the Aswid. Seals (adult and pup), the Greydwarf_Frozen and the frozen Shaman give the stats of Seal Meat Soup, with the seal's trophy as icon. The Elaking and the Elaking Lantern give a Cooked Asksvin Tail. Moose and its calf give Cooked Moose Meat. The rest follow the house rule, health halved up to 150 and twice the health in seconds, now capped at 50 minutes: the Barka, the Jotun Warrior and the dual-wielding one, and the Deep North Goblin, which lasts 20 minutes like every Fuling. Fixed values: the Jotun Witch 120 health for 60 minutes, the Elaking Mole 100 for 30, the Deep North Dvergr 100 for 30, and every earlier Dvergr (mages included, the Ashlands one too) 90 for 25. The Dvergr were never edible before. +- **New - Raw Seal Blubber and Moose Meat for the Draugh:** the Draugh eats raw Seal Blubber for the stats of Seal Meat Soup, and raw Moose Meat for Cooked Moose Meat, keeping the raw item's name and icon. The Sverm and the Aswid blood refinery read the same table, so both now count them as flesh too. +- **New - Elaking Hair Bundle in the blood refinery:** it goes in the bone slot and is worth 20, the slot's whole capacity. +- **New - The Skeleton chooses its look at the barber:** sit in the barber's chair and the hair arrows step through the looks you have unlocked (normal, green from Eikthyr, flames from Moder), with its name between them. Apply keeps it, Cancel puts the old one back, and other players see it too. It is cosmetic only: abilities still follow the bosses you have defeated. Until you choose, you wear the highest one unlocked as before, and a choice stays until you change it. +- **Not tested in game yet:** every prefab name above was read off the 1.0.7 asset list, and the Dvergr and Elaking Mole icons are the nearest trophies. A wrong name only costs a warning in the log and that one creature stays inedible. + ### v1.5.2 - **Fix - Every text still showed as [rov_...] when installed through a mod manager:** 1.5.1 fixed the zip, but that was not the whole story. r2modman, the Thunderstore Mod Manager and Gale flatten any folder in a package they do not recognise, so the `Translations/English` and `Translations/Italian` folders came out as loose files next to the mod, the Italian copy of each file overwrote the English one, and the game found no translations at all. The package now keeps the mod inside the folder mod managers preserve, and the texts come through with their folders. Thanks to the players who kept reporting it and trying clean installs. diff --git a/manifest.json b/manifest.json index 574ca9b..ac2c5e8 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.5.2", + "version_number": "1.5.3", "website_url": "", "dependencies": [ "denikson-BepInExPack_Valheim-5.4.2333", From a047ea45cf20b770d2ea4f83f76fa87f3e0b1d57 Mon Sep 17 00:00:00 2001 From: Ferdinando Date: Thu, 1 Oct 2026 08:21:50 +0200 Subject: [PATCH 003/176] bugfix 01/10/26 + deepnorth food --- .claude/launch.json | 27 +++++++++++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 .claude/launch.json diff --git a/.claude/launch.json b/.claude/launch.json new file mode 100644 index 0000000..a0517b3 --- /dev/null +++ b/.claude/launch.json @@ -0,0 +1,27 @@ +{ + "version": "0.0.1", + "configurations": [ + { + "name": "nandor-museum", + "runtimeExecutable": "npm", + "runtimeArgs": [ + "--prefix", + "C:/Users/FERDINANDO/Desktop/JotunnModStub-master/NandorMuseum", + "run", + "dev" + ], + "port": 5190 + }, + { + "name": "nandor-museum-build", + "runtimeExecutable": "npm", + "runtimeArgs": [ + "--prefix", + "C:/Users/FERDINANDO/Desktop/JotunnModStub-master/NandorMuseum", + "run", + "preview" + ], + "port": 5191 + } + ] +} \ No newline at end of file From 9a3ab78666a1c20c49c57344dc406490f764543a Mon Sep 17 00:00:00 2001 From: Ferdinando Date: Sat, 3 Oct 2026 08:11:05 +0200 Subject: [PATCH 004/176] chore(release): v1.5.4 - Sverm troops keep their own place around the player and the boat Co-Authored-By: Claude Sonnet 5.5 --- JotunnModStub/Package/manifest.json | 2 +- JotunnModStub/RacesOfValheim.cs | 2 +- JotunnModStub/Sverm/SvermConfig.cs | 20 ++++ JotunnModStub/Sverm/SvermTroopFollow.cs | 121 ++++++++++++++++++++++++ README.md | 8 ++ manifest.json | 2 +- 6 files changed, 152 insertions(+), 3 deletions(-) create mode 100644 JotunnModStub/Sverm/SvermTroopFollow.cs diff --git a/JotunnModStub/Package/manifest.json b/JotunnModStub/Package/manifest.json index ac2c5e8..d5f4e66 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.5.3", + "version_number": "1.5.4", "website_url": "", "dependencies": [ "denikson-BepInExPack_Valheim-5.4.2333", diff --git a/JotunnModStub/RacesOfValheim.cs b/JotunnModStub/RacesOfValheim.cs index 79703b3..f6ff75c 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.5.3"; + public const string PluginVersion = "1.5.4"; private readonly Harmony harmony = new Harmony(PluginGUID); diff --git a/JotunnModStub/Sverm/SvermConfig.cs b/JotunnModStub/Sverm/SvermConfig.cs index 0a341ca..70b1ece 100644 --- a/JotunnModStub/Sverm/SvermConfig.cs +++ b/JotunnModStub/Sverm/SvermConfig.cs @@ -523,6 +523,26 @@ namespace RacesOfValheim /// public static readonly float TroopAlertRange = 25f; + /// + /// How far from its player a following troop stands, and how far it may fall behind before it + /// walks back to its place. Vanilla BaseAI.Follow sends every follower to the player's exact + /// position and stops it at three metres, so a squad piled onto one point, shoved each other + /// and shoved the player. See SvermTroopFollow. + /// + public static readonly float TroopFollowRadius = 4f; + + /// How far past its place a troop may drift before it moves again - the hysteresis + /// that keeps a squad from jittering. + public static readonly float TroopFollowSlack = 3f; + + /// How far from a boat's hull a following troop keeps, measured off the hull's + /// bounds. Close enough to be a bodyguard, far enough not to push the ship around. + public static readonly float TroopShipDistance = 5f; + + /// Past this many metres from its player a following troop gives up the walk and + /// goes home to its nest. + public static readonly float TroopFollowGiveUp = 30f; + /// How long a troop outlives the nest that hatched it, in seconds. public static readonly float TroopWitherSeconds = 60f; diff --git a/JotunnModStub/Sverm/SvermTroopFollow.cs b/JotunnModStub/Sverm/SvermTroopFollow.cs new file mode 100644 index 0000000..f7d0ab5 --- /dev/null +++ b/JotunnModStub/Sverm/SvermTroopFollow.cs @@ -0,0 +1,121 @@ +using System.Runtime.CompilerServices; +using HarmonyLib; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// How a Sverm troop walks beside its player. + /// + /// Vanilla BaseAI.Follow (read off the IL) sends the follower to the player's exact position, + /// runs it past ten metres and stops it inside three. Three troops therefore converged on one + /// point, pushed each other and pushed the player - into water, in one report - and on a boat + /// the player's position is on the deck, so they drove into the hull and spun the ship. + /// + /// Replaced for Sverm troops only (a RaisedThrall that answers to the Sverm race). Thralls, + /// Aswid's and the skeletons keep the vanilla walk. + /// + /// - Each troop has its own place: a fixed bearing off the player's back, taken from its ZDO id, + /// so the squad fans out instead of stacking. + /// - It walks to that place only when it has drifted TroopFollowSlack metres off it, and stops + /// within a metre and a half, so it stands still instead of shuffling. + /// - With the player on a ship, the places lie on a ring around the hull, TroopShipDistance + /// metres past its bounds. + /// - Further than TroopFollowGiveUp from the player, it stops following and goes home. + /// + public static class SvermTroopFollow + { + private const float ArriveDistance = 1.5f; + private const float RunDistance = 8f; + + private static readonly System.Reflection.MethodInfo MoveToMethod = + AccessTools.Method(typeof(BaseAI), "MoveTo", new[] { typeof(float), typeof(Vector3), typeof(float), typeof(bool) }); + + private class State { public bool Moving; } + + private static readonly ConditionalWeakTable States = new ConditionalWeakTable(); + + [HarmonyPatch(typeof(BaseAI), "Follow")] + public static class Sverm_TroopFollow_Patch + { + /// False replaces vanilla, true leaves it alone. + public static bool Prefix(BaseAI __instance, GameObject go, float dt) + { + if (go == null) return true; + + RaisedThrall thrall = __instance.GetComponent(); + if (thrall == null || thrall.m_commandingRace != SvermConfig.RaceId) return true; + + Player player = go.GetComponent(); + if (player == null) return true; + + Vector3 here = __instance.transform.position; + Vector3 playerPos = player.transform.position; + + if (Flat(playerPos - here).magnitude > SvermConfig.TroopFollowGiveUp) + { + // Stands it down and sends it to its nest, exactly as the command would. + thrall.SetFollowing(player, false, announce: false); + return false; + } + + Vector3 place = PlaceFor(__instance, player, playerPos); + float toPlace = Flat(place - here).magnitude; + + State state = States.GetOrCreateValue(__instance); + if (state.Moving ? toPlace < ArriveDistance : toPlace < SvermConfig.TroopFollowSlack) state.Moving = false; + else state.Moving = true; + + if (!state.Moving) + { + __instance.StopMoving(); + return false; + } + + // Protected on BaseAI, so reached the way RaisedThrall reaches SetPatrolPoint. If it + // ever goes missing, vanilla's walk is the fallback rather than a frozen squad. + if (MoveToMethod == null) return true; + + MoveToMethod.Invoke(__instance, new object[] { dt, place, 0f, toPlace > RunDistance }); + return false; + } + } + + /// Where this troop should stand: behind the player, or round the player's ship. + private static Vector3 PlaceFor(BaseAI ai, Player player, Vector3 playerPos) + { + ZNetView nview = ai.GetComponent(); + int hash = nview != null && nview.IsValid() ? nview.GetZDO().m_uid.GetHashCode() : ai.GetInstanceID(); + + // Seven bearings, twenty degrees apart, fanned across the back half. Troops hatched + // together draw different ZDO ids, so they mostly land on different bearings. + float bearing = 180f + (((hash % 7) + 7) % 7 - 3) * 20f; + + Ship ship = player.GetControlledShip(); + if (ship == null) ship = player.GetStandingOnShip(); + + if (ship != null && ship.m_floatCollider != null) + { + Bounds bounds = ship.m_floatCollider.bounds; + float reach = Mathf.Max(bounds.extents.x, bounds.extents.z) + SvermConfig.TroopShipDistance; + return Ring(bounds.center, ship.transform.eulerAngles.y, bearing, reach, playerPos.y); + } + + return Ring(playerPos, player.transform.eulerAngles.y, bearing, SvermConfig.TroopFollowRadius, playerPos.y); + } + + private static Vector3 Ring(Vector3 center, float facingDegrees, float bearingDegrees, float radius, float y) + { + Quaternion turn = Quaternion.Euler(0f, facingDegrees + bearingDegrees, 0f); + Vector3 point = center + turn * Vector3.forward * radius; + point.y = y; + return point; + } + + private static Vector3 Flat(Vector3 v) + { + v.y = 0f; + return v; + } + } +} diff --git a/README.md b/README.md index 9f0c992..76a64b4 100644 --- a/README.md +++ b/README.md @@ -13,6 +13,10 @@ Support the mod: [Patreon — NandorTheModder](https://www.patreon.com/c/NandorT --- +## New in v1.5.4 + +Sverm troops no longer crowd you. Following soldiers used to run onto your exact spot, shove each other and push you around, even into the water, and on a boat they drove into the hull and spun it in circles. Each one now keeps its own place around you, and around the hull when you sail. Full details in the [changelog](#v154). + ## New in v1.5.3 Valheim 1.0's new creatures are on the menu. The Aswid can drink the seals, the moose, the Elaking and its Lantern, the Elaking Mole, the frozen Greydwarfs, the Jotun Warriors and Witch, the Barka, the Deep North Goblin and every Dvergr, and the Draugh can eat raw Seal Blubber and Moose Meat. The Aswid blood refinery takes the Elaking Hair Bundle as bone, and a Skeleton can now pick which of its unlocked looks to wear from the barber's chair. Full details in the [changelog](#v153). @@ -435,6 +439,10 @@ Both halves have an off switch under `Factions` in Configuration Manager: **Fact ## Changelog +### v1.5.4 +- **Fix - Sverm troops piled onto the player and pushed boats around:** the game sends every follower to the exact spot where you stand and stops it three metres away, so a squad of three converged on one point, shoved each other and shoved you, in one report into the water. On a boat your spot is on the deck, so they drove into the hull and spun the ship in circles. Each troop now has its own place, about 4 m behind you and fanned out from the others, and only walks back to it once it has drifted 3 m away, so it stands still instead of shuffling. While you are on a ship the places lie on a ring 5 m outside the hull. Past 30 m from you a troop stops following and goes home to its nest. Thralls, the Aswid's thralls and skeletons keep the game's own following. Thanks to the player who reported it. +- **Not tested in game yet:** the distances are estimates, and `SvermConfig` holds them if they need tuning. + ### v1.5.3 - **New - Valheim 1.0's creatures for the Aswid:** killing and devouring any of these now feeds the Aswid. Seals (adult and pup), the Greydwarf_Frozen and the frozen Shaman give the stats of Seal Meat Soup, with the seal's trophy as icon. The Elaking and the Elaking Lantern give a Cooked Asksvin Tail. Moose and its calf give Cooked Moose Meat. The rest follow the house rule, health halved up to 150 and twice the health in seconds, now capped at 50 minutes: the Barka, the Jotun Warrior and the dual-wielding one, and the Deep North Goblin, which lasts 20 minutes like every Fuling. Fixed values: the Jotun Witch 120 health for 60 minutes, the Elaking Mole 100 for 30, the Deep North Dvergr 100 for 30, and every earlier Dvergr (mages included, the Ashlands one too) 90 for 25. The Dvergr were never edible before. - **New - Raw Seal Blubber and Moose Meat for the Draugh:** the Draugh eats raw Seal Blubber for the stats of Seal Meat Soup, and raw Moose Meat for Cooked Moose Meat, keeping the raw item's name and icon. The Sverm and the Aswid blood refinery read the same table, so both now count them as flesh too. diff --git a/manifest.json b/manifest.json index ac2c5e8..d5f4e66 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.5.3", + "version_number": "1.5.4", "website_url": "", "dependencies": [ "denikson-BepInExPack_Valheim-5.4.2333", From 5113225981e6ee6dbd6e8b1f272484a6bad93e56 Mon Sep 17 00:00:00 2001 From: Ferdinando Date: Sun, 4 Oct 2026 07:31:16 +0200 Subject: [PATCH 005/176] chore(release): v1.5.5 - Sverm Gjall bombs spare the player and the ticks they hatch are tame Co-Authored-By: Claude Sonnet 5.5 --- JotunnModStub/Package/manifest.json | 2 +- JotunnModStub/RacesOfValheim.cs | 2 +- JotunnModStub/Sverm/SvermGjallPatches.cs | 102 +++++++++++++++++++++++ README.md | 9 ++ manifest.json | 2 +- 5 files changed, 114 insertions(+), 3 deletions(-) create mode 100644 JotunnModStub/Sverm/SvermGjallPatches.cs diff --git a/JotunnModStub/Package/manifest.json b/JotunnModStub/Package/manifest.json index d5f4e66..f25edd0 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.5.4", + "version_number": "1.5.5", "website_url": "", "dependencies": [ "denikson-BepInExPack_Valheim-5.4.2333", diff --git a/JotunnModStub/RacesOfValheim.cs b/JotunnModStub/RacesOfValheim.cs index f6ff75c..7d6b88a 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.5.4"; + public const string PluginVersion = "1.5.5"; private readonly Harmony harmony = new Harmony(PluginGUID); diff --git a/JotunnModStub/Sverm/SvermGjallPatches.cs b/JotunnModStub/Sverm/SvermGjallPatches.cs new file mode 100644 index 0000000..0251861 --- /dev/null +++ b/JotunnModStub/Sverm/SvermGjallPatches.cs @@ -0,0 +1,102 @@ +using System.Collections.Generic; +using HarmonyLib; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// What a Sverm Gjall's bombs do once they land: no friendly fire, and the ticks they hatch are ours. + /// + /// Two reports in one. The Gjall's bile bomb is an AOE projectile, and Projectile.DoAOE (read off + /// the IL) only spares a victim when m_noDamageFriendly is set on the projectile - the vanilla + /// Gjall never needed it, because nothing it fights has friends. Ours has the player, so a bomb + /// aimed at a turtle killed the player on a boat beside it. And the ticks the bomb spawns + /// (Projectile.SpawnOnHit) are plain wild Ticks, hostile to everyone, the Gjall that threw them + /// included. + /// + /// Both are keyed on the projectile's owner being a Sverm troop (a RaisedThrall that answers to the + /// Sverm race), so a wild Gjall in the Mistlands behaves exactly as before. + /// + public static class SvermGjallPatches + { + /// How long a hatched tick lives. Wild ones never despawn, and ours would pile up. + private const float TickLifetime = 45f; + + private static bool IsSvermTroop(Character owner) + { + if (owner == null) return false; + RaisedThrall thrall = owner.GetComponent(); + return thrall != null && thrall.m_commandingRace == SvermConfig.RaceId; + } + + // ── Friendly fire ──────────────────────────────────────────────────── + + [HarmonyPatch(typeof(Projectile), nameof(Projectile.Setup))] + public static class Sverm_Projectile_Setup_Patch + { + public static void Postfix(Projectile __instance, Character ___m_owner) + { + if (IsSvermTroop(___m_owner)) __instance.m_noDamageFriendly = true; + } + } + + // ── The ticks ──────────────────────────────────────────────────────── + + // Characters that came to life while a Sverm projectile was spawning its payload. Awake has + // run on every component by the time SpawnOnHit returns, which is when they are tamed. + private static bool collecting; + private static readonly List born = new List(); + + [HarmonyPatch(typeof(Projectile), "SpawnOnHit")] + public static class Sverm_Projectile_SpawnOnHit_Patch + { + public static void Prefix(Character ___m_owner) + { + born.Clear(); + collecting = IsSvermTroop(___m_owner); + } + + public static void Postfix() + { + collecting = false; + + foreach (Character spawned in born) + { + if (spawned == null || spawned.IsPlayer() || spawned.IsDead()) continue; + + spawned.SetTamed(true); + spawned.gameObject.AddComponent().m_seconds = TickLifetime; + } + born.Clear(); + } + } + + [HarmonyPatch(typeof(Character), "Awake")] + public static class Sverm_Character_Awake_Patch + { + public static void Postfix(Character __instance) + { + if (collecting) born.Add(__instance); + } + } + } + + /// A tick born of a Sverm Gjall's bomb: tame, and gone after a short while. + public class SvermGjallTickLife : MonoBehaviour + { + public float m_seconds = 45f; + + private void Start() + { + Invoke(nameof(Expire), m_seconds); + } + + private void Expire() + { + ZNetView nview = GetComponent(); + if (nview == null || !nview.IsValid() || !nview.IsOwner()) return; + + ZNetScene.instance.Destroy(gameObject); + } + } +} diff --git a/README.md b/README.md index 76a64b4..c514cc7 100644 --- a/README.md +++ b/README.md @@ -13,6 +13,10 @@ Support the mod: [Patreon — NandorTheModder](https://www.patreon.com/c/NandorT --- +## New in v1.5.5 + +A Sverm Gjall no longer kills you with its own bombs, and the ticks it hatches are on your side. Full details in the [changelog](#v155). + ## New in v1.5.4 Sverm troops no longer crowd you. Following soldiers used to run onto your exact spot, shove each other and push you around, even into the water, and on a boat they drove into the hull and spun it in circles. Each one now keeps its own place around you, and around the hull when you sail. Full details in the [changelog](#v154). @@ -439,6 +443,11 @@ Both halves have an off switch under `Factions` in Configuration Manager: **Fact ## Changelog +### v1.5.5 +- **Fix - a Sverm Gjall's bombs hurt the player:** the Gjall's bile bomb damages everything in its blast unless the projectile is flagged as non-friendly-damaging, which a wild Gjall never needed. A bomb thrown at a turtle killed a player on a boat beside it. Bombs thrown by a Sverm troop now spare the player and the player's tames; wild creatures still take the damage. +- **Fix - the ticks a Sverm Gjall hatches were hostile to everyone:** they were ordinary wild ticks and attacked the player, the tames and the Gjall itself. Ticks hatched by a Sverm Gjall's bomb are now tame, and disappear after 45 seconds. A wild Gjall is unchanged. Thanks to the player who reported it. +- **Not tested in game yet.** + ### v1.5.4 - **Fix - Sverm troops piled onto the player and pushed boats around:** the game sends every follower to the exact spot where you stand and stops it three metres away, so a squad of three converged on one point, shoved each other and shoved you, in one report into the water. On a boat your spot is on the deck, so they drove into the hull and spun the ship in circles. Each troop now has its own place, about 4 m behind you and fanned out from the others, and only walks back to it once it has drifted 3 m away, so it stands still instead of shuffling. While you are on a ship the places lie on a ring 5 m outside the hull. Past 30 m from you a troop stops following and goes home to its nest. Thralls, the Aswid's thralls and skeletons keep the game's own following. Thanks to the player who reported it. - **Not tested in game yet:** the distances are estimates, and `SvermConfig` holds them if they need tuning. diff --git a/manifest.json b/manifest.json index d5f4e66..f25edd0 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.5.4", + "version_number": "1.5.5", "website_url": "", "dependencies": [ "denikson-BepInExPack_Valheim-5.4.2333", From 9690d4d2a1031013af37b8c2887d484d6c76e403 Mon Sep 17 00:00:00 2001 From: Ferdinando Date: Sun, 4 Oct 2026 07:34:11 +0200 Subject: [PATCH 006/176] docs: drop the 'not tested in game yet' notes from the public changelog Co-Authored-By: Claude Sonnet 5.5 --- README.md | 3 --- 1 file changed, 3 deletions(-) diff --git a/README.md b/README.md index c514cc7..a70a5ba 100644 --- a/README.md +++ b/README.md @@ -446,18 +446,15 @@ Both halves have an off switch under `Factions` in Configuration Manager: **Fact ### v1.5.5 - **Fix - a Sverm Gjall's bombs hurt the player:** the Gjall's bile bomb damages everything in its blast unless the projectile is flagged as non-friendly-damaging, which a wild Gjall never needed. A bomb thrown at a turtle killed a player on a boat beside it. Bombs thrown by a Sverm troop now spare the player and the player's tames; wild creatures still take the damage. - **Fix - the ticks a Sverm Gjall hatches were hostile to everyone:** they were ordinary wild ticks and attacked the player, the tames and the Gjall itself. Ticks hatched by a Sverm Gjall's bomb are now tame, and disappear after 45 seconds. A wild Gjall is unchanged. Thanks to the player who reported it. -- **Not tested in game yet.** ### v1.5.4 - **Fix - Sverm troops piled onto the player and pushed boats around:** the game sends every follower to the exact spot where you stand and stops it three metres away, so a squad of three converged on one point, shoved each other and shoved you, in one report into the water. On a boat your spot is on the deck, so they drove into the hull and spun the ship in circles. Each troop now has its own place, about 4 m behind you and fanned out from the others, and only walks back to it once it has drifted 3 m away, so it stands still instead of shuffling. While you are on a ship the places lie on a ring 5 m outside the hull. Past 30 m from you a troop stops following and goes home to its nest. Thralls, the Aswid's thralls and skeletons keep the game's own following. Thanks to the player who reported it. -- **Not tested in game yet:** the distances are estimates, and `SvermConfig` holds them if they need tuning. ### v1.5.3 - **New - Valheim 1.0's creatures for the Aswid:** killing and devouring any of these now feeds the Aswid. Seals (adult and pup), the Greydwarf_Frozen and the frozen Shaman give the stats of Seal Meat Soup, with the seal's trophy as icon. The Elaking and the Elaking Lantern give a Cooked Asksvin Tail. Moose and its calf give Cooked Moose Meat. The rest follow the house rule, health halved up to 150 and twice the health in seconds, now capped at 50 minutes: the Barka, the Jotun Warrior and the dual-wielding one, and the Deep North Goblin, which lasts 20 minutes like every Fuling. Fixed values: the Jotun Witch 120 health for 60 minutes, the Elaking Mole 100 for 30, the Deep North Dvergr 100 for 30, and every earlier Dvergr (mages included, the Ashlands one too) 90 for 25. The Dvergr were never edible before. - **New - Raw Seal Blubber and Moose Meat for the Draugh:** the Draugh eats raw Seal Blubber for the stats of Seal Meat Soup, and raw Moose Meat for Cooked Moose Meat, keeping the raw item's name and icon. The Sverm and the Aswid blood refinery read the same table, so both now count them as flesh too. - **New - Elaking Hair Bundle in the blood refinery:** it goes in the bone slot and is worth 20, the slot's whole capacity. - **New - The Skeleton chooses its look at the barber:** sit in the barber's chair and the hair arrows step through the looks you have unlocked (normal, green from Eikthyr, flames from Moder), with its name between them. Apply keeps it, Cancel puts the old one back, and other players see it too. It is cosmetic only: abilities still follow the bosses you have defeated. Until you choose, you wear the highest one unlocked as before, and a choice stays until you change it. -- **Not tested in game yet:** every prefab name above was read off the 1.0.7 asset list, and the Dvergr and Elaking Mole icons are the nearest trophies. A wrong name only costs a warning in the log and that one creature stays inedible. ### v1.5.2 - **Fix - Every text still showed as [rov_...] when installed through a mod manager:** 1.5.1 fixed the zip, but that was not the whole story. r2modman, the Thunderstore Mod Manager and Gale flatten any folder in a package they do not recognise, so the `Translations/English` and `Translations/Italian` folders came out as loose files next to the mod, the Italian copy of each file overwrote the English one, and the game found no translations at all. The package now keeps the mod inside the folder mod managers preserve, and the texts come through with their folders. Thanks to the players who kept reporting it and trying clean installs. From 7a863b07a650edad7ca662336cbba2604790afa0 Mon Sep 17 00:00:00 2001 From: Ferdinando Date: Mon, 5 Oct 2026 11:39:38 +0200 Subject: [PATCH 007/176] bugfix 05/10/26 --- JotunnModStub/Sverm/SvermGjallPatches.cs | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/JotunnModStub/Sverm/SvermGjallPatches.cs b/JotunnModStub/Sverm/SvermGjallPatches.cs index 0251861..6168866 100644 --- a/JotunnModStub/Sverm/SvermGjallPatches.cs +++ b/JotunnModStub/Sverm/SvermGjallPatches.cs @@ -29,6 +29,28 @@ namespace RacesOfValheim return thrall != null && thrall.m_commandingRace == SvermConfig.RaceId; } + // ── The nest is immune to its own brood ────────────────────────────── + + /// A Sverm troop, or a tick one of them hatched: anything the colony itself put on the field. + private static bool IsColonyMember(Character attacker) + { + if (attacker == null) return false; + return IsSvermTroop(attacker) || attacker.GetComponent() != null; + } + + // RPC_Damage and not Damage: that is where the hit lands on the piece's owner, whoever threw it. + // A raid is where it showed - bombs, ticks' bursts and troop swings all go through here. + [HarmonyPatch(typeof(WearNTear), "RPC_Damage")] + public static class Sverm_Nest_BroodImmunity_Patch + { + public static bool Prefix(WearNTear __instance, HitData hit) + { + if (hit == null || __instance.GetComponent() == null) return true; + + return !IsColonyMember(hit.GetAttacker()); + } + } + // ── Friendly fire ──────────────────────────────────────────────────── [HarmonyPatch(typeof(Projectile), nameof(Projectile.Setup))] From 553303d0fd62ab719b9bbc0cb1937dd65a7cc1ce Mon Sep 17 00:00:00 2001 From: Ferdinando Date: Tue, 6 Oct 2026 11:36:18 +0200 Subject: [PATCH 008/176] bugfix 06/10/26 + bone ship --- JotunnModStub/BoneShip/BoneShip.cs | 368 +++++++++ JotunnModStub/BoneShip/BoneShipArcher.cs | 54 ++ JotunnModStub/BoneShip/BoneShipFittings.cs | 572 ++++++++++++++ JotunnModStub/BoneShip/BoneShipRoster.cs | 709 ++++++++++++++++++ JotunnModStub/BoneShip/BoneShipRowers.cs | 480 ++++++++++++ JotunnModStub/BoneShip/BoneShipSail.cs | 178 +++++ JotunnModStub/BoneShip/ShipMount.cs | 392 ++++++++++ JotunnModStub/Fenrir/FenrirBehaviors.cs | 108 ++- JotunnModStub/Fenrir/FenrirFormShared.cs | 61 ++ JotunnModStub/Package/manifest.json | 2 +- JotunnModStub/RacesOfValheim.cs | 2 +- JotunnModStub/RaisedThrall.cs | 221 +++++- JotunnModStub/Skadi/SkadiRace.cs | 9 - JotunnModStub/Skeleton/SkeletonRace.cs | 16 +- JotunnModStub/Sverm/SvermBlisterTick.cs | 12 + JotunnModStub/Sverm/SvermHiveGoods.cs | 8 +- JotunnModStub/Sverm/SvermWorker.cs | 56 ++ JotunnModStub/Translations/English/hover.json | 4 +- JotunnModStub/Translations/English/items.json | 9 +- .../Translations/English/messages.json | 7 +- JotunnModStub/Translations/Italian/hover.json | 4 +- JotunnModStub/Translations/Italian/items.json | 9 +- .../Translations/Italian/messages.json | 7 +- JotunnModStub/Trol/TrolFoodDebug.cs | 74 -- JotunnModStub/Trol/TrolFoodDebugUI.cs | 67 -- README.md | 9 + manifest.json | 2 +- 27 files changed, 3210 insertions(+), 230 deletions(-) create mode 100644 JotunnModStub/BoneShip/BoneShip.cs create mode 100644 JotunnModStub/BoneShip/BoneShipArcher.cs create mode 100644 JotunnModStub/BoneShip/BoneShipFittings.cs create mode 100644 JotunnModStub/BoneShip/BoneShipRoster.cs create mode 100644 JotunnModStub/BoneShip/BoneShipRowers.cs create mode 100644 JotunnModStub/BoneShip/BoneShipSail.cs create mode 100644 JotunnModStub/BoneShip/ShipMount.cs delete mode 100644 JotunnModStub/Trol/TrolFoodDebug.cs delete mode 100644 JotunnModStub/Trol/TrolFoodDebugUI.cs diff --git a/JotunnModStub/BoneShip/BoneShip.cs b/JotunnModStub/BoneShip/BoneShip.cs new file mode 100644 index 0000000..cb02079 --- /dev/null +++ b/JotunnModStub/BoneShip/BoneShip.cs @@ -0,0 +1,368 @@ +using System.Collections.Generic; +using System.Reflection; +using HarmonyLib; +using Jotunn.Configs; +using Jotunn.Entities; +using Jotunn.Managers; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// The Bone Ship, first piece: the small one, a clone of the Karve. See Skeleton_BoneShip.txt, sections + /// 2, 10 and 11 - every number and node name below was read off the game, not remembered. + /// + /// WHAT THIS STEP DOES + /// - A new buildable ship, BoneKarve, cloned from "Karve" so the vanilla one is left alone. + /// - A hull that is rotten from the first day: WearNTear is pointed at the prefab's own worn hull as + /// its "new" one, so full health shows the worn model, and a light tint goes on top. The game's + /// SetHealthVisual guards the equal case (it only turns a visual off when it differs from the new + /// one), so m_new == m_worn is a supported shape, not a trick. The fresh hull is switched off in + /// the prefab or both would show at once. + /// - It goes where the sails are not: the wind-independent push (SailK) and a sail that never + /// unfurls, in BoneShipSailForcePatch and BoneShipSailPatch below. + /// + /// WHAT IS NOT HERE YET: the torn sail texture, the bones, the rowers, the figurehead, the altar, the + /// roster and the archers. Each is its own step. The archer's mount already exists (ShipMount.cs). + /// + public static class BoneShip + { + // Every vanilla ship but the Raft has a bone version (the design, 2026-10-05). The names are what + // ShipMountTest's post table and the rest of the Bone Ship know them by. + public const string KarveName = "BoneKarve"; + public const string LongshipName = "BoneLongship"; + public const string AshlandsName = "BoneAshlands"; + + /// The hover name of the altar on the deck, where bone fragments are offered. + public const string AltarName = "$rov_piece_boneship_altar_name"; + + /// + /// Places in the roster, melee and archers, by ship (Skeleton_BoneShip.txt 5.7). The small ship is + /// the pile's idea at half size, the Longship a pile's 4+4, and the Ashlands ship - the biggest hull, + /// three times the Karve's mass - 6+6 (decided). Constants, because the answer is a balance call. + /// The rowers' seats follow: one per place, half on each side. + /// + private const int KarveMelee = 2, KarveRanged = 2; + private const int LongshipMelee = 4, LongshipRanged = 4; + private const int AshlandsMelee = 6, AshlandsRanged = 6; + + public static int MeleeCapOf(Component ship) => + IsKarve(ship) ? KarveMelee : IsAshlands(ship) ? AshlandsMelee : LongshipMelee; + + public static int RangedCapOf(Component ship) => + IsKarve(ship) ? KarveRanged : IsAshlands(ship) ? AshlandsRanged : LongshipRanged; + + private static bool IsAshlands(Component ship) + { + return ship != null && ship.name.StartsWith(AshlandsName); + } + + private static bool IsKarve(Component ship) + { + return ship != null && ship.name.StartsWith(KarveName); + } + + public static bool IsKarveShip(Component ship) => IsKarve(ship); + + /// Half the length of the hull, read from the OnboardTrigger every ship carries. + public static float HalfLengthOf(Component ship) + { + Transform trigger = ship != null ? ship.transform.Find("OnboardTrigger") : null; + BoxCollider box = trigger != null ? trigger.GetComponent() : null; + return box != null ? Mathf.Abs(box.size.z * trigger.localScale.z) * 0.5f : 0f; + } + + /// Our prefab, the vanilla one it is cloned from, and the localisation key stem. + private struct Spec + { + public string Name; + public string Source; + public string KeyStem; + public Spec(string name, string source, string keyStem) { Name = name; Source = source; KeyStem = keyStem; } + } + + private static readonly Spec[] Specs = + { + new Spec(KarveName, "Karve", "karve"), + new Spec(LongshipName, "VikingShip", "longship"), + new Spec(AshlandsName, "VikingShip_Ashlands", "ashlands"), + }; + + private static string DisplayKey(Spec s) => "$rov_piece_boneship_" + s.KeyStem + "_name"; + private static string DescriptionKey(Spec s) => "$rov_piece_boneship_" + s.KeyStem + "_desc"; + + /// + /// What the oarsmen push with, as a share of what a perfect wind would. Wind direction and strength + /// no longer matter, so this is the whole sail. The vanilla factor is angle * lerp(0.25, 1, wind): + /// 1.0 is the best a real wind can ever do, and a good breeze on a good heading is about 0.7. Measured + /// on a Karve at Full: 0.46 gave 4.5 m/s. 0.75 is the proposal; to be tuned with an F8 at cruise. + /// + public const float SailK = 0.75f; + + /// The key part of every bone ship's recipe: the swamp's Wishbone. One per ship. + private const string WishbonePrefab = "Wishbone"; + + /// + /// What each costs. The Wishbone is the decided part; the rest are PLACEHOLDERS that grow with the + /// hull, and the Ashlands one asks for the fine wood a late-game ship would. The workbench requirement + /// comes from the vanilla ship each one is cloned from. Open to every race: nothing here, or on the + /// pieces, asks who is building. + /// + private static RequirementConfig[] CostOf(string name) + { + switch (name) + { + case KarveName: + return new[] + { + new RequirementConfig(WishbonePrefab, 1, 0, true), + new RequirementConfig("Wood", 30, 0, true), + new RequirementConfig("BoneFragments", 60, 0, true), + new RequirementConfig("Resin", 10, 0, true), + }; + + case LongshipName: + return new[] + { + new RequirementConfig(WishbonePrefab, 1, 0, true), + new RequirementConfig("Wood", 60, 0, true), + new RequirementConfig("BoneFragments", 120, 0, true), + new RequirementConfig("Resin", 20, 0, true), + }; + + default: // the Ashlands one + return new[] + { + new RequirementConfig(WishbonePrefab, 1, 0, true), + new RequirementConfig("FineWood", 60, 0, true), + new RequirementConfig("BoneFragments", 200, 0, true), + new RequirementConfig("Resin", 30, 0, true), + }; + } + } + + /// Multiplied into the worn hull's colour: a touch darker and greener on top of the worn one. + private static readonly Color RotTint = new Color(0.80f, 0.82f, 0.72f, 1f); + + public static bool IsBoneShip(Ship ship) + { + return ship != null && ship.GetComponent() != null; + } + + public static void Register() + { + BoneShipArcher.Register(); + + foreach (Spec spec in Specs) + { + RegisterShip(spec); + } + } + + private static void RegisterShip(Spec spec) + { + GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(spec.Name, spec.Source); + if (prefab == null) + { + Jotunn.Logger.LogWarning($"[BoneShip] Could not clone '{spec.Source}'; {spec.Name} is not registered."); + return; + } + + prefab.AddComponent(); + RotHull(prefab, spec.Name); + BoneShipSail.Apply(prefab, spec.Name); + + // The roster (the altar's bookkeeping and the troops) and the fittings (bones and the altar + // itself, built when the ship is in the world). The roster registers its RPC in Awake. + prefab.AddComponent(); + prefab.AddComponent(); + prefab.AddComponent(); // the oarsmen; how many show is the roster's count + + Piece piece = prefab.GetComponent(); + if (piece == null) + { + Jotunn.Logger.LogWarning($"[BoneShip] The cloned '{spec.Source}' has no Piece; {spec.Name} is not registered."); + return; + } + + piece.m_name = DisplayKey(spec); + piece.m_description = DescriptionKey(spec); + Sprite icon = BorrowIcon("TrophySkeleton"); + if (icon != null) piece.m_icon = icon; + + PieceManager.Instance.AddPiece(new CustomPiece(prefab, fixReference: false, new PieceConfig + { + Name = DisplayKey(spec), + Description = DescriptionKey(spec), + PieceTable = PieceTables.Hammer, + Category = PieceCategories.Misc, + CraftingStation = CraftingStations.Workbench, + Icon = icon, + Requirements = CostOf(spec.Name), + })); + } + + /// + /// Worn hull from full health. Every vanilla ship keeps its three hull visuals where WearNTear can + /// name them - m_new, m_worn, m_broken - whatever the node path (Karve: ship/visual_new, + /// Longship and Ashlands: ship/visual/hull_new), so the clone's own fields are read instead of a + /// path per ship. The fresh one is on in the prefab and has to be switched off, or both would show. + /// + private static void RotHull(GameObject prefab, string name) + { + WearNTear wear = prefab.GetComponent(); + if (wear == null || wear.m_new == null || wear.m_worn == null) + { + Jotunn.Logger.LogWarning($"[BoneShip] {name}: WearNTear has no new/worn hull to swap; the hull stays as it is."); + return; + } + + GameObject fresh = wear.m_new; + GameObject worn = wear.m_worn; + if (fresh == worn) return; + + wear.m_new = worn; + fresh.SetActive(false); + + Tint(worn, RotTint); + } + + /// + /// Darkens the Piece-shader materials of a hull. COPIES them, so the vanilla ship that shares the + /// asset keeps its colour; the water mask and anything without a plain colour are left alone. + /// + private static void Tint(GameObject root, Color tint) + { + Dictionary copies = new Dictionary(); + + foreach (Renderer renderer in root.GetComponentsInChildren(true)) + { + if (renderer == null || renderer is ParticleSystemRenderer) continue; + + Material[] shared = renderer.sharedMaterials; + bool changed = false; + + for (int i = 0; i < shared.Length; i++) + { + Material source = shared[i]; + if (source == null || source.shader == null) continue; + if (source.shader.name != "Custom/Piece" || !source.HasProperty("_Color")) continue; + + Material copy; + if (!copies.TryGetValue(source, out copy)) + { + copy = new Material(source) { name = source.name + "_bone" }; + copy.SetColor("_Color", source.GetColor("_Color") * tint); + copies[source] = copy; + } + + shared[i] = copy; + changed = true; + } + + if (changed) renderer.sharedMaterials = shared; + } + } + + public static void EnsureKnown(Player player) + { + if (player == null) return; + + Traverse traverse = Traverse.Create(player); + bool any = false; + + foreach (Spec spec in Specs) + { + GameObject prefab = PrefabManager.Instance.GetPrefab(spec.Name); + Piece piece = prefab != null ? prefab.GetComponent() : null; + if (piece == null) continue; + + traverse.Method("AddKnownPiece", piece).GetValue(); + any = true; + } + + if (any) traverse.Method("UpdateAvailablePiecesList").GetValue(); + } + + private static Sprite BorrowIcon(string prefabName) + { + ItemDrop drop = PrefabManager.Cache.GetPrefab(prefabName); + Sprite[] icons = drop != null && drop.m_itemData != null && drop.m_itemData.m_shared != null + ? drop.m_itemData.m_shared.m_icons + : null; + if (icons != null && icons.Length > 0 && icons[0] != null) return icons[0]; + + Jotunn.Logger.LogWarning($"[BoneShip] Could not borrow the icon from '{prefabName}'."); + return null; + } + } + + /// Marks a ship as one of ours. No logic: the patches below and the archers look for it. + public class BoneShipMarker : MonoBehaviour + { + } + + /// + /// The oarsmen's push, in place of the wind's. + /// + /// Ship.GetSailForce is, read off the IL: normalize(windDir + forward) * angleFactor * lerp(0.25, 1, + /// windIntensity) * m_sailForceFactor * sailSize, smoothed into m_sailForce over a second. The angle + /// factor is zero when the wind comes from ahead - that is what stops a vanilla ship dead. For a bone + /// ship the target is simply forward * m_sailForceFactor * sailSize * SailK, smoothed the same way with + /// the same two private fields, so the ship accelerates like a sailing one and the vanilla factor of + /// each hull (Karve 0.03, VikingShip 0.05, Ashlands 0.085) still scales the push. + /// + /// sailSize is 0 below Half, 0.5 at Half and 1 at Full, so Slow and Back are untouched: they were + /// never the wind's. + /// + [HarmonyPatch(typeof(Ship), "GetSailForce")] + public static class BoneShipSailForcePatch + { + private static readonly FieldInfo SailForce = AccessTools.Field(typeof(Ship), "m_sailForce"); + private static readonly FieldInfo WindChangeVelocity = AccessTools.Field(typeof(Ship), "m_windChangeVelocity"); + + public static bool Prefix(Ship __instance, float sailSize, ref Vector3 __result) + { + if (!BoneShip.IsBoneShip(__instance)) return true; + if (SailForce == null || WindChangeVelocity == null) return true; // changed under us: fall back to vanilla + + Vector3 current = (Vector3)SailForce.GetValue(__instance); + Vector3 velocity = (Vector3)WindChangeVelocity.GetValue(__instance); + + Vector3 target = __instance.transform.forward * (__instance.m_sailForceFactor * sailSize * BoneShip.SailK); + current = Vector3.SmoothDamp(current, target, ref velocity, 1f, 99f); + + SailForce.SetValue(__instance, current); + WindChangeVelocity.SetValue(__instance, velocity); + + __result = current; + return false; + } + } + + /// + /// The sail never unfurls and the mast never turns to the wind: there is no sailing to show. Half and + /// Full would otherwise raise a sail that is meant to hang in rags. UpdateSail is what runs + /// UpdateSailSize (the furl animation) and then turns the mast, so skipping it skips both. + /// What the sail looks like left alone is for the game to show: the prefab's own pose. + /// + [HarmonyPatch(typeof(Ship), "UpdateSail")] + public static class BoneShipSailPatch + { + public static bool Prefix(Ship __instance) + { + return !BoneShip.IsBoneShip(__instance); + } + } + + /// Makes the piece buildable without having to craft its parts first, like the bone pile. + [HarmonyPatch(typeof(Player), "OnSpawned")] + public static class BoneShipKnownPatch + { + public static void Postfix(Player __instance) + { + if (__instance != Player.m_localPlayer) return; + BoneShip.EnsureKnown(__instance); + } + } +} diff --git a/JotunnModStub/BoneShip/BoneShipArcher.cs b/JotunnModStub/BoneShip/BoneShipArcher.cs new file mode 100644 index 0000000..f69e4ca --- /dev/null +++ b/JotunnModStub/BoneShip/BoneShipArcher.cs @@ -0,0 +1,54 @@ +using UnityEngine; +using Jotunn.Managers; + +namespace RacesOfValheim +{ + /// + /// The archer a bone ship carries: the Bound Sentry, with the parts of it that make no sense on a deck + /// taken away and the ones that make it a ship's archer put in. + /// + /// A PREFAB OF ITS OWN, not the sentry with a component added when it is spawned. A component added in + /// play is not saved: after a reload the archer would come back with no mount, and stand on nothing. This + /// one is built with ShipMount and ShipBust already on it, so a reloaded archer finds its ship again by the + /// id in its own ZDO (see ShipMount) and the roster, which counts archers by that id, never has to rebuild + /// one that was already there. + /// + /// Taken away from the sentry: + /// - RaisedThrall. The orders (follow, wait, go home) are for troops; an archer on a mast of the ship + /// has no business following anyone, and E on it would send it after the player; + /// - CharacterDrop. The sentry gives back what it cost when it falls. This one is invulnerable while the + /// ship stands, and when the ship goes down it goes too - which must not pay out a soul stone and ten + /// bone fragments for every archer on every ship that sinks. + /// What stays is the bow, the AI and the tamed flag the spawner sets. + /// + public static class BoneShipArcher + { + public const string Name = "BoneShipArcher"; + + public static void Register() + { + // The sentry is registered by the bone pile, earlier in the same window. + GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(Name, SkeletonSentry.SentryName); + if (prefab == null) + { + Jotunn.Logger.LogWarning($"[BoneShip] Could not clone '{SkeletonSentry.SentryName}'; the ships have no archers."); + return; + } + + foreach (RaisedThrall thrall in prefab.GetComponentsInChildren(true)) + { + if (thrall != null) Object.DestroyImmediate(thrall); + } + + foreach (CharacterDrop drop in prefab.GetComponentsInChildren(true)) + { + if (drop != null) Object.DestroyImmediate(drop); + } + + prefab.AddComponent(); + prefab.AddComponent(); + + PrefabManager.Instance.AddPrefab(prefab); + } + } +} diff --git a/JotunnModStub/BoneShip/BoneShipFittings.cs b/JotunnModStub/BoneShip/BoneShipFittings.cs new file mode 100644 index 0000000..8674263 --- /dev/null +++ b/JotunnModStub/BoneShip/BoneShipFittings.cs @@ -0,0 +1,572 @@ +using System.Collections; +using System.Collections.Generic; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// What is bolted to a bone ship's hull: the bones along both rails and the bow, a few scattered on the + /// deck, and the ALTAR where bone fragments are offered (see BoneShipRoster). + /// + /// Built when the ship comes into the world, on every client, and not baked into the prefab - because + /// the three hulls are different shapes (the Karve's nodes bear no relation to the Longship's, and the + /// Ashlands ship's rope nodes are in another axis altogether) and the only generic way to find "the rail" + /// and "the deck" on all of them is to ask the physics engine. So a ray is dropped from above at points + /// scanned inward from outside the hull; the first thing it lands on is the rail's top, and a ray down the + /// centre line lands on the deck. The mast, the sail and the ropes are skipped by NAME up the hierarchy, + /// because the boom of the Karve is a collider that spans the whole beam at six metres. + /// + /// Everything is deterministic from the ship's own id, so every client builds the same bones. + /// + /// The bones are borrowed models (ModelBorrow strips them to renderers) cached once as templates and + /// copied, so a ship coming into view is a few dozen cheap instantiates and not a few dozen strips. + /// The model names that are not certain to exist - the bigger bones - are tried in order and whatever + /// resolves is logged once. + /// + public class BoneShipFittings : MonoBehaviour + { + private const string SkullPrefab = "TrophySkeleton"; + private const string FragmentsPrefab = "BoneFragments"; + // The bigger bones along the rail. A pickable from the forest crypts: it is a pile of remains meant to + // be seen, and it is certain to exist (the earlier guesses - bone_stack, skull_pile, a ribcage item - + // never were). Kept as a list so a second model is one more entry. + private static readonly string[] LargeBonePrefabs = { "Pickable_ForestCryptRemains01" }; + + internal const float RayStartHeight = 14f; + private const float RayLength = 32f; + // The offering chest next to the cargo hatch. Both are tunable by eye: ChestSize is the borrowed chest's + // widest side in metres (the model is measured and fitted by ModelBorrow), ChestHeight the box that is + // clicked and where the skull sits. + private const string ChestPrefab = "piece_chest_wood"; + private const float ChestSize = 0.85f; + private const float ChestHeight = 0.62f; + + private static GameObject s_holder; + private static readonly Dictionary s_templates = new Dictionary(); + private static bool s_reported; + + /// Where the altar ended up, in the ship's space. The roster keeps its hover on this. + public Switch Altar { get; private set; } + + /// One archer's place: where it stands on the ship (ship space) and whether it is a bust. + public struct ArcherPost + { + public Vector3 Local; + public bool Bust; + } + + /// + /// Where the ship's archers stand, found by ray once the hull's colliders exist. Null until then; the + /// roster waits for it. The small ship has one, at the bow; the large ones a pair, bow and stern. + /// All are busts - only the chest and up shows, a figurehead that shoots. + /// + public List ArcherPosts { get; private set; } + + private void Start() + { + StartCoroutine(Build()); + } + + private IEnumerator Build() + { + ZNetView nview = GetComponent(); + if (nview == null || !nview.IsValid()) yield break; // a placement ghost: no bones + + // One physics step so the hull's colliders exist for the rays. + yield return new WaitForFixedUpdate(); + yield return null; + + Bounds hull; + if (!TryHullExtent(out hull)) + { + Jotunn.Logger.LogWarning($"[BoneShip] '{name}' has no OnboardTrigger to measure; no bones were fitted."); + yield break; + } + + ReportModels(); + + System.Random rng = new System.Random(nview.GetZDO().m_uid.GetHashCode()); + float hx = hull.extents.x; + float hz = hull.extents.z; + + int rays = 0; + int placed = 0; + + // ---- both rails + int slots = Mathf.Max(4, Mathf.RoundToInt(2f * 0.92f * hz / 1.3f)); + for (int side = -1; side <= 1; side += 2) + { + for (int i = 0; i < slots; i++) + { + float t = slots == 1 ? 0.5f : i / (float)(slots - 1); + float z = Mathf.Lerp(-0.92f * hz, 0.92f * hz, t) + Range(rng, -0.25f, 0.25f); + + Vector3 point; + if (!FindRail(side, z, hx, out point, ref rays)) continue; + if (rays >= 40) { rays = 0; yield return null; } + + if (PlaceOnRail(point, side, rng)) placed++; + } + } + + // ---- the bow: a cluster on the centre line at the very front + Vector3 bow; + if (FindSurface(new Vector3(0f, RayStartHeight, 0.90f * hz), out bow)) + { + for (int k = 0; k < 3; k++) + { + Vector3 p = bow + new Vector3(Range(rng, -0.35f, 0.35f), 0.02f, Range(rng, -0.35f, 0.15f)); + if (Place(SkullPrefab, p, Range(rng, 0.30f, 0.42f), rng, 25f)) placed++; + } + } + + // ---- loose on the deck + int scatter = Mathf.Max(5, slots / 2); + for (int k = 0; k < scatter; k++) + { + float x = Range(rng, -0.55f, 0.55f) * hx; + float z = Range(rng, -0.8f, 0.8f) * hz; + if (NearHatch(x, z)) continue; // keep the cargo hatch and the offering chest beside it clear + + Vector3 point; + if (!FindSurface(new Vector3(x, RayStartHeight, z), out point)) continue; + if (Place(FragmentsPrefab, point + Vector3.up * 0.02f, Range(rng, 0.22f, 0.34f), rng, 180f)) placed++; + if (++rays >= 40) { rays = 0; yield return null; } + } + + BuildAltar(hz, rng); + FindArcherPosts(hz); + + Jotunn.Logger.LogInfo($"[BoneShip] '{name}': {placed} bones fitted, altar {(Altar != null ? "built" : "not built")}, " + + $"{ArcherPosts.Count} archer post(s)."); + } + + // ---------------------------------------------------------------- the archers' posts + + /// + /// Bow always; the large ships a second one at the stern. A point at the very tip of a hull is often + /// past the end of its colliders and the surface there climbs steeply, so any slope counts and, if + /// nothing is under the point, the search walks back toward the middle in 30 cm steps. + /// + private void FindArcherPosts(float hz) + { + ArcherPosts = new List(); + + AddPost(+0.93f * hz, -1f); + if (!BoneShip.IsKarveShip(this)) AddPost(-0.88f * hz, +1f); + } + + private void AddPost(float z, float towardMiddle) + { + for (float back = 0f; back <= 2.4f; back += 0.3f) + { + Vector3 point; + if (!FindSurface(new Vector3(0f, RayStartHeight, z + towardMiddle * back), out point, -1f)) continue; + + // A hand's breadth INTO the stem, not on top of it: the pelvis stub the bust leaves where the legs + // were then sits in the wood instead of resting on it, which is what made it look hung in air. + ArcherPosts.Add(new ArcherPost { Local = point + Vector3.down * 0.10f, Bust = true }); + Jotunn.Logger.LogInfo($"[BoneShip] '{name}': archer post at local ({point.x:F2}, {point.y:F2}, {point.z:F2}) " + + (back > 0f ? $"(walked back {back:F1} m from the tip)." : "(at the tip).")); + return; + } + + Jotunn.Logger.LogWarning($"[BoneShip] '{name}': no hull found for an archer at z {z:F1}; that post is empty."); + } + + // ---------------------------------------------------------------- the altar + + /// + /// The offering chest: a wooden chest standing on the deck NEXT TO THE CARGO HATCH. Every ship has + /// that hatch (the "piece_chest" Container, a flat square lid on the centre line: 0.9 m on the Karve, + /// 1.5 on the Longship, 1.8 on the Ashlands ship), so it is the one spot that is the same idea on all + /// three and the one a player already knows to look at. The first version put an altar of bones a + /// fixed distance down the centre line, which on the Karve is the stretch between the mast and the + /// helm, right where its rowers sit. + /// + /// Candidate places are tried beside the hatch, then behind it, then in front, and a candidate is + /// taken only if the whole footprint of the chest lies on FLAT deck at the hatch's own height - five + /// rays, the centre and four points around it - and is clear of the mast. A Karve is narrow and its + /// hull closes in toward the bow, so beside the hatch is not always deck; the rays are what say so. + /// + private void BuildAltar(float hz, System.Random rng) + { + Vector3 spot; + string where; + if (!FindChestSpot(hz, out spot, out where)) + { + Jotunn.Logger.LogWarning($"[BoneShip] '{name}': no flat deck found for the offering chest; it was not built."); + return; + } + + GameObject chest = new GameObject("BoneChest"); + chest.transform.SetParent(transform, false); + chest.transform.localPosition = spot; + + // Its front toward the stern, where the helm is and where a player stands when he looks around. + chest.transform.localRotation = Quaternion.Euler(0f, 180f, 0f); + chest.layer = LayerMask.NameToLayer("piece_nonsolid"); + + // The model: the wooden chest of the game, shut, with a skull on the lid so it reads as ours. + GameObject template = TemplateOf(ChestPrefab); + if (template != null) + { + GameObject model = Object.Instantiate(template, chest.transform, false); + model.name = ChestPrefab; + model.transform.localPosition = Vector3.zero; + model.transform.localScale = Vector3.one * ChestSize; + + // A chest prefab carries both an open and a closed lid; the container switches them at run + // time and the copy has no container, so the open one is turned off here. + foreach (Transform node in model.GetComponentsInChildren(true)) + { + if (node != model.transform && node.name.ToLowerInvariant() == "open") node.gameObject.SetActive(false); + } + } + else + { + Jotunn.Logger.LogWarning($"[BoneShip] No '{ChestPrefab}' to borrow; the offering chest is a box of fragments instead."); + Place(FragmentsPrefab, chest.transform, new Vector3(0f, 0f, 0f), 0.45f, rng, 10f); + } + + Place(SkullPrefab, chest.transform, new Vector3(0f, ChestHeight, 0f), 0.26f, rng, 8f); + + BoxCollider box = chest.AddComponent(); + box.center = new Vector3(0f, ChestHeight * 0.5f, 0f); + box.size = new Vector3(ChestSize * 0.95f, ChestHeight, ChestSize * 0.65f); + + Switch sw = chest.AddComponent(); + sw.m_name = BoneShip.AltarName; + Altar = sw; + + BoneShipRoster roster = GetComponent(); + if (roster != null) roster.Bind(sw); + + Jotunn.Logger.LogInfo($"[BoneShip] '{name}': offering chest {where} the cargo hatch, at local " + + $"({spot.x:F2}, {spot.y:F2}, {spot.z:F2})."); + } + + private bool FindChestSpot(float hz, out Vector3 spot, out string where) + { + spot = Vector3.zero; + where = ""; + + Transform hatch = transform.Find("piece_chest"); + BoxCollider hatchBox = hatch != null ? hatch.GetComponent() : null; + if (hatch == null) + { + // A ship with no cargo hatch: the old rule, a fixed place down the centre line. + where = "(no hatch found, fixed spot behind the middle) of"; + return FindSurface(new Vector3(0f, RayStartHeight, -0.42f * hz), out spot); + } + + Vector3 centre = hatch.localPosition; + float half = hatchBox != null ? Mathf.Abs(hatchBox.size.x * hatch.localScale.x) * 0.5f : 0.6f; + float gap = half + ChestSize * 0.5f + 0.1f; + + Vector3 hatchTop; + if (!FindSurface(new Vector3(centre.x, RayStartHeight, centre.z), out hatchTop)) return false; + float level = hatchTop.y; + + // Beside first (the hatch is on the centre line, so beside is out toward a rail), then behind and + // in front. The mast is on the centre line too, and its collider is skipped by the ray, so it is + // kept away from by position. + Vector2[] offsets = + { + new Vector2(+gap, 0f), new Vector2(-gap, 0f), new Vector2(0f, -gap), new Vector2(0f, +gap), + }; + string[] names = { "right of", "left of", "behind", "in front of" }; + + List masts = MastPositions(); + + for (int i = 0; i < offsets.Length; i++) + { + Vector2 c = new Vector2(centre.x + offsets[i].x, centre.z + offsets[i].y); + if (NearAny(masts, c, 0.7f)) continue; + if (!FlatDeckAround(c, level, ChestSize * 0.5f, out spot)) continue; + + where = names[i]; + return true; + } + + return false; + } + + /// + /// The chest's whole footprint is on deck: the centre and four points half a chest away all find a + /// surface that is flat and at the hatch's own height. Returns the centre's point. + /// + private bool FlatDeckAround(Vector2 c, float level, float reach, out Vector3 centre) + { + Vector2[] around = { Vector2.zero, new Vector2(reach, 0f), new Vector2(-reach, 0f), new Vector2(0f, reach), new Vector2(0f, -reach) }; + centre = Vector3.zero; + + for (int i = 0; i < around.Length; i++) + { + Vector3 p; + if (!FindSurface(new Vector3(c.x + around[i].x, RayStartHeight, c.y + around[i].y), out p, 0.85f)) return false; + if (Mathf.Abs(p.y - level) > 0.22f) return false; + if (i == 0) centre = p; + } + return true; + } + + /// Within a couple of metres of the cargo hatch, on any side: where the chest will stand. + private bool NearHatch(float x, float z) + { + Transform hatch = transform.Find("piece_chest"); + if (hatch == null) return false; + + Vector2 d = new Vector2(x - hatch.localPosition.x, z - hatch.localPosition.z); + return d.sqrMagnitude < 2.2f * 2.2f; + } + + private List MastPositions() + { + List masts = new List(); + foreach (Transform t in GetComponentsInChildren(true)) + { + if (t == transform || t.name.ToLowerInvariant() != "mast") continue; + + Vector3 local = transform.InverseTransformPoint(t.position); + masts.Add(new Vector2(local.x, local.z)); + } + return masts; + } + + private static bool NearAny(List points, Vector2 p, float distance) + { + foreach (Vector2 q in points) + { + if ((q - p).sqrMagnitude < distance * distance) return true; + } + return false; + } + + // ---------------------------------------------------------------- placing + + private bool PlaceOnRail(Vector3 point, int side, System.Random rng) + { + double roll = rng.NextDouble(); + Vector3 up = point + Vector3.up * 0.02f; + + if (roll < 0.38) return Place(SkullPrefab, up, Range(rng, 0.30f, 0.38f), rng, 14f); + if (roll < 0.70) return Place(FragmentsPrefab, up, Range(rng, 0.28f, 0.40f), rng, 180f); + if (roll < 0.88) + { + // The big ones lean outward over the side, like something draped there. + string large = LargestAvailable(); + return Place(large ?? SkullPrefab, up + new Vector3(side * 0.05f, 0f, 0f), large != null ? Range(rng, 0.7f, 1.0f) : 0.42f, rng, 20f); + } + return false; // a gap, on purpose: a hull that is covered evenly looks decorated, not grown over + } + + private bool Place(string prefabName, Vector3 localPosition, float size, System.Random rng, float tilt) + { + return Place(prefabName, transform, localPosition, size, rng, tilt); + } + + private static bool Place(string prefabName, Transform parent, Vector3 localPosition, float size, System.Random rng, float tilt) + { + GameObject template = TemplateOf(prefabName); + if (template == null) return false; + + GameObject copy = Object.Instantiate(template, parent, false); + copy.name = prefabName; + copy.transform.localPosition = localPosition; + copy.transform.localRotation = Quaternion.Euler(Range(rng, -tilt, tilt), (float)rng.NextDouble() * 360f, Range(rng, -tilt, tilt)); + copy.transform.localScale = Vector3.one * size; + return true; + } + + // ---------------------------------------------------------------- models + + /// + /// One stripped, 1 m model per source prefab, kept under an inactive holder that survives scene loads. + /// Built on first use. The holder being inactive is what keeps the template from ever being drawn. + /// + private static GameObject TemplateOf(string prefabName) + { + GameObject cached; + if (s_templates.TryGetValue(prefabName, out cached)) return cached; + + if (s_holder == null) + { + s_holder = new GameObject("RoV_BoneShipModels"); + s_holder.SetActive(false); + Object.DontDestroyOnLoad(s_holder); + } + + GameObject source = Jotunn.Managers.PrefabManager.Cache.GetPrefab(prefabName); + GameObject template = null; + if (source != null) + { + template = ModelBorrow.Attach(s_holder.transform, prefabName, source, Vector3.zero, Quaternion.identity, 1f, "BoneShip"); + StripEffects(template); + } + + s_templates[prefabName] = template; + return template; + } + + /// + /// A dropped item is dressed to be seen from far away: sparkles, a glow, sometimes a light and a + /// sound. ModelBorrow removes everything that THINKS (scripts, colliders, bodies, the network + /// view) but a particle system or a light does not think, it just plays - so the first version of + /// the fittings lit every bone on the hull like a drop on the ground, and the whole ship glowed. + /// + /// Only meshes are wanted. A node that carries an effect and no mesh goes with all its children; + /// otherwise just the effect components come off. A particle system cannot be removed while its + /// renderer is there, so the renderer goes first. + /// + internal static void StripEffects(GameObject template) + { + if (template == null) return; + + foreach (ParticleSystem system in template.GetComponentsInChildren(true)) + { + if (system == null) continue; + + GameObject node = system.gameObject; + if (node == template || node.GetComponent() != null || node.GetComponent() != null) + { + ParticleSystemRenderer renderer = node.GetComponent(); + if (renderer != null) Object.DestroyImmediate(renderer); + Object.DestroyImmediate(system); + } + else + { + Object.DestroyImmediate(node); + } + } + + foreach (Light light in template.GetComponentsInChildren(true)) + { + if (light != null) Object.DestroyImmediate(light); + } + + foreach (AudioSource audio in template.GetComponentsInChildren(true)) + { + if (audio != null) Object.DestroyImmediate(audio); + } + + foreach (TrailRenderer trail in template.GetComponentsInChildren(true)) + { + if (trail != null) Object.DestroyImmediate(trail); + } + + foreach (LineRenderer line in template.GetComponentsInChildren(true)) + { + if (line != null) Object.DestroyImmediate(line); + } + } + + private static string LargestAvailable() + { + foreach (string name in LargeBonePrefabs) + { + if (TemplateOf(name) != null) return name; + } + return null; + } + + private static void ReportModels() + { + if (s_reported) return; + s_reported = true; + + List found = new List(); + List missing = new List(); + foreach (string name in LargeBonePrefabs) + { + (TemplateOf(name) != null ? found : missing).Add(name); + } + + Jotunn.Logger.LogInfo("[BoneShip] large bone models: found [" + string.Join(", ", found.ToArray()) + + "], missing [" + string.Join(", ", missing.ToArray()) + "]."); + } + + // ---------------------------------------------------------------- measuring + + /// + /// The hull's footprint in the ship's own space, from the OnboardTrigger every ship has: the volume + /// the game uses to decide who is aboard is, by construction, about the hull. + /// + internal bool TryHullExtent(out Bounds bounds) + { + bounds = new Bounds(); + + Transform trigger = transform.Find("OnboardTrigger"); + BoxCollider box = trigger != null ? trigger.GetComponent() : null; + if (box == null) return false; + + Vector3 centre = transform.InverseTransformPoint(trigger.TransformPoint(box.center)); + Vector3 size = Vector3.Scale(box.size, trigger.lossyScale) ; + size = new Vector3(Mathf.Abs(size.x), Mathf.Abs(size.y), Mathf.Abs(size.z)); + + bounds = new Bounds(centre, size); + return true; + } + + /// + /// The top of the rail on one side at one z: scanned from outside the hull inward, the first ray that + /// lands on the ship is the outer edge of the rail. + /// + internal bool FindRail(int side, float z, float hx, out Vector3 point, ref int rays) + { + for (float x = 1.15f * hx; x > 0.3f * hx; x -= 0.12f) + { + rays++; + if (FindSurface(new Vector3(side * x, RayStartHeight, z), out point)) return true; + } + + point = Vector3.zero; + return false; + } + + /// + /// The highest solid surface of THIS ship under a local point, in local space. Triggers, and anything + /// whose name up the hierarchy says mast, sail, cloth or rope, are not the hull. + /// + internal bool FindSurface(Vector3 localOrigin, out Vector3 localPoint, float minUp = 0.2f) + { + Vector3 origin = transform.TransformPoint(localOrigin); + + RaycastHit best = default(RaycastHit); + bool found = false; + float bestDistance = float.MaxValue; + + foreach (RaycastHit hit in Physics.RaycastAll(origin, -transform.up, RayLength)) + { + Collider collider = hit.collider; + if (collider == null || collider.isTrigger) continue; + if (!collider.transform.IsChildOf(transform)) continue; + if (Vector3.Dot(hit.normal, transform.up) < minUp) continue; + if (IsRigging(collider.transform)) continue; + + if (hit.distance >= bestDistance) continue; + best = hit; + bestDistance = hit.distance; + found = true; + } + + localPoint = found ? transform.InverseTransformPoint(best.point) : Vector3.zero; + return found; + } + + private bool IsRigging(Transform t) + { + for (; t != null && t != transform; t = t.parent) + { + string n = t.name.ToLowerInvariant(); + if (n.Contains("mast") || n.Contains("sail") || n.Contains("cloth") || n.Contains("rope")) return true; + } + return false; + } + + private static float Range(System.Random rng, float min, float max) + { + return min + (float)rng.NextDouble() * (max - min); + } + } +} diff --git a/JotunnModStub/BoneShip/BoneShipRoster.cs b/JotunnModStub/BoneShip/BoneShipRoster.cs new file mode 100644 index 0000000..712236a --- /dev/null +++ b/JotunnModStub/BoneShip/BoneShipRoster.cs @@ -0,0 +1,709 @@ +using System; +using System.Collections.Generic; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// The ship as a mobile bone pile. Skeleton_BoneShip.txt, sections 5.3-5.7. + /// + /// Bone fragments are offered at the altar, twenty to a PLACE, and a place is paid for once and refills + /// itself for ever - exactly the bone pile's economy (SkeletonBonePileBehaviour), because it is the same + /// design: nothing is created or consumed when a skeleton falls, the place simply stands up again. + /// + /// What is different is where the troops are. UNDERWAY they are DATA: a count per kind in the ship's own + /// ZDO ("aboard"), no creature, no AI, nothing to fall in the water. When the ship has been stopped for a + /// few seconds with land in reach they come ashore one at a time, real tamed skeletons that follow whoever + /// built the ship; when it moves off again, the ones that are following and close enough go back aboard, + /// one at a time, and become a number again. + /// + /// The rest of the world is COUNTED, never tallied. A troop's ZDO carries the id of its ship; "how many + /// are out" is however many loaded troops carry it. A death, a despawn, a player killing his own + /// skeleton all correct themselves, as on the pile. The known price is the pile's too: a troop in an + /// unloaded zone is not counted, so its place can refill while it is away. + /// + /// Troops are NOT bound to a point (no RaisedThrall anchor): a ship moves, and the anchor logic would + /// read the empty water it sailed from as a fallen station and wither them. They are bound to the ship by + /// id, and die with it. Only the owner of the ship's ZDO runs any of this. + /// + public class BoneShipRoster : MonoBehaviour + { + // ZDO keys, on the ship. + private const string KeyBones = "RoV_bshBones"; + private const string KeySlotsMelee = "RoV_bshSlotsM"; + private const string KeySlotsRanged = "RoV_bshSlotsR"; + private const string KeyAboardMelee = "RoV_bshAbM"; + private const string KeyAboardRanged = "RoV_bshAbR"; + + /// + /// Set when a troop that was told to go home boards a ship that is standing still: they have been + /// called back on purpose, so nobody should be sent straight out again. Cleared the moment the ship + /// moves, so the next stop lands the crew as usual. + /// + private const string KeyHold = "RoV_bshHold"; + + /// A recalled troop further than BoardRange but within this many metres is walked to the ship. + private const float RecallReach = 80f; + + /// How many rowers should show: everyone aboard. Read by the rowers when they exist. + public const string KeyRowers = "RoV_bshRowers"; + + /// ZDO key on a TROOP: the id of the ship it belongs to. + public const string KeyShip = "RoV_bshShip"; + + // ─── Balance. Same numbers as the pile where the idea is the same. ─── + private const float TickSeconds = 0.5f; + private const float DockedSeconds = 2.5f; // stopped this long before anyone comes ashore + private const float UnderwaySeconds = 1.0f; // moving this long before anyone goes back aboard + private const float StepSeconds = 0.8f; // one troop at a time, this far apart + private const float StillSpeed = 0.6f; // m/s: slower than this counts as stopped + private const float BoardRange = 20f; // decided with the orders: same as the pile's home check + private const float LandingBand = 10f; // how far past the hull to look for shore + private const float LandingMargin = 0.25f; // metres above the water for it to count as land + + private ZNetView m_nview; + private Ship m_ship; + private Rigidbody m_body; + + // The archers are not troops and are not counted with them: their own key, their own check. + private const float ArcherCheckSeconds = 2f; + private const float ArcherGraceSeconds = 4f; // a post whose registered archer is gone this long gets a new one + + private float m_archerTimer; + private float[] m_postEmptyFor = new float[0]; + + private float m_stillTime; + private float m_movingTime; + private float m_stepTimer; + private float m_refillTimer; + private int m_deployIndex; + private bool m_toldNoShore; + + private readonly List m_recentLandings = new List(); + + private void Awake() + { + m_nview = GetComponent(); + m_ship = GetComponent(); + m_body = GetComponent(); + + if (m_nview == null || m_nview.GetZDO() == null) return; // a placement ghost + + m_nview.Register("RoV_BshFeed", RPC_Feed); + + WearNTear wear = GetComponent(); + if (wear != null) wear.m_onDestroyed = (Action)Delegate.Combine(wear.m_onDestroyed, new Action(OnDestroyed)); + + InvokeRepeating("Tick", 2f, TickSeconds); + } + + /// The altar's Switch, once the fittings have built it. + public void Bind(Switch altar) + { + if (altar == null) return; + altar.m_onUse = OnUse; + altar.m_onHover = Hover; + } + + // ---------------------------------------------------------------- interaction + + // With an item in hand every outcome counts as handled, refusals included: false makes + // Humanoid.UseItem cover our own message with the generic one. Same as the pile. + private bool OnUse(Switch caller, Humanoid user, ItemDrop.ItemData item) + { + return Use(user, item) || item != null; + } + + private bool Use(Humanoid user, ItemDrop.ItemData item) + { + Player player = user as Player; + if (player == null || item == null) return false; + + Inventory inventory = player.GetInventory(); + if (inventory == null) return false; + + string prefabName = item.m_dropPrefab != null ? item.m_dropPrefab.name : null; + if (prefabName != SkeletonBonePile.BonePrefab) + { + player.Message(MessageHud.MessageType.Center, "$msg_wontwork"); + return false; + } + + // Bone is measured in fragments, not places: what is left to buy, minus what is already part-paid + // towards the next place. Taken from the player only if the ship will actually keep it. + int room = (TotalCap() - PaidSlots()) * SkeletonBonePile.BonesPerSlot - m_nview.GetZDO().GetInt(KeyBones); + if (room <= 0) + { + player.Message(MessageHud.MessageType.Center, "$msg_itsfull"); + return false; + } + + int taken = Mathf.Min(Mathf.Max(1, item.m_stack), room); + player.Message(MessageHud.MessageType.Center, $"$msg_added {item.m_shared.m_name} x{taken}"); + inventory.RemoveItem(item, taken); + + m_nview.InvokeRPC("RoV_BshFeed", prefabName, taken); + return true; + } + + private void RPC_Feed(long sender, string prefabName, int count) + { + if (!m_nview.IsOwner()) return; + if (prefabName != SkeletonBonePile.BonePrefab) return; + if (count < 1) count = 1; + + int bones = m_nview.GetZDO().GetInt(KeyBones) + count; + + // Melee places fill first, then the archers'. A loop, so a whole stack cannot overflow into bones + // that are never counted. + while (bones >= SkeletonBonePile.BonesPerSlot && PaidSlots() < TotalCap()) + { + bones -= SkeletonBonePile.BonesPerSlot; + + if (Slots(SkeletonBonePile.KindMelee) < MeleeCap()) SetSlots(SkeletonBonePile.KindMelee, Slots(SkeletonBonePile.KindMelee) + 1); + else SetSlots(SkeletonBonePile.KindRanged, Slots(SkeletonBonePile.KindRanged) + 1); + } + + m_nview.GetZDO().Set(KeyBones, bones); + } + + private string Hover() + { + int outM = CountDeployed(SkeletonBonePile.KindMelee); + int outR = CountDeployed(SkeletonBonePile.KindRanged); + int aboard = Aboard(SkeletonBonePile.KindMelee) + Aboard(SkeletonBonePile.KindRanged); + + string body = ModText.Get("rov_hover_boneship_roster", + outM + Aboard(SkeletonBonePile.KindMelee), Slots(SkeletonBonePile.KindMelee), MeleeCap(), + outR + Aboard(SkeletonBonePile.KindRanged), Slots(SkeletonBonePile.KindRanged), RangedCap(), + aboard); + + int bonesToward = m_nview.GetZDO().GetInt(KeyBones); + int placesLeft = TotalCap() - PaidSlots(); + body += placesLeft > 0 + ? ModText.Get("rov_hover_skeleton_bone_toward_next_places", bonesToward, SkeletonBonePile.BonesPerSlot, placesLeft) + : ModText.Get("rov_hover_skeleton_every_place_bought"); + + if (m_refillTimer > 0f) + { + int left = Mathf.Max(1, Mathf.CeilToInt(SkeletonBonePile.RespawnSeconds - m_refillTimer)); + body += ModText.Get("rov_hover_skeleton_next_rises_s", left); + } + + body += ModText.Get("rov_hover_boneship_bone_hand"); + return Localization.instance.Localize($"{BoneShip.AltarName} ({body})"); + } + + // ---------------------------------------------------------------- the tick + + private void Tick() + { + if (m_nview == null || !m_nview.IsValid() || !m_nview.IsOwner()) return; + if (m_ship == null) return; + + Refill(); + PublishRowers(); + + m_archerTimer += TickSeconds; + if (m_archerTimer >= ArcherCheckSeconds) + { + TickArchers(m_archerTimer); + m_archerTimer = 0f; + } + + bool stopped = m_ship.GetSpeedSetting() == Ship.Speed.Stop && + (m_body == null || m_body.velocity.magnitude < StillSpeed); + + if (stopped) + { + m_stillTime += TickSeconds; + m_movingTime = 0f; + } + else + { + m_movingTime += TickSeconds; + m_stillTime = 0f; + m_toldNoShore = false; + m_recentLandings.Clear(); + } + + // Moving off ends any hold: the next stop lands the crew as usual. + if (!stopped && m_movingTime >= UnderwaySeconds && m_nview.GetZDO().GetBool(KeyHold, false)) + { + m_nview.GetZDO().Set(KeyHold, false); + } + + WalkRecalled(); + + m_stepTimer -= TickSeconds; + if (m_stepTimer > 0f) return; + + // A troop sent home boards whether the ship is moving or not; the ones merely following only + // when it is underway. Whichever is first takes the step. + bool underway = !stopped && m_movingTime >= UnderwaySeconds; + string boarded = BoardOne(underway); + if (boarded != null) + { + m_stepTimer = StepSeconds; + + // Anyone who boards while the ship is standing still came aboard on purpose - called back, or + // walked up the plank - and must not be sent straight out again. Held until the ship moves. + if (stopped) m_nview.GetZDO().Set(KeyHold, true); + return; + } + + if (stopped && m_stillTime >= DockedSeconds && !m_nview.GetZDO().GetBool(KeyHold, false)) + { + if (TryDeploy()) m_stepTimer = StepSeconds; + } + } + + /// + /// A paid place with nobody in it - not aboard and not standing somewhere - fills after a while, as + /// the pile's does. Melee first. It fills ABOARD, so on a stopped ship it is then the next to come + /// ashore by the ordinary route. + /// + private void Refill() + { + string empty = FirstEmptyKind(); + if (empty == null) + { + m_refillTimer = 0f; + return; + } + + m_refillTimer += TickSeconds; + if (m_refillTimer < SkeletonBonePile.RespawnSeconds) return; + m_refillTimer = 0f; + + SetAboard(empty, Aboard(empty) + 1); + } + + private string FirstEmptyKind() + { + if (Slots(SkeletonBonePile.KindMelee) - CountDeployed(SkeletonBonePile.KindMelee) - Aboard(SkeletonBonePile.KindMelee) > 0) + return SkeletonBonePile.KindMelee; + if (Slots(SkeletonBonePile.KindRanged) - CountDeployed(SkeletonBonePile.KindRanged) - Aboard(SkeletonBonePile.KindRanged) > 0) + return SkeletonBonePile.KindRanged; + return null; + } + + private void PublishRowers() + { + int rowers = Aboard(SkeletonBonePile.KindMelee) + Aboard(SkeletonBonePile.KindRanged); + if (m_nview.GetZDO().GetInt(KeyRowers, -1) != rowers) m_nview.GetZDO().Set(KeyRowers, rowers); + } + + // ---------------------------------------------------------------- coming ashore + + private bool TryDeploy() + { + int melee = Aboard(SkeletonBonePile.KindMelee); + int ranged = Aboard(SkeletonBonePile.KindRanged); + if (melee + ranged == 0) return false; + + Vector3 landing; + if (!FindLanding(out landing)) + { + // Open water or a cliff: they stay at the oars. Said once per stop, to whoever is looking. + if (!m_toldNoShore && Player.m_localPlayer != null && + Vector3.Distance(Player.m_localPlayer.transform.position, transform.position) < 40f) + { + Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_boneship_no_shore")); + } + m_toldNoShore = true; + return false; + } + + // Whichever kind has more waiting goes first, so the line comes ashore mixed, not all spears then all bows. + string kind = melee >= ranged ? SkeletonBonePile.KindMelee : SkeletonBonePile.KindRanged; + string prefabName = kind == SkeletonBonePile.KindRanged ? SkeletonBonePile.ThrallRangedName : SkeletonBonePile.ThrallMeleeName; + + GameObject prefab = ZNetScene.instance != null ? ZNetScene.instance.GetPrefab(prefabName) : null; + if (prefab == null) + { + Jotunn.Logger.LogWarning($"[BoneShip] No '{prefabName}' in ZNetScene; nothing can come ashore."); + return false; + } + + GameObject spawned = Instantiate(prefab, landing, Quaternion.Euler(0f, UnityEngine.Random.Range(0, 360), 0f)); + + // Tamed, so it never turns on its master: the two calls RaisedThrall.Bind makes, without the anchor. + MonsterAI ai = spawned.GetComponent(); + if (ai != null) ai.MakeTame(); + Character character = spawned.GetComponent(); + if (character != null) character.SetTamed(true); + + ZNetView troopView = spawned.GetComponent(); + if (troopView != null && troopView.GetZDO() != null) troopView.GetZDO().Set(KeyShip, m_nview.GetZDO().m_uid); + + // Out and following their master. NOT through RaisedThrall.SetFollowing: that refuses anyone who is + // not a Skeleton, and the ship is open to every race - a non-Skeleton's crew would come ashore, stand + // there, and never be able to come back aboard, because boarding is for the ones that follow. So the + // follow target is set directly, as the ship's own right. + Player master = Master(); + if (ai != null && master != null) ai.SetFollowTarget(master.gameObject); + + SetAboard(kind, Aboard(kind) - 1); + m_recentLandings.Add(landing); + if (m_recentLandings.Count > 12) m_recentLandings.RemoveAt(0); + return true; + } + + /// + /// Dry land near the hull. Looks on rings around the ship, nearest first, from just past the hull out + /// to LandingBand metres beyond it; a point is land if the terrain there is above the water. The first + /// ring angle moves on with each troop, and a point near one already used is skipped, so they do not + /// all stack on one spot. + /// + private bool FindLanding(out Vector3 landing) + { + landing = Vector3.zero; + if (ZoneSystem.instance == null) return false; + + float hull = Mathf.Max(BoneShip.HalfLengthOf(this), 4f); + float water = ZoneSystem.instance.m_waterLevel + LandingMargin; + + for (float radius = hull + 1.5f; radius <= hull + 1.5f + LandingBand; radius += 1.5f) + { + for (int step = 0; step < 24; step++) + { + float angle = (m_deployIndex * 47f + step * 15f) * Mathf.Deg2Rad; + Vector3 point = transform.position + new Vector3(Mathf.Cos(angle), 0f, Mathf.Sin(angle)) * radius; + + float ground = ZoneSystem.instance.GetGroundHeight(point); + if (ground < water) continue; + if (NearRecent(point)) continue; + + landing = new Vector3(point.x, ground + 0.5f, point.z); + m_deployIndex++; + return true; + } + } + + return false; + } + + private bool NearRecent(Vector3 point) + { + foreach (Vector3 used in m_recentLandings) + { + Vector3 d = used - point; + d.y = 0f; + if (d.sqrMagnitude < 1.4f * 1.4f) return true; + } + return false; + } + + // ---------------------------------------------------------------- going back aboard + + /// + /// Takes ONE troop back aboard: it vanishes and the count goes up. Which: the nearest, within + /// BoardRange, that was SENT HOME (a "go home" order, the troop's RoV_bshRecall flag) - or, when the + /// ship is underway, that is following its master. Ones told to wait, and followers when the ship is + /// standing still, stay where they are: an outpost, still counted, still this ship's. + /// Returns "recalled" or "following" for what it took, null for nothing. + /// + private string BoardOne(bool underway) + { + Player master = Master(); + + Character nearest = null; + RaisedThrall nearestThrall = null; + bool nearestRecalled = false; + float best = BoardRange * BoardRange; + + foreach (Character character in Character.GetAllCharacters()) + { + if (character == null || character.IsDead() || !BelongsHere(character)) continue; + + RaisedThrall thrall = character.GetComponent(); + if (thrall == null) continue; + + bool recalled = IsRecalled(character); + + // A troop that follows its master and has WALKED ONTO THE DECK is aboard, whatever the ship is + // doing: standing about on the planks as a creature is not what a crew is. The first version + // only took followers once the ship was underway, so stepping off and back on left the crew + // standing on deck, never at the oars, until the ship moved. + bool followingMaster = master != null && thrall.IsFollowing(master); + bool following = followingMaster && (underway || OnDeck(character)); + if (!recalled && !following) continue; + + float distance = (character.transform.position - transform.position).sqrMagnitude; + if (distance >= best) continue; + + best = distance; + nearest = character; + nearestThrall = thrall; + nearestRecalled = recalled; + } + + if (nearest == null) return null; + + string kind = nearestThrall.Kind == SkeletonBonePile.KindRanged ? SkeletonBonePile.KindRanged : SkeletonBonePile.KindMelee; + + ZNetView troopView = nearest.GetComponent(); + if (troopView != null) troopView.ClaimOwnership(); // it may belong to another client's zone + ZNetScene.instance.Destroy(nearest.gameObject); + + SetAboard(kind, Aboard(kind) + 1); + return nearestRecalled ? "recalled" : "following"; + } + + /// + /// A recalled troop out of boarding range walks to the ship: its patrol point is pinned on the ship + /// every tick, because the ship may be moving. Past RecallReach it is not chased - out of earshot. + /// + private void WalkRecalled() + { + foreach (Character character in Character.GetAllCharacters()) + { + if (character == null || character.IsDead() || !BelongsHere(character)) continue; + if (!IsRecalled(character)) continue; + + float distance = Vector3.Distance(character.transform.position, transform.position); + if (distance <= BoardRange || distance > RecallReach) continue; + + RaisedThrall thrall = character.GetComponent(); + if (thrall != null) thrall.WalkTo(transform.position); + } + } + + /// Standing inside the hull's boarding volume: the same box the game uses to decide who is aboard. + private bool OnDeck(Character character) + { + BoneShipFittings fittings = GetComponent(); + Bounds hull; + if (fittings == null || !fittings.TryHullExtent(out hull)) return false; + + return hull.Contains(transform.InverseTransformPoint(character.transform.position)); + } + + private static bool IsRecalled(Character character) + { + ZNetView view = character.GetComponent(); + return view != null && view.GetZDO() != null && view.GetZDO().GetBool(RaisedThrall.KeyRecall, false); + } + + // ---------------------------------------------------------------- the archers + + /// + /// Keeps the ship's archers standing. Counted from the world, like the troops: a loaded archer + /// carrying this ship's id and a post number holds that post. A post nobody holds for a while gets a + /// new archer - not at once, because after a reload the ship is loaded a moment before the archers + /// that were standing on it, and spawning then would double them. A second archer found on a post + /// that is already held is removed. + /// + private void TickArchers(float elapsed) + { + BoneShipFittings fittings = GetComponent(); + if (fittings == null || fittings.ArcherPosts == null) return; // the hull is not measured yet + + int posts = fittings.ArcherPosts.Count; + if (m_postEmptyFor.Length != posts) m_postEmptyFor = new float[posts]; + + ZDO shipZdo = m_nview.GetZDO(); + ZDOID mine = shipZdo.m_uid; + + // ---- 1. the archers that are in the world now: adopt the first of each post, remove the rest. + // + // The ship keeps a REGISTER of who holds each post (its own ZDO, one id per post). The first + // version only counted the archers it could see and spawned one for any post it saw nobody on - + // and "can see" is only what is loaded, so a ship that woke before its archers did, or a post + // whose archer sat in a zone the owner had not loaded, got a second archer on top of the first, + // again at every reload. The register does not depend on what is loaded. Archers made before the + // register existed have no entry: the first found is adopted, the others are the duplicates. + foreach (Character character in Character.GetAllCharacters()) + { + if (character == null) continue; + + ZNetView view = character.GetComponent(); + if (view == null || view.GetZDO() == null) continue; + if (view.GetZDO().GetZDOID(ShipMount.KeyArcherShip) != mine) continue; + + int post = view.GetZDO().GetInt(ShipMount.KeyArcherPost, -1); + if (post < 0 || post >= posts) + { + RemoveArcher(character, view, "a post this ship no longer has"); + continue; + } + + ZDOID registered = shipZdo.GetZDOID(SlotKey(post)); + ZDOID self = view.GetZDO().m_uid; + + if (registered == ZDOID.None) shipZdo.Set(SlotKey(post), self); + else if (registered != self) RemoveArcher(character, view, "a duplicate on post " + post); + } + + // ---- 2. posts whose registered archer is gone: a new one, after a short grace. + GameObject prefab = ZNetScene.instance != null ? ZNetScene.instance.GetPrefab(BoneShipArcher.Name) : null; + + for (int i = 0; i < posts; i++) + { + ZDOID registered = shipZdo.GetZDOID(SlotKey(i)); + bool exists = registered != ZDOID.None && ZDOMan.instance != null && ZDOMan.instance.GetZDO(registered) != null; + + if (exists) + { + m_postEmptyFor[i] = 0f; + continue; + } + + m_postEmptyFor[i] += elapsed; + if (m_postEmptyFor[i] < ArcherGraceSeconds) continue; + m_postEmptyFor[i] = 0f; + + if (prefab == null) + { + Jotunn.Logger.LogWarning($"[BoneShip] No '{BoneShipArcher.Name}' in ZNetScene; the ship has no archer at post {i}."); + continue; + } + + SpawnArcher(prefab, i, fittings.ArcherPosts[i]); + } + } + + private static string SlotKey(int post) => "RoV_bshArcher" + post; + + private void RemoveArcher(Character character, ZNetView view, string why) + { + Jotunn.Logger.LogInfo($"[BoneShip] '{name}': removing an archer - {why}."); + view.ClaimOwnership(); + ZNetScene.instance.Destroy(character.gameObject); + } + + private void SpawnArcher(GameObject prefab, int post, BoneShipFittings.ArcherPost at) + { + Vector3 world = transform.TransformPoint(at.Local); + GameObject archer = Instantiate(prefab, world, transform.rotation); + + // The ship's id and the place on it go into the archer's own ZDO at once, before its mount first + // runs, so it knows where it stands from its first physics step - and again after any reload. + ZNetView view = archer.GetComponent(); + if (view != null && view.GetZDO() != null) + { + ZDO zdo = view.GetZDO(); + zdo.Set(ShipMount.KeyArcherShip, m_nview.GetZDO().m_uid); + zdo.Set(ShipMount.KeyArcherPoint, at.Local); + zdo.Set(ShipMount.KeyArcherBust, at.Bust); + zdo.Set(ShipMount.KeyArcherPost, post); + + // Signed into the ship's register straight away, so the very next check already knows. + m_nview.GetZDO().Set(SlotKey(post), zdo.m_uid); + Jotunn.Logger.LogInfo($"[BoneShip] '{name}': archer raised on post {post} at local " + + $"({at.Local.x:F2}, {at.Local.y:F2}, {at.Local.z:F2})."); + } + + // Tamed, so it never turns on whoever is aboard: the two calls the sentry's seed makes. + MonsterAI ai = archer.GetComponent(); + if (ai != null) ai.MakeTame(); + Character character = archer.GetComponent(); + if (character != null) character.SetTamed(true); + } + + // ---------------------------------------------------------------- the ship falls + + /// + /// The ship going down takes its troops with it, those that are loaded. Same as the pile's immediate + /// off switch: a garrison that refills for free needs something that ends it. Any in an unloaded zone + /// outlive the ship - the known gap, noted in the design. + /// + private void OnDestroyed() + { + if (m_nview == null || !m_nview.IsOwner()) return; + + int lost = 0; + foreach (Character character in Character.GetAllCharacters()) + { + if (character == null || character.IsDead() || !BelongsHere(character)) continue; + + RaisedThrall thrall = character.GetComponent(); + if (thrall != null) thrall.Kill(); + lost++; + } + + // The archers go down with it as well; they are not counted among the troops that are lost. + ZDOID mine = m_nview.GetZDO().m_uid; + foreach (Character character in Character.GetAllCharacters()) + { + if (character == null) continue; + + ZNetView view = character.GetComponent(); + if (view == null || view.GetZDO() == null) continue; + if (view.GetZDO().GetZDOID(ShipMount.KeyArcherShip) != mine) continue; + + view.ClaimOwnership(); + ZNetScene.instance.Destroy(character.gameObject); + } + + if (lost > 0 && Player.m_localPlayer != null) + { + Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_boneship_sunk", lost)); + } + } + + // ---------------------------------------------------------------- state + + private Player Master() + { + Piece piece = GetComponent(); + long creator = piece != null ? piece.GetCreator() : 0L; + + if (creator != 0L) + { + foreach (Player player in Player.GetAllPlayers()) + { + if (player != null && player.GetPlayerID() == creator) return player; + } + } + + // Its builder is not here: whoever is nearest, so a ship found abandoned is still crewed. + return Player.GetClosestPlayer(transform.position, 40f); + } + + private bool BelongsHere(Character character) + { + ZNetView view = character.GetComponent(); + if (view == null || view.GetZDO() == null) return false; + return view.GetZDO().GetZDOID(KeyShip) == m_nview.GetZDO().m_uid; + } + + private int CountDeployed(string kind) + { + int count = 0; + foreach (Character character in Character.GetAllCharacters()) + { + if (character == null || character.IsDead() || !BelongsHere(character)) continue; + + RaisedThrall thrall = character.GetComponent(); + string troopKind = thrall != null && thrall.Kind == SkeletonBonePile.KindRanged + ? SkeletonBonePile.KindRanged : SkeletonBonePile.KindMelee; + if (troopKind == kind) count++; + } + return count; + } + + private int Slots(string kind) => m_nview != null && m_nview.IsValid() ? m_nview.GetZDO().GetInt(kind == SkeletonBonePile.KindRanged ? KeySlotsRanged : KeySlotsMelee) : 0; + + private void SetSlots(string kind, int value) + { + if (m_nview != null && m_nview.IsValid()) m_nview.GetZDO().Set(kind == SkeletonBonePile.KindRanged ? KeySlotsRanged : KeySlotsMelee, Mathf.Max(0, value)); + } + + private int Aboard(string kind) => m_nview != null && m_nview.IsValid() ? m_nview.GetZDO().GetInt(kind == SkeletonBonePile.KindRanged ? KeyAboardRanged : KeyAboardMelee) : 0; + + private void SetAboard(string kind, int value) + { + if (m_nview != null && m_nview.IsValid()) m_nview.GetZDO().Set(kind == SkeletonBonePile.KindRanged ? KeyAboardRanged : KeyAboardMelee, Mathf.Max(0, value)); + } + + private int PaidSlots() => Slots(SkeletonBonePile.KindMelee) + Slots(SkeletonBonePile.KindRanged); + + private int MeleeCap() => BoneShip.MeleeCapOf(this); + + private int RangedCap() => BoneShip.RangedCapOf(this); + + private int TotalCap() => MeleeCap() + RangedCap(); + } +} diff --git a/JotunnModStub/BoneShip/BoneShipRowers.cs b/JotunnModStub/BoneShip/BoneShipRowers.cs new file mode 100644 index 0000000..c91aaeb --- /dev/null +++ b/JotunnModStub/BoneShip/BoneShipRowers.cs @@ -0,0 +1,480 @@ +using System.Collections; +using System.Collections.Generic; +using HarmonyLib; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// The oarsmen: skeletons seated at benches along both sides, pulling oars, who are the reason a ship + /// with no wind in its sail goes anywhere. Skeleton_BoneShip.txt, sections 1 and 3.4. + /// + /// PURE SCENERY. There is no creature here: no Character, no AI, no network object. Each is a copy of the + /// skeleton's MODEL, and how many are visible is one number the roster keeps in the ship's own ZDO + /// (RoV_bshRowers = how many troops are aboard), so every client draws the same crew and they come + /// ashore one at a time exactly as the roster says. How hard they pull is the ship's own gear + /// (Stop, Slow, Half, Full, Back), which every client already has, so nothing here needs to be sent. + /// + /// NOTHING TO REUSE: no ship in the game has oars (the dump found none), so the oars are built here too, + /// from two stretched cubes in the ship's own wood. + /// + /// SEATED WITHOUT A SEATED ANIMATION. The model stands, but is lowered until its hips are at bench + /// height: the legs go down through the deck, which hides them from above, so what shows is a body sitting + /// at a bench. The same trick as the bust at the bow, and for the same reason - the model cannot be cut. + /// + /// THE ARMS follow the oar. Each arm bone is turned, in world space, to point at its grip on the handle + /// (FromToRotation from where it points now to where the grip is), after the animator has posed it, so + /// nothing depends on the rig's local axes, which were never read. The bones are found by name (the rig is + /// Mixamo-style: LeftArm, LeftForeArm, LeftHand) and, when any is missing, the whole skeleton is logged + /// once so the names can be corrected; the crew then still sits and rocks, with arms at their sides. + /// + /// THE STROKE. One shared phase per ship, all oars in time. The blade sweeps aft in the water (the pull, + /// the rower leans back and the handle comes toward his chest) and forward out of it (the recovery, the + /// blade lifted). The period follows the gear; Back runs it in reverse; Stop lets the oars settle level. + /// + public class BoneShipRowers : MonoBehaviour + { + // The model, and how big the oarsmen are. + private const string SkeletonPrefab = "Skeleton"; + private const float ModelHeight = 1.7f; + + // Where on the hull they sit, as fractions of the half length, from the stern forward. The Karve's + // are further apart because its helm and bow seats leave less room between. + // The Karve's front pair moved from +0.22 to -0.12 of the half length: the cargo hatch is at z = +1.3 + // and the offering chest stands beside it, and a bench at +1.0 was in the way. + private static readonly float[] SmallSeatsZ = { -0.40f, -0.12f }; + private static readonly float[] LargeSeatsZ = { -0.50f, -0.26f, -0.02f, 0.22f }; + + private const float SeatHeight = 0.47f; // hips above the deck: a bench and a little + private const float OarlockLift = 0.12f; // oarlock above the rail's top + private const float OarInboard = 0.75f; // handle end, from the oarlock + private const float OarOutboard = 1.70f; // blade end + + // The stroke. + private const float SweepMax = 0.45f; // radians, blade fore and aft + private const float LiftMax = 0.35f; // radians, blade up on the recovery + private const float LeanMax = 14f; // degrees, rower back and forth + private const float PeriodSlow = 2.6f; + private const float PeriodHalf = 1.9f; + private const float PeriodFull = 1.3f; + + private class Seat + { + public GameObject Root; // at the hips, in the ship's space + public GameObject Bench; + public Transform Lean; // rotates about the hips + public Transform Oar; + public int Side; // +1 right, -1 left + public Vector3 Oarlock; // ship space + public Transform LeftArm, LeftFore, LeftHand, RightArm, RightFore, RightHand; + } + + private readonly List m_seats = new List(); + private ZNetView m_nview; + private Ship m_ship; + + private float m_phase; + private float m_amplitude; + private bool m_built; + + private static GameObject s_holder; + private static GameObject s_template; + private static bool s_templateTried; + private static Mesh s_cube; + private static bool s_loggedBones; + + private void Start() + { + m_nview = GetComponent(); + m_ship = GetComponent(); + if (m_nview == null || !m_nview.IsValid()) return; // a placement ghost + + StartCoroutine(Build()); + } + + // ---------------------------------------------------------------- building + + private IEnumerator Build() + { + // The fittings measure the hull the same way, a physics step after the ship exists. + yield return new WaitForFixedUpdate(); + yield return null; + yield return null; + + BoneShipFittings fittings = GetComponent(); + Bounds hull; + if (fittings == null || !fittings.TryHullExtent(out hull)) + { + Jotunn.Logger.LogWarning($"[BoneShip] '{name}': no hull to seat rowers on."); + yield break; + } + + GameObject template = Template(); + if (template == null) + { + Jotunn.Logger.LogWarning($"[BoneShip] No '{SkeletonPrefab}' model; '{name}' has no rowers."); + yield break; + } + + float hx = hull.extents.x; + float hz = hull.extents.z; + float[] zs = SeatStations((BoneShip.MeleeCapOf(this) + BoneShip.RangedCapOf(this)) / 2); + Material wood = FindWood(); + int rays = 0; + + for (int side = -1; side <= 1; side += 2) + { + foreach (float f in zs) + { + float z = f * hz; + + Vector3 rail; + if (!fittings.FindRail(side, z, hx, out rail, ref rays)) continue; + + float seatX = side * Mathf.Max(0.45f, Mathf.Abs(rail.x) - 0.55f); + Vector3 deck; + if (!fittings.FindSurface(new Vector3(seatX, BoneShipFittings.RayStartHeight, z), out deck)) continue; + + m_seats.Add(MakeSeat(template, wood, side, deck, rail, z)); + if (++rays >= 30) { rays = 0; yield return null; } + } + } + + // Fill order: both sides at each station, from the bow back, so a short crew is balanced. + m_seats.Sort((a, b) => + { + int byStation = b.Root.transform.localPosition.z.CompareTo(a.Root.transform.localPosition.z); + return byStation != 0 ? byStation : a.Side.CompareTo(b.Side); + }); + + m_built = true; + Jotunn.Logger.LogInfo($"[BoneShip] '{name}': {m_seats.Count} rowers' seats built."); + } + + /// + /// Where along the hull the benches go, for this many on each side: the hand-placed lists where they + /// were tuned (two on the Karve, four on the Longship), an even spread from the stern forward for any + /// other number - the Ashlands ship has six a side. + /// + private static float[] SeatStations(int perSide) + { + if (perSide == SmallSeatsZ.Length) return SmallSeatsZ; + if (perSide == LargeSeatsZ.Length) return LargeSeatsZ; + + float[] stations = new float[perSide]; + for (int i = 0; i < perSide; i++) + { + float t = perSide == 1 ? 0.5f : i / (float)(perSide - 1); + stations[i] = Mathf.Lerp(-0.52f, 0.24f, t); + } + return stations; + } + + private Seat MakeSeat(GameObject template, Material wood, int side, Vector3 deck, Vector3 rail, float z) + { + Seat seat = new Seat { Side = side }; + + // The hips, at bench height above the deck. + GameObject root = new GameObject("Rower"); + root.transform.SetParent(transform, false); + root.transform.localPosition = deck + Vector3.up * SeatHeight; + seat.Root = root; + + GameObject lean = new GameObject("Lean"); + lean.transform.SetParent(root.transform, false); + seat.Lean = lean.transform; + + // Facing the stern, as an oarsman does. The model's own front turned out to be the OTHER way from + // what a 180 degree turn assumed - the first build had the crew looking at the bow - so it is + // left as it comes: no turn. + GameObject model = Instantiate(template, lean.transform, false); + model.name = "model"; + model.transform.localRotation = Quaternion.identity; + model.transform.localScale = Vector3.one * (ModelHeight / 1.8f); + model.SetActive(true); + + Animator animator = model.GetComponentInChildren(true); + if (animator != null) + { + // The idle clip fires animation events at a receiver the strip removed: unanswered, each + // one logs an error. Switched off, the clip still poses the body. + animator.fireEvents = false; + animator.applyRootMotion = false; + } + + FindBones(model.transform, seat); + SeatHips(model.transform, lean.transform, seat); + + // A bench, across the beam, so nobody sits on nothing. + GameObject bench = MakeBox("Bench", transform, wood, new Vector3(0.85f, 0.07f, 0.34f)); + bench.transform.localPosition = new Vector3(deck.x, deck.y + SeatHeight - 0.09f, z); + + // The oar: pivot at the oarlock on the rail, a shaft and a blade along its own +z (outboard). + seat.Oarlock = new Vector3(rail.x, rail.y + OarlockLift, z); + GameObject oar = new GameObject("Oar"); + oar.transform.SetParent(transform, false); + oar.transform.localPosition = seat.Oarlock; + seat.Oar = oar.transform; + + float length = OarInboard + OarOutboard; + GameObject shaft = MakeBox("Shaft", oar.transform, wood, new Vector3(0.07f, 0.07f, length)); + shaft.transform.localPosition = new Vector3(0f, 0f, (OarOutboard - OarInboard) * 0.5f); + GameObject blade = MakeBox("Blade", oar.transform, wood, new Vector3(0.20f, 0.03f, 0.55f)); + blade.transform.localPosition = new Vector3(0f, 0f, OarOutboard - 0.27f); + + root.SetActive(false); + oar.SetActive(false); + bench.SetActive(false); + seat.Root = root; + seat.Bench = bench; + return seat; + } + + /// Moves the model so its hips sit on the lean pivot - or, if no hips are found, by height. + private static void SeatHips(Transform model, Transform pivot, Seat seat) + { + Transform hips = Find(model, "hips") ?? Find(model, "pelvis"); + if (hips != null) + { + Vector3 hipsInPivot = pivot.InverseTransformPoint(hips.position); + model.localPosition -= hipsInPivot; + } + else + { + model.localPosition = new Vector3(0f, -0.95f * (ModelHeight / 1.8f), 0f); + } + } + + // ---------------------------------------------------------------- the stroke + + private void Update() + { + if (!m_built || m_ship == null || m_nview == null || !m_nview.IsValid()) return; + + int crew = m_nview.GetZDO().GetInt(BoneShipRoster.KeyRowers, 0); + + Ship.Speed gear = m_ship.GetSpeedSetting(); + float period = gear == Ship.Speed.Full ? PeriodFull : gear == Ship.Speed.Half ? PeriodHalf : PeriodSlow; + bool rowing = gear != Ship.Speed.Stop && (crew > 0); + + m_amplitude = Mathf.MoveTowards(m_amplitude, rowing ? 1f : 0f, Time.deltaTime * 1.5f); + if (rowing) m_phase = Mathf.Repeat(m_phase + Time.deltaTime / period * (gear == Ship.Speed.Back ? -1f : 1f), 1f); + + float twoPi = Mathf.PI * 2f; + float sweep = -Mathf.Cos(twoPi * m_phase); // forward extreme at 0, aft at 0.5 + float recovery = Mathf.Clamp01(-Mathf.Sin(twoPi * m_phase) * 2f); // 1 mid-recovery, 0 in the water + recovery = recovery * recovery * (3f - 2f * recovery); + float lift = Mathf.Lerp(-0.08f, LiftMax, recovery); + float lean = LeanMax * sweep; + + for (int i = 0; i < m_seats.Count; i++) + { + Seat seat = m_seats[i]; + bool shown = i < crew; + + seat.Root.SetActive(shown); + seat.Oar.gameObject.SetActive(shown); + seat.Bench.SetActive(shown); + if (!shown) continue; + + float psi = SweepMax * sweep * m_amplitude; + float lam = Mathf.Lerp(0.10f, lift, m_amplitude); + + // The oar's outboard direction in the ship's space: out across the beam, a little fore or + // aft with the sweep (positive aft), and tilted up by the lift. + Vector3 outward = new Vector3(seat.Side * Mathf.Cos(psi) * Mathf.Cos(lam), + Mathf.Sin(lam), + -Mathf.Sin(psi) * Mathf.Cos(lam)); + seat.Oar.localRotation = Quaternion.LookRotation(outward, Vector3.up); + + seat.Lean.localRotation = Quaternion.AngleAxis(lean * m_amplitude, Vector3.right); + } + } + + /// After the animator: the arms reach for the handle. + private void LateUpdate() + { + if (!m_built) return; + + foreach (Seat seat in m_seats) + { + if (!seat.Root.activeSelf) continue; + + // Two grips on the handle, near and far from the chest. + Vector3 gripNear = seat.Oar.TransformPoint(0f, 0f, -OarInboard * 0.55f); + Vector3 gripFar = seat.Oar.TransformPoint(0f, 0f, -OarInboard * 0.15f); + + Reach(seat.LeftArm, seat.LeftFore, gripNear); + Reach(seat.LeftFore, seat.LeftHand, gripNear); + Reach(seat.RightArm, seat.RightFore, gripFar); + Reach(seat.RightFore, seat.RightHand, gripFar); + } + } + + /// Turns a bone, in world space, so the line to its child points at the target. + private static void Reach(Transform bone, Transform child, Vector3 target) + { + if (bone == null || child == null) return; + + Vector3 now = child.position - bone.position; + Vector3 want = target - bone.position; + if (now.sqrMagnitude < 1e-6f || want.sqrMagnitude < 1e-6f) return; + + bone.rotation = Quaternion.FromToRotation(now, want) * bone.rotation; + } + + // ---------------------------------------------------------------- bones + + private static void FindBones(Transform model, Seat seat) + { + seat.LeftArm = Find(model, "leftarm"); + seat.LeftFore = Find(model, "leftforearm"); + seat.LeftHand = Find(model, "lefthand"); + seat.RightArm = Find(model, "rightarm"); + seat.RightFore = Find(model, "rightforearm"); + seat.RightHand = Find(model, "righthand"); + + if (seat.LeftArm != null && seat.LeftFore != null && seat.LeftHand != null && + seat.RightArm != null && seat.RightFore != null && seat.RightHand != null) return; + if (s_loggedBones) return; + s_loggedBones = true; + + List names = new List(); + foreach (Transform t in model.GetComponentsInChildren(true)) names.Add(t.name); + Jotunn.Logger.LogWarning("[BoneShip] The rowers' arm bones were not all found by name; they will hang at " + + "their sides. Skeleton: " + string.Join(", ", names.ToArray())); + } + + /// A bone by name, ignoring case and any "mixamorig:"-style prefix. + private static Transform Find(Transform root, string lowerName) + { + foreach (Transform t in root.GetComponentsInChildren(true)) + { + string n = t.name.ToLowerInvariant(); + int colon = n.LastIndexOf(':'); + if (colon >= 0) n = n.Substring(colon + 1); + if (n == lowerName) return t; + } + return null; + } + + // ---------------------------------------------------------------- model, wood, boxes + + /// + /// The skeleton's model with nothing that acts. Instantiated into an INACTIVE holder, so nothing wakes, + /// and then stripped in DEPENDENCY order: ModelBorrow's one pass is not safe on a creature, because + /// Unity refuses to remove a component another one requires - Humanoid under CharacterDrop - and the + /// Humanoid it leaves behind is a live creature. The Hive taught that: it broke the hammer for every + /// piece in the game. So each pass removes only what nothing still present requires, and passes repeat. + /// + private static GameObject Template() + { + if (s_templateTried) return s_template; + s_templateTried = true; + + GameObject source = Jotunn.Managers.PrefabManager.Cache.GetPrefab(SkeletonPrefab); + if (source == null) return null; + + s_holder = new GameObject("RoV_BoneShipRowers"); + s_holder.SetActive(false); + Object.DontDestroyOnLoad(s_holder); + + GameObject copy = Object.Instantiate(source, s_holder.transform); + copy.name = "RowerTemplate"; + + StripBehaviours(copy); + + foreach (Rigidbody body in copy.GetComponentsInChildren(true)) if (body != null) Object.DestroyImmediate(body); + foreach (Collider collider in copy.GetComponentsInChildren(true)) if (collider != null) Object.DestroyImmediate(collider); + BoneShipFittings.StripEffects(copy); + + copy.transform.localPosition = Vector3.zero; + copy.transform.localRotation = Quaternion.identity; + copy.transform.localScale = Vector3.one; + + s_template = copy; + return s_template; + } + + private static void StripBehaviours(GameObject root) + { + for (int pass = 0; pass < 12; pass++) + { + bool any = false; + bool removed = false; + + foreach (MonoBehaviour behaviour in root.GetComponentsInChildren(true)) + { + if (behaviour == null) continue; + any = true; + + if (RequiredByAnother(behaviour)) continue; + Object.DestroyImmediate(behaviour); + removed = true; + } + + if (!any) return; + if (!removed) break; + } + + int left = 0; + foreach (MonoBehaviour behaviour in root.GetComponentsInChildren(true)) if (behaviour != null) left++; + if (left > 0) Jotunn.Logger.LogWarning($"[BoneShip] {left} component(s) of the rower model could not be removed."); + } + + private static bool RequiredByAnother(MonoBehaviour behaviour) + { + System.Type type = behaviour.GetType(); + + foreach (Component other in behaviour.GetComponents()) + { + if (other == null || other == behaviour) continue; + + foreach (object attribute in other.GetType().GetCustomAttributes(typeof(RequireComponent), true)) + { + RequireComponent need = (RequireComponent)attribute; + if (Needs(need.m_Type0, type) || Needs(need.m_Type1, type) || Needs(need.m_Type2, type)) return true; + } + } + return false; + } + + private static bool Needs(System.Type required, System.Type type) + { + return required != null && required.IsAssignableFrom(type); + } + + /// The ship's own rotten wood, so the oars and benches match: the first Piece-shader material on it. + private Material FindWood() + { + foreach (Renderer renderer in GetComponentsInChildren(true)) + { + if (renderer == null || renderer is ParticleSystemRenderer || renderer is LineRenderer) continue; + + foreach (Material material in renderer.sharedMaterials) + { + if (material != null && material.shader != null && material.shader.name == "Custom/Piece") return material; + } + } + return null; + } + + private static GameObject MakeBox(string name, Transform parent, Material material, Vector3 size) + { + if (s_cube == null) + { + GameObject primitive = GameObject.CreatePrimitive(PrimitiveType.Cube); + s_cube = primitive.GetComponent().sharedMesh; + Object.Destroy(primitive); + } + + GameObject box = new GameObject(name); + box.transform.SetParent(parent, false); + box.transform.localScale = size; + box.AddComponent().sharedMesh = s_cube; + MeshRenderer renderer = box.AddComponent(); + if (material != null) renderer.sharedMaterial = material; + return box; + } + } +} diff --git a/JotunnModStub/BoneShip/BoneShipSail.cs b/JotunnModStub/BoneShip/BoneShipSail.cs new file mode 100644 index 0000000..cc00e79 --- /dev/null +++ b/JotunnModStub/BoneShip/BoneShipSail.cs @@ -0,0 +1,178 @@ +using System.Collections.Generic; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// The bone ships' sails: black, and torn. + /// + /// Every vanilla sail is a Custom/Vegetation material - an alpha-cutout shader (it has a _Cutoff of + /// 0.5) - so a hole is simply a texel whose alpha is under that. Nothing is imported: the texture is + /// drawn here in code, one per source material (sail_white on the Karve, sail and sail_brown on the + /// Longship, ashlandshipsail_mat on the Ashlands ship), and goes onto a COPY of the material so the + /// vanilla ships keep theirs. + /// + /// The holes come from value noise, not a drawing, because the sail's UV layout was not read. Two + /// scales: broad tears, and small shreds, with the top and bottom edges frayed. Whether the shader + /// actually clips on that alpha is the one thing only the game can confirm. + /// + public static class BoneShipSail + { + private const int Size = 256; + + // The big tears: a share of the sail, roughly. Higher threshold = fewer, smaller holes. + private const float TearThreshold = 0.62f; + private const float ShredThreshold = 0.70f; + + public static void Apply(GameObject prefab, string shipName) + { + Dictionary copies = new Dictionary(); + int seed = shipName.GetHashCode(); + + foreach (Renderer renderer in prefab.GetComponentsInChildren(true)) + { + if (renderer == null || renderer is ParticleSystemRenderer || renderer is LineRenderer) continue; + + Material[] shared = renderer.sharedMaterials; + bool changed = false; + + for (int i = 0; i < shared.Length; i++) + { + Material source = shared[i]; + if (!IsSail(source)) continue; + + Material copy; + if (!copies.TryGetValue(source, out copy)) + { + copy = new Material(source) { name = source.name + "_bone" }; + copy.SetTexture("_MainTex", Draw(seed + source.name.GetHashCode())); + copy.SetColor("_Color", Color.white); + copies[source] = copy; + } + + shared[i] = copy; + changed = true; + } + + if (changed) renderer.sharedMaterials = shared; + } + + if (copies.Count == 0) + { + Jotunn.Logger.LogWarning($"[BoneShip] {shipName}: no sail material found, the sail is left as it is."); + } + } + + private static bool IsSail(Material material) + { + if (material == null || material.shader == null) return false; + if (!material.HasProperty("_MainTex")) return false; + + string name = material.name.ToLowerInvariant(); + return name.Contains("sail"); + } + + // ---------------------------------------------------------------- the texture + + private static Texture2D Draw(int seed) + { + Texture2D texture = new Texture2D(Size, Size, TextureFormat.RGBA32, true) + { + name = "boneship_sail", + wrapMode = TextureWrapMode.Clamp, + filterMode = FilterMode.Bilinear, + }; + + Color32[] pixels = new Color32[Size * Size]; + for (int y = 0; y < Size; y++) + { + float v = (y + 0.5f) / Size; + for (int x = 0; x < Size; x++) + { + float u = (x + 0.5f) / Size; + pixels[y * Size + x] = Pixel(u, v, seed); + } + } + + texture.SetPixels32(pixels); + texture.Apply(true, false); + return texture; + } + + private static Color32 Pixel(float u, float v, int seed) + { + // Cloth: near black, mottled, with a faint warp of vertical streaks. + float mottle = Fbm(u * 7f, v * 7f, seed + 3); + float streak = 0.5f + 0.5f * Mathf.Sin(u * 90f + Fbm(u * 3f, v * 3f, seed + 5) * 6f); + float shade = Mathf.Lerp(0.04f, 0.17f, mottle) * Mathf.Lerp(0.85f, 1.05f, streak); + Color cloth = new Color(shade * 1.00f, shade * 0.97f, shade * 0.93f, 1f); + + // Holes. Each term is an alpha with 0.5 at its own edge; the lowest wins. + float tear = Fbm(u * 4f, v * 4f, seed + 11); + float shred = Fbm(u * 13f, v * 13f, seed + 29); + + float alpha = 1f; + alpha = Mathf.Min(alpha, 0.5f + (TearThreshold - tear) * 14f); + alpha = Mathf.Min(alpha, 0.5f + (ShredThreshold - shred) * 14f); + + // Fringe: the top and bottom edges are eaten away in ragged teeth, the sides a little. + float edge = Mathf.Min(v, 1f - v); + float teeth = ValueNoise(u * 22f, v * 3f, seed + 41); + alpha = Mathf.Min(alpha, 0.5f + (teeth * 0.16f - edge) * 28f); + + float side = Mathf.Min(u, 1f - u); + float sideTeeth = ValueNoise(u * 3f, v * 20f, seed + 53); + alpha = Mathf.Min(alpha, 0.5f + (sideTeeth * 0.07f - side) * 28f); + + // Scorched round the holes: darker where the tear is nearly through. + float burn = Mathf.Clamp01((tear - (TearThreshold - 0.10f)) * 8f); + cloth = Color.Lerp(cloth, new Color(0.015f, 0.015f, 0.015f, 1f), burn * 0.8f); + + cloth.a = Mathf.Clamp01(alpha); + return cloth; + } + + // ---------------------------------------------------------------- noise + + private static float Hash(int x, int y, int seed) + { + unchecked + { + int h = x * 374761393 + y * 668265263 + seed * 1442695041; + h = (h ^ (h >> 13)) * 1274126177; + return ((h ^ (h >> 16)) & 0xffff) / 65535f; + } + } + + private static float ValueNoise(float x, float y, int seed) + { + int xi = Mathf.FloorToInt(x); + int yi = Mathf.FloorToInt(y); + float tx = x - xi; + float ty = y - yi; + tx = tx * tx * (3f - 2f * tx); + ty = ty * ty * (3f - 2f * ty); + + float a = Hash(xi, yi, seed); + float b = Hash(xi + 1, yi, seed); + float c = Hash(xi, yi + 1, seed); + float d = Hash(xi + 1, yi + 1, seed); + + return Mathf.Lerp(Mathf.Lerp(a, b, tx), Mathf.Lerp(c, d, tx), ty); + } + + private static float Fbm(float x, float y, int seed) + { + float value = 0f; + float amplitude = 0.5f; + for (int octave = 0; octave < 4; octave++) + { + value += amplitude * ValueNoise(x, y, seed + octave * 17); + x *= 2.03f; + y *= 2.03f; + amplitude *= 0.5f; + } + return value / 0.9375f; // 0.5 + 0.25 + 0.125 + 0.0625, so the sum stays in 0..1 + } + } +} diff --git a/JotunnModStub/BoneShip/ShipMount.cs b/JotunnModStub/BoneShip/ShipMount.cs new file mode 100644 index 0000000..29f5e7e --- /dev/null +++ b/JotunnModStub/BoneShip/ShipMount.cs @@ -0,0 +1,392 @@ +using System.Collections.Generic; +using HarmonyLib; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// Holds a creature to one spot of a ship's deck, however the ship moves. + /// + /// The Bone Ship's archers (Skeleton_BoneShip.txt, section 6) are the Bound Sentry - a tamed archer + /// whose speeds are all zero - and zero speed alone does not keep a Character on a moving deck: it + /// is carried only as far as the game's own ground-body inheritance happens to carry it. So each + /// physics step the mount sets its position to the ship's local point and its velocity to the ship's + /// velocity at that point. Rotation is left to the archer: it turns to face what it shoots. + /// + /// Runs on the OWNER of the archer only; everyone else sees the result through the creature's own + /// ZSyncTransform. + /// + /// TWO WAYS TO KNOW THE SHIP. The F7 experiment sets Ship and LocalPoint directly and the mount does not + /// survive a reload (an archer that wakes without its ship is removed). The real archers are a prefab + /// of their own (BoneShipArcher) that carries this component from the start, and know their ship by its + /// id in their own ZDO: after a reload the ship is looked up again as soon as it is loaded. If the ship's + /// ZDO is gone altogether for a few seconds, the ship has sunk, and the archer goes with it - "it dies + /// with the ship", with nothing to remember. + /// + public class ShipMount : MonoBehaviour + { + /// ZDO keys on a ship's ARCHER: the ship it guards, and where it stands on it. + public const string KeyArcherShip = "RoV_bshArcherShip"; + public const string KeyArcherPoint = "RoV_bshArcherPoint"; + public const string KeyArcherBust = "RoV_bshArcherBust"; + public const string KeyArcherPost = "RoV_bshArcherPost"; + + /// Seconds without the ship's ZDO before the archer decides the ship is gone. + private const float GoneAfter = 6f; + + /// The ship this creature is bolted to. + public Ship Ship; + + /// Where on that ship, in the ship's own space. + public Vector3 LocalPoint; + + private ZNetView m_nview; + private Rigidbody m_body; + private Rigidbody m_shipBody; + private ZDOID m_shipId = ZDOID.None; + private bool m_byId; + private float m_missing; + + private float m_nextResolve; + + private void Awake() + { + m_nview = GetComponent(); + m_body = GetComponent(); + + // No interpolation on the archer's own body: the transform is set by hand every frame in + // LateUpdate, and a body that interpolates between physics steps would fight that and put back + // the very stutter this exists to remove. + if (m_body != null) m_body.interpolation = RigidbodyInterpolation.None; + } + + private void Start() + { + if (Ship != null) { IgnoreShipColliders(); return; } + + // The real archers: the ship is a number in their own ZDO. Read on EVERY client, not just the + // owner, because every client pins the visual to the ship (LateUpdate). + if (m_nview == null || !m_nview.IsValid()) return; + m_shipId = m_nview.GetZDO().GetZDOID(KeyArcherShip); + if (m_shipId == ZDOID.None) return; + + LocalPoint = m_nview.GetZDO().GetVec3(KeyArcherPoint, Vector3.zero); + m_byId = true; + } + + /// + /// Every frame, on every client: the archer's transform is the ship's local point, taken from the + /// ship's own (interpolated) transform at render time. + /// + /// The physics pin below only moves the archer once per physics step, from where the ship was at the + /// start of that step. The ship is drawn smoothly between steps and the archer was not, so at speed + /// it jumped in 50 Hz hops against a hull that glides - "in jerks", and, trailing a step behind, + /// looking not quite attached. Setting the transform here, after everything else has moved it, makes + /// it exactly as smooth as the hull it stands on. For a remote client this also overrides the + /// position the network would give it, which is itself a few steps old. + /// + private void LateUpdate() + { + if (Ship == null) + { + if (m_byId && Time.time >= m_nextResolve) + { + m_nextResolve = Time.time + 0.5f; + TryResolveShip(); + } + return; + } + + transform.position = Ship.transform.TransformPoint(LocalPoint); + } + + private bool TryResolveShip() + { + GameObject found = ZNetScene.instance != null ? ZNetScene.instance.FindInstance(m_shipId) : null; + Ship ship = found != null ? found.GetComponent() : null; + if (ship == null) return false; + + Ship = ship; + m_missing = 0f; + IgnoreShipColliders(); + return true; + } + + /// + /// Pinned inside the ship's own volume, so it must not fight the ship's colliders: with them live the + /// physics keeps trying to push it out and the mount keeps putting it back. Ignoring them costs + /// nothing - it is invulnerable, and nobody needs to bump into it. + /// + private void IgnoreShipColliders() + { + Collider[] mine = GetComponentsInChildren(true); + Collider[] theirs = Ship.GetComponentsInChildren(true); + foreach (Collider a in mine) + { + if (a == null) continue; + foreach (Collider b in theirs) + { + if (b != null) Physics.IgnoreCollision(a, b, true); + } + } + } + + private void FixedUpdate() + { + if (m_nview == null || !m_nview.IsValid() || !m_nview.IsOwner()) return; + + if (Ship == null) + { + if (m_byId) FindShip(); + else if (ZNetScene.instance != null) ZNetScene.instance.Destroy(gameObject); // the experiment's way + return; + } + + if (m_body == null) return; + if (m_shipBody == null) m_shipBody = Ship.GetComponent(); + + Vector3 target = Ship.transform.TransformPoint(LocalPoint); + m_body.position = target; + m_body.velocity = m_shipBody != null ? m_shipBody.GetPointVelocity(target) : Vector3.zero; + } + + /// + /// Looks the ship up by id. Loaded: bolted on. Not loaded but still in the world's books: wait, it is + /// about to be (they load together). Not in the books at all, for long enough: it has sunk. + /// + private void FindShip() + { + if (TryResolveShip()) return; + + if (ZDOMan.instance != null && ZDOMan.instance.GetZDO(m_shipId) != null) + { + m_missing = 0f; + return; + } + + m_missing += Time.fixedDeltaTime; + if (m_missing >= GoneAfter && ZNetScene.instance != null) ZNetScene.instance.Destroy(gameObject); + } + } + + /// + /// Makes an archer a BUST: the leg bones are collapsed to nothing every frame, so only the pelvis, the + /// chest and the arms show - a figurehead that shoots. + /// + /// The model cannot be cut, so the legs are scaled to zero where they join the hips: everything skinned + /// to them folds into that point. A leg bone's children inherit the zero, so feet and shins go with it. + /// It is done in LateUpdate, after the animator has written its pose, so nothing animated can put them + /// back. The BONE NAMES are not verified - they are searched for ("upleg", "thigh", "upperleg") on the + /// first frame and what was found is logged. If it finds none it logs the whole skeleton, which is the + /// list the next attempt is written from. + /// + public class ShipBust : MonoBehaviour + { + private static readonly string[] LegBones = { "upleg", "thigh", "upperleg", "leg_upper" }; + + private readonly List m_legs = new List(); + + /// Set by the F7 experiment; the real archers say so in their ZDO instead. + public bool Force; + + private void Start() + { + // On the prefab of the real archers this component is always there, and only the ones placed as a + // bust (the ZDO says so) are cut off at the waist; the deck ones keep their legs. + ZNetView nview = GetComponent(); + bool bust = Force || (nview != null && nview.IsValid() && nview.GetZDO().GetBool(ShipMount.KeyArcherBust, false)); + if (!bust) + { + enabled = false; + return; + } + + foreach (Transform t in GetComponentsInChildren(true)) + { + string n = t.name.ToLowerInvariant(); + foreach (string key in LegBones) + { + if (!n.Contains(key)) continue; + + // Only the topmost of a chain: a bone whose parent is already a leg is covered by it. + if (!m_legs.Contains(t.parent)) m_legs.Add(t); + break; + } + } + + if (m_legs.Count > 0) + { + List names = new List(); + foreach (Transform t in m_legs) names.Add(t.name); + Jotunn.Logger.LogInfo("[ShipBust] collapsing " + m_legs.Count + " leg bone(s): " + string.Join(", ", names.ToArray())); + return; + } + + // Nothing matched: say what is there so the names can be read instead of guessed. + List all = new List(); + foreach (Transform t in GetComponentsInChildren(true)) all.Add(t.name); + Jotunn.Logger.LogWarning("[ShipBust] no leg bone matched. Skeleton: " + string.Join(", ", all.ToArray())); + } + + private void LateUpdate() + { + foreach (Transform leg in m_legs) + { + if (leg != null) leg.localScale = Vector3.zero; + } + } + } + + /// + /// A ship's archer cannot be killed - it goes down with the ship, which is the stake. Skipping + /// Character.Damage is enough: the Bound Sentry's own regeneration patch only listens to it too. + /// + [HarmonyPatch(typeof(Character), "Damage")] + public static class ShipMountInvulnerablePatch + { + public static bool Prefix(Character __instance) + { + return __instance.GetComponent() == null; + } + } + + /// + /// The deck-finding and post table the bone ships use to place their archers. + /// + /// WHERE: a local (x, z) per ship, and the height is NOT guessed - a ray is dropped from above that + /// spot and the deck is wherever it first hits the ship's own solid collider. The mast and the sail's + /// cloth collider are skipped. The point it settled on is reported, so a bad spot is fixed by editing + /// the table below, not by reading code. + /// + public static class ShipMountTest + { + private const float ShipRange = 40f; + private const float RayStartHeight = 8f; + private const float RayLength = 20f; + + /// + /// One archer's place: where on the deck (local x, z), and whether it is a BUST - only the chest and + /// up shows, the legs are collapsed, and it stands on the stem as a figurehead that shoots. + /// + private struct Post + { + public Vector2 At; + public bool Bust; + public Post(float x, float z, bool bust) { At = new Vector2(x, z); Bust = bust; } + } + + /// + /// The Karve's bow is at about local z = +4.8 (its WaterTrigger sits there, and the hull mesh is + /// ~10 m long); the post is a little back from the very tip so the ray finds the hull under it. + /// The large ships keep their deck posts until they get a bust of their own. + /// + private static readonly Dictionary Posts = new Dictionary + { + { "Karve", new[] { new Post(0f, 4.3f, true) } }, + { "BoneKarve", new[] { new Post(0f, 4.3f, true) } }, + { "VikingShip", new[] { new Post(0f, 3.2f, false), new Post(0f, -5.0f, false) } }, + { "BoneLongship", new[] { new Post(0f, 3.2f, false), new Post(0f, -5.0f, false) } }, + { "VikingShip_Ashlands", new[] { new Post(0f, 3.2f, false), new Post(0f, -5.0f, false) } }, + { "BoneAshlands", new[] { new Post(0f, 3.2f, false), new Post(0f, -5.0f, false) } }, + }; + + private static readonly Post[] DefaultPosts = { new Post(0f, 0f, false) }; + + /// + /// How far above the hull's surface a bust stands, in metres: the pelvis is left as a stub where the + /// legs were, and this keeps that stub inside the stem instead of above it. To be tuned by eye. + /// + private const float BustLift = 0.0f; + + /// The deck under a local (x, z): the highest solid surface of THIS ship, not the mast or the sail. + private static bool FindDeck(Ship ship, Vector2 post, bool bust, out Vector3 local, out string hitName) + { + local = Vector3.zero; + hitName = ""; + + // A deck is flat. A bow is not: near the stem the hull's surface climbs steeply, and a flat-only + // filter (normal.y >= 0.5) found nothing there at all. A bust takes ANY surface of the ship under + // the point, and if the point is past the end of the hull it walks back toward the middle until + // something is there - the step it settled on shows in the reported local z. + float minUp = bust ? -1f : 0.5f; + float maxBack = bust ? 2.4f : 0f; + const float Step = 0.3f; + + for (float back = 0f; back <= maxBack + 0.001f; back += Step) + { + Vector3 origin = ship.transform.TransformPoint(new Vector3(post.x, RayStartHeight, post.y - back)); + Vector3 down = -ship.transform.up; + + RaycastHit best = default(RaycastHit); + bool found = false; + float bestDistance = float.MaxValue; + + foreach (RaycastHit hit in Physics.RaycastAll(origin, down, RayLength)) + { + if (hit.collider == null || hit.collider.isTrigger) continue; + if (!hit.collider.transform.IsChildOf(ship.transform)) continue; + if (Vector3.Dot(hit.normal, ship.transform.up) < minUp) continue; + + string n = hit.collider.name.ToLowerInvariant(); + if (n.Contains("mast") || n.Contains("cloth")) continue; + + if (hit.distance >= bestDistance) continue; + best = hit; + bestDistance = hit.distance; + found = true; + } + + if (!found) continue; + + local = ship.transform.InverseTransformPoint(best.point); + hitName = best.collider.name + (back > 0f ? " (stepped back " + back.ToString("F1") + " m)" : ""); + return true; + } + + return false; + } + + private static Ship NearestShip() + { + Player player = Player.m_localPlayer; + if (player == null) return null; + + Ship best = null; + float bestDistance = ShipRange; + foreach (Ship ship in Object.FindObjectsOfType()) + { + float distance = Vector3.Distance(ship.transform.position, player.transform.position); + if (distance >= bestDistance) continue; + best = ship; + bestDistance = distance; + } + return best; + } + + private static List MountsOn(Ship ship) + { + List mounts = new List(); + foreach (Character character in Character.GetAllCharacters()) + { + if (character == null) continue; + + ShipMount mount = character.GetComponent(); + if (mount != null && mount.Ship == ship) mounts.Add(mount); + } + return mounts; + } + + /// "Karve(Clone)" to "Karve". + private static string Clean(string name) + { + int paren = name.IndexOf('('); + return (paren >= 0 ? name.Substring(0, paren) : name).Trim(); + } + + private static void Report(string line) + { + Jotunn.Logger.LogInfo(line); + if (Console.instance != null) Console.instance.Print(line); + } + } +} diff --git a/JotunnModStub/Fenrir/FenrirBehaviors.cs b/JotunnModStub/Fenrir/FenrirBehaviors.cs index ae12e38..abe0846 100644 --- a/JotunnModStub/Fenrir/FenrirBehaviors.cs +++ b/JotunnModStub/Fenrir/FenrirBehaviors.cs @@ -513,6 +513,7 @@ namespace RacesOfValheim private Animator fenrirAnim; private readonly FormLocomotion locomotion = new FormLocomotion(); + private float busySince = -1f; private bool isAttacking = false; void Start() @@ -525,6 +526,12 @@ namespace RacesOfValheim void Update() { + if (FormAnimGuard.Stuck(isAttacking, ref busySince)) + { + StopAllCoroutines(); + isAttacking = false; + } + if (playerAnim == null || fenrirAnim == null) return; // Se stiamo attaccando, l'Update smette di inviare costantemente @@ -590,6 +597,7 @@ namespace RacesOfValheim private IEnumerator ClawRoutine(string triggerName, float baseDamage, float lockDuration, float dmgDelay) { isAttacking = true; + FormAnimGuard.LeaveHowl(fenrirAnim); fenrirAnim.SetFloat("forward_speed", 0f); fenrirAnim.SetFloat("sideway_speed", 0f); @@ -624,6 +632,7 @@ namespace RacesOfValheim private IEnumerator JumpAttackRoutine() { isAttacking = true; + FormAnimGuard.LeaveHowl(fenrirAnim); fenrirAnim.SetFloat("forward_speed", 0f); fenrirAnim.SetFloat("sideway_speed", 0f); @@ -756,6 +765,7 @@ namespace RacesOfValheim private Animator cultistAnim; private readonly FormLocomotion locomotion = new FormLocomotion(); + private float busySince = -1f; private bool isAttacking = false; private bool isShootingFire = false; private float fireTimer = 0f; @@ -769,6 +779,12 @@ namespace RacesOfValheim } void Update() { + if (FormAnimGuard.Stuck(isAttacking, ref busySince)) + { + StopAllCoroutines(); + isAttacking = false; + } + if (playerAnim == null || cultistAnim == null) return; if (!isAttacking) @@ -889,6 +905,7 @@ namespace RacesOfValheim if (Player.m_localPlayer == null || isShootingFire) return; isShootingFire = true; + FormAnimGuard.LeaveHowl(cultistAnim); cultistAnim.SetFloat("forward_speed", 0f); cultistAnim.SetFloat("sideway_speed", 0f); cultistAnim.SetBool("attack_fire", true); @@ -1003,6 +1020,7 @@ namespace RacesOfValheim private IEnumerator ClawRoutine() { isAttacking = true; + FormAnimGuard.LeaveHowl(cultistAnim); cultistAnim.SetFloat("forward_speed", 0f); cultistAnim.SetFloat("sideway_speed", 0f); @@ -1030,6 +1048,7 @@ namespace RacesOfValheim private IEnumerator DoubleClawRoutine() { isAttacking = true; + FormAnimGuard.LeaveHowl(cultistAnim); cultistAnim.SetFloat("forward_speed", 0f); cultistAnim.SetFloat("sideway_speed", 0f); @@ -1130,6 +1149,7 @@ namespace RacesOfValheim private Animator playerAnim; private Animator wolfAnim; private readonly FormLocomotion locomotion = new FormLocomotion(); + private float busySince = -1f; private bool isAttacking = false; void Start() @@ -1142,6 +1162,12 @@ namespace RacesOfValheim void Update() { + if (FormAnimGuard.Stuck(isAttacking, ref busySince)) + { + StopAllCoroutines(); + isAttacking = false; + } + if (playerAnim == null || wolfAnim == null) return; if (!isAttacking) @@ -1195,49 +1221,64 @@ namespace RacesOfValheim { isAttacking = true; - try { wolfAnim.SetFloat("forward_speed", 0f); } catch {} - try { wolfAnim.SetFloat("sideway_speed", 0f); } catch {} + try + { + try { wolfAnim.SetFloat("forward_speed", 0f); } catch {} + try { wolfAnim.SetFloat("sideway_speed", 0f); } catch {} - FenrirCreatureSound.Howl(wolfAnim, "Wolf", Player.m_localPlayer.transform.position); + FenrirCreatureSound.Howl(wolfAnim, "Wolf", Player.m_localPlayer.transform.position); - // The wolf's howl clip runs 3.13s. Held a little past it so the form does not snap back - // into a bite the instant the sound ends. - yield return new WaitForSeconds(3.3f); - - isAttacking = false; + // The wolf's howl clip runs 3.13s. Held a little past it so the form does not snap back + // into a bite the instant the sound ends. + yield return new WaitForSeconds(3.3f); + } + finally + { + isAttacking = false; + } } private IEnumerator WolfAttackRoutine(string triggerName, float baseDamage, float lockDuration, float dmgDelay) { isAttacking = true; - try { wolfAnim.SetFloat("forward_speed", 0f); } catch {} - try { wolfAnim.SetFloat("sideway_speed", 0f); } catch {} - - wolfAnim.SetTrigger(triggerName); - FenrirAttackSync.Publish(triggerName, "sfx_wolf_attack"); - - yield return new WaitForSeconds(dmgDelay); - - if (ZNetScene.instance != null) + // finally and not a plain assignment at the end: an exception anywhere below used to + // leave isAttacking true for good, and Update does nothing at all while it is. + try { - GameObject attackSfx = ZNetScene.instance.GetPrefab("sfx_wolf_attack"); - if (attackSfx != null) + // Out of the howl first - see FormAnimGuard. + FormAnimGuard.LeaveHowl(wolfAnim); + + try { wolfAnim.SetFloat("forward_speed", 0f); } catch {} + try { wolfAnim.SetFloat("sideway_speed", 0f); } catch {} + + wolfAnim.SetTrigger(triggerName); + FenrirAttackSync.Publish(triggerName, "sfx_wolf_attack"); + + yield return new WaitForSeconds(dmgDelay); + + if (ZNetScene.instance != null) { - FenrirCreatureSound.Spawn(attackSfx, Player.m_localPlayer.transform.position); + GameObject attackSfx = ZNetScene.instance.GetPrefab("sfx_wolf_attack"); + if (attackSfx != null) + { + FenrirCreatureSound.Spawn(attackSfx, Player.m_localPlayer.transform.position); + } + } + + ExecuteBiteDamage(baseDamage); + + float remainingTimeToIdle = lockDuration - dmgDelay; + if (remainingTimeToIdle > 0) + { + yield return new WaitForSeconds(remainingTimeToIdle); } } - - ExecuteBiteDamage(baseDamage); - - float remainingTimeToIdle = lockDuration - dmgDelay; - if (remainingTimeToIdle > 0) + finally { - yield return new WaitForSeconds(remainingTimeToIdle); + try { wolfAnim.ResetTrigger(triggerName); } catch {} + isAttacking = false; } - - wolfAnim.ResetTrigger(triggerName); - isAttacking = false; } private void ExecuteBiteDamage(float baseDamage) @@ -1321,6 +1362,7 @@ namespace RacesOfValheim private Animator ulvAnim; private readonly FormLocomotion locomotion = new FormLocomotion(); + private float busySince = -1f; private bool isAttacking = false; void Start() @@ -1332,6 +1374,12 @@ namespace RacesOfValheim void Update() { + if (FormAnimGuard.Stuck(isAttacking, ref busySince)) + { + StopAllCoroutines(); + isAttacking = false; + } + if (Player.m_localPlayer == null || playerAnim == null || ulvAnim == null) return; if (!isAttacking) @@ -1402,6 +1450,7 @@ namespace RacesOfValheim private IEnumerator UlvAttackRoutine(string triggerName, float baseDamage, float lockDuration, float dmgDelay) { isAttacking = true; + FormAnimGuard.LeaveHowl(ulvAnim); try { ulvAnim.SetFloat("forward_speed", 0f); } catch {} try { ulvAnim.SetFloat("sideway_speed", 0f); } catch {} @@ -1510,6 +1559,7 @@ namespace RacesOfValheim private IEnumerator UlvJumpAttackRoutine() { isAttacking = true; + FormAnimGuard.LeaveHowl(ulvAnim); try { ulvAnim.SetFloat("forward_speed", 0f); } catch {} try { ulvAnim.SetFloat("sideway_speed", 0f); } catch {} diff --git a/JotunnModStub/Fenrir/FenrirFormShared.cs b/JotunnModStub/Fenrir/FenrirFormShared.cs index 37d066c..4bb14e4 100644 --- a/JotunnModStub/Fenrir/FenrirFormShared.cs +++ b/JotunnModStub/Fenrir/FenrirFormShared.cs @@ -61,6 +61,67 @@ namespace RacesOfValheim } } + /// + /// Two ways a form's Animator and its attack lock got stuck, shared by all four forms. + /// + /// The idle howl is a looping clip the attack triggers cannot leave: a click during it queued a + /// trigger the Animator never took, and the model stood frozen until the form was dropped. + /// And an exception inside an attack routine left isAttacking true for good - Update does + /// nothing at all while it is - so the watchdog gives any lock a ceiling. + /// + internal static class FormAnimGuard + { + /// Longer than the longest legitimate routine (the Ulv's howl, 3.8 s, plus a margin). + private const float MaxLockSeconds = 8f; + + /// If the Animator is inside a howl clip, puts it back on its default state so the + /// trigger set next lands on the idle and not on the loop. Call after isAttacking is set. + public static void LeaveHowl(Animator animator) + { + if (animator == null) return; + + try + { + foreach (AnimatorClipInfo clip in animator.GetCurrentAnimatorClipInfo(0)) + { + if (clip.clip == null) continue; + + string lower = clip.clip.name.ToLower(); + if (!lower.Contains("hawl") && !lower.Contains("howl")) continue; + + animator.Rebind(); + animator.Update(0f); + return; + } + } + catch {} + } + + /// True once the lock has been held longer than any routine can legitimately hold + /// it. Call every Update; is the caller's own field. + public static bool Stuck(bool locked, ref float since) + { + if (!locked) + { + since = -1f; + return false; + } + + if (since < 0f) + { + since = Time.time; + return false; + } + + if (Time.time - since <= MaxLockSeconds) return false; + + since = -1f; + Jotunn.Logger.LogWarning("[FenrirForm] An attack lock held for more than " + MaxLockSeconds + + " s was released; something in a routine did not finish."); + return true; + } + } + /// /// Whether a melee swing of a form can reach what it found, shared by the four claw and bite /// attacks. diff --git a/JotunnModStub/Package/manifest.json b/JotunnModStub/Package/manifest.json index f25edd0..e29ebe8 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.5.5", + "version_number": "1.5.6", "website_url": "", "dependencies": [ "denikson-BepInExPack_Valheim-5.4.2333", diff --git a/JotunnModStub/RacesOfValheim.cs b/JotunnModStub/RacesOfValheim.cs index 7d6b88a..7bbd88e 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.5.5"; + public const string PluginVersion = "1.5.6"; private readonly Harmony harmony = new Harmony(PluginGUID); diff --git a/JotunnModStub/RaisedThrall.cs b/JotunnModStub/RaisedThrall.cs index c46aea5..ea2c6c1 100644 --- a/JotunnModStub/RaisedThrall.cs +++ b/JotunnModStub/RaisedThrall.cs @@ -38,6 +38,18 @@ namespace RacesOfValheim // bound to a pile in the first place, so the anchor/wither pair has nothing to key off. public const string KeyExpiresAt = "RoV_thrallExpiresAt"; + // WAIT: where it was told to stay. A Vector3 in the creature's own ZDO, zero meaning "not waiting". + // It has to be state that survives, because TickLeash sends anything that is not following home + // every two seconds - a "stay" that was only a follow target of null would walk back to the station + // on the next tick. With this set, the leash pins THERE instead of at the anchor. + public const string KeyWaitPoint = "RoV_waitPoint"; + + // A ship's troop sent home: the ship's roster takes these aboard (BoneShipRoster). + public const string KeyRecall = "RoV_bshRecall"; + + /// How far a waiting thrall will wander from the spot it was told to hold, metres. + private const float WaitRoam = 2.5f; + // ─── Set on the prefab at registration ─────────────────────────────── /// Groups thralls for follower caps and for a station's per-kind roster. @@ -109,16 +121,41 @@ namespace RacesOfValheim private MonsterAI m_monsterAI; private ZNetView m_nview; + // The prefab's own roaming radius, kept so a wait (which tightens it) can give it back. + private float m_roamRange; + private void Awake() { m_character = GetComponent(); m_ai = GetComponent(); m_monsterAI = GetComponent(); m_nview = GetComponent(); + m_roamRange = m_ai != null ? m_ai.m_randomMoveRange : 0f; InvokeRepeating("TickLeash", 2f, 2f); } + /// The three orders a thrall answers to, however they are given. + public enum Order { Follow, Wait, Home } + + /// Where it was told to hold, or null if it is not waiting. + public Vector3? WaitPoint + { + get + { + if (m_nview == null || !m_nview.IsValid()) return null; + + Vector3 point = m_nview.GetZDO().GetVec3(KeyWaitPoint, Vector3.zero); + return point == Vector3.zero ? (Vector3?)null : point; + } + } + + public bool IsWaiting => WaitPoint != null; + + /// True for a troop that belongs to a bone ship: it answers to anyone, as the ship does. + public bool IsShipTroop => + m_nview != null && m_nview.IsValid() && m_nview.GetZDO().GetZDOID(BoneShipRoster.KeyShip) != ZDOID.None; + /// Where the station that made this one stands, or null if it was not made by one. public Vector3? Anchor { @@ -255,22 +292,62 @@ namespace RacesOfValheim /// private void GoHome() { - Vector3? anchor = Anchor; - if (anchor == null || m_ai == null) return; + if (m_ai == null) return; + // A wait wins over the anchor: the leash holds the spot it was told to hold, and tightly. + Vector3? wait = WaitPoint; + if (wait != null) + { + SetRoam(Mathf.Min(WaitRoam, m_roamRange > 0f ? m_roamRange : WaitRoam)); + PinPatrol(wait.Value); + return; + } + + SetRoam(m_roamRange); + + Vector3? anchor = Anchor; + if (anchor == null) return; + + PinPatrol(anchor.Value); + } + + /// Points the patrol at a place. Also how a ship's roster walks a recalled troop to its ship. + public void WalkTo(Vector3 point) + { + if (m_ai != null) PinPatrol(point); + } + + private void PinPatrol(Vector3 point) + { if (SetPatrolPointMethod != null) { - SetPatrolPointMethod.Invoke(m_ai, new object[] { anchor.Value }); + SetPatrolPointMethod.Invoke(m_ai, new object[] { point }); } else { // Fall back to writing the two fields the private method writes. Traverse traverse = Traverse.Create(m_ai); - traverse.Field("m_patrolPoint").SetValue(anchor.Value); + traverse.Field("m_patrolPoint").SetValue(point); traverse.Field("m_patrol").SetValue(true); } } + /// Only for a creature that roams at all: the sentries and golems are rooted at zero and stay so. + private void SetRoam(float range) + { + if (m_ai != null && m_roamRange > 0f) m_ai.m_randomMoveRange = range; + } + + /// Forgets a wait and a recall: any new order starts from nothing. + private void ClearStay() + { + if (m_nview == null || !m_nview.IsValid()) return; + + m_nview.ClaimOwnership(); + m_nview.GetZDO().Set(KeyWaitPoint, Vector3.zero); + m_nview.GetZDO().Set(KeyRecall, false); + } + // ---------------------------------------------------------------- commands public bool MayBeCommandedBy(Player player) @@ -278,6 +355,9 @@ namespace RacesOfValheim if (player == null) return false; if (string.IsNullOrEmpty(m_commandingRace)) return true; + // A bone ship is open to every race, so its crew answers to whoever is on the deck. + if (IsShipTroop) return true; + return player.m_customData != null && player.m_customData.TryGetValue("Race", out string race) && race == m_commandingRace; @@ -296,8 +376,14 @@ namespace RacesOfValheim if (!follow) { + ClearStay(); m_monsterAI.SetFollowTarget(null); GoHome(); + + // A ship's troop has no anchor to go home to: home is the ship, and the ship's roster, which + // sees this flag, walks it there and takes it aboard. + if (IsShipTroop) m_nview.GetZDO().Set(KeyRecall, true); + if (announce) player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_thrall_returns", m_character.m_name)); return true; } @@ -320,6 +406,8 @@ namespace RacesOfValheim // STATION - so the further from home, the fewer fights it would take. ResetPatrolPoint // writes the ZDO as well as the field, which matters: GetPatrolPoint re-reads the ZDO // every second and would switch it straight back on. + ClearStay(); + SetRoam(m_roamRange); if (m_ai != null) m_ai.ResetPatrolPoint(); m_monsterAI.SetFollowTarget(player.gameObject); @@ -328,12 +416,47 @@ namespace RacesOfValheim } /// - /// Follow if it is not, come home if it is - the wolf's own single-key behaviour, plus an escort - /// if this thrall leads one. + /// Tells it to hold where it stands: it stops following, forgets the station for now, and keeps to a + /// couple of metres of this spot until given another order. Returns false if it refused. + /// + public bool SetWaiting(Player player, bool announce) + { + if (player == null || m_monsterAI == null || m_character == null) return false; + if (m_nview == null || !m_nview.IsValid()) return false; + + if (!MayBeCommandedBy(player)) + { + if (announce) player.Message(MessageHud.MessageType.Center, m_refusalMessage); + return false; + } + + ClearStay(); + m_nview.GetZDO().Set(KeyWaitPoint, transform.position); + + m_monsterAI.SetFollowTarget(null); + GoHome(); + + if (announce) player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_thrall_waits", m_character.m_name)); + return true; + } + + /// + /// One key, three orders in a ring: follow, then wait, then home, then follow again. It used to be + /// two (follow, home); "wait" slots in between because it is the step you want most often and the + /// one you can least afford to get by going all the way home and back. Escorts (a Rancid Remains' + /// squad) go with it on follow and home, as before; a wait is for this one alone. /// public void ToggleCommand(Player player) { - bool follow = !IsFollowing(player); + Order next = IsFollowing(player) ? Order.Wait : IsWaiting ? Order.Home : Order.Follow; + + if (next == Order.Wait) + { + SetWaiting(player, announce: true); + return; + } + + bool follow = next == Order.Follow; if (!SetFollowing(player, follow, announce: m_escortCount <= 0)) return; if (m_escortCount <= 0) return; @@ -399,32 +522,48 @@ namespace RacesOfValheim public const float TauntRange = 30f; /// - /// The emote that calls thralls to their master. A SET rather than one string because the emote + /// The emotes that give the three group orders. SETS rather than single strings because the emote /// names are not in the assembly at all - Valheim builds them from what the player types in - /// chat, so unlike every other name in this project this one could not be read off the game and + /// chat, so unlike every other name in this project these could not be read off the game and /// verified. The patch below logs whatever it actually receives, so a wrong guess here is one /// line away from being right instead of a mystery. + /// + /// comehere - follow (the original) + /// thumbsup - wait (decided 2026-10-05; "sit" was ruled out, it is what you do at a fire) + /// wave - go home (decided; a greeting to another player will also send a nearby crew home - + /// the price of the choice, to be watched in play) /// - private static readonly HashSet TauntEmotes = new HashSet + private static readonly HashSet FollowEmotes = new HashSet { "comehere", "come_here", "followme" }; + private static readonly HashSet WaitEmotes = new HashSet { "thumbsup", "thumbs_up" }; + private static readonly HashSet HomeEmotes = new HashSet { "wave" }; + + /// Which group order an emote gives, or null for none. + public static Order? OrderOfEmote(string emote) { - "comehere", "come_here", "followme", - }; + if (emote == null) return null; + + string name = emote.ToLowerInvariant(); + if (FollowEmotes.Contains(name)) return Order.Follow; + if (WaitEmotes.Contains(name)) return Order.Wait; + if (HomeEmotes.Contains(name)) return Order.Home; + return null; + } /// - /// Everything within earshot that answers to this player falls in behind them. - /// - /// Only ever a call, never a dismissal: "come here" means come here. Sending them home stays - /// with the station and with a click on the thrall itself. + /// Everything within earshot that answers to this player gets the order. Follow is the old call to + /// arms; wait and home are its two new sisters, and "home" is a dismissal after all - which the old + /// design kept for the station and for a click, and now has a gesture of its own. /// /// The per-race follower cap needs no special handling - SetFollowing enforces m_maxFollowers /// itself, so the Skeleton's whole garrison answers (-1, no limit) and the Draugh's gets three - /// draugr and one officer, from exactly the same call. + /// draugr and one officer, from exactly the same call. The Butler is not a RaisedThrall (it was kept + /// out of this class on purpose) so it never answers any of them, which is the decision. /// - public static void CallToArms(Player player) + public static void GroupOrder(Player player, Order order) { if (player == null) return; - int came = 0; + int answered = 0; int refused = 0; foreach (Character character in Character.GetAllCharacters()) @@ -432,18 +571,40 @@ namespace RacesOfValheim if (character == null || character.IsDead()) continue; RaisedThrall thrall = character.GetComponent(); - if (thrall == null || thrall.IsFollowing(player)) continue; + if (thrall == null) continue; if (!thrall.MayBeCommandedBy(player)) continue; if (Vector3.SqrMagnitude(character.transform.position - player.transform.position) > TauntRange * TauntRange) continue; - if (thrall.SetFollowing(player, true, announce: false)) came++; - else refused++; + bool following = thrall.IsFollowing(player); + + switch (order) + { + case Order.Follow: + if (following) continue; + if (thrall.SetFollowing(player, true, announce: false)) answered++; + else refused++; + break; + + case Order.Wait: + if (thrall.IsWaiting && !following) continue; + if (thrall.SetWaiting(player, announce: false)) answered++; + break; + + case Order.Home: + // Already home: not following, not waiting. A wait and a follow both end here. + if (!following && !thrall.IsWaiting) continue; + if (thrall.SetFollowing(player, false, announce: false)) answered++; + break; + } } - if (came > 0) + if (answered > 0) { - player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_thrall_answer_call", came)); + string key = order == Order.Follow ? "rov_msg_thrall_answer_call" + : order == Order.Wait ? "rov_msg_thrall_answer_wait" + : "rov_msg_thrall_answer_home"; + player.Message(MessageHud.MessageType.Center, ModText.Get(key, answered)); } else if (refused > 0) { @@ -452,9 +613,12 @@ namespace RacesOfValheim } } + /// The original call, kept under its old name for the places that still use it. + public static void CallToArms(Player player) => GroupOrder(player, Order.Follow); + public static bool IsTauntEmote(string emote) { - return emote != null && TauntEmotes.Contains(emote.ToLowerInvariant()); + return OrderOfEmote(emote) == Order.Follow; } public void Kill() @@ -502,10 +666,11 @@ namespace RacesOfValheim { if (__instance != Player.m_localPlayer) return; - Jotunn.Logger.LogInfo($"[Thrall] emote '{__0}'" + - (RaisedThrall.IsTauntEmote(__0) ? " - calling thralls." : ".")); + RaisedThrall.Order? order = RaisedThrall.OrderOfEmote(__0); - if (RaisedThrall.IsTauntEmote(__0)) RaisedThrall.CallToArms(__instance); + Jotunn.Logger.LogInfo($"[Thrall] emote '{__0}'" + (order != null ? $" - order: {order}." : ".")); + + if (order != null) RaisedThrall.GroupOrder(__instance, order.Value); } } diff --git a/JotunnModStub/Skadi/SkadiRace.cs b/JotunnModStub/Skadi/SkadiRace.cs index 16744af..573685d 100644 --- a/JotunnModStub/Skadi/SkadiRace.cs +++ b/JotunnModStub/Skadi/SkadiRace.cs @@ -258,15 +258,6 @@ namespace RacesOfValheim if (SkadiConfig.DrakeFormKey.Value.IsDownIgnoringHeldKeys()) { TryTransformWithRules(SkadiProgression.GetGKeyRules(state)); return; } if (SkadiConfig.ModerFormKey.Value.IsDownIgnoringHeldKeys()) { TryTransformWithRules(SkadiProgression.GetHKeyRules(state)); return; } if (SkadiConfig.FaderFormKey.Value.IsDownIgnoringHeldKeys()) { TryTransformWithRules(SkadiProgression.GetJKeyRules(state)); return; } - - // Debug Dump - if (Input.GetKeyDown(KeyCode.F8)) - { - DumpPrefabDebugInfo("Dragon"); - DumpPrefabDebugInfo("Hatchling"); - DumpPrefabDebugInfo("Fader"); - if (Player.m_localPlayer != null) Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_skadi_dumped_dragon_drake_fader_debug")); - } } private void DumpPrefabDebugInfo(string prefabName) diff --git a/JotunnModStub/Skeleton/SkeletonRace.cs b/JotunnModStub/Skeleton/SkeletonRace.cs index 94912d1..78aebe6 100644 --- a/JotunnModStub/Skeleton/SkeletonRace.cs +++ b/JotunnModStub/Skeleton/SkeletonRace.cs @@ -22,6 +22,9 @@ namespace RacesOfValheim // Skeleton is ever set up as a bench. SkeletonBonePile.Register(); + // The bone ship, Karve first. Same window, same reason: new pieces only register now. + BoneShip.Register(); + var se = ScriptableObject.CreateInstance(); se.name = "SE_SkeletonStats"; se.m_name = "$rov_se_skeleton_stats_name"; @@ -258,19 +261,6 @@ namespace RacesOfValheim private void Update() { - if (Input.GetKeyDown(KeyCode.F8)) - { - if (Hud.instance != null) - { - Jotunn.Logger.LogInfo("--- HUD HIERARCHY DUMP ---"); - DumpTransformHierarchy(Hud.instance.transform, ""); - Jotunn.Logger.LogInfo("--------------------------"); - } - - LogRaycastHit(); - LogHeadCosmeticsState(); - } - if (Player.m_localPlayer == null) return; if (!IsSkeleton() || Player.m_localPlayer.IsDead()) diff --git a/JotunnModStub/Sverm/SvermBlisterTick.cs b/JotunnModStub/Sverm/SvermBlisterTick.cs index 6fd2a57..5f9e4d5 100644 --- a/JotunnModStub/Sverm/SvermBlisterTick.cs +++ b/JotunnModStub/Sverm/SvermBlisterTick.cs @@ -143,10 +143,22 @@ namespace RacesOfValheim return Mathf.Clamp(nview.GetZDO().GetInt(SlotKey, 0), 0, SvermConfigManagement.BlisterTick); } + /// + /// How many slots this nest may own: the configured cap, and never more than the nest's + /// clutch holds at its stage (five plus the stage). A slot is an egg that never comes back, + /// so the clutch is the honest ceiling - the flat cap alone let a nest at its first stage + /// keep ten ticks on a clutch of six. + /// + public static int SlotCap(Transform nest) + { + return Mathf.Min(SvermConfigManagement.BlisterTick, SvermBroodEggs.Cap(nest)); + } + public static void BuySlot(Transform nest) { ZNetView nview = nest != null ? nest.GetComponent() : null; if (nview == null || !nview.IsValid()) return; + if (SlotsOf(nest) >= SlotCap(nest)) return; if (!nview.IsOwner()) nview.ClaimOwnership(); nview.GetZDO().Set(SlotKey, SlotsOf(nest) + 1); diff --git a/JotunnModStub/Sverm/SvermHiveGoods.cs b/JotunnModStub/Sverm/SvermHiveGoods.cs index 6284a2d..f5381e9 100644 --- a/JotunnModStub/Sverm/SvermHiveGoods.cs +++ b/JotunnModStub/Sverm/SvermHiveGoods.cs @@ -100,7 +100,7 @@ namespace RacesOfValheim Refusal = hive => { int slots = SvermBlisterTick.SlotsOf(hive.transform); - if (slots >= SvermConfigManagement.BlisterTick) + if (slots >= SvermBlisterTick.SlotCap(hive.transform)) { return ModText.Get("rov_sverm_refusal_keeps", slots); } @@ -118,6 +118,12 @@ namespace RacesOfValheim return; } + if (SvermBlisterTick.SlotsOf(hive.transform) >= SvermBlisterTick.SlotCap(hive.transform)) + { + SvermBiomass.Refund(hive.transform, SvermConfig.TickPrice); + return; + } + SvermBlisterTick.BuySlot(hive.transform); SvermBlisterTick.Hatch(hive); }, diff --git a/JotunnModStub/Sverm/SvermWorker.cs b/JotunnModStub/Sverm/SvermWorker.cs index 3a1b6cd..b2d4ac9 100644 --- a/JotunnModStub/Sverm/SvermWorker.cs +++ b/JotunnModStub/Sverm/SvermWorker.cs @@ -1,5 +1,6 @@ using System.Collections.Generic; using System.Text; +using HarmonyLib; using Jotunn.Managers; using UnityEngine; @@ -79,6 +80,14 @@ namespace RacesOfValheim ai.m_afraidOfFire = false; } + // The troops' fighting bounds (SvermConfig.TroopAlertRange). The Seeker's own are 9999. + MonsterAI monster = prefab.GetComponent(); + if (monster != null) + { + monster.m_alertRange = SvermConfig.TroopAlertRange; + monster.m_maxChaseDistance = SvermConfig.TroopAlertRange; + } + prefab.AddComponent(); // The Bone Smith's brain, whole: the Forge family of stations, fed from chests that hold @@ -214,6 +223,13 @@ namespace RacesOfValheim /// How far a worker that has no nest on its ZDO looks for one to adopt. private const float AdoptRange = 40f; + /// Further out than this a worker has been carried off, not sent: it is put back. + /// Also what brings home the ones the old build already let wander. + private const float WorkerHardLeash = 60f; + + private static readonly System.Reflection.FieldInfo SpawnPointField = + AccessTools.Field(typeof(BaseAI), "m_spawnPoint"); + private Character m_character; private MonsterAI m_ai; private ZNetView m_nview; @@ -282,6 +298,46 @@ namespace RacesOfValheim float edge = SvermBrood.RingRadius(nest); m_smith.m_homeDistance = edge; m_smith.m_radiusBonus = edge; + + Leash(nest.transform.position); + } + + /// + /// Keeps a fight inside the nest's own ground. The smith's brain hands the tick to vanilla + /// while there is a fight, and vanilla measures how far it may chase from m_spawnPoint - the + /// place the worker happened to be born, never the nest - with a Seeker's range on top, which + /// is effectively unlimited. A worker that picked a target kept following it across the map. + /// + /// The same three things the Skadi golem does: pin the point vanilla measures from, drop a + /// target that is outside the circle, and as a failsafe put back one that is far out. + /// + private void Leash(Vector3 home) + { + if (m_ai == null) return; + + if (SpawnPointField != null) SpawnPointField.SetValue(m_ai, home); + + float distance = Vector3.Distance(transform.position, home); + + Character target = m_ai.GetTargetCreature(); + bool targetOutside = target != null && + Vector3.Distance(target.transform.position, home) > SvermConfig.TroopAlertRange; + + if (distance > SvermConfig.TroopAlertRange || targetOutside) + { + Traverse traverse = Traverse.Create(m_ai); + traverse.Field("m_targetCreature").SetValue(null); + traverse.Field("m_targetStatic").SetValue(null); + } + + if (distance > WorkerHardLeash) + { + Vector2 offset = Random.insideUnitCircle * 3f; + transform.position = home + new Vector3(offset.x, 0.5f, offset.y); + + Rigidbody body = GetComponent(); + if (body != null) body.linearVelocity = Vector3.zero; + } } /// diff --git a/JotunnModStub/Translations/English/hover.json b/JotunnModStub/Translations/English/hover.json index daaefdf..968461e 100644 --- a/JotunnModStub/Translations/English/hover.json +++ b/JotunnModStub/Translations/English/hover.json @@ -50,5 +50,7 @@ "rov_hover_trol_yagluth_drop_hand_buys_king": "\n(a Yagluth drop in hand buys a king's head, and two more bands)", "rov_hover_ward_personal": "Personal", "rov_hover_ward_race_menu_ward_progression_open": "$rov_piece_racemenuward_name\n$1 progression - $2 ($3/$4)\n[$KEY_Use] Open\n[Use item] Offer a boss relic", - "rov_hover_ward_world": "World" + "rov_hover_ward_world": "World", + "rov_hover_boneship_roster": "\nmelee $1/$2 of $3\narchers $4/$5 of $6\naboard $7", + "rov_hover_boneship_bone_hand": "\nbone in hand to buy a place" } diff --git a/JotunnModStub/Translations/English/items.json b/JotunnModStub/Translations/English/items.json index 1d707d6..a58cd84 100644 --- a/JotunnModStub/Translations/English/items.json +++ b/JotunnModStub/Translations/English/items.json @@ -127,5 +127,12 @@ "rov_piece_trenta_heartwoodgrove_name": "Heartwood Grove", "rov_piece_trenta_heartwoodsapling_name": "Heartwood Sapling", "rov_piece_trol_wartotem_desc": "A head that still remembers how to shout. Coin goes in, a warband walks out.", - "rov_piece_trol_wartotem_name": "War Totem" + "rov_piece_trol_wartotem_name": "War Totem", + "rov_piece_boneship_altar_name": "Offering Chest", + "rov_piece_boneship_ashlands_desc": "A warship that burned and kept going, ribbed with bone. The oarsmen do not tire.", + "rov_piece_boneship_ashlands_name": "Ashen Bone Longship", + "rov_piece_boneship_karve_desc": "A Karve gone to rot, ribbed with bone. It was not built to sail on wind.", + "rov_piece_boneship_karve_name": "Bone Karve", + "rov_piece_boneship_longship_desc": "A longship gone to rot, ribbed with bone. It sails against any wind.", + "rov_piece_boneship_longship_name": "Bone Longship" } diff --git a/JotunnModStub/Translations/English/messages.json b/JotunnModStub/Translations/English/messages.json index 15c0c64..6e6ee1e 100644 --- a/JotunnModStub/Translations/English/messages.json +++ b/JotunnModStub/Translations/English/messages.json @@ -154,6 +154,9 @@ "rov_msg_sverm_they_are_part_hands": "They are part of your hands.", "rov_msg_sverm_x_biomass_digesting": "$1 x$2 -> +$3 biomass, digesting", "rov_msg_thrall_answer_call": "$1 answer the call.", + "rov_msg_thrall_answer_wait": "$1 stand and wait.", + "rov_msg_thrall_answer_home": "$1 head home.", + "rov_msg_thrall_waits": "$1 waits here.", "rov_msg_thrall_follows": "$1 follows.", "rov_msg_thrall_no_more_may_walk_with": "No more may walk with you.", "rov_msg_thrall_only_may_walk_with": "Only $1 may walk with you.", @@ -196,5 +199,7 @@ "rov_msg_warvulture_bird_does_not_know": "The bird does not know you.", "rov_msg_warvulture_vulture_does_not_answer": "The vulture does not answer.", "rov_msg_warvulture_vulture_settles_into_glide": "The vulture settles into a glide.", - "rov_msg_warvulture_vulture_spirals_down": "The vulture spirals down." + "rov_msg_warvulture_vulture_spirals_down": "The vulture spirals down.", + "rov_msg_boneship_no_shore": "No shore in reach. They stay at the oars.", + "rov_msg_boneship_sunk": "The ship goes down, and $1 go with it." } diff --git a/JotunnModStub/Translations/Italian/hover.json b/JotunnModStub/Translations/Italian/hover.json index 01d1d9f..5739dc0 100644 --- a/JotunnModStub/Translations/Italian/hover.json +++ b/JotunnModStub/Translations/Italian/hover.json @@ -50,5 +50,7 @@ "rov_hover_trol_yagluth_drop_hand_buys_king": "\n(un bottino di Yagluth in mano compra la testa di un re, e altre due bande)", "rov_hover_ward_personal": "Personale", "rov_hover_ward_race_menu_ward_progression_open": "$rov_piece_racemenuward_name\nProgressione $1 - $2 ($3/$4)\n[$KEY_Use] Apri\n[Usa oggetto] Offri una reliquia di boss", - "rov_hover_ward_world": "del mondo" + "rov_hover_ward_world": "del mondo", + "rov_hover_boneship_roster": "\nmischia $1/$2 di $3\narcieri $4/$5 di $6\na bordo $7", + "rov_hover_boneship_bone_hand": "\nosso in mano per comprare un posto" } diff --git a/JotunnModStub/Translations/Italian/items.json b/JotunnModStub/Translations/Italian/items.json index 40e5ddd..8bdd60c 100644 --- a/JotunnModStub/Translations/Italian/items.json +++ b/JotunnModStub/Translations/Italian/items.json @@ -127,5 +127,12 @@ "rov_piece_trenta_heartwoodgrove_name": "Boschetto di durame", "rov_piece_trenta_heartwoodsapling_name": "Germoglio di durame", "rov_piece_trol_wartotem_desc": "Una testa che ricorda ancora come si urla. Entrano monete, esce una banda da guerra.", - "rov_piece_trol_wartotem_name": "Totem di guerra" + "rov_piece_trol_wartotem_name": "Totem di guerra", + "rov_piece_boneship_altar_name": "Cassa delle offerte", + "rov_piece_boneship_ashlands_desc": "Una nave da guerra bruciata che ha continuato ad andare, costolata d'ossa. I rematori non si stancano.", + "rov_piece_boneship_ashlands_name": "Drakkar d'ossa di cenere", + "rov_piece_boneship_karve_desc": "Una Karve marcita, costolata d'ossa. Non e' stata fatta per andare a vento.", + "rov_piece_boneship_karve_name": "Karve d'ossa", + "rov_piece_boneship_longship_desc": "Un drakkar marcito, costolato d'ossa. Naviga contro qualunque vento.", + "rov_piece_boneship_longship_name": "Drakkar d'ossa" } diff --git a/JotunnModStub/Translations/Italian/messages.json b/JotunnModStub/Translations/Italian/messages.json index a5e7084..6d3cb6f 100644 --- a/JotunnModStub/Translations/Italian/messages.json +++ b/JotunnModStub/Translations/Italian/messages.json @@ -154,6 +154,9 @@ "rov_msg_sverm_they_are_part_hands": "Fanno parte delle tue mani.", "rov_msg_sverm_x_biomass_digesting": "$1 x$2 -> +$3 biomassa, in digestione", "rov_msg_thrall_answer_call": "$1 rispondono alla chiamata.", + "rov_msg_thrall_answer_wait": "$1 si fermano e aspettano.", + "rov_msg_thrall_answer_home": "$1 tornano a casa.", + "rov_msg_thrall_waits": "$1 aspetta qui.", "rov_msg_thrall_follows": "$1 ti segue.", "rov_msg_thrall_no_more_may_walk_with": "Nessun altro può camminare con te.", "rov_msg_thrall_only_may_walk_with": "Solo $1 possono camminare con te.", @@ -196,5 +199,7 @@ "rov_msg_warvulture_bird_does_not_know": "L'uccello non ti conosce.", "rov_msg_warvulture_vulture_does_not_answer": "L'avvoltoio non risponde.", "rov_msg_warvulture_vulture_settles_into_glide": "L'avvoltoio si mette a planare.", - "rov_msg_warvulture_vulture_spirals_down": "L'avvoltoio scende a spirale." + "rov_msg_warvulture_vulture_spirals_down": "L'avvoltoio scende a spirale.", + "rov_msg_boneship_no_shore": "Nessuna riva a portata. Restano ai remi.", + "rov_msg_boneship_sunk": "La nave affonda, e con lei $1." } diff --git a/JotunnModStub/Trol/TrolFoodDebug.cs b/JotunnModStub/Trol/TrolFoodDebug.cs deleted file mode 100644 index 21995f5..0000000 --- a/JotunnModStub/Trol/TrolFoodDebug.cs +++ /dev/null @@ -1,74 +0,0 @@ -using HarmonyLib; -using UnityEngine; - -namespace RacesOfValheim -{ - [HarmonyPatch] - public static class TrolFoodDebug - { - [HarmonyPatch(typeof(Player), "Update")] - [HarmonyPostfix] - public static void Update_Postfix(Player __instance) - { - if (__instance != Player.m_localPlayer) return; - - if (Input.GetKeyDown(KeyCode.F8)) - { - Jotunn.Logger.LogInfo("=== F8 TROL FOOD DEBUG ==="); - Jotunn.Logger.LogInfo($"IsTrol: {TrolRace.IsTrol()}"); - - var foods = Traverse.Create(__instance).Field("m_foods").GetValue>(); - Jotunn.Logger.LogInfo($"Native m_foods Count: {foods?.Count ?? 0}"); - if (foods != null) - { - for (int i = 0; i < foods.Count; i++) - { - var f = foods[i]; - Jotunn.Logger.LogInfo($" [{i}] {f.m_item?.m_shared?.m_name} | Time: {f.m_time} / {f.m_item?.m_shared?.m_foodBurnTime}"); - } - } - - if (TrolFoodManager.ExtraFoods.TryGetValue(__instance, out Player.Food extraFood)) - { - Jotunn.Logger.LogInfo($"ExtraFoods Dictionary has entry:"); - Jotunn.Logger.LogInfo($" Name: {extraFood?.m_item?.m_shared?.m_name}"); - Jotunn.Logger.LogInfo($" Time: {extraFood?.m_time} / {extraFood?.m_item?.m_shared?.m_foodBurnTime}"); - } - else - { - Jotunn.Logger.LogInfo($"ExtraFoods Dictionary is EMPTY for this player."); - } - - if (__instance.m_customData.TryGetValue("TrolFood_Prefab", out string prefab)) - { - Jotunn.Logger.LogInfo($"m_customData TrolFood_Prefab: {prefab}"); - } - if (__instance.m_customData.TryGetValue("TrolFood_Time", out string time)) - { - Jotunn.Logger.LogInfo($"m_customData TrolFood_Time: {time}"); - } - Jotunn.Logger.LogInfo("=========================="); - } - } - - [HarmonyPatch(typeof(Humanoid), "ConsumeItem")] - [HarmonyPrefix] - public static void ConsumeItem_Prefix(Humanoid __instance, Inventory inventory, ItemDrop.ItemData item) - { - if (__instance == Player.m_localPlayer && item != null && item.m_shared.m_name == "$item_bukeperry") - { - Jotunn.Logger.LogInfo("=== BUKEPERRY CONSUMED ==="); - Jotunn.Logger.LogInfo($"IsTrol: {TrolRace.IsTrol()}"); - if (TrolFoodManager.ExtraFoods.ContainsKey((Player)__instance)) - { - Jotunn.Logger.LogInfo("ExtraFoods HAS entry. Will it clear?"); - } - else - { - Jotunn.Logger.LogInfo("ExtraFoods DOES NOT HAVE entry before clear."); - } - Jotunn.Logger.LogInfo("=========================="); - } - } - } -} diff --git a/JotunnModStub/Trol/TrolFoodDebugUI.cs b/JotunnModStub/Trol/TrolFoodDebugUI.cs deleted file mode 100644 index 9524f7d..0000000 --- a/JotunnModStub/Trol/TrolFoodDebugUI.cs +++ /dev/null @@ -1,67 +0,0 @@ -using HarmonyLib; -using UnityEngine; -using UnityEngine.UI; - -namespace RacesOfValheim -{ - [HarmonyPatch] - public static class TrolFoodDebugUI - { - [HarmonyPatch(typeof(Player), "Update")] - [HarmonyPostfix] - public static void Update_Postfix(Player __instance) - { - if (__instance != Player.m_localPlayer) return; - - if (Input.GetKeyDown(KeyCode.F8)) - { - Jotunn.Logger.LogInfo("=== F8 TROL FOOD UI DEBUG ==="); - - Transform healthPanel = Hud.instance?.transform.Find("hudroot/healthpanel"); - if (healthPanel != null) - { - Transform food3 = healthPanel.Find("TrolExtraFoodSlot"); - if (food3 != null) - { - Transform timeT = food3.Find("time"); - Jotunn.Logger.LogInfo($"Found TrolExtraFoodSlot! time transform found: {timeT != null}"); - if (timeT != null) - { - Component[] comps = timeT.GetComponents(); - Jotunn.Logger.LogInfo("Components on 'time' object:"); - foreach(var c in comps) { - Jotunn.Logger.LogInfo(" - " + c.GetType().FullName); - } - - Text timeText = timeT.GetComponent(); - Jotunn.Logger.LogInfo($"UnityEngine.UI.Text component: {timeText != null}"); - if (timeText != null) Jotunn.Logger.LogInfo($"Text value: '{timeText.text}'"); - - var tmpComp = timeT.GetComponent("TMPro.TMP_Text"); - Jotunn.Logger.LogInfo($"TMPro.TMP_Text component: {tmpComp != null}"); - if (tmpComp != null) { - var prop = tmpComp.GetType().GetProperty("text"); - if (prop != null) { - Jotunn.Logger.LogInfo($"TMP value: '{prop.GetValue(tmpComp, null)}'"); - } - } - } - } - else - { - Jotunn.Logger.LogInfo("TrolExtraFoodSlot NOT FOUND! (Did Awake_Postfix run?)"); - } - } - - if (TrolFoodManager.ExtraFoods.TryGetValue(__instance, out Player.Food extraFood) && extraFood != null) - { - Jotunn.Logger.LogInfo($"ExtraFoods Dictionary:"); - Jotunn.Logger.LogInfo($" Name: {extraFood.m_item?.m_shared?.m_name}"); - Jotunn.Logger.LogInfo($" Time: {extraFood.m_time} / {extraFood.m_item?.m_shared?.m_foodBurnTime}"); - } - - Jotunn.Logger.LogInfo("============================="); - } - } - } -} diff --git a/README.md b/README.md index a70a5ba..f521a75 100644 --- a/README.md +++ b/README.md @@ -13,6 +13,10 @@ Support the mod: [Patreon — NandorTheModder](https://www.patreon.com/c/NandorT --- +## New in v1.5.6 + +Three tester reports. Sverm Seeker Workers no longer wander hundreds of metres from their nest, the Blister Tick can no longer be bought past the nest's egg clutch, and a Fenrir form no longer freezes when you attack during its idle howl. Full details in the [changelog](#v156). + ## New in v1.5.5 A Sverm Gjall no longer kills you with its own bombs, and the ticks it hatches are on your side. Full details in the [changelog](#v155). @@ -443,6 +447,11 @@ Both halves have an off switch under `Factions` in Configuration Manager: **Fact ## Changelog +### v1.5.6 +- **Fix - Sverm Seeker Workers wandered far from their nest:** a worker that picked a fight kept chasing its target across the map, because it carried a Seeker's chase range and the game measured that range from where the worker was born, not from the nest. Workers now fight inside the nest's own ground like the troops (25 m), forget a target that leaves it, and one found more than 60 m from the nest is put back. Workers the old build already let wander come home too. +- **Fix - Blister Ticks could be bought past the nest's limit:** the slot cap was a flat 10 whatever the stage, while every tick spends an egg that does not come back and eggs regrow. The cap is now the lower of the configured number and the nest's clutch at its stage (five plus the stage). Ticks already bought stay and keep respawning. Thanks to the player who reported it. +- **Fix - Fenrir forms froze when you attacked during the idle howl:** the idle howl is a looping clip the attack triggers cannot leave, so the model stood frozen in it and the attack never played until you left the form. Before an attack the form now steps out of the howl, and an attack lock that fails to release is let go after 8 seconds. Applies to the Wolf, the Ulv, the Fenring and the Cultist. Thanks to the player who reported it. + ### v1.5.5 - **Fix - a Sverm Gjall's bombs hurt the player:** the Gjall's bile bomb damages everything in its blast unless the projectile is flagged as non-friendly-damaging, which a wild Gjall never needed. A bomb thrown at a turtle killed a player on a boat beside it. Bombs thrown by a Sverm troop now spare the player and the player's tames; wild creatures still take the damage. - **Fix - the ticks a Sverm Gjall hatches were hostile to everyone:** they were ordinary wild ticks and attacked the player, the tames and the Gjall itself. Ticks hatched by a Sverm Gjall's bomb are now tame, and disappear after 45 seconds. A wild Gjall is unchanged. Thanks to the player who reported it. diff --git a/manifest.json b/manifest.json index f25edd0..e29ebe8 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.5.5", + "version_number": "1.5.6", "website_url": "", "dependencies": [ "denikson-BepInExPack_Valheim-5.4.2333", From b9dc72fdd063d0f4728d5d420be4b9e50d989307 Mon Sep 17 00:00:00 2001 From: kanym Date: Tue, 6 Oct 2026 13:36:31 +0200 Subject: [PATCH 009/176] localisation(ru): add Russian skeleton from English --- .../Translations/Russian/compendium.json | 206 ++++++++++++++++++ JotunnModStub/Translations/Russian/hover.json | 56 +++++ JotunnModStub/Translations/Russian/items.json | 138 ++++++++++++ .../Translations/Russian/merchants.json | 133 +++++++++++ .../Translations/Russian/messages.json | 205 +++++++++++++++++ JotunnModStub/Translations/Russian/races.json | 38 ++++ .../Translations/Russian/status_effects.json | 62 ++++++ 7 files changed, 838 insertions(+) create mode 100644 JotunnModStub/Translations/Russian/compendium.json create mode 100644 JotunnModStub/Translations/Russian/hover.json create mode 100644 JotunnModStub/Translations/Russian/items.json create mode 100644 JotunnModStub/Translations/Russian/merchants.json create mode 100644 JotunnModStub/Translations/Russian/messages.json create mode 100644 JotunnModStub/Translations/Russian/races.json create mode 100644 JotunnModStub/Translations/Russian/status_effects.json diff --git a/JotunnModStub/Translations/Russian/compendium.json b/JotunnModStub/Translations/Russian/compendium.json new file mode 100644 index 0000000..0b27389 --- /dev/null +++ b/JotunnModStub/Translations/Russian/compendium.json @@ -0,0 +1,206 @@ +{ + "rov_compendium_aswid_always_active_every_form_with": "Always active, in every form, with no key to hold - only the on/off toggle. Drains a $1m radius by day, $2m by night, for magic damage that scales with your Blood Magic skill, healing you for the damage dealt. Enemies at or below $3% health are executed outright. The aura hits for half in human form, full as a Bat, and double as Mist. It cannot tell traders from monsters, so switch it off with [I] before talking to Haldor or Hildir.\n", + "rov_compendium_aswid_asmund_passive": "[Fader Unlock] Asmund (Passive):", + "rov_compendium_aswid_aswid_s_curse": "The Aswid's Curse\n", + "rov_compendium_aswid_bat_form_g_key_night": "[Eikthyr Unlock] Bat Form ('G' Key, night only): Take the shape of a bat.\n", + "rov_compendium_aswid_bat_form_now_answers_by": "[The Elder Unlock] Bat Form now answers by day as well as night.\n", + "rov_compendium_aswid_benedictus_et_afflictus": "[Base Passive] Benedictus et Afflictus:", + "rov_compendium_aswid_claws_beast_s_grows_blackened": "[Base Passive] Claws of the Beast ([K], $1s): Grows blackened claws for a limited time instead of a weapon. Bare-handed blows land at $2% of a full-grown pair's weight, all of it as slash, and they grow with every boss that falls. Draw a sword and they wait, sheathe it and they are back, until the timer runs out and they retract on their own - no slot wasted between casts. They cannot be dropped, traded or stolen while grown - and in bat or mist form you have no hands to hold them with.\n", + "rov_compendium_aswid_dominate_native_interact_key": "[Yagluth Unlock] Dominate (native Interact key):", + "rov_compendium_aswid_eclipse_j_key_day_only": "[Yagluth Unlock] Eclipse ('J' Key, day only):", + "rov_compendium_aswid_freezing_blood_passive": "[Moder Unlock] Freezing Blood (Passive):", + "rov_compendium_aswid_gain_permanent_immunity_freezing_status": "You gain permanent immunity to the Freezing status (mountains/snowstorms) and to Poison damage.\n", + "rov_compendium_aswid_hair_beard_turn_as_dark": "Your hair and beard turn as dark as the abyss. You become 10% taller and gain a flat +$1 Physical Damage.\n", + "rov_compendium_aswid_second_cast_that_forces_night": "A $1-second cast that forces the night to fall around you for $2 seconds, letting you claim your night-doubled bonuses under the sun. Fails silently if it is already night. $3-minute cooldown.\n", + "rov_compendium_aswid_sense_every_untamed_creature_within": "You sense every untamed creature within $1m, marking it with a telltale glow.\n", + "rov_compendium_aswid_superhuman_senses_passive": "[Moder Unlock] Superhuman Senses (Passive):", + "rov_compendium_aswid_take_no_fall_damage_physical": "You take no fall damage, and physical kills automatically devour edible enemies (Vae Victis) for Blood Magic XP. Your physical stats scale with every boss you defeat: +$1 Armor, +$2 Damage, +$3% Speed and Jump, and +$4% Lifesteal on physical hits. All of these bonuses double during the night. You can cast Blood Magic items with infinite Eitr, and your Blood Magic skill rises $5x as fast.\n", + "rov_compendium_aswid_tame_u_key_asksvin_join": "[Fader Unlock] Tame ('U' Key): Asksvin join the huntable list.\n", + "rov_compendium_aswid_tame_u_key_lox_join": "[Yagluth Unlock] Tame ('U' Key): Lox join the huntable list.\n", + "rov_compendium_aswid_tame_u_key_tame_boar": "[Eikthyr Unlock] Tame ('U' Key): Tame a boar under your cursor.\n", + "rov_compendium_aswid_tame_u_key_wolves_join": "[Moder Unlock] Tame ('U' Key): Wolves join the huntable list.\n", + "rov_compendium_aswid_target_non_tameable_non_boss": "Target a non-tameable, non-boss enemy to dominate it for $1 seconds ($2-min cooldown). Dominated thralls fight alongside you and drop standard loot.\n", + "rov_compendium_aswid_title": "Aswid Secrets", + "rov_compendium_aswid_transform_into_elusive_mist_become": "You transform into an elusive mist. You become immune to physical (blunt/slash/pierce) and poison damage, and take no fall damage, but you cannot attack, run, or jump. Your Vampiric Aura deals double damage while mist. Sunrise breaks the transformation.\n", + "rov_compendium_aswid_vampiric_aura_passive_toggle": "Vampiric Aura (Passive, [I] to toggle):", + "rov_compendium_aswid_weight_shadows_h_key_toggle": "[The Queen Unlock] Weight of Shadows ('H' Key, toggle):", + "rov_compendium_draugh_born_dead_buried_alive_take": "[Base Passive] Born Dead, Buried Alive: You take $1% less Physical (blunt/slash/pierce) damage, but Fire and Spirit strike you $2% harder. Skeletons, draugr, ghosts and wraiths no longer see you as prey. Your digestive system adapts to death, allowing you to consume raw and rotten meat (neck tail, raw meat, entrails, blood, etc.) - proper cooked food and berries disgust you and cannot be eaten.\n", + "rov_compendium_draugh_draugh_s_awakening": "The Draugh's Awakening\n", + "rov_compendium_draugh_grave_chill_passive_parry_frost": "[Moder Unlock] Grave Chill (Passive/Parry): Frost can no longer touch you at all. A successful parry now also unleashes a freezing nova, dealing $1 Frost damage and pushing back everything within $2m of you - the nova has its own $3 second cooldown, separate from Rotting Edge's poison splash, which still fires on every parry.\n", + "rov_compendium_draugh_rotting_edge_passive_parry_physical": "[The Elder Unlock] Rotting Edge (Passive/Parry): Your physical attacks are laced with the swamp's decay, adding poison damage worth $1% of the physical harm you deal. A successful parry also splashes $2 poison damage onto whoever you parried.\n", + "rov_compendium_draugh_slowly_we_rot_passive_being": "[Eikthyr Unlock] Slowly We Rot (Passive): Being Wet no longer saps your stamina regeneration, and it heals rather than does nothing for you - your health regenerates $1% faster while wet or swimming.\n", + "rov_compendium_draugh_steal_their_breath_execution_while": "[Fader Unlock] Steal Their Breath (Execution): While surviving in the Zombie Ritual's ghost state, scoring a killing blow on any enemy will instantly restore $1% of your maximum health, stop the Eitr drain, and save your life, bringing you fully back to the world of the living.\n", + "rov_compendium_draugh_swarm_terror_retaliation_whenever_are": "[The Queen Unlock] Swarm of Terror (Retaliation): Whenever you are struck in melee combat, you automatically spawn $1 Seeker Broods to fight for you. They live for $2 seconds, with a $3 second cooldown between spawns.\n", + "rov_compendium_draugh_title": "Draugh Secrets", + "rov_compendium_draugh_undead_fortitude_passive_poison_can": "[Bonemass Unlock] Undead Fortitude (Passive): Poison can no longer touch you at all. Striking a staggered enemy deals $1% more physical damage, and death no longer costs you skill experience. Should any player die within $2m of you, their fall leaves Human Meat behind - flesh only a Draugh can stomach.\n", + "rov_compendium_draugh_zombie_ritual_passive_survival_when": "[Yagluth Unlock] Zombie Ritual (Passive Survival): When you take fatal damage, you do not die. Instead, you enter a ghostly state, immune to all damage, while your Eitr drains at $1 per second. If your Eitr hits zero before you are saved, you truly die. Once triggered, the ritual cannot save you again for $2 minutes.\n", + "rov_compendium_dvergar_dvergar_s_craft": "The Dvergar's Craft\n", + "rov_compendium_dvergar_kin_traders_passive_haldor_hildir": "[Bonemass Unlock] Kin of the Traders (Passive): Haldor and Hildir know their own. Their prices drop by $1% for you, and what they pay for your trophies and hunting rewards rises by $2%.\n", + "rov_compendium_dvergar_mining_affinity_passive_pickaxe_answers": "[Eikthyr Unlock] Mining Affinity (Passive): The pickaxe answers to you. Veins break faster, cost you less stamina to work, and sometimes give up more than they should.\n", + "rov_compendium_dvergar_runic_overcharge_key_spend_eitr": "[Fader Unlock] Runic Overcharge ('$1' Key): Spend $2 eitr to load the runes. Your next blow with a favoured weapon lands with $3x its weight. Hold the charge no longer than $4 seconds or it bleeds away.\n", + "rov_compendium_dvergar_runic_ping_key_spend_eitr": "[Yagluth Unlock] Runic Ping ('$1' Key): Spend $2 eitr to send a pulse through the stone. For $3 seconds every ore vein and every hidden enemy within $4 meters is lit for you alone.\n", + "rov_compendium_dvergar_runic_spark_runes_blood_earth": "[Base Passive] Runic Spark: The runes in your blood earth themselves through whatever you strike. Every blow you land carries +$1 Lightning damage - a bonus that grows as each boss falls.\n", + "rov_compendium_dvergar_small_stubborn_stand_shorter_than": "[Base Passive] Small and Stubborn: You stand $1% shorter than a human and carry $2 less health for it. The dvergr hood never leaves your head - wear whatever helm you please and keep every point of its protection, but the runes will always show you as one of the deep folk.\n", + "rov_compendium_dvergar_smithing_jewelry_passive_waste_nothing": "[Bonemass Unlock] Smithing and Jewelry (Passive): You waste nothing at the anvil. Metal and gems cost you $1% less when crafting and upgrading.\n", + "rov_compendium_dvergar_title": "Dvergar Secrets", + "rov_compendium_dvergar_weapon_affinity_passive_blows_struck": "Weapon Affinity (Passive): $1. Blows struck with these land harder and cost less stamina. The saving never grows - a tier only ever hands you another weapon to feel at home with - and your skill rises no faster than anyone else's.\n", + "rov_compendium_dvergar_weapon_axe": "Axe", + "rov_compendium_dvergar_weapon_bow": "Bow", + "rov_compendium_dvergar_weapon_crossbow": "Crossbow", + "rov_compendium_dvergar_weapon_hammer": "Hammer", + "rov_compendium_fenrir_beast_within_physical_stats_scale": "[Base Passive] The Beast Within: Your physical stats scale with every boss you defeat: +$1 Armor, +$2 Damage, +$3% Speed, +$4% Jump, and -$5% Fall Damage.\n", + "rov_compendium_fenrir_cultist_form_j_key_night": "[Yagluth Unlock] Cultist Form ('J' Key, night only): A robed shape that claws and channels fire. Lasts 1 minute, 10-minute cooldown.\n", + "rov_compendium_fenrir_cultist_form_now_answers_by": "[Fader Unlock] Cultist Form now answers by day as well as night, and may be held as long as you wish.\n", + "rov_compendium_fenrir_cultist_form_s_cooldown_falls": "[The Queen Unlock] Cultist Form's cooldown falls to 5 minutes (still night only, still 1 minute).\n", + "rov_compendium_fenrir_curse_pack": "The Curse of the Pack\n", + "rov_compendium_fenrir_cursed_claws_s_wolf_s": "[Base Passive] Cursed Claws ([K], $1s): The wolf's hands, kept on in the man's shape for a limited time instead of a weapon. Bare-handed blows land at $2% of a full-grown pair's weight, all of it as slash, and they grow with every boss that falls. Draw a sword and they wait, sheathe it and they are back, until the timer runs out and they retract on their own - no slot wasted between casts. They cannot be dropped, traded or stolen while grown - and in beast form the jaws do the work instead.\n", + "rov_compendium_fenrir_fenring_form_h_key_night": "[Moder Unlock] Fenring Form ('H' Key, night only): Stand as a true Fenring - heavy claws and a leaping strike, and the strongest of the four shapes so far.\n", + "rov_compendium_fenrir_fenring_form_now_answers_by": "[The Queen Unlock] Fenring Form now answers by day as well as night.\n", + "rov_compendium_fenrir_g_now_calls_ulv_form": "[Moder Unlock] 'G' now calls Ulv Form instead of Wolf, and answers by day as well as night.\n", + "rov_compendium_fenrir_sunrise_breaks_any_night_bound": "Sunrise breaks any night-bound form early and leaves the beast too tired to change shape again for a short while after.\n", + "rov_compendium_fenrir_title": "Fenrir Secrets", + "rov_compendium_fenrir_ulv_form_h_key_night": "[Bonemass Unlock] Ulv Form ('H' Key, night only): A heavier wolf shape - stronger bite attacks, still bound to the dark.\n", + "rov_compendium_fenrir_wolf_form_g_key_night": "[The Elder Unlock] Wolf Form ('G' Key, night only): Take the shape of a wolf. Faster and lighter on your feet, with three claw attacks of growing weight on Left, Right, and Middle Mouse.\n", + "rov_compendium_fenrir_wolf_form_now_answers_by": "[Bonemass Unlock] Wolf Form now answers by day as well as night.\n", + "rov_compendium_furling_all_weapon_combat_skills_gain": "All weapon and combat skills gain $1x XP permanently. You're short, but very fast - your movement speed is permanently increased by $2%.\n", + "rov_compendium_furling_are_permanently_wreathed_flames_are": "You are permanently wreathed in flames. You are completely immune to fire damage. All your physical attacks (regardless of weapon or unarmed) set the target on fire.\n", + "rov_compendium_furling_blue_foods_those_that_restore": "Blue foods (those that restore Eitr) last twice as long for you compared to normal players.\n", + "rov_compendium_furling_combat_mastery": "[Base Passive] Combat Mastery:", + "rov_compendium_furling_dance_dead_passive": "[Bonemass Unlock] Dance of the Dead (Passive):", + "rov_compendium_furling_every_mead_potion_wine_bomb": "Every mead, potion, wine, bomb, or batch of ammunition you craft comes out doubled - one copy for the recipe, one for free.\n", + "rov_compendium_furling_footsteps_small_movements_no_longer": "Your footsteps and small movements no longer betray you - any noise you make within $1 meters goes unheard.\n", + "rov_compendium_furling_master_shadows_passive": "[Eikthyr Unlock] Master of Shadows (Passive):", + "rov_compendium_furling_passive": "[Moder Unlock] $1 (Passive):", + "rov_compendium_furling_passive_2": "[Yagluth Unlock] $1 (Passive):", + "rov_compendium_furling_passive_3": "[The Queen Unlock] $1 (Passive):", + "rov_compendium_furling_secrets_hoard": "The Secrets of the Hoard\n", + "rov_compendium_furling_take_less_fire_damage_less": "You take $1% less Fire damage and $2% less Poison damage. Your arrows carry at least $3 Fire damage of their own.\n", + "rov_compendium_furling_through_fire_flames_passive": "[Fader Unlock] Through Fire and Flames (Passive):", + "rov_compendium_furling_title": "Furling Secrets", + "rov_compendium_furling_whenever_normal_enemy_dies_within": "Whenever a normal enemy dies within 25 meters, its trophy drops are doubled and it drops guaranteed gold coins based on its stars. Furthermore, whenever you mine raw ore deposits, your yield is doubled.\n", + "rov_compendium_furling_while_are_plains_biome_x": "While you are in the Plains biome, your 2x XP multiplier is extended to all non-combat skills (including Elemental Magic and Blood Magic).\n", + "rov_compendium_furling_wickerman_passive": "[The Elder Unlock] The Wickerman (Passive):", + "rov_compendium_skadi_become_great_frost_dragon_herself": "Become the great frost dragon herself for 1 minute, then wait 10 before calling her again. Afoot, Left Mouse bites and claws for no cost at all, while Middle Mouse breathes a stream of ice. On the wing, Left Mouse looses a barrage of shards. Only the breath and the barrage draw upon eitr.\n", + "rov_compendium_skadi_bones_dragon_rise_at_call": "The bones of a dragon rise at your call, wreathed in frost. It rends with bite and claw, sweeps all around it with a spinning tail (Right Mouse), and its breath carries thrice the fury of Moder's.\n", + "rov_compendium_skadi_bound_stonecutter_that_shaped_may": "It is bound to the stonecutter that shaped it and may never leave the $1 meters around it - the same circle the station itself builds in. It cannot be named, cannot be ordered and will not follow you. It guards the stone that cut it, and that is the whole of what it does.\n", + "rov_compendium_skadi_cold_cannot_touch_frost_answers": "The cold cannot touch you, and frost answers to your hand. You are immune to the Cold status, take only half damage from frost, and every blow you land carries +$1 Frost damage - a bonus that grows as each boss falls.\n", + "rov_compendium_skadi_cold_spell_middle_mouse": "[Eikthyr Unlock] Cold Spell (Middle Mouse):", + "rov_compendium_skadi_cold_spell_scatters_into_ten": "Your Cold Spell scatters into ten shards, spreading its bite across all before you. The wider cast needs 4 seconds to gather itself.\n", + "rov_compendium_skadi_crystal_golem": "\n-- THE CRYSTAL GOLEM --\n", + "rov_compendium_skadi_cut_one_at_stonecutter_stone": "Cut one at a stonecutter for a stone golem's trophy, $1 crystal and a dragon tear. The stone answers to no one who is not Skadi, so what you raise is yours and stays yours.\n", + "rov_compendium_skadi_drake_breath_left_mouse": "[Bonemass Unlock] Drake Breath (Left Mouse):", + "rov_compendium_skadi_drake_form_g_key": "[The Elder Unlock] Drake Form ('G' Key):", + "rov_compendium_skadi_drake_form_may_now_spit": "Your drake form may now spit ice at your enemies.\n", + "rov_compendium_skadi_freezing_can_no_longer_reach": "Freezing can no longer reach you at all, and your eitr returns half again as fast.\n", + "rov_compendium_skadi_frost_cannot_wound_at_all": "Frost cannot wound you at all, and a freezing aura bleeds from your skin, gnawing at every untamed creature within 3 meters.\n", + "rov_compendium_skadi_heart_winter_passive": "[Yagluth Unlock] Heart of Winter (Passive):", + "rov_compendium_skadi_hurl_shard_ice_at_whatever": "Hurl a shard of ice at whatever you look upon, for $1 Frost damage. It draws on 20 stamina rather than eitr, so it serves you from your very first winter.\n", + "rov_compendium_skadi_ice_affinity": "[Base Passive] Ice Affinity:", + "rov_compendium_skadi_improved_cold_spell": "[Yagluth Unlock] Improved Cold Spell:", + "rov_compendium_skadi_killing_gales_mountains_soften_mere": "The killing gales of the mountains soften to a mere chill - you suffer Cold where others would freeze.\n", + "rov_compendium_skadi_moder_form_h_key": "[Moder Unlock] Moder Form ('H' Key):", + "rov_compendium_skadi_moder_form_may_now_held": "Moder Form may now be held as long as you wish, with no wait between callings.\n", + "rov_compendium_skadi_moder_form_now_answers_again": "Moder Form now answers you again after only 5 minutes.\n", + "rov_compendium_skadi_one_stonecutter_holds_them_no": "One stonecutter holds $1 of them, and no more than $2 may stand within a day's walk of each other. Break the stonecutter and what it cut goes still $3 seconds later.\n", + "rov_compendium_skadi_secrets_winter": "The Secrets of Winter\n", + "rov_compendium_skadi_skeleton_dragon_form_j_key": "[Fader Unlock] Skeleton Dragon Form ('J' Key):", + "rov_compendium_skadi_take_shape_frost_drake_right": "Take the shape of a frost drake. Right Mouse lifts you into flight: you glide wherever you aim, hold W to climb and gather speed, hold Shift with it to spend stamina on a burst of speed, and press S to beat backwards along your aim while your gaze stays where it was. Release everything and you hold level for five seconds before settling into a slow descent. Water cannot hold you - your wings drag you free of the sea as readily as they lift you from the shore. In this shape you cannot yet strike.\n", + "rov_compendium_skadi_tear_cold_nothing_wakes_stone": "The tear is cold. Nothing wakes in the stone until the mountain's queen has fallen.\n", + "rov_compendium_skadi_title": "Skadi Secrets", + "rov_compendium_skadi_winter_incarnate_passive": "[The Queen Unlock] Winter Incarnate (Passive):", + "rov_compendium_skadi_winter_s_welcome_passive": "[Bonemass Unlock] Winter's Welcome (Passive):", + "rov_compendium_skeleton_blades_points_find_little_cut": "Blades and points find little to cut in you and do half their work, but a hammer's weight finds everything, and hurts you the more for it.\n", + "rov_compendium_skeleton_bones_alight": "[Moder Unlock] Bones Alight:", + "rov_compendium_skeleton_bones_blades": "[Base Passive] Bones and Blades:", + "rov_compendium_skeleton_crypt_answers": "[The Queen Unlock] The Crypt Answers:", + "rov_compendium_skeleton_dead_now_follow_harm_deal": "$1 of the dead now follow you, and $2% of the harm you deal comes back as your own strength.\n", + "rov_compendium_skeleton_every_enemy_put_down_rises": "Every enemy you put down rises to fight for you, up to $1 at your side at once.\n", + "rov_compendium_skeleton_first_blow": "[The Elder Unlock] The First Blow:", + "rov_compendium_skeleton_first_strike_out_dark_staggers": "The first strike out of the dark staggers whatever it lands upon. The dead may do this once every 5 seconds.\n", + "rov_compendium_skeleton_frame_remade_harder_cast_fire": "Your frame is remade in a harder cast, and fire clings to it: everything near enough to feel it is scorched. Your wounds also close faster than bone has any right to.\n", + "rov_compendium_skeleton_green_rot": "[Eikthyr Unlock] The Green Rot:", + "rov_compendium_skeleton_host_own": "[Fader Unlock] A Host of Your Own:", + "rov_compendium_skeleton_killing_blow_no_longer_ends": "A killing blow no longer ends you. You are made whole where you stand - and then the dark magic must gather itself for 5 minutes before it will do so again.\n", + "rov_compendium_skeleton_no_hunger_moves_no_meal": "No hunger moves you and no meal can help you - mortal food is nothing to dry bones. In its place the dead grow strong as their betters fall: you carry +$1 Maximum Health at your present standing. Nor does effort tire you; you have no stamina to spend at all.\n", + "rov_compendium_skeleton_poison_has_nothing_left_poison": "Poison has nothing left to poison - it cannot touch you at all - and your bones take on its sickly cast. Every blow you land returns $1% of what it deals in physical harm to your own frame.\n", + "rov_compendium_skeleton_risen_again": "[Yagluth Unlock] Risen Again:", + "rov_compendium_skeleton_rotten_touch": "[Bonemass Unlock] Rotten Touch:", + "rov_compendium_skeleton_secrets_crypt": "The Secrets of the Crypt\n", + "rov_compendium_skeleton_stand_at_eight_standings_earned": "You stand at the $1 of eight standings, earned by the fall of $2.\n", + "rov_compendium_skeleton_stand_at_first_eight_standings": "You stand at the first of eight standings; no boss has yet fallen to your reckoning.\n", + "rov_compendium_skeleton_title": "Skeleton Secrets", + "rov_compendium_skeleton_undead_diet": "[Base Passive] Undead Diet:", + "rov_compendium_skeleton_what_strike_sicken_every_blow": "What you strike, you sicken - every blow carries 20 Poison damage of its own.\n", + "rov_compendium_sverm_acid_hemolymph_whoever_strikes_melee": "[Bonemass Unlock] Acid Hemolymph: Whoever strikes you in melee takes $1 poison back for the trouble.\n", + "rov_compendium_sverm_annealed_chitin_emberform_eight_tiers": "[Fader Unlock] Annealed Chitin and Emberform: Eight tiers of burning have turned the flaw into armour - fire no longer hurts you, and the chitin goes black with a red heat under it.\n", + "rov_compendium_sverm_beehives_raise_vanilla_hives_inside": "The beehives: raise vanilla hives inside the nest's $1 meters and the colony takes them over after a minute, up to $2 of them per nest - twice the speed, three times the honey, and royal jelly instead once Yagluth is down. Press honey or royal jelly on one of your own insects to heal it: $3 and $4.\n", + "rov_compendium_sverm_blister_tick_buys_slot_forever": "Blister Tick $1: buys a slot forever. It runs at what you are fighting and bursts, and the nest grows another one $2 seconds later, free.\n", + "rov_compendium_sverm_brood_eggs_nest_lays_one": "Brood Eggs: the nest lays one every $1 seconds and holds $2 of them at its first stage, one more at each stage after. Every troop costs an egg as well as biomass - the egg grows back, the biomass does not.\n", + "rov_compendium_sverm_brood_mound_hammer_nest_no": "Brood Mound (Hammer): Your nest, and no more than $1 of them may stand within $2 meters of each other. Press it, or the hive at its foot, to feed it a whole stack out of your pack: any food, any wood, any resin. Honey and royal jelly are medicine now and it will not take them.\n", + "rov_compendium_sverm_carapace_regeneration_knit_yourself_back": "[Fader Unlock] Carapace Regeneration: You knit yourself back together, $1 health a second, always.\n", + "rov_compendium_sverm_chitin_claws_hands_are_weapon": "[Base Passive] Chitin Claws: Your hands are the weapon. Bare-handed blows land at $1% of the claws' full weight, and they cannot be taken from you - draw a sword and they wait, sheathe it and they are back.\n", + "rov_compendium_sverm_chitin_plating_do_not_dress": "[Base Passive] Chitin Plating: You do not dress. Chest, legs and helm are carapace and never come off, and at every tier they are worth the full set of the biome ahead of you - at its best quality, weightless, and without the slowness that armour costs anyone else. Cloak and trinket are the only things you may still wear.\n", + "rov_compendium_sverm_colony": "\n-- THE COLONY --\n", + "rov_compendium_sverm_colony_will_not_wake_until": "The colony will not wake until the Elder falls. Until then you are a body, and the body is enough.\n", + "rov_compendium_sverm_digestion_what_feed_not_yours": "Digestion: what you feed it is not yours to spend yet. It seeps into the nest's bank at $1 a second, and only what has arrived can be spent.\n", + "rov_compendium_sverm_from_at_most": "$1 $2 (from $3, at most $4). ", + "rov_compendium_sverm_grinding_mandibles_seeds_are_food": "[Elder Unlock] Grinding Mandibles: Seeds are food. Raw nourishment and nothing more - the garden's blessings belong to somebody else.\n", + "rov_compendium_sverm_growth_each_one_costs_that": "Growth: $1 $2, $3 $4, $5 $6. Each one costs that stage's whole tankful and opens the next rung of the roster.\n", + "rov_compendium_sverm_hive_market_hammer_counter_raised": "Hive Market (Hammer): a counter raised within $1 meters of a nest. Everything the colony buys is bought here, out of that nest's bank.\n", + "rov_compendium_sverm_hive_pheromones_no_invertebrate_will": "[Base Passive] Hive Pheromones: No invertebrate will attack you - not leeches, not ticks, not deathsquitos, not seekers, not the bees. Bonemass is not an insect and does not care.\n", + "rov_compendium_sverm_insect_metabolism_eat_everything_anyone": "[Base Passive] Insect Metabolism: You eat everything anyone else eats, and honey is worth double to you. Alchemical blood is the one thing you will not swallow.\n", + "rov_compendium_sverm_metabolic_surge_running_jumping_cost": "[Eikthyr Unlock] Metabolic Surge: Running and jumping cost you less, and you jump higher.\n", + "rov_compendium_sverm_ravager_strain_key_become_seeker": "[Yagluth Unlock] Ravager Strain ('$1' Key): Become a Seeker Brute. The claws still fight, the carapace is worth double, and nothing about it flies. It is how you hold a fight, not how you leave one.\n", + "rov_compendium_sverm_seeker_workers_free_always_free": "Seeker Workers: free, and always free - no biomass, no egg, and a new one when an old one dies; $1. While they live the nest feeds itself from the chests at its foot, and they keep the forge the way a Bone Smith does: put $2 in a chest within $3 meters of the nest's edge and they carry ore and fuel from it to the smelters, kilns and mills around, then bring what comes out back to that chest. They are half a Seeker in size, in health and in bite, they take no orders and they never follow - they fight what comes near, mend what you built, and go back to work.\n", + "rov_compendium_sverm_sensory_antennae_feel_what_lives": "[Elder Unlock] Sensory Antennae: You feel what lives around you, through stone and through soil.\n", + "rov_compendium_sverm_surrenal_glands_hyperplasia_everything_hatched": "Surrenal Glands 800 and Hyperplasia 1600: everything hatched after them is born with one star, then two.\n", + "rov_compendium_sverm_surrenal_glands_stand_tenth_larger": "[Queen Unlock] Surrenal Glands: You stand a tenth larger, and the carapace takes its greatest leap.\n", + "rov_compendium_sverm_sverm_s_colony": "The Sverm's Colony\n", + "rov_compendium_sverm_title": "Sverm Secrets", + "rov_compendium_sverm_toxin_immunity_fire": "[Base Passive] Toxin Immunity: Poison cannot touch you. What can is the club and the torch: you take $1% more from blunt blows and $2% more from fire.\n", + "rov_compendium_sverm_toxin_immunity_nofire": "[Base Passive] Toxin Immunity: Poison cannot touch you. What can is the club and the torch: you take $1% more from blunt blows, and fire has stopped being a weakness.\n", + "rov_compendium_sverm_troops_they_follow_when_ask": "Troops: $1They follow when you ask, walk home when you let them go, and mend themselves.\n", + "rov_compendium_sverm_venom_glands_every_blow_land": "[Bonemass Unlock] Venom Glands: Every blow you land carries +$1 poison.\n", + "rov_compendium_sverm_ventral_pouches_carry_more": "[Eikthyr Unlock] Ventral Pouches: You carry $1 more.\n", + "rov_compendium_sverm_vestigial_wings_small_wings_no": "[Moder Unlock] Vestigial Wings: Small wings, and no ground hard enough to hurt you.\n", + "rov_compendium_sverm_workers_none": "none will come out of the nest until Bonemass falls", + "rov_compendium_sverm_workers_up_to": "up to $1 come out of the nest", + "rov_compendium_trenta_awakened_seeds_passive": "[Eikthyr Unlock] Awakened Seeds (Passive):", + "rov_compendium_trenta_closer_come_falling_harder_bark": "The closer you come to falling, the harder your bark grows: your armor rises by up to $1% as your health drops toward zero.\n", + "rov_compendium_trenta_deep_roots_passive": "[Bonemass Unlock] Deep Roots (Passive):", + "rov_compendium_trenta_every_hit_take_returns_its": "Every hit you take returns $1% of its damage to whoever landed it.\n", + "rov_compendium_trenta_every_seed_cone_acorn_self": "Every seed, cone, acorn and self-seeding mushroom you carry has woken up. Eat one on the spot and it consumes itself for the strongest meal its home biome has to offer, health or eitr as the biome favors, instead of sitting idle as planting stock.\n", + "rov_compendium_trenta_heartwood": "[Base Passive] Heartwood:", + "rov_compendium_trenta_homecoming_portal_h_key": "[Yagluth Unlock] Homecoming Portal ('H' Key):", + "rov_compendium_trenta_hornet_s_nest_passive": "[The Queen Unlock] Hornet's Nest (Passive):", + "rov_compendium_trenta_last_stand_passive": "[Moder Unlock] Last Stand (Passive):", + "rov_compendium_trenta_muspell_j_key_toggle": "[Fader Unlock] Muspell ('J' Key, toggle):", + "rov_compendium_trenta_open_linked_pair_portals_one": "Open a linked pair of portals - one where you stand, one at your respawn point - for anyone to walk through, no ore or item carried against them. They fade after $1 seconds. $2-minute cooldown.\n", + "rov_compendium_trenta_photosynthesis": "[Base Passive] Photosynthesis:", + "rov_compendium_trenta_purple_rain_g_key": "[The Elder Unlock] Purple Rain ('G' Key):", + "rov_compendium_trenta_sap_heartwood_conduct_lightning_turn": "Sap and heartwood conduct lightning and turn away the dead: you take half damage from Lightning and Spirit. But kindling burns and the woodsman's axe still bites - you take half again as much from Fire and Slash. Meat, fish, eggs and honey are nothing you can stomach; only what grows from the ground sustains you, and it does so for $1x as long as it would a normal body.\n", + "rov_compendium_trenta_secrets_heartwood": "The Secrets of the Heartwood\n", + "rov_compendium_trenta_spray_toxic_pollen_bursts_out": "A spray of toxic pollen bursts out to $1 meters: every ally caught in it is healed $2, every foe is poisoned for $3. $4-second cooldown, shortened to $5 seconds while transformed into Muspell.\n", + "rov_compendium_trenta_stand_still_daylight_roof_over": "Stand still in daylight, roof over nothing but sky, for $1 unbroken seconds, and roots take hold: $2 ticks of healing follow, $3% of your maximum health apiece, along with a Rested buff lasting $4 minutes - longer with every boss you have felled.\n", + "rov_compendium_trenta_swamp_has_nothing_left_spoil": "The swamp has nothing left to spoil in you. Poison cannot touch you, the Wet effect cannot land on you, and swimming costs no stamina at all.\n", + "rov_compendium_trenta_swarm_hornets_has_made_its": "A swarm of hornets has made its home in your branches and never leaves. Any foe that comes within $1 meters is stung for $2 poison and pierce damage every $3 seconds until it breaks off or falls.\n", + "rov_compendium_trenta_take_shape_young_elder_root": "Take the shape of a young Elder, root and bramble given fury. Left Mouse stomps the ground for $1 damage in a ring around you, Right Mouse looses a root-spike that pierces for $2 - both rising with your Unarmed skill. Purple Rain still answers your call while transformed, on its shorter cooldown.\n", + "rov_compendium_trenta_thorns_passive": "[Moder Unlock] Thorns (Passive):", + "rov_compendium_trenta_title": "Trenta Secrets", + "rov_compendium_trol_base_passive_are_natively_larger": "Base Passive: You are natively 20% larger than a human with immense strength. You have +200 Max Carry Weight, gain +3 Armor per boss defeated, and carry a 4th food slot from your very first meal - no boss required.\n", + "rov_compendium_trol_base_passive_black_forest_kin": "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", + "rov_compendium_trol_base_weakness_kindling_fire_finds": "Base Weakness - Kindling: Fire finds you where nothing else does. Every burn you take lands for $1% more than it would on anyone else, and no armor or resistance changes that.\n", + "rov_compendium_trol_bonemass_defeated_size_carry_weight": "Bonemass Defeated: +5% Size, +50 Carry Weight, +10 Damage to Clubs/Unarmed/Axes, +10 Rock Throwing Damage.\n", + "rov_compendium_trol_eikthyr_defeated_increased_xp_gain": "Eikthyr Defeated: Increased XP gain for physical labor and blunt combat (Clubs, Unarmed, Axes, Pickaxes, WoodCutting).\n", + "rov_compendium_trol_elder_defeated_unlocked_rock_throwing": "The Elder Defeated: Unlocked Rock Throwing ability. +10% passive health regeneration.\n", + "rov_compendium_trol_fader_defeated_wielded_trees_can": "Fader Defeated: Your wielded trees can now instantly smash through the toughest materials in the Ashlands. True Form no longer runs out and has no cooldown - press the key again to return to your normal size.\n", + "rov_compendium_trol_moder_defeated_unlocked_true_form": "Moder Defeated: Unlocked True Form (Transformation ability).\n", + "rov_compendium_trol_queen_defeated_unlocked_log_weapon": "The Queen Defeated: Unlocked Log Weapon (in True Form, interact with trees to wield them as weapons). True Form size is massively increased.\n", + "rov_compendium_trol_title": "Trol Secrets", + "rov_compendium_trol_trol_s_heritage": "The Trol's Heritage\n", + "rov_compendium_trol_yagluth_defeated_size_carry_weight": "Yagluth Defeated: +5% Size, +50 Carry Weight, +5 Damage to Clubs/Unarmed/Axes, +5 Rock Throwing Damage. Unlocked 5th Food Slot.\n", + "rov_compendium_warvulture_goes_where_look_goes_as": "It goes where you look, and it goes as long as you care to stay up: $1 meters a second costs it nothing at all. Hold your run key and it gives you $2 for $3 seconds and not a moment longer - there is only so much haste in a bird. Let go and the wind comes back into it in $4 seconds, in the air. You never have to land for it.\n", + "rov_compendium_warvulture_vulture_s_head_kept_stick": "A vulture's head kept on a stick, and the bird answers to it. Raise it and the vulture comes back under you. Raise it again and it carries you down, deaf to you until the ground arrives - and a third time lets go of it where you are.\n", + "rov_compendium_warvulture_war_vulture": "\n-- THE WAR VULTURE --\n", + "rov_compendium_warvulture_what_bird_has_left_bar": "What the bird has left is the bar under your own.\n" +} diff --git a/JotunnModStub/Translations/Russian/hover.json b/JotunnModStub/Translations/Russian/hover.json new file mode 100644 index 0000000..968461e --- /dev/null +++ b/JotunnModStub/Translations/Russian/hover.json @@ -0,0 +1,56 @@ +{ + "rov_hover_aswid_dominate": "[$KEY_Use] Dominate", + "rov_hover_aswid_dominate_cooldown_m": "[$KEY_Use] Dominate (Cooldown: $1m)", + "rov_hover_aswid_follow": "[$KEY_Use] Follow", + "rov_hover_aswid_stay": "[$KEY_Use] Stay", + "rov_hover_aswid_tame": "\n[$1] Tame", + "rov_hover_butler_no_servant_stands_here_raise": "$1\nNo servant stands here.\n[$KEY_Use] Raise one", + "rov_hover_butler_waiting": "Waiting.", + "rov_hover_draugh_feed_flesh_or_draugr_s": "\n[$KEY_Use] Feed it flesh, or a draugr's head", + "rov_hover_draugh_flesh_risen_waiting": "flesh $1/$2, risen $3/$4, waiting $5/$6", + "rov_hover_draugh_next_rises_s": "\nnext rises in $1s", + "rov_hover_draugh_officers_waiting": "\nofficers $1/$2, waiting $3/$4", + "rov_hover_dvergar_at_barrel_pour_round": "$1 $2/$3\n$4 at the barrel\n[$KEY_Use] Pour a round", + "rov_hover_dvergar_contracts": "contracts $1/$2", + "rov_hover_dvergar_empty_pour_brew": "empty\n[$KEY_Use] Pour a brew in", + "rov_hover_dvergar_read_ledger": "\n[$KEY_Use] Read the ledger", + "rov_hover_dvergar_seal_worth_off": "\nyour seal is worth $1% off", + "rov_hover_dvergar_what_queen_left_behind_buys": "\n(what the Queen left behind buys two more crews)", + "rov_hover_fenrir_blood_thin_here_raises_no": "\nthe blood is thin here - it raises no fenrir yet", + "rov_hover_fenrir_fenrir": ", fenrir $1/$2", + "rov_hover_fenrir_fill_with_meat": "\n[$KEY_Use] Fill it with meat", + "rov_hover_fenrir_meat_wolves_ulv": "meat $1/$2\nwolves $3/$4, ulv $5/$6", + "rov_hover_fenrir_next_s": "\nnext in $1s", + "rov_hover_fenrir_not_enough_meat_next_one": "\nnot enough meat for the next one ($1 needed)", + "rov_hover_fenrir_pack_whole": "\nthe pack is whole", + "rov_hover_skeleton_bone_hand_buy_place_empty": "\n[$KEY_Use] Bone in hand to buy a place, empty hands to move the line", + "rov_hover_skeleton_bone_toward_next_places": "\nbone $1/$2 toward the next of $3 places", + "rov_hover_skeleton_every_place_bought": "\nevery place is bought", + "rov_hover_skeleton_melee_archers_rotten": "\nmelee $1/$2 of $3\narchers $4/$5 of $6\nrotten $7/$8 of $9", + "rov_hover_skeleton_needs_greater_cursed_skull": " (needs a Greater Cursed Skull)", + "rov_hover_skeleton_next_rises_s": "\nnext rises in $1s", + "rov_hover_sverm_beehives_taken_allowed_range_feed": "$1\n$2Beehives $3 taken of $4 allowed, $5 in range\n$6[$KEY_Use] Feed it a stack", + "rov_hover_sverm_market_no_hive": "$1\nNo hive within $2 metres.", + "rov_hover_sverm_msg": "$1\n$2[$KEY_Use] $3", + "rov_hover_sverm_stomach_prompt": "Feed it a stack", + "rov_hover_sverm_stomach_title": "Hive Stomach", + "rov_hover_sverm_tank": "Biomass $1 / $2\nDigesting $3\nBrood eggs $4 / $5\n", + "rov_hover_sverm_trade_with_hive": "$1\n$2[$KEY_Use] Trade with the hive", + "rov_hover_trenta_flesh_feed_raw_flesh": "flesh $1/$2\n[$KEY_Use] Feed it raw flesh", + "rov_hover_trenta_grove_growing": "$1 (growing, $2 minutes left)", + "rov_hover_trenta_grove_grown": "$1 ($2 $3/$4, honey $5)\n[$KEY_Use] Feed it Fertilizer", + "rov_hover_trenta_honey_full": "$1, full", + "rov_hover_trenta_honey_next": "$1, next in $2 min", + "rov_hover_trenta_honey_none": "none (no honey item found)", + "rov_hover_trenta_ready_empty": "ready: $1 $2\n[$KEY_Use] Empty it", + "rov_hover_trenta_rotting_minutes_left": "rotting, $1 minutes left", + "rov_hover_trol_call_warbands": "\n[$KEY_Use] Call the warbands", + "rov_hover_trol_grab_log": "\n[$1] Grab Log", + "rov_hover_trol_warbands": "warbands $1/$2", + "rov_hover_trol_yagluth_drop_hand_buys_king": "\n(a Yagluth drop in hand buys a king's head, and two more bands)", + "rov_hover_ward_personal": "Personal", + "rov_hover_ward_race_menu_ward_progression_open": "$rov_piece_racemenuward_name\n$1 progression - $2 ($3/$4)\n[$KEY_Use] Open\n[Use item] Offer a boss relic", + "rov_hover_ward_world": "World", + "rov_hover_boneship_roster": "\nmelee $1/$2 of $3\narchers $4/$5 of $6\naboard $7", + "rov_hover_boneship_bone_hand": "\nbone in hand to buy a place" +} diff --git a/JotunnModStub/Translations/Russian/items.json b/JotunnModStub/Translations/Russian/items.json new file mode 100644 index 0000000..a58cd84 --- /dev/null +++ b/JotunnModStub/Translations/Russian/items.json @@ -0,0 +1,138 @@ +{ + "rov_creature_bonecook_name": "Bone Cook", + "rov_creature_bonesmith_name": "Bone Smith", + "rov_creature_draugh_thrall_name": "Draugr Thrall", + "rov_creature_draugh_thrallelite_name": "Draugr Elite Thrall", + "rov_creature_fenrir_pack_desc": "It answers to the blood of the wolf, not to you.", + "rov_creature_fenrir_packfenrir_desc": "Only the blood of the wolf commands this one.", + "rov_creature_fenrir_packfenrir_name": "Fenrir", + "rov_creature_fenrir_packulv_name": "Ulv", + "rov_creature_fenrir_packwolf_name": "Pack Wolf", + "rov_creature_skadi_crystalgolem_name": "Crystal Golem", + "rov_creature_skeleton_sentry_name": "Bound Sentry", + "rov_creature_skeleton_thrallmelee_name": "Bound Skeleton", + "rov_creature_skeleton_thrallrancid_name": "Bound Rancid Remains", + "rov_creature_skeleton_thrallranged_name": "Bound Archer", + "rov_creature_sverm_blistertick_name": "Blister Tick", + "rov_creature_sverm_worker_name": "Seeker Worker", + "rov_item_aswid_bloodcore_desc": "A knot of clotted blood kept beating by something that is not a heart. The dead trade them; only the dead know how they are made.", + "rov_item_aswid_bloodcore_name": "Blood Core", + "rov_item_aswid_bloodessence_desc": "Blood rendered down to what it actually is. The only real food an Aswid can still chew, and the base of every draught worth brewing.", + "rov_item_aswid_bloodessence_name": "Blood Essence", + "rov_item_aswid_bloodpotion_desc": "Drink and the hunger stops mattering for a while. Fills every stomach with blood essence, full or not, and knits the flesh back together.", + "rov_item_aswid_bloodpotion_name": "Blood Potion", + "rov_item_aswid_bloodpotionbase_desc": "Blood, berries and crypt light, waiting on a barrel.", + "rov_item_aswid_bloodpotionbase_name": "Blood Potion Mead Base", + "rov_item_aswid_claws_desc": "Grown in the dark, and darker for it. They do not come off.", + "rov_item_aswid_claws_name": "Claws of the Beast", + "rov_item_aswid_food_desc": "The life force of the conquered.", + "rov_item_aswid_food_name": "Aswid Food:", + "rov_item_aswid_spectralclaw_desc": "A claw of pure shadow, bound to your rage rather than your grip.", + "rov_item_aswid_spectralclaw_name": "Spectral Claw", + "rov_item_aswid_superiorbloodessence_desc": "The same blood, rendered twice. Darker, thicker, and worth five of the first pass.", + "rov_item_aswid_superiorbloodessence_name": "Superior Blood Essence", + "rov_item_aswid_superiorbloodpotion_desc": "The same mercy, twice as deep.", + "rov_item_aswid_superiorbloodpotion_name": "Superior Blood Potion", + "rov_item_aswid_superiorbloodpotionbase_desc": "The twice-rendered draught, still raw.", + "rov_item_aswid_superiorbloodpotionbase_name": "Superior Blood Potion Mead Base", + "rov_item_draugh_cursedbone_desc": "A bone that will not stay quiet. The dead sell them; the dead do not say why.", + "rov_item_draugh_cursedbone_name": "Cursed Bone", + "rov_item_draugh_greatercursedbone_desc": "The same bone, older, and louder. A pile fed one of these starts keeping officers.", + "rov_item_draugh_greatercursedbone_name": "Greater Cursed Bone", + "rov_item_draugh_humanmeat_desc": "A piece of somebody. The living gag on it; you do not.", + "rov_item_draugh_humanmeat_name": "Human Meat", + "rov_item_fenrir_claws_desc": "The wolf's hands, kept on in the man's shape. They do not come off.", + "rov_item_fenrir_claws_name": "Cursed Claws", + "rov_item_fenrir_greaterulvsblod_desc": "Older blood, and further down the line. A trough given one of these starts raising something worse than ulv.", + "rov_item_fenrir_greaterulvsblod_name": "Greater Ulvsblod", + "rov_item_fenrir_ulvsblod_desc": "Wolf blood, kept warm by something that should not be able to keep anything warm. The Fenring sell it and do not explain it.", + "rov_item_fenrir_ulvsblod_name": "Ulvsblod", + "rov_item_furling_copperdust_desc": "A sack of copper ground fine. A furnace cannot tell it from ore, and it will not go through a portal either.", + "rov_item_furling_copperdust_name": "Copper Dust", + "rov_item_furling_copperflax_desc": "Flax grown in copper-poisoned soil, and it took. Useless as cloth. Grind it and see.", + "rov_item_furling_copperflax_name": "Copper Flax", + "rov_item_furling_flintberry_desc": "Not a berry, whatever it looks like. Bury one and a flint-bearing bush comes up.", + "rov_item_furling_flintberry_name": "Flintberry", + "rov_item_furling_irondust_desc": "A sack of iron ground fine. A furnace cannot tell it from ore, and it will not go through a portal either.", + "rov_item_furling_irondust_name": "Iron Dust", + "rov_item_furling_ironflax_desc": "Flax grown in iron-poisoned soil, and it took. Useless as cloth. Grind it and see.", + "rov_item_furling_ironflax_name": "Iron Flax", + "rov_item_furling_stoneberry_desc": "Not a berry, whatever it looks like. Bury one and a stone-bearing bush comes up.", + "rov_item_furling_stoneberry_name": "Stoneberry", + "rov_item_furling_tindust_desc": "A sack of tin ground fine. A furnace cannot tell it from ore, and it will not go through a portal either.", + "rov_item_furling_tindust_name": "Tin Dust", + "rov_item_furling_tinflax_desc": "Flax grown in tin-poisoned soil, and it took. Useless as cloth. Grind it and see.", + "rov_item_furling_tinflax_name": "Tin Flax", + "rov_item_skadi_greaterfrostheart_desc": "Older cold than the mountain's. The cultists sell it and will not say where they dig.", + "rov_item_skadi_greaterfrostheart_name": "Greater Frost Heart", + "rov_item_skeleton_cursedskull_desc": "A skull that keeps counting. Set it down and the ground starts answering.", + "rov_item_skeleton_cursedskull_name": "Cursed Skull", + "rov_item_skeleton_greatercursedskull_desc": "Older, and it counts higher. A pile given one of these raises the rotten too.", + "rov_item_skeleton_greatercursedskull_name": "Greater Cursed Skull", + "rov_item_skeleton_soulstone_desc": "Something is still in there, and it is still angry. Bind it to a skull and it will stand watch as long as the bones hold.", + "rov_item_skeleton_soulstone_name": "Soul Stone", + "rov_item_sverm_claws_desc": "Grown, not forged. They do not come off.", + "rov_item_sverm_claws_name": "Chitin Claws", + "rov_item_trenta_fertilizer_desc": "Everything that was meat, a month later. Press it into the soil and whatever is rooted there stops waiting.", + "rov_item_trenta_fertilizer_name": "Fertilizer", + "rov_item_trenta_heartwoodseed_desc": "A seed fed on a whole barrel of rot. Plant it and go away for a while.", + "rov_item_trenta_heartwoodseed_name": "Heartwood Seed", + "rov_item_trenta_rotseed_desc": "A seed that died before it could sprout, and did not stop. The forest folk sell them; only the forest knows what grows from one.", + "rov_item_trenta_rotseed_name": "Rot Seed", + "rov_item_trol_giantslog_desc": "A massive tree log wielded as a weapon.", + "rov_item_trol_giantslog_name": "Giant's Log", + "rov_item_trolshammer_desc": "A hammer swung by something that never had to duck through a doorway. It builds everything the ordinary one builds, out of the same materials, and simply builds it bigger.", + "rov_item_trolshammer_name": "Trol's Hammer", + "rov_item_warvulture_desc": "A vulture's head, kept. Raise it and the bird comes back under you, and it will carry you as long as you care to stay up - though it only has so much haste in it before it settles into a glide.", + "rov_item_warvulture_name": "War Vulture", + "rov_piece_aswid_bloodrefinery_desc": "Flesh goes in, bone goes in, and what is left of both comes out red.", + "rov_piece_aswid_bloodrefinery_name": "Blood Refinery", + "rov_piece_cooktable_desc": "A slab of bone and slate, worn smooth. Something patient waits by the hearth.", + "rov_piece_cooktable_name": "Cook's Table", + "rov_piece_draugh_bodypile_desc": "Feed it and it answers. The dead here are yours, if you are dead enough to ask.", + "rov_piece_draugh_bodypile_name": "Cursed Body Pile", + "rov_piece_dvergar_contractbank_desc": "A ledger, a seal and a heap of coin. Sign here and someone else does the dying.", + "rov_piece_dvergar_contractbank_name": "Contract Bank", + "rov_piece_dvergar_runebarrel_desc": "Pour a brew in and the crew drinks. What it does to them is whatever it would have done to you - if they have the parts for it.", + "rov_piece_dvergar_runebarrel_name": "Rune Barrel", + "rov_piece_fenrir_packtrough_desc": "Fill it with meat and the pack comes. One at a time, and it remembers its dead.", + "rov_piece_fenrir_packtrough_name": "Pack Trough", + "rov_piece_furling_copperflaxsapling_desc": "Plant it and it grows more Copper Flax.", + "rov_piece_furling_copperflaxsapling_name": "Copper Flax", + "rov_piece_furling_flintberrybush_desc": "Yields flint, and keeps yielding it.", + "rov_piece_furling_flintberrybush_name": "Flintberry Bush", + "rov_piece_furling_ironflaxsapling_desc": "Plant it and it grows more Iron Flax.", + "rov_piece_furling_ironflaxsapling_name": "Iron Flax", + "rov_piece_furling_stoneberrybush_desc": "Yields stone, and keeps yielding it.", + "rov_piece_furling_stoneberrybush_name": "Stoneberry Bush", + "rov_piece_furling_tinflaxsapling_desc": "Plant it and it grows more Tin Flax.", + "rov_piece_furling_tinflaxsapling_name": "Tin Flax", + "rov_piece_racemenuward_desc": "Commune with your heritage. Offer a fallen boss's relic to claim its power.", + "rov_piece_racemenuward_name": "Race Menu Ward", + "rov_piece_skadi_crystalgolem_desc": "Cut at the stone and woken with a tear. It will not follow you, and it will not leave the stonecutter that shaped it.", + "rov_piece_skeleton_bonepile_desc": "Twenty fragments buy a place in the line. The one who fills it will keep standing up.", + "rov_piece_skeleton_bonepile_name": "Bound Bone Pile", + "rov_piece_skeleton_sentry_desc": "A skull on a soul stone. It will not walk, and it will not stop watching.", + "rov_piece_smithtable_desc": "A slab of bone and slate, dusted with ore. Something patient waits by the fires.", + "rov_piece_smithtable_name": "Smith's Table", + "rov_piece_sverm_broodmound_desc": "The colony begins here. Everything else grows out of it.", + "rov_piece_sverm_broodmound_name": "Brood Mound", + "rov_piece_sverm_hivemarket_desc": "Where the colony trades. It spends the tank of the nest it stands in.", + "rov_piece_sverm_hivemarket_name": "Hive Market", + "rov_piece_trenta_composter_desc": "What rots is not lost. It feeds.", + "rov_piece_trenta_composter_name": "Composter", + "rov_piece_trenta_elderroot_desc": "What the Elder left behind, still growing. Mends itself, and everything a player built close enough to it.", + "rov_piece_trenta_elderroot_name": "Root of the Elder", + "rov_piece_trenta_heartwoodgrove_desc": "A crate of rot with something growing out of it. Give it time.", + "rov_piece_trenta_heartwoodgrove_name": "Heartwood Grove", + "rov_piece_trenta_heartwoodsapling_name": "Heartwood Sapling", + "rov_piece_trol_wartotem_desc": "A head that still remembers how to shout. Coin goes in, a warband walks out.", + "rov_piece_trol_wartotem_name": "War Totem", + "rov_piece_boneship_altar_name": "Offering Chest", + "rov_piece_boneship_ashlands_desc": "A warship that burned and kept going, ribbed with bone. The oarsmen do not tire.", + "rov_piece_boneship_ashlands_name": "Ashen Bone Longship", + "rov_piece_boneship_karve_desc": "A Karve gone to rot, ribbed with bone. It was not built to sail on wind.", + "rov_piece_boneship_karve_name": "Bone Karve", + "rov_piece_boneship_longship_desc": "A longship gone to rot, ribbed with bone. It sails against any wind.", + "rov_piece_boneship_longship_name": "Bone Longship" +} diff --git a/JotunnModStub/Translations/Russian/merchants.json b/JotunnModStub/Translations/Russian/merchants.json new file mode 100644 index 0000000..3b40204 --- /dev/null +++ b/JotunnModStub/Translations/Russian/merchants.json @@ -0,0 +1,133 @@ +{ + "rov_joke_fantasma_01": "Why was the ghost lonely? It had no-body.", + "rov_joke_fantasma_02": "What's the most useless room in a house for a ghost? A living room.", + "rov_joke_fantasma_03": "What's a ghost's favourite cheese? Ghoul-da cheese.", + "rov_joke_fantasma_04": "What's a ghost's favourite food? Boo-rritos.", + "rov_joke_fantasma_05": "What's a ghost's favourite dessert? I-scream.", + "rov_joke_fantasma_06": "What's a ghost's favourite game? Hide and Shriek.", + "rov_joke_fantasma_07": "What do you call a ghost with a broken leg? A hoblin goblin.", + "rov_joke_fantasma_08": "What happens when a ghost gets lost in the fog? He is mist.", + "rov_joke_fantasma_09": "Ghosts love elevators because it lifts their spirits.", + "rov_joke_fantasma_10": "Why did the ghost cross the road? Because it was a poultry-geist.", + "rov_joke_goblin_01": "Those goblin fingers are dexter-gnome-us.", + "rov_joke_goblin_02": "Why did the goblin break the vase? He wanted to smash expectations.", + "rov_joke_goblin_03": "That goblin really gnome-napped my sandwich.", + "rov_joke_goblin_04": "Just goblin around.", + "rov_joke_goblin_05": "They love orc-strating trouble.", + "rov_joke_goblin_06": "If a goblin smiles at you, check your pockets.", + "rov_joke_goblin_07": "Why don't goblins shower? They prefer natural grime.", + "rov_joke_goblin_08": "What's a goblin's favorite sport? Lootball.", + "rov_joke_goblin_09": "How do goblins shop? Five-finger discount only.", + "rov_joke_goblin_10": "What's a goblin's password? 'MineMineMine!'", + "rov_joke_legnofalegname_01": "Carpenters nail it every time: that's their true calling.", + "rov_joke_legnofalegname_02": "I told my saw a joke: it couldn't handle the cut.", + "rov_joke_legnofalegname_03": "I dated a carpenter once: it was a solid relationship.", + "rov_joke_legnofalegname_04": "Carpenters have great timing: they always measure up.", + "rov_joke_legnofalegname_05": "My friend builds furniture: he really wood make you laugh.", + "rov_joke_legnofalegname_06": "A good carpenter never quits: he just saws what he started.", + "rov_joke_legnofalegname_07": "I asked the wood if it was okay: it said, 'I'm board.'", + "rov_joke_legnofalegname_08": "I made a joke about a piece of wood, but it was too plane.", + "rov_joke_legnofalegname_09": "How do trees access the internet? They just log on!", + "rov_joke_legnofalegname_10": "Why did the plank cross the road? To get to the other siding!", + "rov_joke_lupolicantropo_01": "Why did the werewolf laugh while chewing on the skeleton? He got to the funny bone.", + "rov_joke_lupolicantropo_02": "Why did the werewolf need to talk with the skeleton? He had a bone to pick with him.", + "rov_joke_lupolicantropo_03": "A what-to-wear-wolf.", + "rov_joke_lupolicantropo_04": "My werewolf skills are claw-some.", + "rov_joke_lupolicantropo_05": "'Howl'-oween, hands down - a werewolf's favorite holiday.", + "rov_joke_lupolicantropo_06": "Why don't werewolves use cell phones? Because they prefer to roam.", + "rov_joke_lupolicantropo_07": "Why did the werewolf sit in the corner? He didn't want to be spotted.", + "rov_joke_lupolicantropo_08": "Why don't werewolves gossip? They can't keep a straight paw.", + "rov_joke_lupolicantropo_09": "You're fur-ociously awesome.", + "rov_joke_lupolicantropo_10": "Howl you doin' tonight?", + "rov_joke_nano_01": "A dwarf who loved gardening had a real green thumbelina.", + "rov_joke_nano_02": "Dwarves make excellent bakers; their scone courses are always the shortest.", + "rov_joke_nano_03": "Why do dwarfs make great secret agents? They can really keep things low-key.", + "rov_joke_nano_04": "A dwarf walks into a bar and hits his head - the bar was set too low.", + "rov_joke_nano_05": "Why are dwarfs so good at math? Because it's the little things that count.", + "rov_joke_nano_06": "I saw a dwarf climbing down a prison wall - it was a little condescending.", + "rov_joke_nano_07": "What do dwarfs use to fight trolls? Short swords.", + "rov_joke_nano_08": "What's a dwarf warrior's motto? Small but deadly.", + "rov_joke_nano_09": "A dwarf opened a bakery because he kneaded dough at his level.", + "rov_joke_nano_10": "What do you call a dwarf who can be invisible? A short circuit!", + "rov_joke_nonmortozombie_01": "When do zombies go to sleep? When they are dead tired.", + "rov_joke_nonmortozombie_02": "What streets do zombies live on? Dead ends.", + "rov_joke_nonmortozombie_03": "Where do zombies go sailing? Lake Eerie.", + "rov_joke_nonmortozombie_04": "What do you call a zombie in pajamas? The sleepwalking dead.", + "rov_joke_nonmortozombie_05": "How are zombies like computers? They use mega-bites!", + "rov_joke_nonmortozombie_06": "Why did the zombie lose his lawsuit? He had no leg to stand on!", + "rov_joke_nonmortozombie_07": "Why did the zombie eat a light bulb? Because he wanted a light snack.", + "rov_joke_nonmortozombie_08": "Why don't zombies eat clowns? Because they taste funny!", + "rov_joke_nonmortozombie_09": "Why did the zombie go to school? To improve his brainpower.", + "rov_joke_nonmortozombie_10": "Zombies are hopeless romantics, seeking their ghoul-mate.", + "rov_joke_scheletro_01": "What do you call a skeleton who never does his chores? Lazy bones.", + "rov_joke_scheletro_02": "Why did the skeleton quit his job? His heart wasn't in it.", + "rov_joke_scheletro_03": "What skeleton was the first emperor of France? Napoleon Bone-aparte.", + "rov_joke_scheletro_04": "Who is the world's most famous skeleton detective? Sherlock Bones.", + "rov_joke_scheletro_05": "What did the French skeletons say before eating their dinner? Bone appetit!", + "rov_joke_scheletro_06": "What do skeletons always order when they go to a restaurant? Spare ribs.", + "rov_joke_scheletro_07": "How do skeletons call each other? On their tele-bone.", + "rov_joke_scheletro_08": "What's a skeleton's favorite fruit? Bone-ana!", + "rov_joke_scheletro_09": "Why are skeletons bad at lying? You can see right through them!", + "rov_joke_scheletro_10": "Why don't skeletons fight each other? They don't have the guts.", + "rov_joke_strega_01": "Resting witch face.", + "rov_joke_strega_02": "Hag a nice day.", + "rov_joke_strega_03": "What do you call a mage in the desert? A sand-witch.", + "rov_joke_strega_04": "What happens to witches who break the rules at school? They get ex-spelled.", + "rov_joke_strega_05": "What do witches put in their hair? Scare spray.", + "rov_joke_strega_06": "Why did three witches call in the plumber? Hubble, bubble, toilet trouble.", + "rov_joke_strega_07": "Why couldn't the little witch read her spellbook? It was written in curse-ive.", + "rov_joke_strega_08": "Why did the witch become a lawyer? She wanted to practice witchcraft.", + "rov_joke_strega_09": "Witches don't fart. They cast smells.", + "rov_joke_strega_10": "A witch tells the time by looking at her witch watch.", + "rov_joke_troll_01": "Why do trolls love bridges? They're always crossing into new territory.", + "rov_joke_troll_02": "Why did the troll get a bad grade? He was always under the bridge of understanding.", + "rov_joke_troll_03": "Trolls don't watch TV - they stream mischief.", + "rov_joke_troll_04": "Trolls love parties - they bring the bridge snacks.", + "rov_joke_troll_05": "Trolls hate Mondays - they bridge the gap to Friday.", + "rov_joke_troll_06": "Where do trolls keep their money? Under the bridge, of course.", + "rov_joke_troll_07": "What's a troll's favorite candy? Bridge bars.", + "rov_joke_troll_08": "Why did the troll go to school? To bridge the knowledge gap.", + "rov_joke_troll_09": "What's a troll's favorite movie? The Bridge Runner.", + "rov_joke_troll_10": "What makes a troll laugh? Someone taking it seriously.", + "rov_merchant_buy": "Deal.", + "rov_merchant_dverg_name": "Dverg", + "rov_merchant_sell": "Thanks.", + "rov_merchant_start_trade": "What do you need?", + "rov_sverm_good_glands_desc": "Every troop hatched from now on is born with one star.\n\nIt does nothing for the ones already walking around: what is born is born.", + "rov_sverm_good_glands_name": "Surrenal Glands", + "rov_sverm_good_hyperplasia_desc": "Every troop hatched from now on is born with two stars.\n\nThe colony has to have grown the glands first.", + "rov_sverm_good_hyperplasia_name": "Hyperplasia", + "rov_sverm_good_stage_desc": "Grows the nest into a $1: it holds $2 biomass instead of $3, and stands half again as tall.\n\nIt costs this stage's whole tankful, so it leaves the hive all but empty. Grow or field an army - never both in the same breath.", + "rov_sverm_good_tick_desc": "Buys a PERMANENT slot in the colony. What stands in it runs at whatever the colony is fighting and bursts, and thirty seconds later the nest grows another one - no egg, no biomass, forever.\n\nThe blast spares you, your tames and the rest of the colony.", + "rov_sverm_good_troop_desc": "Hatches a $1, bound to this nest: it follows when you ask, walks home when you let it go, and mends itself.\n\nCosts one brood egg as well as the biomass. At most $2 of them alive at once.", + "rov_sverm_refusal_already_breeds": "The colony already breeds like this.", + "rov_sverm_refusal_grown_past": "Already grown past this.", + "rov_sverm_refusal_keeping": "The colony is already keeping $1 of them.", + "rov_sverm_refusal_keeps": "The colony already keeps $1 of them.", + "rov_sverm_refusal_no_egg": "No brood egg ready.", + "rov_sverm_refusal_no_hive": "No hive.", + "rov_sverm_refusal_one_star": "One star at a time.", + "rov_sverm_refusal_stage_first": "The nest has to be a $1 first.", + "rov_sverm_refusal_working_m": "The hive is still working on the last one ($1m).", + "rov_sverm_refusal_working_s": "The hive is still working on the last one ($1s).", + "rov_sverm_stage_gorgedhive": "Gorged Hive", + "rov_sverm_stage_hivecitadel": "Hive Citadel", + "rov_sverm_stage_nestingspire": "Nesting Spire", + "rov_troop_dvergar_ash_guard": "Ash Guard", + "rov_troop_dvergar_escort": "Escort", + "rov_troop_dvergar_fire_crew": "Fire Crew", + "rov_troop_dvergar_runic_crew": "Runic Crew", + "rov_troop_dvergar_seal_price": "List price $1 - your seal takes it to $2.", + "rov_troop_dvergar_terms": "They answer the follow command, knit their own wounds shut, keep your truce with the mountain's dvergr, drop nothing, and do not come back. A dead crew is money spent.", + "rov_troop_dvergar_yard_patrol": "Yard Patrol", + "rov_troop_sverm_brood": "Brood", + "rov_troop_sverm_gjall": "Gjall", + "rov_troop_sverm_seeker": "Seeker", + "rov_troop_sverm_soldier": "Soldier", + "rov_troop_trol_goblin_band": "Fuling War Band", + "rov_troop_trol_goblin_patrol": "Fuling Patrol", + "rov_troop_trol_greydwarf_patrol": "Greydwarf Patrol", + "rov_troop_trol_terms": "They answer the follow command, knit their own wounds shut, drop nothing, and do not come back. A dead warband is money spent.", + "rov_troop_trol_troll": "Troll", + "rov_troop_trol_troll_summoned": "Staff Troll" +} diff --git a/JotunnModStub/Translations/Russian/messages.json b/JotunnModStub/Translations/Russian/messages.json new file mode 100644 index 0000000..6e6ee1e --- /dev/null +++ b/JotunnModStub/Translations/Russian/messages.json @@ -0,0 +1,205 @@ +{ + "rov_msg_aswid_aura_disabled": "Vampiric Aura: DISABLED", + "rov_msg_aswid_aura_enabled": "Vampiric Aura: ENABLED", + "rov_msg_aswid_dominate_cooldown_m_s": "Dominate on cooldown ($1m $2s)", + "rov_msg_aswid_dominated": "$1 dominated!", + "rov_msg_aswid_eclipse_cooldown_remaining_s": "Eclipse is on cooldown. Remaining: $1s", + "rov_msg_aswid_eclipse_descends": "An Eclipse descends...", + "rov_msg_aswid_eclipse_has_ended": "The Eclipse has ended.", + "rov_msg_aswid_following": "$1 is following.", + "rov_msg_aswid_living_blood_curdles_living_throat": "Living blood curdles in a living throat.", + "rov_msg_aswid_morning_sun_drives_bat_back": "The morning sun drives the bat back into your body", + "rov_msg_aswid_morning_sun_has_vanquished_horrible": "The morning sun has vanquished the horrible night", + "rov_msg_aswid_no_bone_grind": "No bone to grind.", + "rov_msg_aswid_no_raw_flesh_render": "No raw flesh to render.", + "rov_msg_aswid_staying": "$1 is staying.", + "rov_msg_aswid_sun_burns_can_only_take": "The sun burns. You can only take bat form at night.", + "rov_msg_aswid_tamed": "Tamed!", + "rov_msg_aswid_vae_victis": "Vae Victis", + "rov_msg_aswid_what_horrible_night_have_curse": "what a horrible night to have a curse", + "rov_msg_build_limit_cooktable": "Another cook's table stands within forty paces. One cook to a yard.", + "rov_msg_build_limit_draugh_bodypile": "The ground here already carries $1 of these. Find another country.", + "rov_msg_build_limit_dvergar_contractbank": "There is already $1 contract bank within a day's walk. One ledger per valley.", + "rov_msg_build_limit_fenrir_packtrough": "There is already $1 of these within a day's walk. A pack needs room.", + "rov_msg_build_limit_skeleton_bonepile": "There are already $1 of these listening nearby. Take it further out.", + "rov_msg_build_limit_smithtable": "Another smith's table stands within forty paces. One smith to a yard.", + "rov_msg_build_limit_sverm_hive": "There is already a hive holding this ground.", + "rov_msg_build_limit_sverm_market": "This hive already has a market.", + "rov_msg_build_limit_trenta_grove": "This country already answers to $1 of these. Plant it somewhere else.", + "rov_msg_build_this_cave_will_hold_what": "This cave will hold what you build in it.", + "rov_msg_butler_already_at_work": "It is already at work.", + "rov_msg_butler_bones_are_not_ready_s": "The bones are not ready. $1s.", + "rov_msg_butler_bones_do_not_answer_blood": "The bones do not answer to your blood.", + "rov_msg_butler_nothing_answers": "Nothing answers.", + "rov_msg_butler_only_skadi_s_hearth_kept": "Only Skadi's hearth is kept by the dead.", + "rov_msg_butler_servant_rises": "The servant rises.", + "rov_msg_claws_they_are_part_hands": "They are part of your hands.", + "rov_msg_core_chose_path_aswid": "You chose the path of the Aswid.", + "rov_msg_core_chose_path_draugh": "You chose the path of the Draugh.", + "rov_msg_core_chose_path_dvergar": "You chose the path of the Dvergar.", + "rov_msg_core_chose_path_fenrir": "You chose the path of the Fenrir.", + "rov_msg_core_chose_path_furling": "You chose the path of the Furling.", + "rov_msg_core_chose_path_skadi": "You chose the path of Skadi.", + "rov_msg_core_chose_path_skeleton": "You chose the path of the Skeleton.", + "rov_msg_core_chose_path_sverm": "You chose the path of the Sverm.", + "rov_msg_core_chose_path_trenta": "You chose the path of the Trenta.", + "rov_msg_core_chose_path_trol": "You chose the path of the Trol.", + "rov_msg_core_chose_remain_human": "You chose to remain Human.", + "rov_msg_core_debug_override_cleared": "Debug override cleared.", + "rov_msg_core_nothing_reset_personal": "Nothing to reset - you have claimed no relics yet ($1/$2).", + "rov_msg_core_nothing_reset_world": "Nothing to reset - you follow the world's progression: $1 ($2/$3).", + "rov_msg_core_progression_reset": "Personal progression reset to $1 ($2/$3). Claim your relics again.", + "rov_msg_core_progression_state": "Progression State: $1", + "rov_msg_core_world_progression_state": "World Progression State: $1", + "rov_msg_draugh_bone_will_not_wake_something": "The bone will not wake. Something older has to fall first.", + "rov_msg_draugh_draugr_consume_only_raw_flesh": "Draugr consume only raw flesh, eyes, entrails or blood.", + "rov_msg_draugh_has_already_had_one": "It has already had one.", + "rov_msg_draugh_northern_wind_blows": "The northern wind blows", + "rov_msg_draugh_pile_broken_will_not_outlast": "The pile is broken. $1 will not outlast it by more than a minute.", + "rov_msg_draugh_pile_stirs_will_keep_officers": "The pile stirs. It will keep officers now.", + "rov_msg_draugh_steal_their_breath_death_denied": "Steal Their Breath! Death is denied.", + "rov_msg_draugh_swarm_terror": "Swarm of Terror!", + "rov_msg_draugh_this_pile_keeps_no_officers": "This pile keeps no officers yet.", + "rov_msg_draugh_this_rotting_flesh_fatal_living": "This rotting flesh is fatal to the living.", + "rov_msg_draugh_wants_flesh_or_head_one": "It wants flesh, or the head of one of its own.", + "rov_msg_draugh_zombie_ritual_activated_borrowed_time": "Zombie Ritual Activated! Your borrowed time is fading...", + "rov_msg_dvergar_contract_runic_do_not_sign": "The contract is in runic. You do not sign it.", + "rov_msg_dvergar_do_not_know_what_goes": "You do not know what goes in it.", + "rov_msg_dvergar_drink": "$1 drink $2.", + "rov_msg_dvergar_drink_barrel_runs_dry": "$1 drink $2. The barrel runs dry.", + "rov_msg_dvergar_empty_so_are": "It is empty, and so are you.", + "rov_msg_dvergar_five_contracts_all_ledger_holds": "Five contracts is all the ledger holds.", + "rov_msg_dvergar_has_already_had_one": "It has already had one.", + "rov_msg_dvergar_ledger_not_written": "The ledger is not written for you.", + "rov_msg_dvergar_ledger_rewritten_better_names_sign": "The ledger is rewritten. Better names sign it now.", + "rov_msg_dvergar_ledger_shut": "The ledger is shut.", + "rov_msg_dvergar_nobody_at_barrel": "Nobody is at the barrel.", + "rov_msg_dvergar_not_drop_went_down": "Not a drop went down.", + "rov_msg_dvergar_not_enough_eitr": "Not enough eitr", + "rov_msg_dvergar_not_while_she_still_sits": "Not while she still sits under the mist.", + "rov_msg_dvergar_runic_overcharge_discharges": "Runic Overcharge discharges", + "rov_msg_dvergar_runic_overcharge_next_blow_loaded": "Runic Overcharge: your next blow is loaded", + "rov_msg_dvergar_runic_ping_echoes_answer": "Runic Ping: $1 echoes answer", + "rov_msg_dvergar_runic_ping_stone_silent": "Runic Ping: the stone is silent", + "rov_msg_dvergar_signs": "$1 signs on.", + "rov_msg_dvergar_there_still": "There is still $1 in it.", + "rov_msg_dvergar_whatever_does_nothing_anyone": "Whatever is in it does nothing to anyone.", + "rov_msg_fenrir_are_cultist": "You are a Cultist!", + "rov_msg_fenrir_are_fenring": "You are a Fenring!", + "rov_msg_fenrir_are_ulv": "You are an Ulv!", + "rov_msg_fenrir_are_wolf": "You are a Wolf!", + "rov_msg_fenrir_beast_rests_can_only_transform": "The beast rests. You can only transform at night.", + "rov_msg_fenrir_beast_tired": "The beast is tired", + "rov_msg_fenrir_blood_will_not_take_something": "The blood will not take. Something in the plains has to fall first.", + "rov_msg_fenrir_form_cooldown": "$1 form is on cooldown ($2:$3).", + "rov_msg_fenrir_formname_cultist": "Cultist", + "rov_msg_fenrir_formname_fenrir": "Fenrir", + "rov_msg_fenrir_formname_ulv": "Ulv", + "rov_msg_fenrir_formname_wolf": "Wolf", + "rov_msg_fenrir_has_already_had_one": "It has already had one.", + "rov_msg_fenrir_only_breath_comes_out_fire": "Only breath comes out. The fire wants eitr.", + "rov_msg_fenrir_ready": "$1 is Ready!", + "rov_msg_fenrir_returned_human_form": "You returned to human form.", + "rov_msg_fenrir_sun_takes_form": "The sun takes the beast back. This form only answers at night.", + "rov_msg_fenrir_sun_takes_form_day_key": "The sun takes the beast back. This form only answers at night; by day, press $2 for the $1 form.", + "rov_msg_fenrir_trough_broken_will_not_outlast": "The trough is broken. $1 will not outlast it by long.", + "rov_msg_fenrir_trough_takes_line_runs_deeper": "The trough takes it. The line runs deeper now.", + "rov_msg_fenrir_wants_meat_any_meat": "It wants meat. Any meat.", + "rov_msg_fenrir_wants_what_yagluth_left_behind": "It wants what Yagluth left behind.", + "rov_msg_skadi_are_drake": "You are a Drake!", + "rov_msg_skadi_are_fader": "You are Fader!", + "rov_msg_skadi_are_moder": "You are Moder!", + "rov_msg_skadi_dragon_form_cooldown": "Dragon Form is on cooldown ($1:$2).", + "rov_msg_skadi_dragon_form_fades": "Your dragon form fades.", + "rov_msg_skadi_dumped_dragon_drake_fader_debug": "Dumped Dragon/Drake/Fader debug info to console!", + "rov_msg_skadi_needs_stonecutter_cut_at": "It needs a stonecutter to be cut at.", + "rov_msg_skadi_not_enough_stamina": "Not enough stamina", + "rov_msg_skadi_returned_human_form": "You returned to human form.", + "rov_msg_skadi_stone_does_not_answer": "The stone does not answer to you.", + "rov_msg_skadi_stonecutter_gone_what_cut_will": "The stonecutter is gone. What it cut will not outlast it by long.", + "rov_msg_skadi_tear_cold_nothing_wakes_stone": "The tear is cold. Nothing wakes in the stone until the mountain's queen has fallen.", + "rov_msg_skadi_that_stonecutter_already_holds_will": "That stonecutter already holds $1. It will not hold more.", + "rov_msg_skadi_there_are_already_these_within": "There are already $1 of these within a day's walk. The stone is spent.", + "rov_msg_skeleton_has_already_had_one": "It has already had one.", + "rov_msg_skeleton_have_been_resurrected_by_dark": "You have been resurrected by dark magic!", + "rov_msg_skeleton_look_normal": "Look: normal bones", + "rov_msg_skeleton_look_green": "Look: green bones", + "rov_msg_skeleton_look_flames": "Look: burning bones", + "rov_msg_skeleton_mortal_food_disgusts": "Mortal food disgusts you.", + "rov_msg_skeleton_nothing_standing_yet_wants_bone": "Nothing is standing yet. It wants bone.", + "rov_msg_skeleton_pile_broken_fall_where_they": "The pile is broken. $1 fall where they stand.", + "rov_msg_skeleton_pile_deepens_rotten_will_stand": "The pile deepens. The rotten will stand here too.", + "rov_msg_skeleton_return_pile": "$1 return to the pile.", + "rov_msg_skeleton_rise_follow": "$1 rise and follow.", + "rov_msg_skeleton_skeletons_do_not_need_eat": "Skeletons do not need to eat.", + "rov_msg_skeleton_skull_will_not_wake_something": "The skull will not wake. Something older has to fall first.", + "rov_msg_skeleton_these_bones_answer_only_their": "These bones answer only to their own kind.", + "rov_msg_skeleton_this_pile_cannot_hold_rotten": "This pile cannot hold the rotten yet.", + "rov_msg_sverm_alchemical_blood_not_food": "Alchemical blood is not food.", + "rov_msg_sverm_carapace_has_no_room_that": "Your carapace has no room for that.", + "rov_msg_sverm_colony_will_not_wake_until": "The colony will not wake until the Elder falls.", + "rov_msg_sverm_hive_does_not_know": "The hive does not know you.", + "rov_msg_sverm_hive_full_give_time_digest": "The hive is full. Give it time to digest.", + "rov_msg_sverm_market_has_stand_within_metres": "A market has to stand within $1 metres of a hive.", + "rov_msg_sverm_no_hive_within_metres_this": "No hive within $1 metres. This counter is dead.", + "rov_msg_sverm_not_enough_biomass_bank": "Not enough biomass in the bank.", + "rov_msg_sverm_not_hurt": "$1 is not hurt.", + "rov_msg_sverm_nothing_here_will_eat_food": "Nothing here it will eat. Food, wood and resin - honey and royal jelly are medicine.", + "rov_msg_sverm_only_sverm_can_raise_hive": "Only the Sverm can raise a hive.", + "rov_msg_sverm_only_sverm_can_raise_market": "Only the Sverm can raise a market.", + "rov_msg_sverm_ravager_strain_takes_hold": "The Ravager Strain takes hold.", + "rov_msg_sverm_shell_recedes": "The shell recedes.", + "rov_msg_sverm_strain_has_not_taken_yet": "The strain has not taken yet.", + "rov_msg_sverm_strain_spent": "The strain is spent.", + "rov_msg_sverm_they_are_part_hands": "They are part of your hands.", + "rov_msg_sverm_x_biomass_digesting": "$1 x$2 -> +$3 biomass, digesting", + "rov_msg_thrall_answer_call": "$1 answer the call.", + "rov_msg_thrall_answer_wait": "$1 stand and wait.", + "rov_msg_thrall_answer_home": "$1 head home.", + "rov_msg_thrall_waits": "$1 waits here.", + "rov_msg_thrall_follows": "$1 follows.", + "rov_msg_thrall_no_more_may_walk_with": "No more may walk with you.", + "rov_msg_thrall_only_may_walk_with": "Only $1 may walk with you.", + "rov_msg_thrall_refusal_default": "It does not answer to you.", + "rov_msg_thrall_refusal_draugh": "The dead do not take orders from the living.", + "rov_msg_thrall_refusal_dvergar": "Your name is not on the contract.", + "rov_msg_thrall_refusal_skeleton": "These bones answer only to their own kind.", + "rov_msg_thrall_refusal_sverm": "It does not smell your colony on you.", + "rov_msg_thrall_refusal_trol": "They were not paid by you.", + "rov_msg_thrall_returns": "$1 returns.", + "rov_msg_thrall_rises_with": "$1 rises with $2.", + "rov_msg_thrall_stands_down_with": "$1 stands down with $2.", + "rov_msg_trenta_are_muspell_ash_ember_given": "You are Muspell, ash and ember given shape.", + "rov_msg_trenta_elder_has_not_fallen_yet": "The Elder has not fallen yet.", + "rov_msg_trenta_grows": "It grows.", + "rov_msg_trenta_no_raw_flesh_rot": "No raw flesh to rot.", + "rov_msg_trenta_nothing_feed_wants_fertilizer": "Nothing to feed it. It wants Fertilizer.", + "rov_msg_trenta_nothing_there_feed": "Nothing there to feed.", + "rov_msg_trenta_return_rooted_form": "You return to your rooted form.", + "rov_msg_trenta_ripe_already": "It is ripe already.", + "rov_msg_trenta_root_will_not_take_hold": "The root will not take hold for you.", + "rov_msg_trenta_still_growing_minutes": "Still growing. $1 minutes.", + "rov_msg_trenta_still_rotting_minutes": "Still rotting. $1 minutes.", + "rov_msg_trenta_this_one_not_well_nothing": "This one is not well. Nothing will hurry it.", + "rov_msg_trenta_trenta_eat_only_what_grows": "The Trenta eat only what grows from root and leaf - no meat, fish, egg or honey.", + "rov_msg_trol_answers": "$1 answers.", + "rov_msg_trol_are_already_holding_log": "You are already holding a log!", + "rov_msg_trol_five_warbands_all_can_shout": "Five warbands is all it can shout for.", + "rov_msg_trol_has_already_had_one": "It has already had one.", + "rov_msg_trol_head_has_nothing_say": "The head has nothing to say.", + "rov_msg_trol_head_will_not_shout": "The head will not shout for you.", + "rov_msg_trol_must_true_form_lift_this": "You must be in True Form to lift this!", + "rov_msg_trol_no_room_lift": "No room to lift it!", + "rov_msg_trol_not_until_one_belonged_has": "Not until the one it belonged to has fallen.", + "rov_msg_trol_totem_wears_king_now": "The totem wears a king now.", + "rov_msg_ward_already_carry_s_power": "You already carry $1's power.", + "rov_msg_ward_s_power_yours": "$1's power is yours.", + "rov_msg_ward_switch_personal_progression_first": "Switch to personal progression first.", + "rov_msg_ward_ward_has_no_use_that": "The ward has no use for that.", + "rov_msg_warvulture_bird_does_not_know": "The bird does not know you.", + "rov_msg_warvulture_vulture_does_not_answer": "The vulture does not answer.", + "rov_msg_warvulture_vulture_settles_into_glide": "The vulture settles into a glide.", + "rov_msg_warvulture_vulture_spirals_down": "The vulture spirals down.", + "rov_msg_boneship_no_shore": "No shore in reach. They stay at the oars.", + "rov_msg_boneship_sunk": "The ship goes down, and $1 go with it." +} diff --git a/JotunnModStub/Translations/Russian/races.json b/JotunnModStub/Translations/Russian/races.json new file mode 100644 index 0000000..8d930c3 --- /dev/null +++ b/JotunnModStub/Translations/Russian/races.json @@ -0,0 +1,38 @@ +{ + "rov_menu_choose_race": "Choose your Race", + "rov_menu_ok": "OK", + "rov_menu_back": "Back", + + "rov_race_human_name": "Human", + "rov_race_human_desc": "The versatile founders of Midgard. Balanced stats with no specific weaknesses.", + + "rov_race_fenrir_name": "Fenrir", + "rov_race_fenrir_desc": "Cursed by the blood of the wolf. Fast and deadly, but vulnerable to silver.", + + "rov_race_skadi_name": "Skadi", + "rov_race_skadi_desc": "Children of the mountains. Resistant to frost, at home in the freezing cold.", + + "rov_race_skeleton_name": "Skeleton", + "rov_race_skeleton_desc": "Undead warriors. Immune to poison, but brittle against blunt trauma.", + + "rov_race_aswid_name": "Aswid", + "rov_race_aswid_desc": "Fierce night stalker. Strong and resilient, transforms into a bat.", + + "rov_race_furling_name": "Furling", + "rov_race_furling_desc": "Cunning goblin-like creatures. Agile and resourceful.", + + "rov_race_trol_name": "Trol", + "rov_race_trol_desc": "Massive brute strength. Towering over others, at peace with the Black Forest - but fire burns a Trol $1% harder than anyone else.", + + "rov_race_draugh_name": "Draugh", + "rov_race_draugh_desc": "A decaying undead warrior fueled by dark magic and extreme metal.", + + "rov_race_dvergar_name": "Dvergar", + "rov_race_dvergar_desc": "Small, stubborn smiths of the deep. Frail of frame, but masters of metal, mine and market.", + + "rov_race_trenta_name": "Trenta", + "rov_race_trenta_desc": "Tree-born folk, kin to root and leaf. Patient and hard to fell.", + + "rov_race_sverm_name": "Sverm", + "rov_race_sverm_desc": "Chitin-born swarm kin. Armoured from birth and never slowed, venomous, at peace with every crawling thing - but blunt trauma and fire find the seams." +} diff --git a/JotunnModStub/Translations/Russian/status_effects.json b/JotunnModStub/Translations/Russian/status_effects.json new file mode 100644 index 0000000..ba0b959 --- /dev/null +++ b/JotunnModStub/Translations/Russian/status_effects.json @@ -0,0 +1,62 @@ +{ + "rov_se_aswid_auspex_name": "Auspex", + "rov_se_aswid_auspex_tooltip": "Sensing life force of nearby creatures.", + "rov_se_aswid_batform_name": "Like a Bat out of Hell", + "rov_se_aswid_batform_tooltip": "You have taken the form of a Bat. You can fly, but cannot attack.", + "rov_se_aswid_bloodpotion_tooltip": "Stomachs filled with blood. Healing $1% over $2 seconds.", + "rov_se_aswid_mistform_name": "Weight of Shadows", + "rov_se_aswid_mistform_tooltip": "You are mist. Immune to physical damage and poison. Cannot attack or run.", + "rov_se_aswid_nightaura_name": "Night Aura", + "rov_se_aswid_nightaura_tooltip": "The cold strengthens your beastly senses.", + "rov_se_aswid_sensed_name": "Sensed", + "rov_se_aswid_stats_name": "Benedictus et Afflictus", + "rov_se_aswid_stats_tooltip": "Vampiric senses and life drain.", + "rov_se_claws_tooltip": "Your claws are out. They retract when this runs out.", + "rov_se_draugh_wet_tooltip": "The water restores your rotten flesh. Health regeneration increased.", + "rov_se_dvergar_overcharge_name": "Runic Overcharge", + "rov_se_dvergar_overcharge_tooltip": "Your next blow with a favoured weapon carries the whole of the charge.", + "rov_se_dvergar_overchargecd_name": "Overcharge Cooldown", + "rov_se_dvergar_overchargecd_tooltip": "The runes are spent.", + "rov_se_dvergar_pingcd_name": "Runic Ping", + "rov_se_dvergar_pingcd_tooltip": "The runes must settle before you may call on them again.", + "rov_se_dvergar_stats_name": "Stone and Forge", + "rov_se_dvergar_stats_tooltip": "Small, sturdy, and born to the anvil.", + "rov_se_fenrir_cultistcd_name": "Cultist Form Cooldown", + "rov_se_fenrir_cultistform_name": "Cultist Fury", + "rov_se_fenrir_curse_name": "Fenrir's Blood", + "rov_se_fenrir_curse_tooltip": "You are of the Fenrir race.", + "rov_se_fenrir_form_name": "Bestial Fury", + "rov_se_fenrir_formcd_name": "Fenrir Form Cooldown", + "rov_se_fenrir_wolfform_name": "Wolf Senses", + "rov_se_skadi_aura_name": "Skadi's Aura", + "rov_se_skadi_aura_tooltip": "Empowered by the frost.", + "rov_se_skadi_coldspellcd_name": "Cold Spell", + "rov_se_skadi_coldspellcd_tooltip": "The frost must gather again before you may cast.", + "rov_se_skadi_dragonattackcd_name": "Dragon Attack", + "rov_se_skadi_dragonattackcd_tooltip": "Your dragon shape must ready itself to strike again.", + "rov_se_skadi_form_name": "Dragon Form", + "rov_se_skadi_form_tooltip": "Your dragon shape holds for a while longer.", + "rov_se_skadi_formcd_name": "Dragon Form Cooldown", + "rov_se_skadi_stats_name": "Skadi's Blessing", + "rov_se_skeleton_resurrectcd_name": "Resurrection Cooldown", + "rov_se_skeleton_resurrectcd_tooltip": "Your skeletal body is too weak to resurrect again right now.", + "rov_se_skeleton_stats_name": "Undead Fortitude", + "rov_se_sverm_ravager_name": "Ravager Strain", + "rov_se_sverm_ravager_tooltip": "The shell doubles, and nothing that hits it lands the same again.", + "rov_se_sverm_ravagercd_name": "Ravager Strain Cooldown", + "rov_se_sverm_ravagercd_tooltip": "The strain is spent. It will take again soon.", + "rov_se_sverm_stats_name": "Chitin Plating", + "rov_se_sverm_stats_tooltip": "Armoured, venomous, and never alone.", + "rov_se_trenta_portalcd_name": "Homecoming Portal", + "rov_se_trenta_portalcd_tooltip": "The way home has not yet settled enough to open again.", + "rov_se_trenta_purpleraincd_name": "Purple Rain", + "rov_se_trenta_purpleraincd_tooltip": "The pollen must settle before you may call the rain again.", + "rov_se_trenta_stats_name": "Heartwood", + "rov_se_trenta_stats_tooltip": "Rooted, patient, and hard to fell.", + "rov_se_trol_throwcd_name": "Throw Rock Cooldown", + "rov_se_trol_throwcd_tooltip": "You must wait before throwing another rock.", + "rov_se_trol_trueform_name": "True Form", + "rov_se_trol_trueform_tooltip": "You have unleashed your inner troll!", + "rov_se_trol_trueformcd_name": "True Form Cooldown", + "rov_se_trol_trueformcd_tooltip": "You are exhausted from your True Form." +} From c5eef16dc2796adbbc0c4a786972335c94b44ec5 Mon Sep 17 00:00:00 2001 From: kanym Date: Tue, 6 Oct 2026 13:46:00 +0200 Subject: [PATCH 010/176] docs: add translator guide --- TRANSLATING.md | 55 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 TRANSLATING.md diff --git a/TRANSLATING.md b/TRANSLATING.md new file mode 100644 index 0000000..77e734d --- /dev/null +++ b/TRANSLATING.md @@ -0,0 +1,55 @@ +# Translating Races of Valheim + +Thanks for helping. This page covers the rules for translations. + +## Where to work + +- Each language has its own branch, `localisation-` (for example `localisation-russian`). Work only on that branch. +- When you're done, open a pull request into `localisation`. Never open one into `main`. +- Edit only the files under `JotunnModStub/Translations//`. Leave every other file alone. + +If your language has no branch yet, ask for one. + +## The files + +Each file is a JSON list of key/value pairs: + +```json +"rov_race_furling_desc": "Cunning goblin-like creatures. Agile and resourceful." +``` + +- **Never change a key.** Keys look like `rov_
_`. Translate only the value on the right. +- **Keep placeholders exactly as they are.** `$1`, `$2` and any other `$word` inside a value get replaced by numbers or names in game. You can move them around in the sentence, but don't rename, translate or delete them. +- Keep `\n` line breaks where they are. + +## What not to translate + +- **Race IDs.** These are the internal race names the code uses, and they never change. Race display names, such as the value of `rov_race_furling_name`, are translated. +- **Ability names that are quotes or song titles.** These stay in the original language: + - Purple Rain + - Weight of Shadows + - Like a Bat out of Hell + - Vae Victis + - Swarm of Terror + - The Furling passives: Master of Shadows, Dance of the Dead, Through Fire and Flames, The Wickerman + + If one of these names appears inside a longer sentence, translate the sentence and leave the name as it is. +- Translate every other, purely functional, ability name (for example "Combat Mastery"). + +## Keep the JSON valid + +- Save files as UTF-8 **without** a BOM. +- No trailing comma after the last entry. +- Escape double quotes inside values as `\"`. + +Check each file before you push: + +``` +python -m json.tool JotunnModStub/Translations//races.json +``` + +If it prints the file back, it's fine. If it prints an error, it shows the line to fix. + +## Partial translations are fine + +Any key missing from your files, or still in English, falls back to the English text in game. You can translate a file at a time and push as you go. From 2f744cf3b32b6348787b4606def71f5a3bf73035 Mon Sep 17 00:00:00 2001 From: kanym Date: Tue, 6 Oct 2026 13:46:46 +0200 Subject: [PATCH 011/176] scripts: add sync-localisation.sh to carry main into the translation branches --- .gitattributes | 1 + scripts/sync-localisation.sh | 88 ++++++++++++++++++++++++++++++++++++ 2 files changed, 89 insertions(+) create mode 100644 .gitattributes create mode 100644 scripts/sync-localisation.sh diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..dfdb8b7 --- /dev/null +++ b/.gitattributes @@ -0,0 +1 @@ +*.sh text eol=lf diff --git a/scripts/sync-localisation.sh b/scripts/sync-localisation.sh new file mode 100644 index 0000000..187844f --- /dev/null +++ b/scripts/sync-localisation.sh @@ -0,0 +1,88 @@ +#!/usr/bin/env bash +# Carry main forward into the translation branches after a release. +# +# origin/main -> localisation -> every localisation- +# +# Each merge is a --no-ff merge commit, pushed right away. On the first conflict +# the script stops and leaves the merge in progress, so you can resolve it by hand +# (or back out with: git merge --abort). +# +# Run from anywhere inside the repo, with a clean working tree: +# bash scripts/sync-localisation.sh + +set -euo pipefail + +cd "$(git rev-parse --show-toplevel)" + +if [ -n "$(git status --porcelain --untracked-files=no)" ]; then + echo "Working tree has uncommitted changes. Commit or stash them first." >&2 + exit 1 +fi + +start_branch="$(git rev-parse --abbrev-ref HEAD)" +summary=() + +# Check out a local branch that matches origin/, creating it if needed. +# Refuses when the local branch has commits that origin doesn't. +checkout_synced() { + local branch="$1" + if git show-ref --verify --quiet "refs/heads/$branch"; then + git checkout --quiet "$branch" + if ! git merge --quiet --ff-only "origin/$branch"; then + echo "Local $branch has diverged from origin/$branch. Sort that out first." >&2 + exit 1 + fi + else + git checkout --quiet -b "$branch" --track "origin/$branch" + fi +} + +# Merge into the current branch and push it. +merge_and_push() { + local source="$1" target="$2" + local before + before="$(git rev-parse HEAD)" + if ! git merge --no-ff --no-edit "$source"; then + echo + echo "CONFLICT merging $source into $target. Stopped here." + echo "Resolve it, commit, push $target, then run this script again." + echo "To back out instead: git merge --abort" + if [ ${#summary[@]} -gt 0 ]; then + echo + echo "Done before the conflict:" + printf ' %s\n' "${summary[@]}" + fi + exit 1 + fi + if [ "$(git rev-parse HEAD)" = "$before" ]; then + summary+=("$source -> $target: already up to date") + else + git push --quiet origin "$target" + summary+=("$source -> $target: merged and pushed ($(git rev-parse --short HEAD))") + fi +} + +echo "Fetching origin..." +git fetch --prune origin + +checkout_synced localisation +merge_and_push origin/main localisation + +language_branches=() +while IFS= read -r ref; do + language_branches+=("${ref#origin/}") +done < <(git for-each-ref --format='%(refname:short)' 'refs/remotes/origin/localisation-*') + +for branch in "${language_branches[@]}"; do + checkout_synced "$branch" + merge_and_push localisation "$branch" +done + +git checkout --quiet "$start_branch" + +echo +echo "Summary:" +printf ' %s\n' "${summary[@]}" +if [ ${#language_branches[@]} -eq 0 ]; then + echo " (no localisation-* branches on origin)" +fi From 60e9b0ab7210ae795b94dd2aea4c34e5a58df7c5 Mon Sep 17 00:00:00 2001 From: kanym Date: Tue, 6 Oct 2026 13:59:52 +0200 Subject: [PATCH 012/176] localisation(ru): add Russian translation MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Merged from two community translations (Rudra and Axibed). Axibed's set is the base; Rudra's lines replace it where they read better or are more faithful, mostly the merchant jokes. Boss, creature and resource names follow vanilla Valheim's own Russian (Матерь, Прародитель, Драугр, Эйтр, Быкоящер, Пеплозавр, Масса костей). Ability names that are quotes or song titles stay in English, as in Italian. The bone-ship and thrall-order keys that neither translation had are translated here. --- .../Translations/Russian/compendium.json | 206 ++++++++++++++++++ JotunnModStub/Translations/Russian/hover.json | 56 +++++ JotunnModStub/Translations/Russian/items.json | 138 ++++++++++++ .../Translations/Russian/merchants.json | 133 +++++++++++ .../Translations/Russian/messages.json | 205 +++++++++++++++++ JotunnModStub/Translations/Russian/races.json | 27 +++ .../Translations/Russian/status_effects.json | 62 ++++++ 7 files changed, 827 insertions(+) create mode 100644 JotunnModStub/Translations/Russian/compendium.json create mode 100644 JotunnModStub/Translations/Russian/hover.json create mode 100644 JotunnModStub/Translations/Russian/items.json create mode 100644 JotunnModStub/Translations/Russian/merchants.json create mode 100644 JotunnModStub/Translations/Russian/messages.json create mode 100644 JotunnModStub/Translations/Russian/races.json create mode 100644 JotunnModStub/Translations/Russian/status_effects.json diff --git a/JotunnModStub/Translations/Russian/compendium.json b/JotunnModStub/Translations/Russian/compendium.json new file mode 100644 index 0000000..ac6eb7b --- /dev/null +++ b/JotunnModStub/Translations/Russian/compendium.json @@ -0,0 +1,206 @@ +{ + "rov_compendium_aswid_always_active_every_form_with": "Активна всегда и в любом облике, не требует зажатия клавиши — только переключение вкл/выкл. Высасывает жизнь в радиусе $1 м днем и $2 м ночью, нанося магический урон, зависящий от навыка «Магия крови», и исцеляя вас на величину нанесенного урона. Враги с запасом здоровья $3% и ниже погибают мгновенно. В человеческом облике аура наносит половинный урон, в облике летучей мыши — полный, а в облике тумана — удвоенный. Аура не отличает торговцев от монстров, поэтому отключайте ее клавишей [I] перед разговором с Хальдором или Хильдир.\n", + "rov_compendium_aswid_asmund_passive": "[Награда: Прародитель] Асмунд (Пассивное):", + "rov_compendium_aswid_aswid_s_curse": "Проклятие Асвида\n", + "rov_compendium_aswid_bat_form_g_key_night": "[Награда: Эйктюр] Облик мыши (клавиша «G», только ночью): Примите облик летучей мыши.\n", + "rov_compendium_aswid_bat_form_now_answers_by": "[Награда: Древний] Облик мыши теперь доступен как ночью, так и днем.\n", + "rov_compendium_aswid_benedictus_et_afflictus": "[Базовое пассивное] Benedictus et Afflictus:", + "rov_compendium_aswid_claws_beast_s_grows_blackened": "[Базовое пассивное] Когти зверя ([K], $1 с): На ограниченное время отращивает черные когти вместо оружия. Удары кулаками наносят $2% от урона зрелых когтей (полностью режущий урон), и их сила растет с каждым поверженным боссом. Если достать меч — когти спрячутся, убрать его — вернутся, пока не истечет таймер. Не занимают ячейку экипировки. Их нельзя выбросить, передать или украсть, пока они активны. В облике мыши или тумана когти недоступны, так как у вас нет рук.\n", + "rov_compendium_aswid_dominate_native_interact_key": "[Награда: Яглут] Порабощение (клавиша взаимодействия):", + "rov_compendium_aswid_eclipse_j_key_day_only": "[Награда: Яглут] Затмение (клавиша «J», только днем):", + "rov_compendium_aswid_freezing_blood_passive": "[Награда: Матерь] Ледяная кровь (Пассивное):", + "rov_compendium_aswid_gain_permanent_immunity_freezing_status": "Вы получаете постоянный иммунитет к эффекту переохлаждения/замерзания (горы/снежные бури) и к урону от яда.\n", + "rov_compendium_aswid_hair_beard_turn_as_dark": "Ваши волосы и борода становятся черными, как бездна. Вы становитесь выше на 10% и получаете фиксированную прибавку +$1 к физическому урону.\n", + "rov_compendium_aswid_second_cast_that_forces_night": "Сотворение в течение $1 с опускает ночную тьму вокруг вас на $2 с, позволяя получать ночные бонусы прямо под солнцем. Если уже наступила ночь, способность просто уйдет на перезарядку. Перезарядка: $3 мин.\n", + "rov_compendium_aswid_sense_every_untamed_creature_within": "Вы чувствуете любое неприрученное существо в радиусе $1 м, подсвечивая его характерным свечением.\n", + "rov_compendium_aswid_superhuman_senses_passive": "[Награда: Матерь] Сверхчеловеческие чувства (Пассивное):", + "rov_compendium_aswid_take_no_fall_damage_physical": "Вы не получаете урона от падения, а убийства в ближнем бою автоматически пожирают съедобных врагов (Vae Victis), принося опыт магии крови. Ваши физические характеристики растут с каждым убитым боссом: +$1 к броне, +$2 к урону, +$3% к скорости и прыжку, и +$4% вампиризма при физ. атаках. Все эти бонусы удваиваются ночью. Вы можете использовать предметы магии крови с бесконечным эйтром, а навык «Магия крови» качается в $5 раз быстрее.\n", + "rov_compendium_aswid_tame_u_key_asksvin_join": "[Награда: Прародитель] Приручение (клавиша «U»): Пеплозавры добавляются в список доступных для приручения.\n", + "rov_compendium_aswid_tame_u_key_lox_join": "[Награда: Яглут] Приручение (клавиша «U»): Быкоящеры добавляются в список доступных для приручения.\n", + "rov_compendium_aswid_tame_u_key_tame_boar": "[Награда: Эйктюр] Приручение (клавиша «U»): Мгновенно приручает кабана под прицелом.\n", + "rov_compendium_aswid_tame_u_key_wolves_join": "[Награда: Матерь] Приручение (клавиша «U»): Волки добавляются в список доступных для приручения.\n", + "rov_compendium_aswid_target_non_tameable_non_boss": "Выберите неприручаемого врага (кроме боссов), чтобы подчинить его волю на $1 с (перезарядка: $2 мин). Порабощенные существа сражаются на вашей стороне и оставляют стандартную добычу.\n", + "rov_compendium_aswid_title": "Тайны Асвида", + "rov_compendium_aswid_transform_into_elusive_mist_become": "Вы превращаетесь в бесплотный туман. Вы получаете иммунитет к физическому (дробящий/рубящий/колющий) урону и яду, а также не получаете урона от падения, но не можете атаковать, бегать или прыгать. Вампирическая аура наносит удвоенный урон в этой форме. Восход солнца развеивает превращение.\n", + "rov_compendium_aswid_vampiric_aura_passive_toggle": "Вампирическая аура (Пассивное, переключение на [I]):", + "rov_compendium_aswid_weight_shadows_h_key_toggle": "[Награда: Королева] Weight of Shadows (клавиша «H», переключение):", + "rov_compendium_draugh_born_dead_buried_alive_take": "[Базовое пассивное] Born Dead, Buried Alive: Вы получаете на $1% меньше физического (дробящий/рубящий/колющий) урона, но урон от огня и духа бьет по вам на $2% больнее. Скелеты, драугры, призраки и духи больше не считают вас добычей. Ваше пищеварение адаптировалось к смерти, позволяя есть сырое и гнилое мясо (хвосты шеек, сырое мясо, потроха, кровь и т. д.) — обычная приготовленная еда и ягоды вызывают отвращение и не могут быть съедены.\n", + "rov_compendium_draugh_draugh_s_awakening": "Пробуждение Драуга\n", + "rov_compendium_draugh_grave_chill_passive_parry_frost": "[Награда: Матерь] Могильный холод (Пассивное/Парирование): Мороз больше не может навредить вам. Успешное парирование также высвобождает волну холода, наносящую $1 урона от мороза и отталкивающую всё в радиусе $2 м от вас. У волны отдельная перезарядка в $3 с, независимая от всплеска яда «Гниющего клинка», который срабатывает при каждом парировании.\n", + "rov_compendium_draugh_rotting_edge_passive_parry_physical": "[Награда: Древний] Гниющий клинок (Пассивное/Парирование): Ваши физические атаки пропитаны болотным тленом, добавляя урон ядом в размере $1% от нанесенного физ. урона. Успешное парирование также окатывает парированного врага $2 ед. урона ядом.\n", + "rov_compendium_draugh_slowly_we_rot_passive_being": "[Награда: Эйктюр] Slowly We Rot (Пассивное): Статус «Сырость» больше не снижает восстановление выносливости, а вместо этого исцеляет вас — здоровье восстанавливается на $1% быстрее, пока вы мокрые или плывете.\n", + "rov_compendium_draugh_steal_their_breath_execution_while": "[Награда: Прародитель] Steal Their Breath (Казнь): Находясь в призрачном состоянии выживания «Обряда зомби», нанесение смертельного удара любому врагу мгновенно восстановит $1% вашего максимального здоровья, остановит утечку эйтра и вернет вас к полноценной жизни.\n", + "rov_compendium_draugh_swarm_terror_retaliation_whenever_are": "[Награда: Королева] Swarm of Terror (Возмездие): Каждый раз при получении удара в ближнем бою вы автоматически призываете $1 выводков искателя для защиты. Они живут $2 с. Перезарядка между призывами: $3 с.\n", + "rov_compendium_draugh_title": "Тайны Драуга", + "rov_compendium_draugh_undead_fortitude_passive_poison_can": "[Награда: Масса костей] Стойкость нежити (Пассивное): Яд больше совершенно не действует на вас. Удары по ошеломленным врагам наносят на $1% больше физ. урона, а смерть больше не отнимает опыт навыков. Если любой игрок погибнет в пределах $2 м от вас, на месте его гибели останется Человечина — пища, которую может переварить только Драуг.\n", + "rov_compendium_draugh_zombie_ritual_passive_survival_when": "[Награда: Яглут] Обряд зомби (Пассивное выживание): При получении смертельного урона вы не погибаете. Вместо этого вы переходите в призрачное состояние с неуязвимостью ко всему урону, пока ваш эйтр сгорает со скоростью $1 ед./с. Если эйтр иссякнет до вашего спасения, наступит истинная смерть. Ритуал срабатывает не чаще одного раза в $2 мин.\n", + "rov_compendium_dvergar_dvergar_s_craft": "Ремесло Дверга\n", + "rov_compendium_dvergar_kin_traders_passive_haldor_hildir": "[Награда: Масса костей] Родня торговцев (Пассивное): Хальдор и Хильдир узнают сородича. Их цены для вас снижены на $1%, а выплата за ваши трофеи и охотничьи награды увеличена на $2%.\n", + "rov_compendium_dvergar_mining_affinity_passive_pickaxe_answers": "[Награда: Эйктюр] Сродство с киркой (Пассивное): Кирка подчиняется вам беспрекословно. Рудные жилы поддаются быстрее, требуют меньше выносливости и порой дают больше руды, чем должны.\n", + "rov_compendium_dvergar_runic_overcharge_key_spend_eitr": "[Награда: Прародитель] Руническая перегрузка (клавиша «$1»): Потратьте $2 эйтра, чтобы зарядить руны. Ваш следующий удар излюбленным оружием нанесет урон с силой в $3x. Удерживайте заряд не дольше $4 с, иначе руны рассеются впустую.\n", + "rov_compendium_dvergar_runic_ping_key_spend_eitr": "[Награда: Яглут] Рунический эхолокатор (клавиша «$1»): Потратьте $2 эйтра, чтобы послать импульс сквозь толщу камня. На $3 с каждая рудная жила и каждый скрытый враг в радиусе $4 метров подсветятся только для вас.\n", + "rov_compendium_dvergar_runic_spark_runes_blood_earth": "[Базовое пассивное] Руническая искра: Руны в вашей крови заземляются через каждую цель, по которой вы бьете. Каждый нанесенный удар несет +$1 урона молнией — этот бонус растет по мере гибели боссов.\n", + "rov_compendium_dvergar_small_stubborn_stand_shorter_than": "[Базовое пассивное] Мал да удал: Вы на $1% ниже человека и обладаете базовым запасом здоровья на $2 ед. меньше. Капюшон дверга сросся с вами навечно — надевайте любой шлем и сохраняйте все его показатели защиты, но руны всегда будут выдавать в вас дитя глубин.\n", + "rov_compendium_dvergar_smithing_jewelry_passive_waste_nothing": "[Награда: Масса костей] Кузнечное и ювелирное дело (Пассивное): В вашей наковальне ни крупицы не пропадет даром. Металлы и самоцветы тратятся на $1% экономнее при создании и улучшении предметов.\n", + "rov_compendium_dvergar_title": "Тайны Дверга", + "rov_compendium_dvergar_weapon_affinity_passive_blows_struck": "Владение оружием (Пассивное): $1. Удары этим оружием бьют сильнее и расходуют меньше выносливости. Экономия выносливости не увеличивается — открытие уровней лишь расширяет список доступного вам родного оружия, а сам навык растет с обычной скоростью.\n", + "rov_compendium_dvergar_weapon_axe": "Топор", + "rov_compendium_dvergar_weapon_bow": "Лук", + "rov_compendium_dvergar_weapon_crossbow": "Арбалет", + "rov_compendium_dvergar_weapon_hammer": "Молот", + "rov_compendium_fenrir_beast_within_physical_stats_scale": "[Базовое пассивное] Зверь внутри: Ваши физические характеристики растут с каждым убитым боссом: +$1 к броне, +$2 к урону, +$3% к скорости, +$4% к прыжку и -$5% к урону от падения.\n", + "rov_compendium_fenrir_cultist_form_j_key_night": "[Награда: Яглут] Облик культиста (клавиша «J», только ночью): Облик в балахоне, раздирающий врагов когтями и направляющий потоки пламени. Длится 1 минуту, перезарядка: 10 минут.\n", + "rov_compendium_fenrir_cultist_form_now_answers_by": "[Награда: Прародитель] Облик культиста теперь подчиняется как днем, так и ночью, и его можно удерживать сколько угодно.\n", + "rov_compendium_fenrir_cultist_form_s_cooldown_falls": "[Награда: Королева] Перезарядка облика культиста снижена до 5 минут (все еще только ночью, длительность 1 минута).\n", + "rov_compendium_fenrir_curse_pack": "Проклятие Стаи\n", + "rov_compendium_fenrir_cursed_claws_s_wolf_s": "[Базовое пассивное] Проклятые когти ([K], $1 с): Волчьи лапы, сохраняющиеся в человеческом теле на ограниченное время вместо оружия. Удары голыми руками наносят $2% от урона зрелых когтей (полностью режущий урон), и их сила растет с каждым павшим боссом. Достаньте меч — они исчезнут, вложите в ножны — вернутся, пока не истечет время. Не тратят место в инвентаре. Их нельзя выбросить, передать или украсть, пока они активны — а в зверином облике вместо них работают челюсти.\n", + "rov_compendium_fenrir_fenring_form_h_key_night": "[Награда: Матерь] Облик фенринга (клавиша «H», только ночью): Станьте истинным Фенрингом — тяжелые когти, сокрушительный удар в прыжке и мощнейшая из четырех форм на данный момент.\n", + "rov_compendium_fenrir_fenring_form_now_answers_by": "[Награда: Королева] Облик фенринга теперь доступен как днем, так и ночью.\n", + "rov_compendium_fenrir_g_now_calls_ulv_form": "[Награда: Матерь] Клавиша «G» теперь призывает облик Ульва вместо Волка и доступна и днем, и ночью.\n", + "rov_compendium_fenrir_sunrise_breaks_any_night_bound": "Восход солнца прерывает любую ночную форму раньше срока и оставляет зверя истощенным, не позволяя перевоплощаться еще некоторое время.\n", + "rov_compendium_fenrir_title": "Тайны Фенрира", + "rov_compendium_fenrir_ulv_form_h_key_night": "[Награда: Масса костей] Облик ульва (клавиша «H», только ночью): Более тяжелая волчья форма — смертоносные укусы, по-прежнему скованные тьмой.\n", + "rov_compendium_fenrir_wolf_form_g_key_night": "[Награда: Древний] Облик волка (клавиша «G», только ночью): Примите форму волка. Более быстрый и ловкий на лапах, обладающий тремя атаками когтями возрастающей мощи на ЛКМ, ПКМ и СКМ.\n", + "rov_compendium_fenrir_wolf_form_now_answers_by": "[Награда: Масса костей] Облик волка теперь доступен как днем, так и ночью.\n", + "rov_compendium_furling_all_weapon_combat_skills_gain": "Все боевые навыки и владение оружием навсегда получают в $1x больше опыта. Вы малорослы, но невероятно быстры — ваша базовая скорость передвижения увеличена на $2%.\n", + "rov_compendium_furling_are_permanently_wreathed_flames_are": "Вы постоянно объяты пламенем и абсолютно невосприимчивы к урону от огня. Все ваши физические атаки (любым оружием или без него) поджигают цель.\n", + "rov_compendium_furling_blue_foods_those_that_restore": "Синяя пища (восстанавливающая эйтр) действует на вас вдвое дольше, чем на обычных игроков.\n", + "rov_compendium_furling_combat_mastery": "[Базовое пассивное] Боевое мастерство:", + "rov_compendium_furling_dance_dead_passive": "[Награда: Масса костей] Dance of the Dead (Пассивное):", + "rov_compendium_furling_every_mead_potion_wine_bomb": "Каждая порция медовухи, зелья, вина, бомб или патронов варится в двойном объеме: одна порция по рецепту, вторая — бесплатно.\n", + "rov_compendium_furling_footsteps_small_movements_no_longer": "Ваши шаги и шорохи больше не выдают вас — любые звуки, издаваемые вами в пределах $1 м, остаются неуслышанными.\n", + "rov_compendium_furling_master_shadows_passive": "[Награда: Эйктюр] Master of Shadows (Пассивное):", + "rov_compendium_furling_passive": "[Награда: Матерь] $1 (Пассивное):", + "rov_compendium_furling_passive_2": "[Награда: Яглут] $1 (Пассивное):", + "rov_compendium_furling_passive_3": "[Награда: Королева] $1 (Пассивное):", + "rov_compendium_furling_secrets_hoard": "Тайны Сокровищницы\n", + "rov_compendium_furling_take_less_fire_damage_less": "Вы получаете на $1% меньше урона от огня и на $2% меньше урона от яда. Ваши стрелы наносят как минимум $3 ед. огненного урона сами по себе.\n", + "rov_compendium_furling_through_fire_flames_passive": "[Награда: Прародитель] Through Fire and Flames (Пассивное):", + "rov_compendium_furling_title": "Тайны Фурлинга", + "rov_compendium_furling_whenever_normal_enemy_dies_within": "Когда обычный враг погибает в радиусе 25 метров, шанс выпадения трофеев удваивается, и с него гарантированно выпадают золотые монеты в зависимости от количества звезд. Кроме того, при добыче сырой руды вы получаете вдвое больше ресурсов.\n", + "rov_compendium_furling_while_are_plains_biome_x": "Пока вы находитесь на Равнинах, множитель 2x к опыту распространяется на все небоевые навыки (включая магию стихий и магию крови).\n", + "rov_compendium_furling_wickerman_passive": "[Награда: Древний] The Wickerman (Пассивное):", + "rov_compendium_skadi_become_great_frost_dragon_herself": "Станьте самой великой ледяной драконицей на 1 минуту с перезарядкой в 10 минут. На земле: ЛКМ наносит удары пастью и когтями безо всяких затрат, а СКМ извергает поток льда. В воздухе: ЛКМ обрушивает град ледяных осколков. Только дыхание и град осколков расходуют эйтр.\n", + "rov_compendium_skadi_bones_dragon_rise_at_call": "Кости дракона поднимаются по вашему зову, объятые инеем. Он рвет зубами и когтями, сметает всё вокруг круговым ударом хвоста (ПКМ), а его ледяное дыхание несет троекратную ярость самой Матери.\n", + "rov_compendium_skadi_bound_stonecutter_that_shaped_may": "Он привязан к камнерезу, из которого был высечен, и никогда не покинет радиус в $1 м вокруг него — ту же область, где работает сам станок. Ему нельзя дать имя, им нельзя командовать, и он не пойдет за вами. Он стережет камень, что породил его, и в этом всё его естество.\n", + "rov_compendium_skadi_cold_cannot_touch_frost_answers": "Холод не властен над вами, а мороз повинуется каждому движению руки. Вы невосприимчивы к статусу «Холод», получаете лишь половину урона от мороза, и каждый ваш удар несет +$1 урона льдом — этот бонус растет с каждым павшим боссом.\n", + "rov_compendium_skadi_cold_spell_middle_mouse": "[Награда: Эйктюр] Ледяное заклятие (Средняя кнопка мыши):", + "rov_compendium_skadi_cold_spell_scatters_into_ten": "Ваше Ледяное заклятие распадается на десять осколков, поражая холодом всё перед вами. Для столь широкого залпа требуется 4 секунды на концентрацию.\n", + "rov_compendium_skadi_crystal_golem": "\n-- КРИСТАЛЬНЫЙ ГОЛЕМ --\n", + "rov_compendium_skadi_cut_one_at_stonecutter_stone": "Высеките его на камнерезе за трофей каменного голема, $1 кристаллов и слезу дракона. Камень не подчинится никому, кроме Скади, так что созданный страж всецело принадлежит вам.\n", + "rov_compendium_skadi_drake_breath_left_mouse": "[Награда: Масса костей] Дыхание дрейка (Левая кнопка мыши):", + "rov_compendium_skadi_drake_form_g_key": "[Награда: Древний] Облик дрейка (клавиша «G»):", + "rov_compendium_skadi_drake_form_may_now_spit": "Ваш облик дрейка теперь может плеваться льдом во врагов.\n", + "rov_compendium_skadi_freezing_can_no_longer_reach": "Лютый мороз больше не может тронуть вас, а эйтр восстанавливается в полтора раза быстрее.\n", + "rov_compendium_skadi_frost_cannot_wound_at_all": "Мороз больше не наносит вам никакого урона, а от вашей кожи исходит ледяная аура, терзающая всех неприрученных существ в радиусе 3 метров.\n", + "rov_compendium_skadi_heart_winter_passive": "[Награда: Яглут] Сердце зимы (Пассивное):", + "rov_compendium_skadi_hurl_shard_ice_at_whatever": "Метните ледяной осколок в точку прицела, нанося $1 урона морозом. Заклинание требует 20 выносливости вместо эйтра, благодаря чему верно служит вам с вашей первой зимы.\n", + "rov_compendium_skadi_ice_affinity": "[Базовое пассивное] Сродство со льдом:", + "rov_compendium_skadi_improved_cold_spell": "[Награда: Яглут] Улучшенное ледяное заклятие:", + "rov_compendium_skadi_killing_gales_mountains_soften_mere": "Смертоносные горные бури оборачиваются лишь легкой прохладой: вы испытываете лишь легкий холод там, где другие замерзают насмерть.\n", + "rov_compendium_skadi_moder_form_h_key": "[Награда: Матерь] Облик Матери (клавиша «H»):", + "rov_compendium_skadi_moder_form_may_now_held": "Облик Матери теперь можно поддерживать сколь угодно долго без задержек между призывами.\n", + "rov_compendium_skadi_moder_form_now_answers_again": "Облик Матери вновь готов к зову уже через 5 минут перезарядки.\n", + "rov_compendium_skadi_one_stonecutter_holds_them_no": "Один камнерез поддерживает $1 таких стражей, и не более $2 могут находиться на расстоянии дневного перехода друг от друга. Сломайте камнерез — и сотворенный голем замрет навеки спустя $3 с.\n", + "rov_compendium_skadi_secrets_winter": "Тайны Зимы\n", + "rov_compendium_skadi_skeleton_dragon_form_j_key": "[Награда: Прародитель] Облик дракона-скелета (клавиша «J»):", + "rov_compendium_skadi_take_shape_frost_drake_right": "Примите облик ледяного дрейка. ПКМ поднимает вас в воздух: вы парите туда, куда смотрите; зажмите W, чтобы набирать высоту и скорость; зажмите с ней Shift, чтобы ускориться за счет выносливости; нажмите S, чтобы пятиться спиной назад, удерживая прицел. Отпустите клавиши управления — и вы замрете в воздухе на 5 секунд перед медленным снижением. Вода не удержит вас: крылья выдернут вас из морской пучины так же легко, как и с берега. В этой форме вы пока не можете атаковать.\n", + "rov_compendium_skadi_tear_cold_nothing_wakes_stone": "Слеза холодна. Ничто в камне не пробудится, пока владычица гор не падет.\n", + "rov_compendium_skadi_title": "Тайны Скади", + "rov_compendium_skadi_winter_incarnate_passive": "[Награда: Королева] Воплощение зимы (Пассивное):", + "rov_compendium_skadi_winter_s_welcome_passive": "[Награда: Масса костей] Объятия зимы (Пассивное):", + "rov_compendium_skeleton_blades_points_find_little_cut": "Клинкам и наконечникам почти нечего резать в ваших сухих костях — они наносят лишь половину урона, однако тяжелый молот крушит скелет целиком и бьет куда больнее обычного.\n", + "rov_compendium_skeleton_bones_alight": "[Награда: Матерь] Пылающие кости:", + "rov_compendium_skeleton_bones_blades": "[Базовое пассивное] Кости и клинки:", + "rov_compendium_skeleton_crypt_answers": "[Награда: Королева] Зов склепа:", + "rov_compendium_skeleton_dead_now_follow_harm_deal": "$1 мертвецов теперь следуют за вами, и $2% наносимого вами урона возвращается к вам в виде вашей собственной силы.\n", + "rov_compendium_skeleton_every_enemy_put_down_rises": "Каждый сраженный враг восстает из праха и бьется за вас (вплоть до $1 спутников одновременно).\n", + "rov_compendium_skeleton_first_blow": "[Награда: Древний] Первый удар:", + "rov_compendium_skeleton_first_strike_out_dark_staggers": "Первый внезапный удар из темноты ошеломляет жертву. Мертвые способны делать это раз в 5 секунд.\n", + "rov_compendium_skeleton_frame_remade_harder_cast_fire": "Ваш скелет перекован в более прочный каркас, и к нему цепляется огонь: все, кто окажется достаточно близко, чтобы почувствовать его, будут обожжены. Ваши раны также закрываются быстрее, чем кости имеют на это право.\n", + "rov_compendium_skeleton_green_rot": "[Награда: Эйктюр] Изумрудный тлен:", + "rov_compendium_skeleton_host_own": "[Награда: Прародитель] Собственная армия:", + "rov_compendium_skeleton_killing_blow_no_longer_ends": "Смертельный удар больше не приканчивает вас. Вы исцеляетесь там, где стоите - а затем темной магии потребуется 5 минут, чтобы она смогла сделать это снова.\n", + "rov_compendium_skeleton_no_hunger_moves_no_meal": "Вами не движет голод, и смертная пища не дает сил — праху нет дела до бренной еды. Вместо этого нежить крепнет по мере гибели великих противников: сейчас вы обладаете +$1 к максимальному здоровью. Труд не утомляет вас, ведь у вас вовсе нет выносливости.\n", + "rov_compendium_skeleton_poison_has_nothing_left_poison": "Яду больше нечего отравлять внутри вас — он не способен причинить вам вред, а кости наливаются болезненной зеленью. Каждый ваш удар возвращает $1% нанесенного физического урона вашему собственному телу.\n", + "rov_compendium_skeleton_risen_again": "[Награда: Яглут] Восставший вновь:", + "rov_compendium_skeleton_rotten_touch": "[Награда: Масса костей] Гнилостное касание:", + "rov_compendium_skeleton_secrets_crypt": "Тайны Склепа\n", + "rov_compendium_skeleton_stand_at_eight_standings_earned": "Вы достигли ступени $1 из восьми, дарованной гибелью босса: $2.\n", + "rov_compendium_skeleton_stand_at_first_eight_standings": "Вы стоите на первой из восьми ступеней: ни один босс пока не пал от вашей руки.\n", + "rov_compendium_skeleton_title": "Тайны Скелета", + "rov_compendium_skeleton_undead_diet": "[Базовое пассивное] Диета нежити:", + "rov_compendium_skeleton_what_strike_sicken_every_blow": "Каждое ваше прикосновение несет заразу — любой удар наносит дополнительные 20 ед. урона ядом.\n", + "rov_compendium_sverm_acid_hemolymph_whoever_strikes_melee": "[Награда: Масса костей] Кислотная гемолимфа: Любой, кто ударит вас в ближнем бою, получит $1 ед. урона ядом в ответ.\n", + "rov_compendium_sverm_annealed_chitin_emberform_eight_tiers": "[Награда: Прародитель] Закаленный хитин и Пепельный облик: Восемь кругов адского пламени превратили былую уязвимость в крепчайшую броню: огонь больше не вредит вам, а хитин чернеет, наливаясь изнутри багровым жаром.\n", + "rov_compendium_sverm_beehives_raise_vanilla_hives_inside": "Ульи: постройте обычные пчелиные ульи в пределах $1 м от гнезда, и колония подчинит их через минуту (до $2 шт. на гнездо). Они работают вдвое быстрее, производят втрое больше меда, а после падения Яглута дают маточное молочко. Нажмите медом или маточным молочком по своим насекомым, чтобы вылечить их: на $3 и $4 ед.\n", + "rov_compendium_sverm_blister_tick_buys_slot_forever": "Чумной клещ $1: навсегда открывает ячейку. Он мчится на врагов и взрывается, а гнездо бесплатно выращивает нового через $2 с.\n", + "rov_compendium_sverm_brood_eggs_nest_lays_one": "Яйца расплода: гнездо откладывает по одному каждые $1 с и вмещает $2 шт. на первом этапе развития (плюс одно яйцо на каждом следующем этапе). Каждая особь требует яйцо и биомассу. Яйца восстанавливаются со временем, биомасса — нет.\n", + "rov_compendium_sverm_brood_mound_hammer_nest_no": "Курган расплода (Молот): Ваше гнездо; не более $1 шт. в пределах $2 метров друг от друга. Нажмите на него или на улей у подножия, чтобы скормить целую стопку из инвентаря: любую еду, древесину, смолу. Мед и маточное молочко считаются лекарством, и курган их не примет.\n", + "rov_compendium_sverm_carapace_regeneration_knit_yourself_back": "[Награда: Прародитель] Регенерация панциря: Вы восстанавливаете свое тело со скоростью $1 ед. здоровья в секунду, всегда.\n", + "rov_compendium_sverm_chitin_claws_hands_are_weapon": "[Базовое пассивное] Хитиновые когти: Ваши руки — смертоносное оружие. Удары голыми руками наносят $1% от полной силы когтей, и их невозможно отнять: обнажите клинок — они спрячутся, уберите в ножны — снова предстанут перед вами.\n", + "rov_compendium_sverm_chitin_plating_do_not_dress": "[Базовое пассивное] Хитиновый панцирь: Вы не носите одежду. Нагрудник, поножи и шлем заменены природным карапаксом и не снимаются. На каждом этапе они равны лучшему комплекту брони следующего биома наивысшего качества: невесомы и не замедляют передвижение. Вы можете надевать только плащи и аксессуары.\n", + "rov_compendium_sverm_colony": "\n-- КОЛОНИЯ --\n", + "rov_compendium_sverm_colony_will_not_wake_until": "Колония не пробудится, пока Древний не падет. До тех пор вы — лишь единичная особь, но этого более чем достаточно.\n", + "rov_compendium_sverm_digestion_what_feed_not_yours": "Пищеварение: скормленное нельзя потратить мгновенно. Ресурсы перерабатываются в запас биомассы гнезда со скоростью $1 ед./с, и расходовать можно лишь переработанное.\n", + "rov_compendium_sverm_from_at_most": "$1 $2 (из $3, максимум $4). ", + "rov_compendium_sverm_grinding_mandibles_seeds_are_food": "[Награда: Древний] Жерновные жвалы: Семена становятся пищей. Чистые питательные вещества — благословения культурных садов оставьте другим.\n", + "rov_compendium_sverm_growth_each_one_costs_that": "Рост: $1 $2, $3 $4, $5 $6. Каждое улучшение требует полного запаса биомассы текущей стадии и открывает следующий ранг существ.\n", + "rov_compendium_sverm_hive_market_hammer_counter_raised": "Рынок улья (Молот): торговый прилавок, возводимый в пределах $1 м от гнезда. Все улучшения и войска колонии приобретаются здесь за счет биомассы этого гнезда.\n", + "rov_compendium_sverm_hive_pheromones_no_invertebrate_will": "[Базовое пассивное] Феромоны улья: Ни одно беспозвоночное не нападет на вас: ни пиявки, ни клещи, ни комары смерти, ни искатели, ни пчелы. Массе костей чужды насекомые, и феромоны на нее не действуют.\n", + "rov_compendium_sverm_insect_metabolism_eat_everything_anyone": "[Базовое пассивное] Метаболизм насекомого: Вы можете есть всё, что едят остальные, а мед дает вам вдвое больше пользы. Алхимическая кровь — единственное, к чему вы не притронетесь.\n", + "rov_compendium_sverm_metabolic_surge_running_jumping_cost": "[Награда: Эйктюр] Метаболический всплеск: Бег и прыжки расходуют меньше сил, а прыгаете вы гораздо выше.\n", + "rov_compendium_sverm_ravager_strain_key_become_seeker": "[Награда: Яглут] Штамм опустошителя (клавиша «$1»): Обернитесь в свирепого искателя-солдата. Когти разят беспощадно, прочность панциря удваивается, но полет исключен. Эта форма рождена для битвы, а не для бегства.\n", + "rov_compendium_sverm_seeker_workers_free_always_free": "Рабочие искатели: абсолютно бесплатны — не требуют биомассы и яиц; павший сменяется новым: $1. Пока они живы, гнездо кормится само из сундуков у подножия. Они ведут хозяйство подобно Костяному кузнецу: положите $2 в сундук в радиусе $3 м от края гнезда, и они понесут руду и топливо в плавильни, печи и мельницы вокруг, а готовый продукт отнесут обратно. По размеру, здоровью и силе укуса они уступают взрослым искателям вдвое, не принимают приказов и не следуют за вами — лишь защищают периметр, чинят постройки и неустанно работают.\n", + "rov_compendium_sverm_sensory_antennae_feel_what_lives": "[Награда: Древний] Чуткие усики: Вы ощущаете биение чужой жизни вокруг себя сквозь толщу камня и земли.\n", + "rov_compendium_sverm_surrenal_glands_hyperplasia_everything_hatched": "Надпочечные железы (800) и Гиперплазия (1600): все рожденные после улучшения существа получают одну, а затем две звезды.\n", + "rov_compendium_sverm_surrenal_glands_stand_tenth_larger": "[Награда: Королева] Надпочечные железы: Вы вырастаете на десятую часть, а прочность панциря совершает колоссальный скачок.\n", + "rov_compendium_sverm_sverm_s_colony": "Колония Сверма\n", + "rov_compendium_sverm_title": "Тайны Сверма", + "rov_compendium_sverm_toxin_immunity_fire": "[Базовое пассивное] Иммунитет к токсинам: Яд не властен над вами. Опасность представляют лишь дубины и факелы: вы получаете на $1% больше урона от дробящих ударов и на $2% больше от огня.\n", + "rov_compendium_sverm_toxin_immunity_nofire": "[Базовое пассивное] Иммунитет к токсинам: Яд не может навредить вам. Опасность представляют лишь дробящие удары (+ $1% урона), однако огонь перестал быть вашей уязвимостью.\n", + "rov_compendium_sverm_troops_they_follow_when_ask": "Войска: $1Они следуют за вами по приказу, возвращаются домой, если отпустить, и восстанавливают здоровье сами.\n", + "rov_compendium_sverm_venom_glands_every_blow_land": "[Награда: Масса костей] Ядовитые железы: Каждый ваш удар несет дополнительно +$1 ед. яда.\n", + "rov_compendium_sverm_ventral_pouches_carry_more": "[Награда: Эйктюр] Брюшные сумки: Вы можете нести на $1 ед. больше груза.\n", + "rov_compendium_sverm_vestigial_wings_small_wings_no": "[Награда: Матерь] Рудиментарные крылья: Небольшие крылья уберегут от любого жесткого падения.\n", + "rov_compendium_sverm_workers_none": "ни один рабочий не покинет гнездо, пока Масса костей не повержена", + "rov_compendium_sverm_workers_up_to": "до $1 рабочих покинут гнездо", + "rov_compendium_trenta_awakened_seeds_passive": "[Награда: Эйктюр] Пробужденные семена (Пассивное):", + "rov_compendium_trenta_closer_come_falling_harder_bark": "Чем ближе вы к гибели, тем прочнее становится кора: показатель брони возрастает вплоть до $1% по мере приближения здоровья к нулю.\n", + "rov_compendium_trenta_deep_roots_passive": "[Награда: Масса костей] Глубокие корни (Пассивное):", + "rov_compendium_trenta_every_hit_take_returns_its": "Каждый полученный вами удар возвращает $1% нанесенного урона нападающему.\n", + "rov_compendium_trenta_every_seed_cone_acorn_self": "Любое семя, шишка, желудь и споры грибов в вашей сумке пробуждаются. Съешьте их прямо на месте: семя переварится и послужит мощнейшей трапезой своего биома (давая здоровье или эйтр в зависимости от природы биома) вместо того, чтобы пылиться на складе.\n", + "rov_compendium_trenta_heartwood": "[Базовое пассивное] Сердцевина:", + "rov_compendium_trenta_homecoming_portal_h_key": "[Награда: Яглут] Портал домой (клавиша «H»):", + "rov_compendium_trenta_hornet_s_nest_passive": "[Награда: Королева] Осиное гнездо (Пассивное):", + "rov_compendium_trenta_last_stand_passive": "[Награда: Матерь] Последний рубеж (Пассивное):", + "rov_compendium_trenta_muspell_j_key_toggle": "[Награда: Прародитель] Муспелль (клавиша «J», переключение):", + "rov_compendium_trenta_open_linked_pair_portals_one": "Открывает пару связанных порталов — один под вашими ногами, другой в точке вашего возрождения, через которые может пройти любой путник без ограничений на руду и груз. Врата исчезают через $1 с. Перезарядка: $2 мин.\n", + "rov_compendium_trenta_photosynthesis": "[Базовое пассивное] Фотосинтез:", + "rov_compendium_trenta_purple_rain_g_key": "[Награда: Древний] Purple Rain (клавиша «G»):", + "rov_compendium_trenta_sap_heartwood_conduct_lightning_turn": "Смола и сердцевина древесины проводят молнию и отваживают нежить: вы получаете половинный урон от молнии и духа. Но сухие ветви быстро разгораются, а топор дровосека безжалостен — урон от огня и рубящих атак увеличен в полтора раза. Мясо, рыба, яйца и мед противны вашей натуре; лишь то, что произрастает из земли, дает вам силы, и действует в $1 раз дольше, чем на обычного человека.\n", + "rov_compendium_trenta_secrets_heartwood": "Тайны Сердцевины\n", + "rov_compendium_trenta_spray_toxic_pollen_bursts_out": "Выброс токсичной пыльцы в радиусе $1 м: каждый союзник внутри исцеляется на $2 ед., а каждый враг отравляется на $3 ед. урона. Перезарядка: $4 с (сокращается до $5 с в облике Муспелля).\n", + "rov_compendium_trenta_stand_still_daylight_roof_over": "Постойте неподвижно под чистым небом при дневном свете в течение $1 с, и корни войдут в почву: последуют $2 тактов исцеления по $3% от макс. здоровья каждый, а также эффект «Отдых» на $4 минут — время действия растет с каждым павшим боссом.\n", + "rov_compendium_trenta_swamp_has_nothing_left_spoil": "Болотам нечего осквернять в вашем теле. Яд не может навредить вам, эффект сырости не накладывается, а плавание вовсе не расходует выносливость.\n", + "rov_compendium_trenta_swarm_hornets_has_made_its": "Рой шершней свил гнездо в вашей кроне. Любой враг, приблизившийся на расстояние ближе $1 м, получает $2 ед. урона ядом и колющими ударами каждые $3 с, пока не отступит или не погибнет.\n", + "rov_compendium_trenta_take_shape_young_elder_root": "Примите облик юного Древнего, воплотив ярость корней и терновника. ЛКМ сотрясает землю, нанося $1 ед. урона в круге вокруг вас, а ПКМ выпускает пронзающий корень на $2 ед. урона — мощь обоих приемов зависит от навыка «Без оружия». В этой форме вы по-прежнему можете призывать Purple Rain с уменьшенным временем перезарядки.\n", + "rov_compendium_trenta_thorns_passive": "[Награда: Матерь] Шипы (Пассивное):", + "rov_compendium_trenta_title": "Тайны Тренты", + "rov_compendium_trol_base_passive_are_natively_larger": "Базовое пассивное: Вы от природы на 20% крупнее человека и наделены колоссальной силой. Ваш максимальный переносимый вес увеличен на 200, вы получаете +3 к броне за каждого поверженного босса и имеете 4-ю ячейку для еды с самого начала — убийства боссов для этого не требуется.\n", + "rov_compendium_trol_base_passive_black_forest_kin": "Базовое пассивное: Сын Черного леса. Грейдворфы, фулинги и тролли не питают к вам вражды и первыми в бой не вступят — впрочем, если ударить одного из них, они не оставят вызов без ответа.\n", + "rov_compendium_trol_base_weakness_kindling_fire_finds": "Базовая слабость — Растопка: Огонь находит вас там, где пасует всё остальное. Любой урон от ожогов обжигает вас на $1% сильнее обычного, и никакая броня или сопротивление этого не изменят.\n", + "rov_compendium_trol_bonemass_defeated_size_carry_weight": "Масса костей повержена: +5% к размеру, +50 к переносимому весу, +10 к урону дубинами/кулаками/топорами, +10 к урону броском камня.\n", + "rov_compendium_trol_eikthyr_defeated_increased_xp_gain": "Эйктюр повержен: Увеличенный прирост опыта за физический труд и дробящее оружие (дубины, без оружия, топоры, кирки, рубка деревьев).\n", + "rov_compendium_trol_elder_defeated_unlocked_rock_throwing": "Древний повержен: Открыта способность бросать камни. +10% к пассивной регенерации здоровья.\n", + "rov_compendium_trol_fader_defeated_wielded_trees_can": "Прародитель повержен: Вырванные с корнем деревья теперь в мгновение ока крушат прочнейшие препятствия Пепельных земель. Истинный облик больше не ограничен таймером и не имеет перезарядки — нажмите клавишу повторно, чтобы вернуться к нормальному размеру.\n", + "rov_compendium_trol_moder_defeated_unlocked_true_form": "Матерь повержена: Открыт Истинный облик (способность превращения).\n", + "rov_compendium_trol_queen_defeated_unlocked_log_weapon": "Королева повержена: Открыто Бревно в качестве оружия (в Истинном облике взаимодействуйте с деревьями, чтобы использовать стволы как дубины). Габариты Истинного облика колоссально возрастают.\n", + "rov_compendium_trol_title": "Тайны Тролля", + "rov_compendium_trol_trol_s_heritage": "Наследие Тролля\n", + "rov_compendium_trol_yagluth_defeated_size_carry_weight": "Яглут повержен: +5% к размеру, +50 к переносимому весу, +5 к урону дубинами/кулаками/топорами, +5 к урону броском камня. Открыта 5-я ячейка для еды.\n", + "rov_compendium_warvulture_goes_where_look_goes_as": "Она летит туда, куда обращен ваш взор, и летит так долго, как вы того пожелаете: полет со скоростью $1 м/с не стоит птице никаких сил. Зажмите клавишу бега — и она выдаст рывок со скоростью $2 м/с на $3 с, не дольше: птичьи силы не безграничны. Отпустите бег, и дыхание вернется к ней через $4 с прямо в воздухе. Садиться на землю не придется.\n", + "rov_compendium_warvulture_vulture_s_head_kept_stick": "Голова стервятника на шесте, и хищная птица повинуется ей. Поднимите ее — и птица опустится вам под ноги. Поднимите снова — и она понесет вас к земле, не слушая команд до самого приземления, а поднятая в третий раз — отпустит вас на лету.\n", + "rov_compendium_warvulture_war_vulture": "\n-- БОЕВОЙ СТЕРВЯТНИК --\n", + "rov_compendium_warvulture_what_bird_has_left_bar": "Остаток выносливости птицы отображается шкалой под вашей собственной.\n" +} diff --git a/JotunnModStub/Translations/Russian/hover.json b/JotunnModStub/Translations/Russian/hover.json new file mode 100644 index 0000000..b5fc367 --- /dev/null +++ b/JotunnModStub/Translations/Russian/hover.json @@ -0,0 +1,56 @@ +{ + "rov_hover_aswid_dominate": "[$KEY_Use] Поработить", + "rov_hover_aswid_dominate_cooldown_m": "[$KEY_Use] Порабощение (перезарядка: $1 мин)", + "rov_hover_aswid_follow": "[$KEY_Use] Следовать", + "rov_hover_aswid_stay": "[$KEY_Use] Ждать", + "rov_hover_aswid_tame": "\n[$1] Приручить", + "rov_hover_butler_no_servant_stands_here_raise": "$1\nСлуги здесь нет.\n[$KEY_Use] Поднять слугу", + "rov_hover_butler_waiting": "Ожидает.", + "rov_hover_draugh_feed_flesh_or_draugr_s": "\n[$KEY_Use] Скормить плоть или голову драугра", + "rov_hover_draugh_flesh_risen_waiting": "плоть $1/$2, восстало $3/$4, ожидает $5/$6", + "rov_hover_draugh_next_rises_s": "\nследующий восстанет через $1 с", + "rov_hover_draugh_officers_waiting": "\nофицеры $1/$2, ожидает $3/$4", + "rov_hover_dvergar_at_barrel_pour_round": "$1 $2/$3\n$4 у бочки\n[$KEY_Use] Налить по кружке", + "rov_hover_dvergar_contracts": "контракты $1/$2", + "rov_hover_dvergar_empty_pour_brew": "пусто\n[$KEY_Use] Залить варево", + "rov_hover_dvergar_read_ledger": "\n[$KEY_Use] Прочесть гроссбух", + "rov_hover_dvergar_seal_worth_off": "\nваша печать дает скидку $1%", + "rov_hover_dvergar_what_queen_left_behind_buys": "\n(оставленное Королевой позволит нанять еще два отряда)", + "rov_hover_fenrir_blood_thin_here_raises_no": "\nкровь здесь жидка - пока она не поднимет фенрира", + "rov_hover_fenrir_fenrir": ", фенрир $1/$2", + "rov_hover_fenrir_fill_with_meat": "\n[$KEY_Use] Заполнить мясом", + "rov_hover_fenrir_meat_wolves_ulv": "мясо $1/$2\nволки $3/$4, ульвы $5/$6", + "rov_hover_fenrir_next_s": "\nследующий через $1 с", + "rov_hover_fenrir_not_enough_meat_next_one": "\nнедостаточно мяса для следующего (нужно $1)", + "rov_hover_fenrir_pack_whole": "\nстая в сборе", + "rov_hover_skeleton_bone_hand_buy_place_empty": "\n[$KEY_Use] Кость в руке — купить место, пустые руки — двинуть строй", + "rov_hover_skeleton_bone_toward_next_places": "\nкостей $1/$2 для следующего из $3 мест", + "rov_hover_skeleton_every_place_bought": "\nвсе места заняты", + "rov_hover_skeleton_melee_archers_rotten": "\nближний бой $1/$2 из $3\nлучники $4/$5 из $6\nгнилые $7/$8 из $9", + "rov_hover_skeleton_needs_greater_cursed_skull": " (требуется большой проклятый череп)", + "rov_hover_skeleton_next_rises_s": "\nследующий восстанет через $1 с", + "rov_hover_sverm_beehives_taken_allowed_range_feed": "$1\n$2Ульев занято $3 из $4 доступных, $5 поблизости\n$6[$KEY_Use] Скормить стопку", + "rov_hover_sverm_market_no_hive": "$1\nВ пределах $2 метров нет улья.", + "rov_hover_sverm_msg": "$1\n$2[$KEY_Use] $3", + "rov_hover_sverm_stomach_prompt": "Скормить стопку", + "rov_hover_sverm_stomach_title": "Желудок улья", + "rov_hover_sverm_tank": "Биомасса $1 / $2\nПереваривается $3\nЯйца расплода $4 / $5\n", + "rov_hover_sverm_trade_with_hive": "$1\n$2[$KEY_Use] Торговать с ульем", + "rov_hover_trenta_flesh_feed_raw_flesh": "плоть $1/$2\n[$KEY_Use] Скормить сырую плоть", + "rov_hover_trenta_grove_growing": "$1 (растет, осталось $2 мин)", + "rov_hover_trenta_grove_grown": "$1 ($2 $3/$4, мед $5)\n[$KEY_Use] Внести удобрение", + "rov_hover_trenta_honey_full": "$1, заполнено", + "rov_hover_trenta_honey_next": "$1, следующий через $2 мин", + "rov_hover_trenta_honey_none": "нет (мед не обнаружен)", + "rov_hover_trenta_ready_empty": "готово: $1 $2\n[$KEY_Use] Опустошить", + "rov_hover_trenta_rotting_minutes_left": "гниет, осталось $1 мин", + "rov_hover_trol_call_warbands": "\n[$KEY_Use] Созвать боевые дружины", + "rov_hover_trol_grab_log": "\n[$1] Взять бревно", + "rov_hover_trol_warbands": "дружины $1/$2", + "rov_hover_trol_yagluth_drop_hand_buys_king": "\n(трофей Яглута в руке позволит насадить голову конунга и нанять еще две дружины)", + "rov_hover_ward_personal": "Личный", + "rov_hover_ward_race_menu_ward_progression_open": "$rov_piece_racemenuward_name\n$1 прогресс — $2 ($3/$4)\n[$KEY_Use] Открыть\n[Использовать предмет] Пожертвовать реликвию босса", + "rov_hover_ward_world": "Общий", + "rov_hover_boneship_roster": "\nближний бой $1/$2 из $3\nлучники $4/$5 из $6\nна борту $7", + "rov_hover_boneship_bone_hand": "\nкость в руке — купить место" +} diff --git a/JotunnModStub/Translations/Russian/items.json b/JotunnModStub/Translations/Russian/items.json new file mode 100644 index 0000000..7181215 --- /dev/null +++ b/JotunnModStub/Translations/Russian/items.json @@ -0,0 +1,138 @@ +{ + "rov_creature_bonecook_name": "Костяной повар", + "rov_creature_bonesmith_name": "Костяной кузнец", + "rov_creature_draugh_thrall_name": "Драугр-раб", + "rov_creature_draugh_thrallelite_name": "Элитный драугр-раб", + "rov_creature_fenrir_pack_desc": "Оно откликается на кровь волка, а не на вас.", + "rov_creature_fenrir_packfenrir_desc": "Только кровь волка способна повелевать этим созданием.", + "rov_creature_fenrir_packfenrir_name": "Фенрир", + "rov_creature_fenrir_packulv_name": "Ульв", + "rov_creature_fenrir_packwolf_name": "Стайный волк", + "rov_creature_skadi_crystalgolem_name": "Кристальный голем", + "rov_creature_skeleton_sentry_name": "Скованный часовой", + "rov_creature_skeleton_thrallmelee_name": "Скованный скелет", + "rov_creature_skeleton_thrallrancid_name": "Скованные сгнившие останки", + "rov_creature_skeleton_thrallranged_name": "Скованный лучник", + "rov_creature_sverm_blistertick_name": "Чумной клещ", + "rov_creature_sverm_worker_name": "Рабочий искатель", + "rov_item_aswid_bloodcore_desc": "Сгусток запекшейся крови, поддерживаемый биением чего-то чуждого. Мертвые торгуют ими, и лишь мертвые знают секрет их создания.", + "rov_item_aswid_bloodcore_name": "Кровавое ядро", + "rov_item_aswid_bloodessence_desc": "Кровь, очищенная до своего первозданного естества. Единственная истинная пища, которую еще способен усвоить Асвид, и основа любого стоящего зелья.", + "rov_item_aswid_bloodessence_name": "Кровавая эссенция", + "rov_item_aswid_bloodpotion_desc": "Испейте, и голод на время отступит. Наполняет все желудки кровавой эссенцией, сыты вы или нет, и сращивает разорванную плоть.", + "rov_item_aswid_bloodpotion_name": "Кровавое зелье", + "rov_item_aswid_bloodpotionbase_desc": "Кровь, лесные ягоды и бледный свет склепов, ожидающие своего часа в бродильной бочке.", + "rov_item_aswid_bloodpotionbase_name": "Основа медовухи: Кровавое зелье", + "rov_item_aswid_claws_desc": "Выращены во тьме, и оттого стали темнее. Они не снимаются.", + "rov_item_aswid_claws_name": "Когти зверя", + "rov_item_aswid_food_desc": "Жизненная сила побежденных.", + "rov_item_aswid_food_name": "Пища Асвида:", + "rov_item_aswid_spectralclaw_desc": "Коготь из чистейшей тени, повинующийся вашей ярости, а не хватке пальцев.", + "rov_item_aswid_spectralclaw_name": "Призрачный коготь", + "rov_item_aswid_superiorbloodessence_desc": "Та же кровь, очищенная дважды. Гуще, темнее и ценнее пяти порций обычной выжимки.", + "rov_item_aswid_superiorbloodessence_name": "Превосходная кровавая эссенция", + "rov_item_aswid_superiorbloodpotion_desc": "То же милосердие, но исцеляющее вдвое глубже.", + "rov_item_aswid_superiorbloodpotion_name": "Превосходное кровавое зелье", + "rov_item_aswid_superiorbloodpotionbase_desc": "Дважды перегнанное варево, еще не добродившее до конца.", + "rov_item_aswid_superiorbloodpotionbase_name": "Основа медовухи: Превосходное кровавое зелье", + "rov_item_draugh_cursedbone_desc": "Кость, что никак не обретет покой. Мертвые продают их, но не раскрывают причин.", + "rov_item_draugh_cursedbone_name": "Проклятая кость", + "rov_item_draugh_greatercursedbone_desc": "Та же кость, но гораздо древнее и беспокойнее. Куча останков, вскормленная ею, начинает порождать офицеров.", + "rov_item_draugh_greatercursedbone_name": "Большая проклятая кость", + "rov_item_draugh_humanmeat_desc": "Отрезанный кусок плоти. Живых от нее выворачивает, вас — нисколько.", + "rov_item_draugh_humanmeat_name": "Человечина", + "rov_item_fenrir_claws_desc": "Руки волка, сохраненные в человеческом облике. Они не снимаются.", + "rov_item_fenrir_claws_name": "Проклятые когти", + "rov_item_fenrir_greaterulvsblod_desc": "Древняя кровь первородных хищников. Корыто, наполненное ею, взращивает созданий куда страшнее обычных ульвов.", + "rov_item_fenrir_greaterulvsblod_name": "Великая кровь ульва", + "rov_item_fenrir_ulvsblod_desc": "Волчья кровь, сохраняющая тепло благодаря неестественной магии. Фенринги продают ее без лишних слов.", + "rov_item_fenrir_ulvsblod_name": "Кровь ульва", + "rov_item_furling_copperdust_desc": "Мешок мелко намолотой меди. Печь не отличит её от руды, и через портал она тоже не пройдет.", + "rov_item_furling_copperdust_name": "Медная пыль", + "rov_item_furling_copperflax_desc": "Лен, выросший на отравленной медью почве и впитавший ее суть. Для ткани непригоден — измельчите и увидите сами.", + "rov_item_furling_copperflax_name": "Медный лен", + "rov_item_furling_flintberry_desc": "Вовсе не ягода, как бы ни казалось на первый взгляд. Закопайте в землю, и из нее прорастет куст, дающий кремень.", + "rov_item_furling_flintberry_name": "Кремнеягода", + "rov_item_furling_irondust_desc": "Мешок мелко намолотого железа. Печь не отличит его от руды, и через портал он тоже не пройдет.", + "rov_item_furling_irondust_name": "Железная пыль", + "rov_item_furling_ironflax_desc": "Лен, выросший на отравленной железом почве и впитавший ее суть. Для ткани непригоден — измельчите и увидите сами.", + "rov_item_furling_ironflax_name": "Железный лен", + "rov_item_furling_stoneberry_desc": "Вовсе не ягода, как бы ни казалось на первый взгляд. Закопайте в землю, и из нее прорастет куст, дающий камень.", + "rov_item_furling_stoneberry_name": "Камнеягода", + "rov_item_furling_tindust_desc": "Мешок мелко намолотого олова. Печь не отличит его от руды, и через портал оно тоже не пройдет.", + "rov_item_furling_tindust_name": "Оловянная пыль", + "rov_item_furling_tinflax_desc": "Лен, выросший на отравленной оловом почве и впитавший ее суть. Для ткани непригоден — измельчите и увидите сами.", + "rov_item_furling_tinflax_name": "Оловянный лен", + "rov_item_skadi_greaterfrostheart_desc": "Холод куда более древний, чем дыхание ледяных пиков. Культисты торгуют им, но не скажут, где ведут раскопки.", + "rov_item_skadi_greaterfrostheart_name": "Большое сердце холода", + "rov_item_skeleton_cursedskull_desc": "Череп, ведущий неустанный счет. Опустите его на землю, и мертвые отзовутся на зов.", + "rov_item_skeleton_cursedskull_name": "Проклятый череп", + "rov_item_skeleton_greatercursedskull_desc": "Старше прочих, и его счет куда длиннее. Куча останков с таким черепом поднимает и гниющих мертвецов.", + "rov_item_skeleton_greatercursedskull_name": "Большой проклятый череп", + "rov_item_skeleton_soulstone_desc": "Внутри все еще что-то теплится, исполненное ярости. Привяжите его к черепу, и он будет стоять на часах, пока держатся кости.", + "rov_item_skeleton_soulstone_name": "Камень душ", + "rov_item_sverm_claws_desc": "Выращены телом, а не выкованы в кузнице. Они не отделятся от рук.", + "rov_item_sverm_claws_name": "Хитиновые когти", + "rov_item_trenta_fertilizer_desc": "Всё, что когда-то было плотью, месяц спустя. Воткните в почву — и укоренившийся росток больше не заставит себя ждать.", + "rov_item_trenta_fertilizer_name": "Удобрение", + "rov_item_trenta_heartwoodseed_desc": "Семя, вскормленное целым бочонком болотного тлена. Посадите его и забудьте о нем на время.", + "rov_item_trenta_heartwoodseed_name": "Семя сердцевины", + "rov_item_trenta_rotseed_desc": "Семя, погибшее до того, как успело дать росток, но не остановившееся в росте. Лесной народ торгует ими, и лишь лесу ведомо, что из них взойдет.", + "rov_item_trenta_rotseed_name": "Семя гнили", + "rov_item_trol_giantslog_desc": "Исполинский ствол векового дерева, используемый как сокрушительное оружие.", + "rov_item_trol_giantslog_name": "Бревно великана", + "rov_item_trolshammer_desc": "Молот, которым размахивает тот, кому никогда не приходилось пригибаться в дверях. Возводит те же постройки, что и обычный молот, из тех же материалов, но с истинным тролльим размахом.", + "rov_item_trolshammer_name": "Молот тролля", + "rov_item_warvulture_desc": "Высушенная голова стервятника. Поднимите ее — и птица опустится вам под ноги, неся вас вперед, пока вам не надоест (хотя силы для рывка у нее быстро сменяются плавным парением).", + "rov_item_warvulture_name": "Боевой стервятник", + "rov_piece_aswid_bloodrefinery_desc": "Загрузите плоть, бросьте кости — и то, что от них останется, выйдет алым соком.", + "rov_piece_aswid_bloodrefinery_name": "Кровавый перегонный куб", + "rov_piece_cooktable_desc": "Плита из шлифованной кости и сланца. Нечто терпеливое дежурит у очага.", + "rov_piece_cooktable_name": "Стол повара", + "rov_piece_draugh_bodypile_desc": "Скормите ей подношение, и она отзовется. Лежащие здесь мертвецы послужат вам, если в вас самих достаточно тлена.", + "rov_piece_draugh_bodypile_name": "Куча проклятых тел", + "rov_piece_dvergar_contractbank_desc": "Гроссбух, печать и гора золотых монет. Поставьте подпись — и пусть умирает кто-то другой.", + "rov_piece_dvergar_contractbank_name": "Контрактная контора", + "rov_piece_dvergar_runebarrel_desc": "Залейте варево — и наемники выпьют до дна. Напиток подействует на них в точности так же, как и на вас (если их анатомия позволяет).", + "rov_piece_dvergar_runebarrel_name": "Руническая бочка", + "rov_piece_fenrir_packtrough_desc": "Наполните мясом — и стая придет. По одному, помня о каждом павшем собрате.", + "rov_piece_fenrir_packtrough_name": "Кормушка стаи", + "rov_piece_furling_copperflaxsapling_desc": "Посадите, чтобы вырастить больше медного льна.", + "rov_piece_furling_copperflaxsapling_name": "Саженец медного льна", + "rov_piece_furling_flintberrybush_desc": "Дает кремень и продолжает плодоносить снова и снова.", + "rov_piece_furling_flintberrybush_name": "Куст кремнеягоды", + "rov_piece_furling_ironflaxsapling_desc": "Посадите, чтобы вырастить больше железного льна.", + "rov_piece_furling_ironflaxsapling_name": "Саженец железного льна", + "rov_piece_furling_stoneberrybush_desc": "Дает камень и продолжает плодоносить снова и снова.", + "rov_piece_furling_stoneberrybush_name": "Куст камнеягоды", + "rov_piece_furling_tinflaxsapling_desc": "Посадите, чтобы вырастить больше оловянного льна.", + "rov_piece_furling_tinflaxsapling_name": "Саженец оловянного льна", + "rov_piece_racemenuward_desc": "Обратитесь к наследию предков. Принесите трофей поверженного босса, чтобы забрать его первородную мощь.", + "rov_piece_racemenuward_name": "Оберег наследия рас", + "rov_piece_skadi_crystalgolem_desc": "Высечен из камня и пробужден драконьей слезой. Он не пойдет за вами и не покинет камнерез, даровавший ему форму.", + "rov_piece_skeleton_bonepile_desc": "Двадцать обломков костей покупают место в строю. Тот, кто займет его, будет подниматься снова и снова.", + "rov_piece_skeleton_bonepile_name": "Скованная куча костей", + "rov_piece_skeleton_sentry_desc": "Череп, водруженный на камень душ. Он не умеет ходить, но не прекратит дозор ни на мгновение.", + "rov_piece_smithtable_desc": "Плита из кости и сланца, припорошенная рудной пылью. Нечто терпеливое ждет у огня кузницы.", + "rov_piece_smithtable_name": "Стол кузнеца", + "rov_piece_sverm_broodmound_desc": "Здесь зарождается жизнь роя. Всё остальное произрастает из его недр.", + "rov_piece_sverm_broodmound_name": "Курган расплода", + "rov_piece_sverm_hivemarket_desc": "Место торговли колонии. Тратит запасы биомассы того гнезда, возле которого возведено.", + "rov_piece_sverm_hivemarket_name": "Рынок улья", + "rov_piece_trenta_composter_desc": "То, что сгнило, не пропало зря. Оно послужит пищей.", + "rov_piece_trenta_composter_name": "Компостер", + "rov_piece_trenta_elderroot_desc": "Остатки наследия Древнего, продолжающие расти. Исцеляет себя и любые постройки игроков поблизости.", + "rov_piece_trenta_elderroot_name": "Корень Древнего", + "rov_piece_trenta_heartwoodgrove_desc": "Ящик с перегноем, из которого пробивается нечто живое. Дайте ему время.", + "rov_piece_trenta_heartwoodgrove_name": "Роща сердцевины", + "rov_piece_trenta_heartwoodsapling_name": "Саженец сердцевины", + "rov_piece_trol_wartotem_desc": "Отрубленная голова, не разучившаяся рычать. Бросьте монеты — и боевая дружина выступит в поход.", + "rov_piece_trol_wartotem_name": "Боевой тотем", + "rov_piece_boneship_altar_name": "Сундук подношений", + "rov_piece_boneship_ashlands_desc": "Боевой корабль, что сгорел и всё равно плывет дальше, с ребрами из костей. Гребцы не знают усталости.", + "rov_piece_boneship_ashlands_name": "Костяной драккар", + "rov_piece_boneship_karve_desc": "Сгнивший карви с ребрами из костей. Его строили не для того, чтобы ходить под парусом.", + "rov_piece_boneship_karve_name": "Костяной карви", + "rov_piece_boneship_longship_desc": "Сгнивший длинный корабль с ребрами из костей. Он идет против любого ветра.", + "rov_piece_boneship_longship_name": "Костяной длинный корабль" +} diff --git a/JotunnModStub/Translations/Russian/merchants.json b/JotunnModStub/Translations/Russian/merchants.json new file mode 100644 index 0000000..f554511 --- /dev/null +++ b/JotunnModStub/Translations/Russian/merchants.json @@ -0,0 +1,133 @@ +{ + "rov_joke_fantasma_01": "Почему призрак был одинок? Вокруг ни души.", + "rov_joke_fantasma_02": "Какая комната в доме самая бесполезная для призрака? Гостиная... ведь там кипит жизнь!", + "rov_joke_fantasma_03": "Какой любимый сыр призрака? Гуль-да.", + "rov_joke_fantasma_04": "Какая любимая еда призрака? Бу-ррито.", + "rov_joke_fantasma_05": "Какой любимый десерт призрака? Крик-брюле.", + "rov_joke_fantasma_06": "В какую игру любят играть призраки? Прятки и визги.", + "rov_joke_fantasma_07": "Как назвать призрака со сломанной ногой? Хромо-гоблин.", + "rov_joke_fantasma_08": "Что бывает, когда призрак теряется в тумане? Он растворяется в воздухе.", + "rov_joke_fantasma_09": "Призраки любят лифты, потому что они поднимают их дух.", + "rov_joke_fantasma_10": "Почему призрак перешел дорогу? Потому что он был полтер-гусем.", + "rov_joke_goblin_01": "Эти гоблинские пальцы просто гном-стически ловкие.", + "rov_joke_goblin_02": "Зачем гоблин разбил драгоценную вазу? Хотел сокрушить ожидания!", + "rov_joke_goblin_03": "Этот гоблин средь бела дня сгном-здил мой бутерброд.", + "rov_joke_goblin_04": "Просто мелкие гоблинские шалости.", + "rov_joke_goblin_05": "Они обожают орк-естровать чужие неприятности.", + "rov_joke_goblin_06": "Если гоблин тебе улыбается, проверь карманы.", + "rov_joke_goblin_07": "Почему гоблины не моются? Они предпочитают естественную грязь.", + "rov_joke_goblin_08": "Любимый спорт любого уважающего себя гоблина? Хапутбол.", + "rov_joke_goblin_09": "Как гоблины делают покупки? Только со скидкой 'пять пальцев'.", + "rov_joke_goblin_10": "Какой пароль у гоблинского сундука? «МоёМоёМоё!»", + "rov_joke_legnofalegname_01": "Плотники всегда попадают в точку: это их истинное призвание.", + "rov_joke_legnofalegname_02": "Рассказал пиле анекдот — она чуть по швам от смеха не разошлась.", + "rov_joke_legnofalegname_03": "Встречался однажды со столяршей: это были на редкость сколоченные отношения.", + "rov_joke_legnofalegname_04": "У плотников отличное чувство времени: они всегда знают меру.", + "rov_joke_legnofalegname_05": "Мой друг делает мебель: его шутки дубовые, но сколачивают публику.", + "rov_joke_legnofalegname_06": "Хороший плотник никогда не сдается: он просто допиливает то, что начал.", + "rov_joke_legnofalegname_07": "Я спросил у дерева, всё ли в порядке: оно сказало 'Мне как-то досочно'.", + "rov_joke_legnofalegname_08": "Я пошутил про кусок дерева, но шутка оказалась слишком плоской.", + "rov_joke_legnofalegname_09": "Как деревья выходят в интернет? Они просто 'лог-инятся'!", + "rov_joke_legnofalegname_10": "Зачем доска перешла дорогу? Чтобы попасть на другую обшивку!", + "rov_joke_lupolicantropo_01": "Почему оборотень засмеялся, когда грыз скелет? Он добрался до смешной косточки.", + "rov_joke_lupolicantropo_02": "Зачем оборотню понадобилось поговорить со скелетом? Ему нужно было перемыть ему косточки.", + "rov_joke_lupolicantropo_03": "Волк-модник: что-мне-надеть-оборотень.", + "rov_joke_lupolicantropo_04": "Мои навыки оборотня просто с-когте-сшибательны!", + "rov_joke_lupolicantropo_05": "Вой-лоуин, без сомнения - любимый праздник оборотня.", + "rov_joke_lupolicantropo_06": "Почему оборотни не пользуются мобильными? Они предпочитают роуминг.", + "rov_joke_lupolicantropo_07": "Почему оборотень сел в угол? Он не хотел привлекать внимание.", + "rov_joke_lupolicantropo_08": "Почему оборотни не верят сплетням? Потому что чуют запах подвоха за версту.", + "rov_joke_lupolicantropo_09": "Ты просто зверски неотразим.", + "rov_joke_lupolicantropo_10": "Ну что, по-волчьи повоем этой ночью?", + "rov_joke_nano_01": "У гнома-садовода был настоящий талант: сам с ноготок, а репка с кулак.", + "rov_joke_nano_02": "Гномы - отличные пекари; их курсы выпечки всегда самые короткие.", + "rov_joke_nano_03": "Почему из гномов выходят отличные секретные агенты? Они умеют не высовываться.", + "rov_joke_nano_04": "Гном заходит в бар и ударяется головой - планка была установлена слишком низко.", + "rov_joke_nano_05": "Почему гномы так хороши в математике? Потому что считаются именно мелочи.", + "rov_joke_nano_06": "Я видел, как гном спускается по тюремной стене - это было легкое снисхождение.", + "rov_joke_nano_07": "Чем гномы сражаются с троллями? Короткими мечами.", + "rov_joke_nano_08": "Каков девиз воина-дверга? Мал золотник, да смертоносен!", + "rov_joke_nano_09": "Гном открыл пекарню, потому что месил тесто на своем уровне.", + "rov_joke_nano_10": "Как называют невидимого гнома? Короткое замыкание!", + "rov_joke_nonmortozombie_01": "Когда зомби ложатся спать? Когда устают до полусмерти.", + "rov_joke_nonmortozombie_02": "На какой улице живут зомби? В мертвом тупике.", + "rov_joke_nonmortozombie_03": "Где зомби ходят под парусом? На Жутком озере.", + "rov_joke_nonmortozombie_04": "Как называют зомби в пижаме? Ходячий лунатик.", + "rov_joke_nonmortozombie_05": "Чем зомби похожи на компьютеры? Они используют мега-укусы!", + "rov_joke_nonmortozombie_06": "Почему зомби проиграл суд? У него не было ноги, на которую можно опереться!", + "rov_joke_nonmortozombie_07": "Зачем зомби проглотил факел? Захотелось легкого перекуса с огоньком.", + "rov_joke_nonmortozombie_08": "Почему зомби не едят клоунов? Потому что они странные на вкус!", + "rov_joke_nonmortozombie_09": "Почему зомби пошел в школу? Чтобы прокачать мозги.", + "rov_joke_nonmortozombie_10": "Зомби — безнадежные романтики: они всю вечность ищут свою могильную половинку.", + "rov_joke_scheletro_01": "Как называют скелета, который никогда не делает работу по дому? Ленивые кости.", + "rov_joke_scheletro_02": "Почему скелет бросил службу? Сердце к работе не лежало.", + "rov_joke_scheletro_03": "Какой скелет правил Францией? Наполеон Костепарт.", + "rov_joke_scheletro_04": "Кто самый известный в мире скелет-детектив? Шерлок Костс.", + "rov_joke_scheletro_05": "Что говорят французские скелеты перед ужином? Бон аппетит!", + "rov_joke_scheletro_06": "Что скелеты всегда заказывают в ресторане? Запасные ребра.", + "rov_joke_scheletro_07": "Как скелеты переговариваются на расстоянии? По костефону.", + "rov_joke_scheletro_08": "Любимый фрукт скелета? Костян-ка!", + "rov_joke_scheletro_09": "Почему скелеты не умеют врать? Их насквозь видно!", + "rov_joke_scheletro_10": "Почему скелеты не устраивают дуэли? У них для этого кишка тонка.", + "rov_joke_strega_01": "Дежурное ведьминское лицо.", + "rov_joke_strega_02": "Ведьмолепного дня.", + "rov_joke_strega_03": "Как называют мага в пустыне? Сэнд-вич (песчаная ведьма).", + "rov_joke_strega_04": "Что происходит с ведьмами, нарушившими правила школы? Их с позором отвораживают!", + "rov_joke_strega_05": "Что ведьмы наносят на волосы? Лак для у-страшки.", + "rov_joke_strega_06": "Зачем три ведьмы вызвали сантехника? Кипи, котел, унитаз потек.", + "rov_joke_strega_07": "Почему маленькая ведьма не могла прочитать свою книгу заклинаний? Она была написана проклятым курсивом.", + "rov_joke_strega_08": "Почему ведьма стала юристом? Она хотела вести колдовскую практику.", + "rov_joke_strega_09": "Ведьмы не портят воздух. Они наводят зловонные чары.", + "rov_joke_strega_10": "Ведьма всегда знает время, заглядывая в свои ведьмины часики.", + "rov_joke_troll_01": "Почему тролли любят мосты? Они всегда переходят на новую территорию.", + "rov_joke_troll_02": "Почему тролль схлопотал нагоняй? Он так и застрял под мостом недопонимания.", + "rov_joke_troll_03": "Тролли не смотрят ТВ - они стримят пакости.", + "rov_joke_troll_04": "Тролли любят вечеринки - они приносят мостовые закуски.", + "rov_joke_troll_05": "Тролли терпеть не могут понедельники: приходится наводить мосты до пятницы.", + "rov_joke_troll_06": "Где тролли прячут золото? Разумеется, под мостом.", + "rov_joke_troll_07": "Любимые конфеты тролля? Мостовые батончики.", + "rov_joke_troll_08": "Зачем тролль пошел учиться? Хотел перекинуть мост через пропасть в знаниях.", + "rov_joke_troll_09": "Любимый фильм тролля? Бегущий по мосту.", + "rov_joke_troll_10": "Что способно рассмешить тролля? Тот, кто пытается спорить с ним всерьез.", + "rov_merchant_buy": "По рукам.", + "rov_merchant_dverg_name": "Дверг", + "rov_merchant_sell": "Благодарю.", + "rov_merchant_start_trade": "Что тебе нужно?", + "rov_sverm_good_glands_desc": "Каждая выведенная отныне особь рождается с одной звездой.\n\nНа уже существующих особей это не действует: что вылупилось, то вылупилось.", + "rov_sverm_good_glands_name": "Надпочечные железы", + "rov_sverm_good_hyperplasia_desc": "Каждая выведенная отныне особь рождается с двумя звездами.\n\nПеред этим колония должна развить надпочечные железы.", + "rov_sverm_good_hyperplasia_name": "Гиперплазия", + "rov_sverm_good_stage_desc": "Превращает гнездо в $1: оно вмещает $2 биомассы вместо $3 и становится в полтора раза выше.\n\nУлучшение поглощает весь запас текущей стадии, оставляя улей пустым. Растите или выводите армию — но не всё сразу.", + "rov_sverm_good_tick_desc": "Покупает ПОСТОЯННУЮ ячейку в колонии. Созданная особь мчится на врагов колонии и взрывается, а через 30 секунд гнездо выращивает новую — без затрат яиц и биомассы, навсегда.\n\nВзрыв безопасен для вас, ваших прирученных тварей и остальной колонии.", + "rov_sverm_good_troop_desc": "Выводит особь ($1), привязанную к этому гнезду: следует по приказу, возвращается домой, если отпустить, и исцеляет себя.\n\nТребует одно яйцо расплода и биомассу. Одновременно может жить не более $2 особей.", + "rov_sverm_refusal_already_breeds": "Колония уже выводит данный вид.", + "rov_sverm_refusal_grown_past": "Гнездо уже переросло эту стадию.", + "rov_sverm_refusal_keeping": "Колония уже содержит $1 из них.", + "rov_sverm_refusal_keeps": "Колония уже содержит $1 из них.", + "rov_sverm_refusal_no_egg": "Яйцо расплода еще не готово.", + "rov_sverm_refusal_no_hive": "Нет улья.", + "rov_sverm_refusal_one_star": "По одной звезде за раз.", + "rov_sverm_refusal_stage_first": "Сначала гнездо должно развиться до стадии: $1.", + "rov_sverm_refusal_working_m": "Улей все еще переваривает предыдущую порцию ($1 мин).", + "rov_sverm_refusal_working_s": "Улей все еще переваривает предыдущую порцию ($1 с).", + "rov_sverm_stage_gorgedhive": "Обожравшийся улей", + "rov_sverm_stage_hivecitadel": "Цитадель улья", + "rov_sverm_stage_nestingspire": "Гнездовой шпиль", + "rov_troop_dvergar_ash_guard": "Пепельный страж", + "rov_troop_dvergar_escort": "Эскорт", + "rov_troop_dvergar_fire_crew": "Огненный отряд", + "rov_troop_dvergar_runic_crew": "Рунический отряд", + "rov_troop_dvergar_seal_price": "Обычная цена: $1 — ваша печать снижает ее до $2.", + "rov_troop_dvergar_terms": "Они подчиняются команде следовать за вами, сами залечивают свои раны, соблюдают перемирие с горными двергами, не оставляют добычи после смерти и не возрождаются. Погибший отряд — потраченные впустую монеты.", + "rov_troop_dvergar_yard_patrol": "Дворовый патруль", + "rov_troop_sverm_brood": "Выводок", + "rov_troop_sverm_gjall": "Гьялль", + "rov_troop_sverm_seeker": "Искатель", + "rov_troop_sverm_soldier": "Солдат", + "rov_troop_trol_goblin_band": "Боевой отряд фулингов", + "rov_troop_trol_goblin_patrol": "Патруль фулингов", + "rov_troop_trol_greydwarf_patrol": "Патруль грейдворфов", + "rov_troop_trol_terms": "Они подчиняются команде следовать за вами, залечивают раны, не оставляют добычи и не возрождаются. Павшая дружина — это потерянные монеты.", + "rov_troop_trol_troll": "Тролль", + "rov_troop_trol_troll_summoned": "Тролль с дубиной" +} diff --git a/JotunnModStub/Translations/Russian/messages.json b/JotunnModStub/Translations/Russian/messages.json new file mode 100644 index 0000000..aaf65ef --- /dev/null +++ b/JotunnModStub/Translations/Russian/messages.json @@ -0,0 +1,205 @@ +{ + "rov_msg_aswid_aura_disabled": "Вампирическая аура: ОТКЛЮЧЕНА", + "rov_msg_aswid_aura_enabled": "Вампирическая аура: ВКЛЮЧЕНА", + "rov_msg_aswid_dominate_cooldown_m_s": "Порабощение на перезарядке ($1 мин $2 с)", + "rov_msg_aswid_dominated": "$1 порабощен(а)!", + "rov_msg_aswid_eclipse_cooldown_remaining_s": "Затмение перезаряжается. Осталось: $1 с", + "rov_msg_aswid_eclipse_descends": "Нисходит Затмение...", + "rov_msg_aswid_eclipse_has_ended": "Затмение завершилось.", + "rov_msg_aswid_following": "$1 следует за вами.", + "rov_msg_aswid_living_blood_curdles_living_throat": "Живая кровь стынет в живом горле.", + "rov_msg_aswid_morning_sun_drives_bat_back": "Утреннее солнце изгоняет летучую мышь обратно в ваше тело", + "rov_msg_aswid_morning_sun_has_vanquished_horrible": "Утреннее солнце развеяло этот кошмар ночи", + "rov_msg_aswid_no_bone_grind": "Нет костей для перемалывания.", + "rov_msg_aswid_no_raw_flesh_render": "Нет сырой плоти для переработки.", + "rov_msg_aswid_staying": "$1 остается.", + "rov_msg_aswid_sun_burns_can_only_take": "Солнце жжет плоть. Принять облик мыши можно лишь ночью.", + "rov_msg_aswid_tamed": "Приручено!", + "rov_msg_aswid_vae_victis": "Vae Victis", + "rov_msg_aswid_what_horrible_night_have_curse": "Какая ужасная ночь для носителя проклятия...", + "rov_msg_build_limit_cooktable": "В пределах сорока шагов уже стоит стол повара. Один повар на двор.", + "rov_msg_build_limit_draugh_bodypile": "Здешняя земля уже несет на себе $1 таких построек. Найдите другое место.", + "rov_msg_build_limit_dvergar_contractbank": "В радиусе дневного перехода уже есть $1 контрактная контора. Один гроссбух на долину.", + "rov_msg_build_limit_fenrir_packtrough": "В пределах дневного перехода уже есть $1 кормушка. Стае нужен простор.", + "rov_msg_build_limit_skeleton_bonepile": "Поблизости уже внимают $1 таких куч. Постройте ее дальше.", + "rov_msg_build_limit_smithtable": "В пределах сорока шагов уже стоит стол кузнеца. Один кузнец на двор.", + "rov_msg_build_limit_sverm_hive": "Эту территорию уже занимает другой улей.", + "rov_msg_build_limit_sverm_market": "У этого улья уже есть свой рынок.", + "rov_msg_build_limit_trenta_grove": "Здешняя земля уже подчинена $1 таких рощ. Посадите ее в другом месте.", + "rov_msg_build_this_cave_will_hold_what": "Эта пещера вместит то, что вы в ней построите.", + "rov_msg_butler_already_at_work": "Он уже за работой.", + "rov_msg_butler_bones_are_not_ready_s": "Кости еще не готовы. Осталось $1 с.", + "rov_msg_butler_bones_do_not_answer_blood": "Кости не подчиняются вашей крови.", + "rov_msg_butler_nothing_answers": "Никто не отзывается.", + "rov_msg_butler_only_skadi_s_hearth_kept": "Лишь очаг Скади хранят мертвецы.", + "rov_msg_butler_servant_rises": "Слуга восстает.", + "rov_msg_claws_they_are_part_hands": "Они — часть ваших рук.", + "rov_msg_core_chose_path_aswid": "Вы избрали путь Асвида.", + "rov_msg_core_chose_path_draugh": "Вы избрали путь Драуга.", + "rov_msg_core_chose_path_dvergar": "Вы избрали путь Дверга.", + "rov_msg_core_chose_path_fenrir": "Вы избрали путь Фенрира.", + "rov_msg_core_chose_path_furling": "Вы избрали путь Фурлинга.", + "rov_msg_core_chose_path_skadi": "Вы избрали путь Скади.", + "rov_msg_core_chose_path_skeleton": "Вы избрали путь Скелета.", + "rov_msg_core_chose_path_sverm": "Вы избрали путь Сверма.", + "rov_msg_core_chose_path_trenta": "Вы избрали путь Тренты.", + "rov_msg_core_chose_path_trol": "Вы избрали путь Тролля.", + "rov_msg_core_chose_remain_human": "Вы решили остаться Человеком.", + "rov_msg_core_debug_override_cleared": "Отладочное переопределение сброшено.", + "rov_msg_core_nothing_reset_personal": "Нечего сбрасывать: вы еще не пожертвовали ни одной реликвии ($1/$2).", + "rov_msg_core_nothing_reset_world": "Нечего сбрасывать: вы следуете общему прогрессу мира: $1 ($2/$3).", + "rov_msg_core_progression_reset": "Личный прогресс сброшен до: $1 ($2/$3). Принесите реликвии заново.", + "rov_msg_core_progression_state": "Статус прогресса: $1", + "rov_msg_core_world_progression_state": "Статус прогресса мира: $1", + "rov_msg_draugh_bone_will_not_wake_something": "Кость не пробудится. Сперва должно пасть нечто более древнее.", + "rov_msg_draugh_draugr_consume_only_raw_flesh": "Драугры питаются лишь сырой плотью, глазами, потрохами или кровью.", + "rov_msg_draugh_has_already_had_one": "Куча уже получила подношение.", + "rov_msg_draugh_northern_wind_blows": "Повеяло северным ветром...", + "rov_msg_draugh_pile_broken_will_not_outlast": "Куча разрушена. $1 не переживет ее более чем на минуту.", + "rov_msg_draugh_pile_stirs_will_keep_officers": "Куча шевелится. Теперь она сможет содержать офицеров.", + "rov_msg_draugh_steal_their_breath_death_denied": "Steal Their Breath! Смерть отступает.", + "rov_msg_draugh_swarm_terror": "Swarm of Terror!", + "rov_msg_draugh_this_pile_keeps_no_officers": "Эта куча пока не может содержать офицеров.", + "rov_msg_draugh_this_rotting_flesh_fatal_living": "Эта гниющая плоть смертельно опасна для живых.", + "rov_msg_draugh_wants_flesh_or_head_one": "Ей требуется плоть или голова сородича.", + "rov_msg_draugh_zombie_ritual_activated_borrowed_time": "Активирован обряд зомби! Ваше одолженное время тает...", + "rov_msg_dvergar_contract_runic_do_not_sign": "Контракт начертан рунами. Вы не можете подписать его.", + "rov_msg_dvergar_do_not_know_what_goes": "Вы не знаете, что туда заливать.", + "rov_msg_dvergar_drink": "$1 пьют: $2.", + "rov_msg_dvergar_drink_barrel_runs_dry": "$1 пьют: $2. Бочка опустела.", + "rov_msg_dvergar_empty_so_are": "Она пуста, как и ваши карманы.", + "rov_msg_dvergar_five_contracts_all_ledger_holds": "Пять контрактов — предел для этого гроссбуха.", + "rov_msg_dvergar_has_already_had_one": "Сюда уже сделан вклад.", + "rov_msg_dvergar_ledger_not_written": "Этот гроссбух писался не для вас.", + "rov_msg_dvergar_ledger_rewritten_better_names_sign": "Гроссбух переписан. Теперь в нем расписываются более грозные бойцы.", + "rov_msg_dvergar_ledger_shut": "Гроссбух закрыт.", + "rov_msg_dvergar_nobody_at_barrel": "У бочки никого нет.", + "rov_msg_dvergar_not_drop_went_down": "Ни капли не попало внутрь.", + "rov_msg_dvergar_not_enough_eitr": "Недостаточно эйтра", + "rov_msg_dvergar_not_while_she_still_sits": "Только не пока она все еще скрывается во мгле.", + "rov_msg_dvergar_runic_overcharge_discharges": "Руническая перегрузка разряжается", + "rov_msg_dvergar_runic_overcharge_next_blow_loaded": "Руническая перегрузка: следующий удар заряжен", + "rov_msg_dvergar_runic_ping_echoes_answer": "Рунический эхолокатор: ответило $1 эхо", + "rov_msg_dvergar_runic_ping_stone_silent": "Рунический эхолокатор: камень безмолвствует", + "rov_msg_dvergar_signs": "$1 подписывает контракт.", + "rov_msg_dvergar_there_still": "Внутри все еще плещется $1.", + "rov_msg_dvergar_whatever_does_nothing_anyone": "Содержимое бочки ни на кого не подействовало.", + "rov_msg_fenrir_are_cultist": "Вы — Культист!", + "rov_msg_fenrir_are_fenring": "Вы — Фенринг!", + "rov_msg_fenrir_are_ulv": "Вы — Ульв!", + "rov_msg_fenrir_are_wolf": "Вы — Волк!", + "rov_msg_fenrir_beast_rests_can_only_transform": "Зверь спит. Перевоплощение доступно лишь ночью.", + "rov_msg_fenrir_beast_tired": "Зверь истощен", + "rov_msg_fenrir_blood_will_not_take_something": "Кровь не примется. Сперва должно пасть нечто на Равнинах.", + "rov_msg_fenrir_form_cooldown": "Облик ($1) перезаряжается ($2:$3).", + "rov_msg_fenrir_formname_cultist": "Культист", + "rov_msg_fenrir_formname_fenrir": "Фенрир", + "rov_msg_fenrir_formname_ulv": "Ульв", + "rov_msg_fenrir_formname_wolf": "Волк", + "rov_msg_fenrir_has_already_had_one": "Кормушка уже заполнена.", + "rov_msg_fenrir_only_breath_comes_out_fire": "Вырывается лишь дыхание. Огню требуется эйтр.", + "rov_msg_fenrir_ready": "$1 завершена!", + "rov_msg_fenrir_returned_human_form": "Вы вернулись в человеческий облик.", + "rov_msg_fenrir_sun_takes_form": "Солнце забирает зверя обратно. Эта форма доступна только ночью.", + "rov_msg_fenrir_sun_takes_form_day_key": "Солнце изгоняет зверя. Эта форма отвечает лишь ночью; днем нажмите $2 для облика $1.", + "rov_msg_fenrir_trough_broken_will_not_outlast": "Кормушка сломана. $1 вскоре исчезнет вслед за ней.", + "rov_msg_fenrir_trough_takes_line_runs_deeper": "Кормушка принимает жертву. Родословная стаи крепнет.", + "rov_msg_fenrir_wants_meat_any_meat": "Требуется мясо. Любое мясо.", + "rov_msg_fenrir_wants_what_yagluth_left_behind": "Требуется то, что осталось после падения Яглута.", + "rov_msg_skadi_are_drake": "Вы — Дрейк!", + "rov_msg_skadi_are_fader": "Вы — Прародитель!", + "rov_msg_skadi_are_moder": "Вы — Матерь!", + "rov_msg_skadi_dragon_form_cooldown": "Облик дракона перезаряжается ($1:$2).", + "rov_msg_skadi_dragon_form_fades": "Ваш облик дракона рассеивается.", + "rov_msg_skadi_dumped_dragon_drake_fader_debug": "Отладочная информация Dragon/Drake/Fader сброшена в консоль!", + "rov_msg_skadi_needs_stonecutter_cut_at": "Для обработки требуется камнерез.", + "rov_msg_skadi_not_enough_stamina": "Недостаточно выносливости", + "rov_msg_skadi_returned_human_form": "Вы вернулись в человеческий облик.", + "rov_msg_skadi_stone_does_not_answer": "Камень не отзывается на ваш зов.", + "rov_msg_skadi_stonecutter_gone_what_cut_will": "Камнерез разрушен. Его творение ненадолго переживет создателя.", + "rov_msg_skadi_tear_cold_nothing_wakes_stone": "Слеза холодна. Ничто в камне не пробудится, пока повелительница гор не падет.", + "rov_msg_skadi_that_stonecutter_already_holds_will": "Этот камнерез уже удерживает: $1. Больше создать нельзя.", + "rov_msg_skadi_there_are_already_these_within": "В радиусе дневного перехода уже есть $1 таких стражей. Сила камня иссякла.", + "rov_msg_skeleton_has_already_had_one": "Куча уже получила кости.", + "rov_msg_skeleton_have_been_resurrected_by_dark": "Вы воскрешены силами темной магии!", + "rov_msg_skeleton_look_normal": "Внешний вид: обычные кости", + "rov_msg_skeleton_look_green": "Внешний вид: зеленые кости", + "rov_msg_skeleton_look_flames": "Внешний вид: пылающие кости", + "rov_msg_skeleton_mortal_food_disgusts": "Смертная пища вызывает у вас отвращение.", + "rov_msg_skeleton_nothing_standing_yet_wants_bone": "Никто еще не поднялся. Требуются кости.", + "rov_msg_skeleton_pile_broken_fall_where_they": "Куча разбита. $1 падают замертво там, где стояли.", + "rov_msg_skeleton_pile_deepens_rotten_will_stand": "Куча наполняется тьмой. Гниющие мертвецы тоже встанут в строй.", + "rov_msg_skeleton_return_pile": "$1 возвращаются в кучу костей.", + "rov_msg_skeleton_rise_follow": "$1 поднимаются и следуют за вами.", + "rov_msg_skeleton_skeletons_do_not_need_eat": "Скелетам не нужна еда.", + "rov_msg_skeleton_skull_will_not_wake_something": "Череп не проснется. Сперва должно пасть нечто более древнее.", + "rov_msg_skeleton_these_bones_answer_only_their": "Эти кости повинуются лишь собственному роду.", + "rov_msg_skeleton_this_pile_cannot_hold_rotten": "Эта куча пока не способна поднимать гниющих.", + "rov_msg_sverm_alchemical_blood_not_food": "Алхимическая кровь — не еда.", + "rov_msg_sverm_carapace_has_no_room_that": "Ваш панцирь не примет этот доспех.", + "rov_msg_sverm_colony_will_not_wake_until": "Колония не проснется, пока не падет Древний.", + "rov_msg_sverm_hive_does_not_know": "Улей не признает вас.", + "rov_msg_sverm_hive_full_give_time_digest": "Улей полон. Дайте ему время переварить пищу.", + "rov_msg_sverm_market_has_stand_within_metres": "Рынок должен располагаться не дальше $1 метров от улья.", + "rov_msg_sverm_no_hive_within_metres_this": "В радиусе $1 метров нет улья. Этот прилавок мертв.", + "rov_msg_sverm_not_enough_biomass_bank": "В хранилище недостаточно биомассы.", + "rov_msg_sverm_not_hurt": "$1 не имеет ранений.", + "rov_msg_sverm_nothing_here_will_eat_food": "Здесь нет ничего съедобного для улья. Принесите еду, древесину или смолу (мед и маточное молочко — лекарства).", + "rov_msg_sverm_only_sverm_can_raise_hive": "Только Сверм может основать улей.", + "rov_msg_sverm_only_sverm_can_raise_market": "Только Сверм может возвести рынок.", + "rov_msg_sverm_ravager_strain_takes_hold": "Штамм опустошителя вступает в силу.", + "rov_msg_sverm_shell_recedes": "Панцирь возвращается в исходное состояние.", + "rov_msg_sverm_strain_has_not_taken_yet": "Мутация еще не прижилась.", + "rov_msg_sverm_strain_spent": "Сила мутации иссякла.", + "rov_msg_sverm_they_are_part_hands": "Они — часть ваших рук.", + "rov_msg_sverm_x_biomass_digesting": "$1 x$2 -> +$3 биомассы, переваривается", + "rov_msg_thrall_answer_call": "$1 откликаются на призыв.", + "rov_msg_thrall_answer_wait": "$1 стоят и ждут.", + "rov_msg_thrall_answer_home": "$1 идут домой.", + "rov_msg_thrall_waits": "$1 ждет здесь.", + "rov_msg_thrall_follows": "$1 следует за вами.", + "rov_msg_thrall_no_more_may_walk_with": "Больше спутников не могут сопровождать вас.", + "rov_msg_thrall_only_may_walk_with": "Только $1 могут сопровождать вас.", + "rov_msg_thrall_refusal_default": "Оно вам не подчиняется.", + "rov_msg_thrall_refusal_draugh": "Мертвые не принимают приказов от живых.", + "rov_msg_thrall_refusal_dvergar": "Вашего имени нет в контракте.", + "rov_msg_thrall_refusal_skeleton": "Эти кости повинуются лишь своему роду.", + "rov_msg_thrall_refusal_sverm": "От вас не пахнет феромонами колонии.", + "rov_msg_thrall_refusal_trol": "Им платили не вы.", + "rov_msg_thrall_returns": "$1 возвращается назад.", + "rov_msg_thrall_rises_with": "$1 встает в строй с $2.", + "rov_msg_thrall_stands_down_with": "$1 покидает строй с $2.", + "rov_msg_trenta_are_muspell_ash_ember_given": "Вы — Муспелль, воплощение пепла и тлеющих углей.", + "rov_msg_trenta_elder_has_not_fallen_yet": "Древний еще не повержен.", + "rov_msg_trenta_grows": "Оно растет.", + "rov_msg_trenta_no_raw_flesh_rot": "Нет сырой плоти для гниения.", + "rov_msg_trenta_nothing_feed_wants_fertilizer": "Нечем подкормить. Требуется Удобрение.", + "rov_msg_trenta_nothing_there_feed": "Здесь нечего подкармливать.", + "rov_msg_trenta_return_rooted_form": "Вы возвращаетесь в свой древесный облик.", + "rov_msg_trenta_ripe_already": "Оно уже созрело.", + "rov_msg_trenta_root_will_not_take_hold": "Корень не приживется для вас.", + "rov_msg_trenta_still_growing_minutes": "Все еще растет. Осталось $1 мин.", + "rov_msg_trenta_still_rotting_minutes": "Все еще перегнивает. Осталось $1 мин.", + "rov_msg_trenta_this_one_not_well_nothing": "Этому нездоровится. Ничто не ускорит это.", + "rov_msg_trenta_trenta_eat_only_what_grows": "Трента питается лишь тем, что рождено корнями и листвой: никакого мяса, рыбы, яиц или меда.", + "rov_msg_trol_answers": "$1 откликается.", + "rov_msg_trol_are_already_holding_log": "Вы уже держите бревно!", + "rov_msg_trol_five_warbands_all_can_shout": "Пять дружин — предел того, сколько может созвать тотем.", + "rov_msg_trol_has_already_had_one": "Подношение уже принесено.", + "rov_msg_trol_head_has_nothing_say": "Голове нечего сказать.", + "rov_msg_trol_head_will_not_shout": "Голова не станет кричать по вашей воле.", + "rov_msg_trol_must_true_form_lift_this": "Вы должны быть в Истинном облике, чтобы поднять это!", + "rov_msg_trol_no_room_lift": "Недостаточно места, чтобы поднять ствол!", + "rov_msg_trol_not_until_one_belonged_has": "Не раньше, чем падет тот, кому оно принадлежало.", + "rov_msg_trol_totem_wears_king_now": "Теперь тотем венчает голова конунга.", + "rov_msg_ward_already_carry_s_power": "Вы уже владеете силой: $1.", + "rov_msg_ward_s_power_yours": "Сила ($1) теперь принадлежит вам.", + "rov_msg_ward_switch_personal_progression_first": "Сперва переключитесь на личный прогресс.", + "rov_msg_ward_ward_has_no_use_that": "Оберег не примет этот предмет.", + "rov_msg_warvulture_bird_does_not_know": "Птица не признает вас.", + "rov_msg_warvulture_vulture_does_not_answer": "Стервятник не откликается.", + "rov_msg_warvulture_vulture_settles_into_glide": "Стервятник переходит в планирующий полет.", + "rov_msg_warvulture_vulture_spirals_down": "Стервятник кружит, спускаясь по спирали.", + "rov_msg_boneship_no_shore": "Берега не видно. Они остаются на веслах.", + "rov_msg_boneship_sunk": "Корабль идет ко дну, и $1 вместе с ним." +} diff --git a/JotunnModStub/Translations/Russian/races.json b/JotunnModStub/Translations/Russian/races.json new file mode 100644 index 0000000..eaf2ab2 --- /dev/null +++ b/JotunnModStub/Translations/Russian/races.json @@ -0,0 +1,27 @@ +{ + "rov_menu_choose_race": "Выберите расу", + "rov_menu_ok": "ОК", + "rov_menu_back": "Назад", + "rov_race_human_name": "Человек", + "rov_race_human_desc": "Универсальные первопроходцы Мидгарда. Сбалансированные характеристики без явных слабостей.", + "rov_race_fenrir_name": "Фенрир", + "rov_race_fenrir_desc": "Проклятые волчьей кровью. Быстрые и смертоносные, но уязвимые к серебру.", + "rov_race_skadi_name": "Скади", + "rov_race_skadi_desc": "Дети гор. Устойчивы к холоду и чувствуют себя как дома среди ледяных вершин.", + "rov_race_skeleton_name": "Скелет", + "rov_race_skeleton_desc": "Неупокоенные воины. Невосприимчивы к яду, но уязвимы перед дробящими ударами.", + "rov_race_aswid_name": "Асвид", + "rov_race_aswid_desc": "Свирепый ночной охотник. Силен, живуч и способен обращаться в летучую мышь.", + "rov_race_furling_name": "Фурлинг", + "rov_race_furling_desc": "Коварные гоблиноподобные создания. Невероятно ловкие и запасливые.", + "rov_race_trol_name": "Тролль", + "rov_race_trol_desc": "Обладает сокрушительной физической силой и возвышается над всеми. В ладах с обитателями Черного леса, однако огонь наносит Троллю на $1% больше урона, чем остальным.", + "rov_race_draugh_name": "Драуг", + "rov_race_draugh_desc": "Гниющий неупокоенный воин, движимый темной магией и яростью первобытной стали.", + "rov_race_dvergar_name": "Дверг", + "rov_race_dvergar_desc": "Низкорослые, упрямые кузнецы из подземных глубин. Физически хрупки, но не знают равных в металлургии, горном деле и торговле.", + "rov_race_trenta_name": "Трента", + "rov_race_trenta_desc": "Древоподобный народ, единый с корнями и листвой. Невозмутимы, и их невероятно трудно свалить с ног.", + "rov_race_sverm_name": "Сверм", + "rov_race_sverm_desc": "Порождение хитинового роя. Закованы в природный панцирь с рождения, ядовиты, дружественны ко всем ползучим тварям, однако дробящие удары и огонь легко находят щели в их защите." +} diff --git a/JotunnModStub/Translations/Russian/status_effects.json b/JotunnModStub/Translations/Russian/status_effects.json new file mode 100644 index 0000000..f1f2d58 --- /dev/null +++ b/JotunnModStub/Translations/Russian/status_effects.json @@ -0,0 +1,62 @@ +{ + "rov_se_aswid_auspex_name": "Ауспекс", + "rov_se_aswid_auspex_tooltip": "Ощущение жизненной силы ближайших существ.", + "rov_se_aswid_batform_name": "Like a Bat out of Hell", + "rov_se_aswid_batform_tooltip": "Вы приняли форму летучей мыши. Вы умеете летать, но не можете нападать.", + "rov_se_aswid_bloodpotion_tooltip": "Желудки наполнены кровью. Восстановление $1% здоровья за $2 с.", + "rov_se_aswid_mistform_name": "Weight of Shadows", + "rov_se_aswid_mistform_tooltip": "Вы — бесплотный туман. Неуязвимость к физическому урону и яду. Нельзя атаковать и бегать.", + "rov_se_aswid_nightaura_name": "Ночная аура", + "rov_se_aswid_nightaura_tooltip": "Холод ночи обостряет ваши звериные чувства.", + "rov_se_aswid_sensed_name": "Обнаружен", + "rov_se_aswid_stats_name": "Benedictus et Afflictus", + "rov_se_aswid_stats_tooltip": "Вампирические чувства и похищение жизни.", + "rov_se_claws_tooltip": "Когти выпущены. Они исчезнут, когда действие эффекта закончится.", + "rov_se_draugh_wet_tooltip": "Вода насыщает вашу истлевшую плоть. Регенерация здоровья ускорена.", + "rov_se_dvergar_overcharge_name": "Руническая перегрузка", + "rov_se_dvergar_overcharge_tooltip": "Следующий удар любимым оружием обрушит всю накопленную мощь рун.", + "rov_se_dvergar_overchargecd_name": "Перезарядка перегрузки", + "rov_se_dvergar_overchargecd_tooltip": "Руны истощены.", + "rov_se_dvergar_pingcd_name": "Рунический эхолокатор", + "rov_se_dvergar_pingcd_tooltip": "Рунам требуется время на покой, прежде чем вы сможете воззвать к ним снова.", + "rov_se_dvergar_stats_name": "Камень и наковальня", + "rov_se_dvergar_stats_tooltip": "Низкорослый, выносливый и рожденный для кузницы.", + "rov_se_fenrir_cultistcd_name": "Перезарядка облика культиста", + "rov_se_fenrir_cultistform_name": "Ярость культиста", + "rov_se_fenrir_curse_name": "Кровь Фенрира", + "rov_se_fenrir_curse_tooltip": "В ваших жилах течет кровь Фенрира.", + "rov_se_fenrir_form_name": "Звериная ярость", + "rov_se_fenrir_formcd_name": "Перезарядка облика фенрира", + "rov_se_fenrir_wolfform_name": "Волчье чутье", + "rov_se_skadi_aura_name": "Аура Скади", + "rov_se_skadi_aura_tooltip": "Усиление первозданным морозом.", + "rov_se_skadi_coldspellcd_name": "Ледяное заклятие", + "rov_se_skadi_coldspellcd_tooltip": "Мороз должен накопиться вновь перед повторным применением.", + "rov_se_skadi_dragonattackcd_name": "Атака дракона", + "rov_se_skadi_dragonattackcd_tooltip": "Облик дракона восстанавливает силы для следующего удара.", + "rov_se_skadi_form_name": "Облик дракона", + "rov_se_skadi_form_tooltip": "Вы сохраняете драконий облик еще некоторое время.", + "rov_se_skadi_formcd_name": "Перезарядка облика дракона", + "rov_se_skadi_stats_name": "Благословение Скади", + "rov_se_skeleton_resurrectcd_name": "Перезарядка воскрешения", + "rov_se_skeleton_resurrectcd_tooltip": "Ваш костяк слишком слаб, чтобы воскреснуть вновь прямо сейчас.", + "rov_se_skeleton_stats_name": "Стойкость нежити", + "rov_se_sverm_ravager_name": "Штамм опустошителя", + "rov_se_sverm_ravager_tooltip": "Панцирь становится вдвое прочнее, и удары отскакивают от него без следа.", + "rov_se_sverm_ravagercd_name": "Перезарядка штамма опустошителя", + "rov_se_sverm_ravagercd_tooltip": "Мутация угасла. Скоро тело будет готово к ней вновь.", + "rov_se_sverm_stats_name": "Хитиновый панцирь", + "rov_se_sverm_stats_tooltip": "Бронированный, ядовитый и никогда не остающийся в одиночестве.", + "rov_se_trenta_portalcd_name": "Портал домой", + "rov_se_trenta_portalcd_tooltip": "Путь домой еще не стабилизировался для повторного открытия.", + "rov_se_trenta_purpleraincd_name": "Purple Rain", + "rov_se_trenta_purpleraincd_tooltip": "Пыльца должна осесть, прежде чем вы сможете призвать дождь снова.", + "rov_se_trenta_stats_name": "Сердцевина", + "rov_se_trenta_stats_tooltip": "Укорененный, терпеливый, несокрушимый.", + "rov_se_trol_throwcd_name": "Перезарядка броска камня", + "rov_se_trol_throwcd_tooltip": "Нужно подождать, прежде чем метнуть следующий валун.", + "rov_se_trol_trueform_name": "Истинный облик", + "rov_se_trol_trueform_tooltip": "Вы выпустили своего внутреннего тролля на свободу!", + "rov_se_trol_trueformcd_name": "Перезарядка истинного облика", + "rov_se_trol_trueformcd_tooltip": "Вы истощены после пребывания в Истинном облике." +} From 02c640e1d9a8051fde7683af5ae33daa408fc5d6 Mon Sep 17 00:00:00 2001 From: kanym Date: Tue, 6 Oct 2026 14:20:22 +0200 Subject: [PATCH 013/176] chore(release): v1.5.7 - Bone Ships and the Russian translation README: the stack of "New in" blocks at the top is down to the latest release, a languages line with flags sits under the intro, Bone Ships gets its own section, and the Translations section credits Rudra and Axibed for the Russian. nexus-readme.py keeps an image inside a line of text inline, so the flags do not come out as 350 px pictures on Nexus. --- JotunnModStub/Package/manifest.json | 2 +- JotunnModStub/RacesOfValheim.cs | 2 +- README.md | 58 +++++++++++++++-------------- manifest.json | 2 +- scripts/nexus-readme.py | 3 ++ 5 files changed, 37 insertions(+), 30 deletions(-) diff --git a/JotunnModStub/Package/manifest.json b/JotunnModStub/Package/manifest.json index e29ebe8..6791a68 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.5.6", + "version_number": "1.5.7", "website_url": "", "dependencies": [ "denikson-BepInExPack_Valheim-5.4.2333", diff --git a/JotunnModStub/RacesOfValheim.cs b/JotunnModStub/RacesOfValheim.cs index 7bbd88e..c530409 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.5.6"; + public const string PluginVersion = "1.5.7"; private readonly Harmony harmony = new Harmony(PluginGUID); diff --git a/README.md b/README.md index f521a75..f396ea9 100644 --- a/README.md +++ b/README.md @@ -2,6 +2,8 @@ A comprehensive Valheim mod allowing you to play as unique races, each providing new mechanics, visual forms, and a progression system for your journey. +**Languages:** ![English](https://flagcdn.com/24x18/gb.png) English · ![Italiano](https://flagcdn.com/24x18/it.png) Italiano · ![Русский](https://flagcdn.com/24x18/ru.png) Русский. The mod follows the language set in Valheim. See [Translations](#translations). + --- ## Development & Feedback @@ -13,33 +15,9 @@ Support the mod: [Patreon — NandorTheModder](https://www.patreon.com/c/NandorT --- -## New in v1.5.6 +## New in v1.5.7 -Three tester reports. Sverm Seeker Workers no longer wander hundreds of metres from their nest, the Blister Tick can no longer be bought past the nest's egg clutch, and a Fenrir form no longer freezes when you attack during its idle howl. Full details in the [changelog](#v156). - -## New in v1.5.5 - -A Sverm Gjall no longer kills you with its own bombs, and the ticks it hatches are on your side. Full details in the [changelog](#v155). - -## New in v1.5.4 - -Sverm troops no longer crowd you. Following soldiers used to run onto your exact spot, shove each other and push you around, even into the water, and on a boat they drove into the hull and spun it in circles. Each one now keeps its own place around you, and around the hull when you sail. Full details in the [changelog](#v154). - -## New in v1.5.3 - -Valheim 1.0's new creatures are on the menu. The Aswid can drink the seals, the moose, the Elaking and its Lantern, the Elaking Mole, the frozen Greydwarfs, the Jotun Warriors and Witch, the Barka, the Deep North Goblin and every Dvergr, and the Draugh can eat raw Seal Blubber and Moose Meat. The Aswid blood refinery takes the Elaking Hair Bundle as bone, and a Skeleton can now pick which of its unlocked looks to wear from the barber's chair. Full details in the [changelog](#v153). - -## New in v1.5.2 - -The mod's texts finally show for everyone who installs through a mod manager (r2modman, the Thunderstore Mod Manager, Gale). Those managers were taking the translation folders apart on install, so every name and message read like `[rov_...]`. Update, and the texts are back. Full details in the [changelog](#v152). - -## New in v1.5.1 - -A fix release for v1.5.0. The mod's texts show properly again for players whose install turned them into [rov_...] keys, mod managers included. Weapons and shields now match a resized player instead of shrinking after you put them away, and a True Form Trol can reach the log at its feet. The Sverm's Hive Market sells again, because the nest lays its brood eggs while you stand by it. The Trenta's Muspell looks out from its own head and keeps idling, a Furling no longer carries its fire onto another race, and raids made only of your allies no longer come for you. - -v1.5.0 made the mod translatable, in English and Italian, and adding a language needs no code - see [Translations](#translations). - -Full details in the [changelog](#v151). +Bone Ships: every vanilla ship but the Raft now has a bone version, rowed by skeletons and crewed from an Offering Chest on deck. The mod is also translated into Russian. Full details under [Bone Ships](#bone-ships) and in the [changelog](#v157). --- @@ -148,7 +126,9 @@ Three races grow a pair of their own, refused by the holster key and never dragg ## Translations -Every text the mod shows lives in plain JSON files under `Translations//`, next to the DLL: the race menu, status effects, items and pieces, messages, hover prompts, merchants and the compendium. The mod ships in **English** and **Italian**, and follows the language you pick in Valheim's own settings. +Every text the mod shows lives in plain JSON files under `Translations//`, next to the DLL: the race menu, status effects, items and pieces, messages, hover prompts, merchants and the compendium. The mod ships in **English**, **Italian** and **Russian**, and follows the language you pick in Valheim's own settings. + +The Russian translation is by **Rudra** and **Axibed**. Thank you both. To translate it into another language: @@ -394,6 +374,26 @@ Speeds, sprint duration, recharge, mount size and seat position are all in Confi --- +## Bone Ships + +Every vanilla ship but the Raft has a bone version: the **Bone Karve**, the **Bone Longship** and the **Ashen Bone Longship**. Build them with the Hammer, in the Misc tab. Any race can build them. + +- **Cost:** 1 Wishbone, bone fragments (60 / 120 / 200), resin (10 / 20 / 30) and wood (30 / 60). The Ashlands one asks for 60 fine wood instead of wood. +- **Looks:** the hull is rotten from day one, ribbed with bone along the rails and the bow, and the sail is black and torn. +- **No wind needed:** skeletons seated at benches pull the oars in time, and the push follows the ship's gear. The number of oarsmen is the number of troops aboard. + +### Offering Chest and the crew + +There is an Offering Chest on the deck. Offer bone fragments there, twenty per place. A place is paid for once and refills itself forever, like the bone pile. + +- **Places (melee + archers):** Karve 2+2, Longship 4+4, Ashlands 6+6. +- **Sailing:** the troops are just a number on the ship. +- **Landing:** when the ship has been stopped for a few seconds with land in reach, they come ashore one at a time as tame skeletons and follow whoever built the ship. When the ship moves off again, the ones close enough go back aboard. +- **Archers:** Bound Sentries fixed to the deck and the bow. +- **Sinking:** if the ship sinks, the crew goes down with it. + +--- + ## Trol's Hammer (Building, One Size Up) A builder's hammer swung by something that never had to duck through a doorway. @@ -447,6 +447,10 @@ Both halves have an off switch under `Factions` in Configuration Manager: **Fact ## Changelog +### v1.5.7 +- **New - Bone Ships:** a bone version of the Karve, the Longship and the Ashlands Drakkar, built with the Hammer by any race. Skeletons row them, so they need no wind, and an Offering Chest on deck buys the crew with bone fragments, like the bone pile. The crew comes ashore as tame skeletons when you land. See [Bone Ships](#bone-ships). +- **New - Russian translation:** every text in the mod, by Rudra and Axibed. Boss and creature names follow Valheim's own Russian. + ### v1.5.6 - **Fix - Sverm Seeker Workers wandered far from their nest:** a worker that picked a fight kept chasing its target across the map, because it carried a Seeker's chase range and the game measured that range from where the worker was born, not from the nest. Workers now fight inside the nest's own ground like the troops (25 m), forget a target that leaves it, and one found more than 60 m from the nest is put back. Workers the old build already let wander come home too. - **Fix - Blister Ticks could be bought past the nest's limit:** the slot cap was a flat 10 whatever the stage, while every tick spends an egg that does not come back and eggs regrow. The cap is now the lower of the configured number and the nest's clutch at its stage (five plus the stage). Ticks already bought stay and keep respawning. Thanks to the player who reported it. diff --git a/manifest.json b/manifest.json index e29ebe8..6791a68 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.5.6", + "version_number": "1.5.7", "website_url": "", "dependencies": [ "denikson-BepInExPack_Valheim-5.4.2333", diff --git a/scripts/nexus-readme.py b/scripts/nexus-readme.py index d83142d..c2dcbcc 100644 --- a/scripts/nexus-readme.py +++ b/scripts/nexus-readme.py @@ -27,6 +27,9 @@ def inline(text): """Markdown's inline marks, in an order where they cannot eat each other.""" text = re.sub(r"\*\*(.+?)\*\*", r"[b]\1[/b]", text) text = re.sub(r"`([^`]+)`", r'"\1"', text) + # An image inside a line of text (the language flags) stays inline at its own size; a line that + # is only an image never gets here, convert() gathers those first. + text = re.sub(r"!\[[^\]]*\]\(([^)]+)\)", r"[img]\1[/img]", text) # An in-page anchor means nothing on a Nexus description, so the link text stays and the # link goes: "Full details under Sverm" reads the same, and a dead #10-sverm does not. text = re.sub(r"\[([^\]]+)\]\(#[^)]*\)", r"\1", text) From 1848725f2a8d91bce2e33542029be5e9e2a7de19 Mon Sep 17 00:00:00 2001 From: kanym Date: Wed, 7 Oct 2026 04:11:08 +0200 Subject: [PATCH 014/176] fix(skeleton): rise on resurrect, truce for bound troops, pile and sentry on floors The Yagluth auto-resurrect now plays the crypt rise. The player rig has no rise state, so the body is hidden and the skeleton model is worn for the length of the clip with "wakeup" set; the start time goes on the ZDO so other clients play it too. The player takes no damage and does not move until it is out. Wild faction mobs left the player alone but attacked the player's thralls, which are tamed and so in the Players faction. IsEnemy now gives a thrall the same truce through its m_commandingRace, broken by a grudge against any player. Covers every race with thralls. The Bound Bone Pile and the Bound Sentry seed drop m_groundPiece and m_groundOnly, so both can be built on floors and foundations. --- .../Factions/FactionHostilityPatch.cs | 31 ++ JotunnModStub/Skeleton/SkeletonBonePile.cs | 6 +- JotunnModStub/Skeleton/SkeletonPatches.cs | 6 + JotunnModStub/Skeleton/SkeletonRise.cs | 278 ++++++++++++++++++ JotunnModStub/Skeleton/SkeletonSentry.cs | 6 +- JotunnModStub/ZdoVisualSync.cs | 1 + 6 files changed, 324 insertions(+), 4 deletions(-) create mode 100644 JotunnModStub/Skeleton/SkeletonRise.cs diff --git a/JotunnModStub/Factions/FactionHostilityPatch.cs b/JotunnModStub/Factions/FactionHostilityPatch.cs index c171a84..f8f873f 100644 --- a/JotunnModStub/Factions/FactionHostilityPatch.cs +++ b/JotunnModStub/Factions/FactionHostilityPatch.cs @@ -126,12 +126,43 @@ namespace RacesOfValheim return player.m_customData.TryGetValue("Race", out string race) ? race : null; } + // The truce used to cover the player only. A thrall is tamed, so it sits in the Players + // faction, and a wild mob of the player's own faction still saw it as fair game: a wild + // Rancid Remains walked up to a Skeleton's bone pile, ignored the Skeleton and tore into + // the garrison. The thrall's own race is on the prefab (m_commandingRace), so the same + // faction sets answer for it without needing its owner nearby. + // + // The truce breaks the moment that wild mob holds a grudge against any player: it is + // fighting the thralls' master, and the thralls should fight back. + private static bool IsThrallTruce(Character thrallSide, Character wildSide) + { + if (wildSide.IsPlayer() || wildSide.IsTamed()) return false; + + RaisedThrall thrall = thrallSide.GetComponent(); + if (thrall == null || string.IsNullOrEmpty(thrall.m_commandingRace)) return false; + if (wildSide.GetComponent() != null) return false; + + if (!IsAlliedMob(thrall.m_commandingRace, wildSide.gameObject.name)) return false; + + foreach (Player player in Player.GetAllPlayers()) + { + if (RaceGrudge.Holds(wildSide, player)) return false; + } + return true; + } + public static void Postfix(Character a, Character b, ref bool __result) { if (!FactionsConfig.Hostility) return; if (!__result) return; // already not enemies, nothing to add if (a == null || b == null) return; + if (IsThrallTruce(a, b) || IsThrallTruce(b, a)) + { + __result = false; + return; + } + Character playerCharacter = a.IsPlayer() ? a : (b.IsPlayer() ? b : null); Character monster = a.IsPlayer() ? b : (b.IsPlayer() ? a : null); if (!(playerCharacter is Player p) || monster == null) return; diff --git a/JotunnModStub/Skeleton/SkeletonBonePile.cs b/JotunnModStub/Skeleton/SkeletonBonePile.cs index 9c6d6c1..af65819 100644 --- a/JotunnModStub/Skeleton/SkeletonBonePile.cs +++ b/JotunnModStub/Skeleton/SkeletonBonePile.cs @@ -326,8 +326,10 @@ namespace RacesOfValheim piece.m_resources = new Piece.Requirement[0]; piece.m_name = PieceDisplayName; piece.m_canBeRemoved = true; - piece.m_groundPiece = true; - piece.m_groundOnly = true; + // Neither flag: a garrison belongs inside the house as much as outside it, so the pile + // goes on floors and foundations too, not only on terrain. + piece.m_groundPiece = false; + piece.m_groundOnly = false; piece.m_icon = BorrowIcon("TrophySkeleton"); // A Piece added to world scenery is born with no icon and no place effect - the Furling's diff --git a/JotunnModStub/Skeleton/SkeletonPatches.cs b/JotunnModStub/Skeleton/SkeletonPatches.cs index e28239a..b977f35 100644 --- a/JotunnModStub/Skeleton/SkeletonPatches.cs +++ b/JotunnModStub/Skeleton/SkeletonPatches.cs @@ -613,6 +613,9 @@ namespace RacesOfValheim 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) { @@ -633,6 +636,9 @@ namespace RacesOfValheim 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 } diff --git a/JotunnModStub/Skeleton/SkeletonRise.cs b/JotunnModStub/Skeleton/SkeletonRise.cs new file mode 100644 index 0000000..d44cd75 --- /dev/null +++ b/JotunnModStub/Skeleton/SkeletonRise.cs @@ -0,0 +1,278 @@ +using System; +using System.Collections.Generic; +using HarmonyLib; +using Jotunn.Managers; +using UnityEngine; +using Object = UnityEngine.Object; + +namespace RacesOfValheim +{ + /// + /// The Skeleton's auto-resurrection, played as the crypt rise: the body climbs out of the ground + /// instead of simply staying on its feet. + /// + /// The player cannot play that clip itself. A Skeleton player is the human rig wearing a + /// skeleton's meshes (see VisEquipment_UpdateVisuals_Patch), and the human controller has no + /// rise state - "wakeup" lives in the skeleton creature's own controller. So for the few seconds + /// of the rise the player's Visual is hidden and a costume is worn in its place: the creature's + /// animated model, stripped down to renderers and its Animator, with the same "wakeup" bool set + /// that vanilla's CreatureSpawner sets on a Spawner_Skeleton_rise skeleton. + /// + /// The start time goes on the ZDO, so every client that can see this player plays the same rise. + /// While it runs the local player takes no damage and does not move: they are half in the ground. + /// + public static class SkeletonRise + { + public const string ZdoKey = "RoV_skelRiseAt"; + + // How long after the start a client that only just noticed the key still bothers to play it. + // A player who walks into view a minute later should not see a resurrection replayed. + private const float RemoteLateStartSeconds = 2f; + + private const float FallbackSeconds = 3f; + private const float MaxSeconds = 6f; + + // Clips that look like a rise, by name. Matched loosely and logged once, so a wrong pick + // shows up in the log with every clip the controller actually has. + private static readonly string[] RiseClipWords = { "wake", "rise", "spawn", "getup", "emerge" }; + + private static readonly Dictionary templates = new Dictionary(); + private static readonly Dictionary riseSeconds = new Dictionary(); + + public static bool IsRising(Player player) + { + if (player == null) return false; + SkeletonRiseCostume costume = player.GetComponent(); + return costume != null && costume.IsPlaying; + } + + /// Starts the rise for the local player and tells everyone else. + public static void Begin(Player player) + { + if (player == null || ZNet.instance == null) return; + + long ticks = ZNet.instance.GetTime().Ticks; + ZNetView nview = player.GetComponent(); + if (nview != null && nview.IsValid()) nview.GetZDO().Set(ZdoKey, ticks); + + Play(player, ticks); + } + + /// For a remote player: plays a rise this client has not played yet, if it is fresh. + public static void CheckRemote(Player player) + { + if (player == null || ZNet.instance == null) return; + + ZNetView nview = player.GetComponent(); + if (nview == null || !nview.IsValid()) return; + + long ticks = nview.GetZDO().GetLong(ZdoKey, 0L); + if (ticks == 0L) return; + + SkeletonRiseCostume costume = player.GetComponent(); + if (costume != null && costume.StartedTicks == ticks) return; + + double age = (ZNet.instance.GetTime() - new DateTime(ticks)).TotalSeconds; + if (age < 0 || age > RemoteLateStartSeconds) + { + // Remember it anyway, so the age is not worked out again every frame. + if (costume == null) costume = player.gameObject.AddComponent(); + costume.StartedTicks = ticks; + return; + } + + Play(player, ticks); + } + + private static void Play(Player player, long ticks) + { + string model = SkeletonVisuals.GetModel(player, SkeletonVisuals.GetProgressionState(player)); + GameObject template = GetTemplate(model); + if (template == null) return; + + SkeletonRiseCostume costume = player.GetComponent() + ?? player.gameObject.AddComponent(); + costume.StartedTicks = ticks; + costume.Play(template, riseSeconds.TryGetValue(model, out float seconds) ? seconds : FallbackSeconds); + } + + /// + /// The creature's animated model, stripped once per model name. Built into an inactive + /// holder, so nothing on the copy wakes before the strip - the rule ModelBorrow exists for. + /// + private static GameObject GetTemplate(string modelPrefab) + { + if (templates.TryGetValue(modelPrefab, out GameObject cached)) return cached; + templates[modelPrefab] = null; + + GameObject source = PrefabManager.Cache.GetPrefab(modelPrefab); + Animator sourceAnim = source != null ? source.GetComponentInChildren(true) : null; + if (sourceAnim == null) + { + Jotunn.Logger.LogWarning($"[Skeleton] Rise: no animated model on '{modelPrefab}'; the resurrection plays without the rise."); + return null; + } + + GameObject holder = new GameObject("SkeletonRiseTemplate_" + modelPrefab); + Object.DontDestroyOnLoad(holder); + holder.SetActive(false); // BEFORE Instantiate: nothing on the copy gets to Awake. + + GameObject copy = Object.Instantiate(sourceAnim.gameObject, holder.transform); + copy.name = "model"; + copy.transform.localPosition = sourceAnim.transform.localPosition; + copy.transform.localRotation = sourceAnim.transform.localRotation; + copy.transform.localScale = sourceAnim.transform.localScale; + + // Everything that is not a Renderer, a Transform or the Animator. Animator is a Behaviour, + // not a MonoBehaviour, so the first loop never touches it. + foreach (MonoBehaviour behaviour in copy.GetComponentsInChildren(true)) + { + if (behaviour != null) Object.DestroyImmediate(behaviour); + } + foreach (Collider collider in copy.GetComponentsInChildren(true)) + { + if (collider != null) Object.DestroyImmediate(collider); + } + foreach (Rigidbody body in copy.GetComponentsInChildren(true)) + { + if (body != null) Object.DestroyImmediate(body); + } + + riseSeconds[modelPrefab] = MeasureRise(sourceAnim, modelPrefab); + templates[modelPrefab] = copy; + return copy; + } + + private static float MeasureRise(Animator animator, string modelPrefab) + { + RuntimeAnimatorController controller = animator.runtimeAnimatorController; + if (controller == null) return FallbackSeconds; + + AnimationClip best = null; + List names = new List(); + foreach (AnimationClip clip in controller.animationClips) + { + if (clip == null) continue; + names.Add($"{clip.name} ({clip.length:0.00}s)"); + + string lower = clip.name.ToLower(); + foreach (string word in RiseClipWords) + { + if (!lower.Contains(word)) continue; + if (best == null || clip.length > best.length) best = clip; + break; + } + } + + float seconds = best != null ? Mathf.Clamp(best.length, 1f, MaxSeconds) : FallbackSeconds; + Jotunn.Logger.LogInfo( + $"[Skeleton] Rise on '{modelPrefab}': clip '{(best != null ? best.name : "none, fallback")}', {seconds:0.00}s. " + + $"Clips: {string.Join(", ", names.ToArray())}"); + return seconds; + } + } + + /// The worn costume for one rise. Lives on the player and is reused for the next one. + public class SkeletonRiseCostume : MonoBehaviour + { + private const string HiderContext = "skeleton-rise"; + + public long StartedTicks; + + private Player m_player; + private GameObject m_model; + private float m_endsAt; + + public bool IsPlaying => m_model != null; + + public void Play(GameObject template, float seconds) + { + m_player = GetComponent(); + End(); + + m_model = Instantiate(template, transform); + m_model.name = "SkeletonRiseCostume"; + m_model.transform.localPosition = template.transform.localPosition; + m_model.transform.localRotation = template.transform.localRotation; + m_model.transform.localScale = template.transform.localScale; + + Animator anim = m_model.GetComponentInChildren(); + if (anim != null) + { + // Same settings the other borrowed costumes use: the clip must not walk the model off + // its wearer, its events have no receivers left, and it keeps animating close to the + // camera. + anim.applyRootMotion = false; + anim.fireEvents = false; + anim.cullingMode = AnimatorCullingMode.AlwaysAnimate; + + bool hasWakeup = false; + foreach (AnimatorControllerParameter param in anim.parameters) + { + if (param.type == AnimatorControllerParameterType.Bool && param.name == "wakeup") hasWakeup = true; + } + + if (hasWakeup) + { + anim.SetBool("wakeup", true); + // Settle into the rise now, so the first rendered frame is not a standing skeleton. + anim.Update(0f); + anim.Update(0f); + } + else + { + Jotunn.Logger.LogWarning("[Skeleton] Rise: the model's Animator has no 'wakeup' bool; it will stand instead of rising."); + } + } + + PlayerVisualHider.Hide(transform.Find("Visual"), HiderContext); + m_endsAt = Time.time + seconds; + } + + private void Update() + { + if (m_model == null) return; + if (Time.time >= m_endsAt || m_player == null || m_player.IsDead()) End(); + } + + private void End() + { + if (m_model == null) return; + + // Switched off first: Destroy waits for the end of the frame, and nothing on the costume + // should run in between. + m_model.SetActive(false); + Destroy(m_model); + m_model = null; + + PlayerVisualHider.Show(transform.Find("Visual"), HiderContext); + } + + private void OnDestroy() => End(); + } + + /// + /// Holds the local player still while they climb out. The movement direction is bound by + /// position, not name: it is the first argument of Player.SetControls. + /// + [HarmonyPatch(typeof(Player), "SetControls")] + public static class SkeletonRiseControlsPatch + { + public static void Prefix(Player __instance, ref Vector3 __0, + ref bool attack, ref bool attackHold, + ref bool secondaryAttack, ref bool secondaryAttackHold, + ref bool jump, ref bool crouch, ref bool dodge) + { + if (__instance != Player.m_localPlayer || !SkeletonRise.IsRising(__instance)) return; + + __0 = Vector3.zero; + attack = false; + attackHold = false; + secondaryAttack = false; + secondaryAttackHold = false; + jump = false; + crouch = false; + dodge = false; + } + } +} diff --git a/JotunnModStub/Skeleton/SkeletonSentry.cs b/JotunnModStub/Skeleton/SkeletonSentry.cs index dd96949..93137e5 100644 --- a/JotunnModStub/Skeleton/SkeletonSentry.cs +++ b/JotunnModStub/Skeleton/SkeletonSentry.cs @@ -150,8 +150,10 @@ namespace RacesOfValheim piece.m_resources = new Piece.Requirement[0]; piece.m_name = DisplayName; piece.m_canBeRemoved = true; - piece.m_groundPiece = true; - piece.m_groundOnly = true; + // Neither flag: a sentry is meant to stand on a wall walk or a floor as much as on the + // ground outside it. + piece.m_groundPiece = false; + piece.m_groundOnly = false; piece.m_icon = BorrowIcon("TrophySkeleton"); PieceManager.Instance.AddPiece(new CustomPiece(prefab, fixReference: false, new PieceConfig diff --git a/JotunnModStub/ZdoVisualSync.cs b/JotunnModStub/ZdoVisualSync.cs index 15fd55a..0df6988 100644 --- a/JotunnModStub/ZdoVisualSync.cs +++ b/JotunnModStub/ZdoVisualSync.cs @@ -65,6 +65,7 @@ namespace RacesOfValheim if (race == "Skeleton") { UpdateSkeletonVisuals(); + SkeletonRise.CheckRemote(m_player); } else if (race == "Fenrir") { From 68cdbd6de6f967bc15373aa04fe3c37e397e8349 Mon Sep 17 00:00:00 2001 From: kanym Date: Wed, 7 Oct 2026 04:11:08 +0200 Subject: [PATCH 015/176] chore(release): v1.5.8 - Skeleton rise, truce for bound troops README: the New in block is v1.5.8 only, a changelog entry for the three fixes, and the Skeleton stations line says the pile and the Sentry go on floors too. --- JotunnModStub/Package/manifest.json | 2 +- JotunnModStub/RacesOfValheim.cs | 2 +- README.md | 11 ++++++++--- manifest.json | 2 +- 4 files changed, 11 insertions(+), 6 deletions(-) diff --git a/JotunnModStub/Package/manifest.json b/JotunnModStub/Package/manifest.json index 6791a68..4c2b199 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.5.7", + "version_number": "1.5.8", "website_url": "", "dependencies": [ "denikson-BepInExPack_Valheim-5.4.2333", diff --git a/JotunnModStub/RacesOfValheim.cs b/JotunnModStub/RacesOfValheim.cs index c530409..4e14cc4 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.5.7"; + public const string PluginVersion = "1.5.8"; private readonly Harmony harmony = new Harmony(PluginGUID); diff --git a/README.md b/README.md index f396ea9..cc27003 100644 --- a/README.md +++ b/README.md @@ -15,9 +15,9 @@ Support the mod: [Patreon — NandorTheModder](https://www.patreon.com/c/NandorT --- -## New in v1.5.7 +## New in v1.5.8 -Bone Ships: every vanilla ship but the Raft now has a bone version, rowed by skeletons and crewed from an Offering Chest on deck. The mod is also translated into Russian. Full details under [Bone Ships](#bone-ships) and in the [changelog](#v157). +Three Skeleton fixes. The Yagluth auto-resurrect now plays the crypt rise, so you climb out of the ground instead of staying on your feet. Wild creatures of your faction no longer attack your bound skeletons. The Bound Bone Pile and the Bound Sentry can be built on floors and foundations, not only on the ground. Full details in the [changelog](#v158). --- @@ -297,7 +297,7 @@ Every race has a buildable station of its own, gated by a reagent bought from it - **Draugh — Cursed Body Pile:** eats raw flesh and answers with tamed draugr; Draugr and Elite trophies are worth a whole batch. Anyone can build it, but only a Draugh gives the draugr orders — for everyone else it is a grave that defends its own ten meters. - **Furling — Five crops:** Copper, Tin and Iron Flax grow metal out of poisoned soil; Stoneberry and Flintberry bushes give stone and flint. - **Skadi — Crystal Golem & Bone Cook:** a stonecutter-bound guardian on a leash. Skadi (and Trol) may also build inside any troll cave in the world. The Cook is Skadi's own half of the [Bone Servants](#skeleton--skadi--bone-servants). -- **Skeleton — Bound Bone Pile, Bound Sentry & Bone Smith:** pay once per slot and that slot refills itself forever, because an army you re-buy after every fight is one nobody takes out of the house. The Sentry is a bound archer that cannot walk, regenerates when left alone, and hands its parts back when it falls. The Smith is Skeleton and Skadi's shared half of the [Bone Servants](#skeleton--skadi--bone-servants). +- **Skeleton — Bound Bone Pile, Bound Sentry & Bone Smith:** pay once per slot and that slot refills itself forever, because an army you re-buy after every fight is one nobody takes out of the house. Both the pile and the Sentry can be built on the ground, on floors and on foundations. The Sentry is a bound archer that cannot walk, regenerates when left alone, and hands its parts back when it falls. The Smith is Skeleton and Skadi's shared half of the [Bone Servants](#skeleton--skadi--bone-servants). - **Sverm — Brood Mound & Hive Market:** see [The Colony](#race-progressions-level-by-level). - **Trenta — Composter, Heartwood Grove & Root of the Elder:** the Composter rots raw flesh into Fertilizer, which grows any plant on the spot. The Grove is a tree that fertilises what surrounds it, stings what approaches it, and fills a chest with honey. The Root is one of the Elder's own summoned roots, planted for good: it knits its own wounds shut, and once a minute it repairs every player-built thing within five meters of it — anyone's, not just the Trenta's. Race locked, and only after the Elder falls. - **Trol — War Totem:** hires warbands of trolls and greydwarves for coin. Race locked — the hammer refuses it to anyone who is not a Trol. A dead warband is money spent. @@ -447,6 +447,11 @@ Both halves have an off switch under `Factions` in Configuration Manager: **Fact ## Changelog +### v1.5.8 +- **Fix - Skeleton auto-resurrect played no rise:** coming back from a lethal hit, the Skeleton stayed on its feet. It now climbs out of the ground like a crypt skeleton, and every player nearby sees it. You take no damage and cannot move or attack until you are out. +- **Fix - wild faction creatures attacked bound troops:** the faction truce covered the player but not the player's troops, so a wild Rancid Remains left a Skeleton alone and tore into the garrison of its bone pile. Wild creatures of a race's faction now leave that race's troops alone too, for every race that has them. Hit one of those creatures and the truce ends: it fights you, and your troops fight it. +- **Change - Bound Bone Pile and Bound Sentry:** both can now be built on floors and foundations, not only on the ground. + ### v1.5.7 - **New - Bone Ships:** a bone version of the Karve, the Longship and the Ashlands Drakkar, built with the Hammer by any race. Skeletons row them, so they need no wind, and an Offering Chest on deck buys the crew with bone fragments, like the bone pile. The crew comes ashore as tame skeletons when you land. See [Bone Ships](#bone-ships). - **New - Russian translation:** every text in the mod, by Rudra and Axibed. Boss and creature names follow Valheim's own Russian. diff --git a/manifest.json b/manifest.json index 6791a68..4c2b199 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.5.7", + "version_number": "1.5.8", "website_url": "", "dependencies": [ "denikson-BepInExPack_Valheim-5.4.2333", From 0159f1e8c41a0a19e65fefb6397fbbb21699509f Mon Sep 17 00:00:00 2001 From: Ferdinando Date: Wed, 7 Oct 2026 17:31:29 +0200 Subject: [PATCH 016/176] bugfix 07/10/26 + evil laugh --- JotunnModStub/Aswid/AswidPatches.cs | 27 ++ JotunnModStub/Fenrir/FenrirPatches.cs | 26 ++ JotunnModStub/Furling/FurlingPatches.cs | 6 +- JotunnModStub/Package/manifest.json | 2 +- JotunnModStub/RacesOfValheim.cs | 3 +- JotunnModStub/Skadi/SkadiPatches.cs | 26 ++ JotunnModStub/Skeleton/SkeletonEvilLaugh.cs | 294 ++++++++++++++++++++ JotunnModStub/Skeleton/SkeletonPatches.cs | 6 + JotunnModStub/Sverm/SvermRavagerForm.cs | 24 ++ README.md | 9 +- manifest.json | 2 +- 11 files changed, 417 insertions(+), 8 deletions(-) create mode 100644 JotunnModStub/Skeleton/SkeletonEvilLaugh.cs diff --git a/JotunnModStub/Aswid/AswidPatches.cs b/JotunnModStub/Aswid/AswidPatches.cs index e2bb353..6931d80 100644 --- a/JotunnModStub/Aswid/AswidPatches.cs +++ b/JotunnModStub/Aswid/AswidPatches.cs @@ -239,6 +239,33 @@ namespace RacesOfValheim } } + /// + /// Bat and mist form shut the rest of the human's attack loop as well as StartAttack: crossbow + /// reload and draw live in PlayerAttackInput, and the form's Animator fires the held attack + /// through OnAttackTrigger. See Fenrir's BlockPlayerAttackInputPatch. + /// + public static class AswidFormAttackLoop + { + public static bool InForm(Humanoid player) + { + if (player != Player.m_localPlayer) return false; + return player.GetComponentInChildren() != null + || player.GetSEMan().HaveStatusEffect("SE_MistForm".GetStableHashCode()); + } + } + + [HarmonyPatch(typeof(Player), "PlayerAttackInput")] + public static class Aswid_BlockAttackInput_Patch + { + public static bool Prefix(Player __instance) => !AswidFormAttackLoop.InForm(__instance); + } + + [HarmonyPatch(typeof(Humanoid), nameof(Humanoid.OnAttackTrigger))] + public static class Aswid_BlockAttackTrigger_Patch + { + public static bool Prefix(Humanoid __instance) => !AswidFormAttackLoop.InForm(__instance); + } + [HarmonyPatch(typeof(Character), "SetRun")] public static class Aswid_Run_Patch { diff --git a/JotunnModStub/Fenrir/FenrirPatches.cs b/JotunnModStub/Fenrir/FenrirPatches.cs index ccb2fdf..4b91b46 100644 --- a/JotunnModStub/Fenrir/FenrirPatches.cs +++ b/JotunnModStub/Fenrir/FenrirPatches.cs @@ -34,6 +34,32 @@ namespace RacesOfValheim } } + /// + /// The rest of the human's attack loop, shut while a form is up. StartAttack is the only door an + /// attack starts through and it is blocked above, but a crossbow also lives in the loop around it: + /// PlayerAttackInput reloads it and holds its draw, and the form's own Animator carries + /// CharacterAnimEvent, whose OnAttackTrigger event resolves to the PLAYER (its Character is the first + /// one up the hierarchy) and fires whatever attack the human still has in hand. A tester's crossbow + /// shot on all three form attacks, reloaded for free, like a semi-automatic. + /// + [HarmonyPatch(typeof(Player), "PlayerAttackInput")] + public static class BlockPlayerAttackInputPatch + { + public static bool Prefix(Player __instance) + { + return !FenrirForms.LocalInForm(__instance); + } + } + + [HarmonyPatch(typeof(Humanoid), nameof(Humanoid.OnAttackTrigger))] + public static class BlockPlayerAttackTriggerPatch + { + public static bool Prefix(Humanoid __instance) + { + return !FenrirForms.LocalInForm(__instance); + } + } + // --- PATCH 2: BLOCCO ANIMAZIONI ED EFFETTI SONORI NATIVI --- // Every form now, not the Fenring alone: see BlockPlayerLogicAttackPatch. [HarmonyPatch(typeof(ZSyncAnimation), nameof(ZSyncAnimation.SetTrigger))] diff --git a/JotunnModStub/Furling/FurlingPatches.cs b/JotunnModStub/Furling/FurlingPatches.cs index ce998f9..01bb0d3 100644 --- a/JotunnModStub/Furling/FurlingPatches.cs +++ b/JotunnModStub/Furling/FurlingPatches.cs @@ -402,9 +402,9 @@ namespace RacesOfValheim { if (BossProgressionManager.GetCurrentProgressionState() >= 3) // The Wickerman (Elder) { - // Check if it's an arrow (either by skill or by checking if a bow/ammo was used) - if ((hitData != null && hitData.m_skill == Skills.SkillType.Bows) || - (ammo != null && ammo.m_shared.m_skillType == Skills.SkillType.Bows)) + // Check if it's an arrow or a bolt (either by skill or by checking if a bow/crossbow/ammo was used) + if ((hitData != null && (hitData.m_skill == Skills.SkillType.Bows || hitData.m_skill == Skills.SkillType.Crossbows)) || + (ammo != null && (ammo.m_shared.m_skillType == Skills.SkillType.Bows || ammo.m_shared.m_skillType == Skills.SkillType.Crossbows))) { // If the arrow doesn't already have significant fire damage, add it if (hitData != null && hitData.m_damage.m_fire < 22f) diff --git a/JotunnModStub/Package/manifest.json b/JotunnModStub/Package/manifest.json index 4c2b199..8b25e6f 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.5.8", + "version_number": "1.5.9", "website_url": "", "dependencies": [ "denikson-BepInExPack_Valheim-5.4.2333", diff --git a/JotunnModStub/RacesOfValheim.cs b/JotunnModStub/RacesOfValheim.cs index 4e14cc4..fe1cebb 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.5.8"; + public const string PluginVersion = "1.5.9"; private readonly Harmony harmony = new Harmony(PluginGUID); @@ -80,6 +80,7 @@ namespace RacesOfValheim CommandManager.Instance.AddConsoleCommand(new DumpPotionsCommand()); CommandManager.Instance.AddConsoleCommand(new ListPrefabsCommand()); CommandManager.Instance.AddConsoleCommand(new DumpAnimCommand()); + CommandManager.Instance.AddConsoleCommand(new EvilLaughCommand()); } /// diff --git a/JotunnModStub/Skadi/SkadiPatches.cs b/JotunnModStub/Skadi/SkadiPatches.cs index 2979b84..a2aecb0 100644 --- a/JotunnModStub/Skadi/SkadiPatches.cs +++ b/JotunnModStub/Skadi/SkadiPatches.cs @@ -601,4 +601,30 @@ namespace RacesOfValheim return true; } } + + /// + /// The rest of the human's attack loop, shut while a dragon form is up: crossbow reload and draw + /// live in PlayerAttackInput, and the form's Animator fires the held attack through + /// OnAttackTrigger. Without these a crossbow in hand shot on every form attack. See Fenrir's + /// BlockPlayerAttackInputPatch. + /// + [HarmonyPatch(typeof(Player), "PlayerAttackInput")] + public static class SkadiBlockAttackInputPatch + { + public static bool Prefix(Player __instance) + { + if (__instance != Player.m_localPlayer) return true; + return __instance.GetComponentInChildren() == null; + } + } + + [HarmonyPatch(typeof(Humanoid), nameof(Humanoid.OnAttackTrigger))] + public static class SkadiBlockAttackTriggerPatch + { + public static bool Prefix(Humanoid __instance) + { + if (__instance != Player.m_localPlayer) return true; + return __instance.GetComponentInChildren() == null; + } + } } diff --git a/JotunnModStub/Skeleton/SkeletonEvilLaugh.cs b/JotunnModStub/Skeleton/SkeletonEvilLaugh.cs new file mode 100644 index 0000000..e981c81 --- /dev/null +++ b/JotunnModStub/Skeleton/SkeletonEvilLaugh.cs @@ -0,0 +1,294 @@ +using System; +using System.Collections.Generic; +using Jotunn.Entities; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// The Skeleton's villain laugh: /evillaugh. Head thrown back, jaw clacking, shoulders + /// shaking, both fists punched up into the air. + /// + /// It is not an animation clip and it is not the vanilla 'laugh' emote. It is a pose written + /// over the rig in LateUpdate, the way SkeletonJawFix does for the mandible, so it needs no + /// asset bundle and no Animator parameter. + /// + /// The start time goes on the player's ZDO, so every client that can see the Skeleton plays + /// the same laugh - the command only has to run on the laughing player's own machine. + /// + /// Two kinds of bone, two rules (see SkeletonJawFix for why it matters): + /// - Bones the Animator rewrites every frame (head, chest, arms) get the pose multiplied on + /// top of whatever the animation left, so it can never accumulate. + /// - Bones nothing animates (the jaw, the fingers) are written ABSOLUTELY from the rest + /// pose captured once, so the pose is the same however many frames it has been applied. + /// + /// Every direction is worked out in the player's own frame (right / up / forward) rather than + /// in a bone's local axes, which the rig does not make guessable. The angles below are first + /// guesses to be tuned in game. + /// + public class SkeletonEvilLaugh : MonoBehaviour + { + public const string ZdoKey = "RoV_skelEvilLaughAt"; + + private const float DurationSeconds = 4f; + private const float BlendSeconds = 0.3f; + + // The laugh itself: how fast the shoulders shake and the jaw clacks, per second. + private const float ShakeHz = 8f; + + private const float HeadBackDegrees = 28f; + private const float NeckBackDegrees = 8f; + private const float ChestBackDegrees = 10f; + private const float ChestShakeDegrees = 3.5f; + private const float HeadNodDegrees = 4f; + private const float JawOpenDegrees = 24f; + + // Fingers curl about the bone's own Z, the usual axis of a humanoid finger. If the fists + // open instead of closing in game, flip the sign. + private const float FingerCurlDegrees = 70f; + + // Where the fists go, in the player's frame: outward, up, a little forward. + private static readonly Vector3 UpperArmAim = new Vector3(0.5f, 0.8f, 0.25f); + private static readonly Vector3 ForearmAim = new Vector3(0.15f, 1f, 0.1f); + + private struct Side + { + public Transform upper, lower, hand; + public float sign; + public List fingers; + public List fingerRest; + } + + private Player m_player; + private VisEquipment m_vis; + private ZNetView m_nview; + + private bool m_resolved; + private Transform m_head, m_neck, m_chest, m_jaw; + private Quaternion m_jawRest; + private Side m_left, m_right; + + private float m_weight; + private bool m_wroteHands; + + // ── Starting it ────────────────────────────────────────────────────── + + /// Starts the laugh for the local player; everyone else picks it up from the ZDO. + public static bool Begin(Player player) + { + if (player == null || ZNet.instance == null) return false; + if (!SkeletonVisuals.IsSkeletonPlayer(player)) return false; + + ZNetView nview = player.GetComponent(); + if (nview == null || !nview.IsValid()) return false; + + nview.GetZDO().Set(ZdoKey, ZNet.instance.GetTime().Ticks); + return true; + } + + private void Awake() + { + m_player = GetComponent(); + m_vis = GetComponent(); + m_nview = GetComponent(); + } + + // ── The pose ───────────────────────────────────────────────────────── + + private void LateUpdate() + { + if (m_player == null || m_nview == null || !m_nview.IsValid() || ZNet.instance == null) return; + + float elapsed = ElapsedSinceStart(); + bool laughing = elapsed >= 0f && elapsed < DurationSeconds + && SkeletonVisuals.IsSkeletonPlayer(m_player) + && !m_player.IsDead(); + + // Fade in over the first moments, out over the last, so the pose never pops. + float target = 0f; + if (laughing) target = Mathf.Clamp01(Mathf.Min(elapsed, DurationSeconds - elapsed) / BlendSeconds); + + m_weight = Mathf.MoveTowards(m_weight, target, Time.deltaTime / BlendSeconds); + + if (m_weight <= 0f) + { + if (m_wroteHands) RestoreHands(); + return; + } + + if (!m_resolved) Resolve(); + + float t = Time.time; + float wave = Mathf.Sin(t * ShakeHz * Mathf.PI * 2f); + float open = 0.5f + 0.5f * Mathf.Sin(t * ShakeHz * Mathf.PI * 2f + 0.6f); + + Vector3 right = m_player.transform.right; + + // Back and up, the whole spine in on it: chest first, then neck, then head. + Pitch(m_chest, -(ChestBackDegrees + ChestShakeDegrees * wave) * m_weight, right); + Pitch(m_neck, -NeckBackDegrees * m_weight, right); + Pitch(m_head, -(HeadBackDegrees + HeadNodDegrees * wave) * m_weight, right); + + if (m_jaw != null && m_jaw.parent != null) + { + m_jaw.localRotation = m_jawRest; + m_jaw.rotation = Quaternion.AngleAxis(JawOpenDegrees * open * m_weight, right) * m_jaw.rotation; + } + + Fists(m_left, wave); + Fists(m_right, wave); + m_wroteHands = true; + } + + /// Seconds since the laugh began, by the same clock on every client; -1 if there is none. + private float ElapsedSinceStart() + { + long ticks = m_nview.GetZDO().GetLong(ZdoKey, 0L); + if (ticks == 0L) return -1f; + + double age = (ZNet.instance.GetTime() - new DateTime(ticks)).TotalSeconds; + return age < 0 ? -1f : (float)age; + } + + private static void Pitch(Transform bone, float degrees, Vector3 axis) + { + if (bone == null) return; + bone.rotation = Quaternion.AngleAxis(degrees, axis) * bone.rotation; + } + + private void Fists(Side side, float wave) + { + if (side.upper == null || side.lower == null || side.hand == null) return; + + Vector3 right = m_player.transform.right; + Vector3 up = Vector3.up; + Vector3 fwd = m_player.transform.forward; + + // Each fist punches up and down a little with the laugh. + Vector3 pump = up * (0.12f * wave); + + Aim(side.upper, side.lower, Frame(UpperArmAim, side.sign, right, up, fwd) + pump); + Aim(side.lower, side.hand, Frame(ForearmAim, -side.sign, right, up, fwd) + pump); + + if (side.fingers == null) return; + + for (int i = 0; i < side.fingers.Count; i++) + { + Transform finger = side.fingers[i]; + if (finger == null) continue; + finger.localRotation = side.fingerRest[i] + * Quaternion.Euler(0f, 0f, FingerCurlDegrees * m_weight); + } + } + + private static Vector3 Frame(Vector3 aim, float sideSign, Vector3 right, Vector3 up, Vector3 fwd) + => (right * (aim.x * sideSign) + up * aim.y + fwd * aim.z).normalized; + + /// + /// Turns a bone so the line from it to its child points along 'desired', by as much as the + /// weight allows. The child follows the parent, so the forearm is aimed after the upper arm. + /// + private void Aim(Transform bone, Transform child, Vector3 desired) + { + Vector3 current = child.position - bone.position; + if (current.sqrMagnitude < 1e-8f) return; + + Quaternion full = Quaternion.FromToRotation(current.normalized, desired.normalized); + bone.rotation = Quaternion.Slerp(Quaternion.identity, full, m_weight) * bone.rotation; + } + + private void RestoreHands() + { + foreach (Side side in new[] { m_left, m_right }) + { + if (side.fingers == null) continue; + for (int i = 0; i < side.fingers.Count; i++) + if (side.fingers[i] != null) side.fingers[i].localRotation = side.fingerRest[i]; + } + + if (m_jaw != null) m_jaw.localRotation = m_jawRest; + m_wroteHands = false; + } + + // ── Finding the bones ──────────────────────────────────────────────── + + private void Resolve() + { + Animator anim = m_player.GetComponentInChildren(); + + m_head = Find(anim, HumanBodyBones.Head, "head"); + m_neck = Find(anim, HumanBodyBones.Neck, "neck"); + m_chest = Find(anim, HumanBodyBones.UpperChest, "spine2") ?? Find(anim, HumanBodyBones.Chest, "spine1"); + + m_jaw = FindByName("jaw"); + if (m_jaw != null) m_jawRest = m_jaw.localRotation; + + m_left = BuildSide(anim, true); + m_right = BuildSide(anim, false); + + m_resolved = true; + } + + private Side BuildSide(Animator anim, bool left) + { + string prefix = left ? "left" : "right"; + Side side = new Side + { + sign = left ? -1f : 1f, + upper = Find(anim, left ? HumanBodyBones.LeftUpperArm : HumanBodyBones.RightUpperArm, prefix + "arm"), + lower = Find(anim, left ? HumanBodyBones.LeftLowerArm : HumanBodyBones.RightLowerArm, prefix + "forearm"), + hand = Find(anim, left ? HumanBodyBones.LeftHand : HumanBodyBones.RightHand, prefix + "hand"), + fingers = new List(), + fingerRest = new List() + }; + + // Every bone below the hand is a finger or a thumb; a hand with none just opens and + // closes nothing, and the arms still go up. + if (side.hand != null) + { + foreach (Transform child in side.hand.GetComponentsInChildren()) + { + if (child == side.hand) continue; + side.fingers.Add(child); + side.fingerRest.Add(child.localRotation); + } + } + + return side; + } + + private Transform Find(Animator anim, HumanBodyBones bone, string fallbackName) + { + Transform t = anim != null ? anim.GetBoneTransform(bone) : null; + return t != null ? t : FindByName(fallbackName); + } + + private Transform FindByName(string part) + { + if (m_vis == null || m_vis.m_bodyModel == null || m_vis.m_bodyModel.bones == null) return null; + + foreach (Transform bone in m_vis.m_bodyModel.bones) + if (bone != null && bone.name.ToLower().Contains(part)) return bone; + + return null; + } + } + + public class EvilLaughCommand : ConsoleCommand + { + public override string Name => "evillaugh"; + public override string Help => "The Skeleton's villain laugh"; + + public override void Run(string[] args) + { + if (Player.m_localPlayer == null) + { + Console.instance.Print("You must be in-game to laugh."); + return; + } + + if (!SkeletonEvilLaugh.Begin(Player.m_localPlayer)) + Console.instance.Print("Only a Skeleton laughs like that."); + } + } +} diff --git a/JotunnModStub/Skeleton/SkeletonPatches.cs b/JotunnModStub/Skeleton/SkeletonPatches.cs index b977f35..0937e37 100644 --- a/JotunnModStub/Skeleton/SkeletonPatches.cs +++ b/JotunnModStub/Skeleton/SkeletonPatches.cs @@ -359,6 +359,12 @@ namespace RacesOfValheim p.gameObject.AddComponent(); } + // The /evillaugh pose; same reasoning as the jaw, so remote players laugh too. + if (p.GetComponent() == null) + { + p.gameObject.AddComponent(); + } + // 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 diff --git a/JotunnModStub/Sverm/SvermRavagerForm.cs b/JotunnModStub/Sverm/SvermRavagerForm.cs index 91055b1..b0e6497 100644 --- a/JotunnModStub/Sverm/SvermRavagerForm.cs +++ b/JotunnModStub/Sverm/SvermRavagerForm.cs @@ -452,6 +452,30 @@ namespace RacesOfValheim } } + /// + /// The rest of the human's attack loop - crossbow reload and draw, and the animation event that + /// fires a held attack - shut for the form too. See Fenrir's BlockPlayerAttackInputPatch. + /// + [HarmonyPatch(typeof(Player), "PlayerAttackInput")] + public static class Sverm_RavagerBlockAttackInput_Patch + { + public static bool Prefix(Player __instance) + { + if (__instance != Player.m_localPlayer) return true; + return !IsActive; + } + } + + [HarmonyPatch(typeof(Humanoid), nameof(Humanoid.OnAttackTrigger))] + public static class Sverm_RavagerBlockAttackTrigger_Patch + { + public static bool Prefix(Humanoid __instance) + { + if (__instance != Player.m_localPlayer) return true; + return !IsActive; + } + } + /// No food, no mead, no potions. The form is meant to be survived, not sustained. [HarmonyPatch(typeof(Humanoid), "UseItem")] public static class Sverm_RavagerUseItem_Patch diff --git a/README.md b/README.md index cc27003..39865d8 100644 --- a/README.md +++ b/README.md @@ -15,9 +15,9 @@ Support the mod: [Patreon — NandorTheModder](https://www.patreon.com/c/NandorT --- -## New in v1.5.8 +## New in v1.5.9 -Three Skeleton fixes. The Yagluth auto-resurrect now plays the crypt rise, so you climb out of the ground instead of staying on your feet. Wild creatures of your faction no longer attack your bound skeletons. The Bound Bone Pile and the Bound Sentry can be built on floors and foundations, not only on the ground. Full details in the [changelog](#v158). +Skeletons can laugh: type /evillaugh. The Furling's fire bonus now covers crossbow bolts, and a crossbow in hand no longer fires on every attack while you are transformed. Full details in the [changelog](#v159). --- @@ -447,6 +447,11 @@ Both halves have an off switch under `Factions` in Configuration Manager: **Fact ## Changelog +### v1.5.9 +- **New - /evillaugh (Skeleton):** the Skeleton throws its head back, clacks its jaw, shakes its shoulders and punches both fists into the air for four seconds. Everyone nearby sees it. +- **Change - Furling fire bolts:** the Wickerman's fire damage now also applies to crossbow bolts, not only to arrows. +- **Fix - crossbow fired on every attack while transformed:** with a crossbow equipped, every attack of a form (left, right and middle mouse) shot the crossbow and reloaded it for free, like a semi-automatic. The human's attack loop is now shut while the form is up. Applies to the Fenrir forms, the Sverm Ravager, the Skadi dragon forms and the Aswid bat and mist forms. Thanks to the player who reported it. + ### v1.5.8 - **Fix - Skeleton auto-resurrect played no rise:** coming back from a lethal hit, the Skeleton stayed on its feet. It now climbs out of the ground like a crypt skeleton, and every player nearby sees it. You take no damage and cannot move or attack until you are out. - **Fix - wild faction creatures attacked bound troops:** the faction truce covered the player but not the player's troops, so a wild Rancid Remains left a Skeleton alone and tore into the garrison of its bone pile. Wild creatures of a race's faction now leave that race's troops alone too, for every race that has them. Hit one of those creatures and the truce ends: it fights you, and your troops fight it. diff --git a/manifest.json b/manifest.json index 4c2b199..8b25e6f 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.5.8", + "version_number": "1.5.9", "website_url": "", "dependencies": [ "denikson-BepInExPack_Valheim-5.4.2333", From 8bad4092bedd94ad6ebb462fa8dfed2b930d266e Mon Sep 17 00:00:00 2001 From: Axibed Date: Thu, 8 Oct 2026 07:45:13 +0200 Subject: [PATCH 017/176] =?UTF-8?q?=D0=9E=D0=B1=D0=BD=D0=BE=D0=B2=D0=B8?= =?UTF-8?q?=D1=82=D1=8C=20JotunnModStub/Translations/Russian/races.json?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit по канону Valheim Драуг - Драугр --- JotunnModStub/Translations/Russian/races.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/JotunnModStub/Translations/Russian/races.json b/JotunnModStub/Translations/Russian/races.json index eaf2ab2..e09b7f9 100644 --- a/JotunnModStub/Translations/Russian/races.json +++ b/JotunnModStub/Translations/Russian/races.json @@ -16,7 +16,7 @@ "rov_race_furling_desc": "Коварные гоблиноподобные создания. Невероятно ловкие и запасливые.", "rov_race_trol_name": "Тролль", "rov_race_trol_desc": "Обладает сокрушительной физической силой и возвышается над всеми. В ладах с обитателями Черного леса, однако огонь наносит Троллю на $1% больше урона, чем остальным.", - "rov_race_draugh_name": "Драуг", + "rov_race_draugh_name": "Драугр", "rov_race_draugh_desc": "Гниющий неупокоенный воин, движимый темной магией и яростью первобытной стали.", "rov_race_dvergar_name": "Дверг", "rov_race_dvergar_desc": "Низкорослые, упрямые кузнецы из подземных глубин. Физически хрупки, но не знают равных в металлургии, горном деле и торговле.", From c45ca80d99cfe9638d6f72a85b50aba6ff4fc040 Mon Sep 17 00:00:00 2001 From: Axibed Date: Thu, 8 Oct 2026 07:52:10 +0200 Subject: [PATCH 018/176] =?UTF-8?q?=D0=9E=D0=B1=D0=BD=D0=BE=D0=B2=D0=B8?= =?UTF-8?q?=D1=82=D1=8C=20JotunnModStub/Translations/Russian/compendium.js?= =?UTF-8?q?on?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Translations/Russian/compendium.json | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/JotunnModStub/Translations/Russian/compendium.json b/JotunnModStub/Translations/Russian/compendium.json index ac6eb7b..bc64748 100644 --- a/JotunnModStub/Translations/Russian/compendium.json +++ b/JotunnModStub/Translations/Russian/compendium.json @@ -5,7 +5,7 @@ "rov_compendium_aswid_bat_form_g_key_night": "[Награда: Эйктюр] Облик мыши (клавиша «G», только ночью): Примите облик летучей мыши.\n", "rov_compendium_aswid_bat_form_now_answers_by": "[Награда: Древний] Облик мыши теперь доступен как ночью, так и днем.\n", "rov_compendium_aswid_benedictus_et_afflictus": "[Базовое пассивное] Benedictus et Afflictus:", - "rov_compendium_aswid_claws_beast_s_grows_blackened": "[Базовое пассивное] Когти зверя ([K], $1 с): На ограниченное время отращивает черные когти вместо оружия. Удары кулаками наносят $2% от урона зрелых когтей (полностью режущий урон), и их сила растет с каждым поверженным боссом. Если достать меч — когти спрячутся, убрать его — вернутся, пока не истечет таймер. Не занимают ячейку экипировки. Их нельзя выбросить, передать или украсть, пока они активны. В облике мыши или тумана когти недоступны, так как у вас нет рук.\n", + "rov_compendium_aswid_claws_beast_s_grows_blackened": "[Базовое пассивное] Когти зверя ([K], $1 с): На ограниченное время отращивает черные когти вместо оружия. Удары кулаками наносят $2% от урона зрелых когтей (полностью рубящий урон), и их сила растет с каждым поверженным боссом. Если достать меч — когти спрячутся, убрать его — вернутся, пока не истечет таймер. Не занимают ячейку экипировки. Их нельзя выбросить, передать или украсть, пока они активны. В облике мыши или тумана когти недоступны, так как у вас нет рук.\n", "rov_compendium_aswid_dominate_native_interact_key": "[Награда: Яглут] Порабощение (клавиша взаимодействия):", "rov_compendium_aswid_eclipse_j_key_day_only": "[Награда: Яглут] Затмение (клавиша «J», только днем):", "rov_compendium_aswid_freezing_blood_passive": "[Награда: Матерь] Ледяная кровь (Пассивное):", @@ -24,15 +24,15 @@ "rov_compendium_aswid_transform_into_elusive_mist_become": "Вы превращаетесь в бесплотный туман. Вы получаете иммунитет к физическому (дробящий/рубящий/колющий) урону и яду, а также не получаете урона от падения, но не можете атаковать, бегать или прыгать. Вампирическая аура наносит удвоенный урон в этой форме. Восход солнца развеивает превращение.\n", "rov_compendium_aswid_vampiric_aura_passive_toggle": "Вампирическая аура (Пассивное, переключение на [I]):", "rov_compendium_aswid_weight_shadows_h_key_toggle": "[Награда: Королева] Weight of Shadows (клавиша «H», переключение):", - "rov_compendium_draugh_born_dead_buried_alive_take": "[Базовое пассивное] Born Dead, Buried Alive: Вы получаете на $1% меньше физического (дробящий/рубящий/колющий) урона, но урон от огня и духа бьет по вам на $2% больнее. Скелеты, драугры, призраки и духи больше не считают вас добычей. Ваше пищеварение адаптировалось к смерти, позволяя есть сырое и гнилое мясо (хвосты шеек, сырое мясо, потроха, кровь и т. д.) — обычная приготовленная еда и ягоды вызывают отвращение и не могут быть съедены.\n", - "rov_compendium_draugh_draugh_s_awakening": "Пробуждение Драуга\n", + "rov_compendium_draugh_born_dead_buried_alive_take": "[Базовое пассивное] Born Dead, Buried Alive: Вы получаете на $1% меньше физического (дробящий/рубящий/колющий) урона, но урон от огня и духа бьет по вам на $2% больнее. Скелеты, драугры, призраки и духи больше не считают вас добычей. Ваше пищеварение адаптировалось к смерти, позволяя есть сырое и гнилое мясо (хвосты никсов, сырое мясо, потроха, кровь и т. д.) — обычная приготовленная еда и ягоды вызывают отвращение и не могут быть съедены.\n", + "rov_compendium_draugh_draugh_s_awakening": "Пробуждение Драугра\n", "rov_compendium_draugh_grave_chill_passive_parry_frost": "[Награда: Матерь] Могильный холод (Пассивное/Парирование): Мороз больше не может навредить вам. Успешное парирование также высвобождает волну холода, наносящую $1 урона от мороза и отталкивающую всё в радиусе $2 м от вас. У волны отдельная перезарядка в $3 с, независимая от всплеска яда «Гниющего клинка», который срабатывает при каждом парировании.\n", "rov_compendium_draugh_rotting_edge_passive_parry_physical": "[Награда: Древний] Гниющий клинок (Пассивное/Парирование): Ваши физические атаки пропитаны болотным тленом, добавляя урон ядом в размере $1% от нанесенного физ. урона. Успешное парирование также окатывает парированного врага $2 ед. урона ядом.\n", "rov_compendium_draugh_slowly_we_rot_passive_being": "[Награда: Эйктюр] Slowly We Rot (Пассивное): Статус «Сырость» больше не снижает восстановление выносливости, а вместо этого исцеляет вас — здоровье восстанавливается на $1% быстрее, пока вы мокрые или плывете.\n", "rov_compendium_draugh_steal_their_breath_execution_while": "[Награда: Прародитель] Steal Their Breath (Казнь): Находясь в призрачном состоянии выживания «Обряда зомби», нанесение смертельного удара любому врагу мгновенно восстановит $1% вашего максимального здоровья, остановит утечку эйтра и вернет вас к полноценной жизни.\n", "rov_compendium_draugh_swarm_terror_retaliation_whenever_are": "[Награда: Королева] Swarm of Terror (Возмездие): Каждый раз при получении удара в ближнем бою вы автоматически призываете $1 выводков искателя для защиты. Они живут $2 с. Перезарядка между призывами: $3 с.\n", - "rov_compendium_draugh_title": "Тайны Драуга", - "rov_compendium_draugh_undead_fortitude_passive_poison_can": "[Награда: Масса костей] Стойкость нежити (Пассивное): Яд больше совершенно не действует на вас. Удары по ошеломленным врагам наносят на $1% больше физ. урона, а смерть больше не отнимает опыт навыков. Если любой игрок погибнет в пределах $2 м от вас, на месте его гибели останется Человечина — пища, которую может переварить только Драуг.\n", + "rov_compendium_draugh_title": "Тайны Драугра", + "rov_compendium_draugh_undead_fortitude_passive_poison_can": "[Награда: Масса костей] Стойкость нежити (Пассивное): Яд больше совершенно не действует на вас. Удары по ошеломленным врагам наносят на $1% больше физ. урона, а смерть больше не отнимает опыт навыков. Если любой игрок погибнет в пределах $2 м от вас, на месте его гибели останется Человечина — пища, которую может переварить только Драугр.\n", "rov_compendium_draugh_zombie_ritual_passive_survival_when": "[Награда: Яглут] Обряд зомби (Пассивное выживание): При получении смертельного урона вы не погибаете. Вместо этого вы переходите в призрачное состояние с неуязвимостью ко всему урону, пока ваш эйтр сгорает со скоростью $1 ед./с. Если эйтр иссякнет до вашего спасения, наступит истинная смерть. Ритуал срабатывает не чаще одного раза в $2 мин.\n", "rov_compendium_dvergar_dvergar_s_craft": "Ремесло Дверга\n", "rov_compendium_dvergar_kin_traders_passive_haldor_hildir": "[Награда: Масса костей] Родня торговцев (Пассивное): Хальдор и Хильдир узнают сородича. Их цены для вас снижены на $1%, а выплата за ваши трофеи и охотничьи награды увеличена на $2%.\n", @@ -53,7 +53,7 @@ "rov_compendium_fenrir_cultist_form_now_answers_by": "[Награда: Прародитель] Облик культиста теперь подчиняется как днем, так и ночью, и его можно удерживать сколько угодно.\n", "rov_compendium_fenrir_cultist_form_s_cooldown_falls": "[Награда: Королева] Перезарядка облика культиста снижена до 5 минут (все еще только ночью, длительность 1 минута).\n", "rov_compendium_fenrir_curse_pack": "Проклятие Стаи\n", - "rov_compendium_fenrir_cursed_claws_s_wolf_s": "[Базовое пассивное] Проклятые когти ([K], $1 с): Волчьи лапы, сохраняющиеся в человеческом теле на ограниченное время вместо оружия. Удары голыми руками наносят $2% от урона зрелых когтей (полностью режущий урон), и их сила растет с каждым павшим боссом. Достаньте меч — они исчезнут, вложите в ножны — вернутся, пока не истечет время. Не тратят место в инвентаре. Их нельзя выбросить, передать или украсть, пока они активны — а в зверином облике вместо них работают челюсти.\n", + "rov_compendium_fenrir_cursed_claws_s_wolf_s": "[Базовое пассивное] Проклятые когти ([K], $1 с): Волчьи лапы, сохраняющиеся в человеческом теле на ограниченное время вместо оружия. Удары голыми руками наносят $2% от урона зрелых когтей (полностью рубящий урон), и их сила растет с каждым павшим боссом. Достаньте меч — они исчезнут, вложите в ножны — вернутся, пока не истечет время. Не тратят место в инвентаре. Их нельзя выбросить, передать или украсть, пока они активны — а в зверином облике вместо них работают челюсти.\n", "rov_compendium_fenrir_fenring_form_h_key_night": "[Награда: Матерь] Облик фенринга (клавиша «H», только ночью): Станьте истинным Фенрингом — тяжелые когти, сокрушительный удар в прыжке и мощнейшая из четырех форм на данный момент.\n", "rov_compendium_fenrir_fenring_form_now_answers_by": "[Награда: Королева] Облик фенринга теперь доступен как днем, так и ночью.\n", "rov_compendium_fenrir_g_now_calls_ulv_form": "[Награда: Матерь] Клавиша «G» теперь призывает облик Ульва вместо Волка и доступна и днем, и ночью.\n", @@ -147,7 +147,7 @@ "rov_compendium_sverm_grinding_mandibles_seeds_are_food": "[Награда: Древний] Жерновные жвалы: Семена становятся пищей. Чистые питательные вещества — благословения культурных садов оставьте другим.\n", "rov_compendium_sverm_growth_each_one_costs_that": "Рост: $1 $2, $3 $4, $5 $6. Каждое улучшение требует полного запаса биомассы текущей стадии и открывает следующий ранг существ.\n", "rov_compendium_sverm_hive_market_hammer_counter_raised": "Рынок улья (Молот): торговый прилавок, возводимый в пределах $1 м от гнезда. Все улучшения и войска колонии приобретаются здесь за счет биомассы этого гнезда.\n", - "rov_compendium_sverm_hive_pheromones_no_invertebrate_will": "[Базовое пассивное] Феромоны улья: Ни одно беспозвоночное не нападет на вас: ни пиявки, ни клещи, ни комары смерти, ни искатели, ни пчелы. Массе костей чужды насекомые, и феромоны на нее не действуют.\n", + "rov_compendium_sverm_hive_pheromones_no_invertebrate_will": "[Базовое пассивное] Феромоны улья: Ни одно беспозвоночное не нападет на вас: ни пиявки, ни клещи, ни смертожалы, ни искатели, ни пчелы. Массе костей чужды насекомые, и феромоны на нее не действуют.\n", "rov_compendium_sverm_insect_metabolism_eat_everything_anyone": "[Базовое пассивное] Метаболизм насекомого: Вы можете есть всё, что едят остальные, а мед дает вам вдвое больше пользы. Алхимическая кровь — единственное, к чему вы не притронетесь.\n", "rov_compendium_sverm_metabolic_surge_running_jumping_cost": "[Награда: Эйктюр] Метаболический всплеск: Бег и прыжки расходуют меньше сил, а прыгаете вы гораздо выше.\n", "rov_compendium_sverm_ravager_strain_key_become_seeker": "[Награда: Яглут] Штамм опустошителя (клавиша «$1»): Обернитесь в свирепого искателя-солдата. Когти разят беспощадно, прочность панциря удваивается, но полет исключен. Эта форма рождена для битвы, а не для бегства.\n", @@ -181,7 +181,7 @@ "rov_compendium_trenta_sap_heartwood_conduct_lightning_turn": "Смола и сердцевина древесины проводят молнию и отваживают нежить: вы получаете половинный урон от молнии и духа. Но сухие ветви быстро разгораются, а топор дровосека безжалостен — урон от огня и рубящих атак увеличен в полтора раза. Мясо, рыба, яйца и мед противны вашей натуре; лишь то, что произрастает из земли, дает вам силы, и действует в $1 раз дольше, чем на обычного человека.\n", "rov_compendium_trenta_secrets_heartwood": "Тайны Сердцевины\n", "rov_compendium_trenta_spray_toxic_pollen_bursts_out": "Выброс токсичной пыльцы в радиусе $1 м: каждый союзник внутри исцеляется на $2 ед., а каждый враг отравляется на $3 ед. урона. Перезарядка: $4 с (сокращается до $5 с в облике Муспелля).\n", - "rov_compendium_trenta_stand_still_daylight_roof_over": "Постойте неподвижно под чистым небом при дневном свете в течение $1 с, и корни войдут в почву: последуют $2 тактов исцеления по $3% от макс. здоровья каждый, а также эффект «Отдых» на $4 минут — время действия растет с каждым павшим боссом.\n", + "rov_compendium_trenta_stand_still_daylight_roof_over": "Постойте неподвижно под чистым небом при дневном свете в течение $1 с, и корни войдут в почву: последуют $2 тактов исцеления по $3% от макс. здоровья каждый, а также эффект «Бодрость» на $4 минут — время действия растет с каждым павшим боссом.\n", "rov_compendium_trenta_swamp_has_nothing_left_spoil": "Болотам нечего осквернять в вашем теле. Яд не может навредить вам, эффект сырости не накладывается, а плавание вовсе не расходует выносливость.\n", "rov_compendium_trenta_swarm_hornets_has_made_its": "Рой шершней свил гнездо в вашей кроне. Любой враг, приблизившийся на расстояние ближе $1 м, получает $2 ед. урона ядом и колющими ударами каждые $3 с, пока не отступит или не погибнет.\n", "rov_compendium_trenta_take_shape_young_elder_root": "Примите облик юного Древнего, воплотив ярость корней и терновника. ЛКМ сотрясает землю, нанося $1 ед. урона в круге вокруг вас, а ПКМ выпускает пронзающий корень на $2 ед. урона — мощь обоих приемов зависит от навыка «Без оружия». В этой форме вы по-прежнему можете призывать Purple Rain с уменьшенным временем перезарядки.\n", From 9f11cab70d221f12146518d1726b01ff25451fe2 Mon Sep 17 00:00:00 2001 From: Axibed Date: Thu, 8 Oct 2026 07:57:09 +0200 Subject: [PATCH 019/176] =?UTF-8?q?=D0=9E=D0=B1=D0=BD=D0=BE=D0=B2=D0=B8?= =?UTF-8?q?=D1=82=D1=8C=20JotunnModStub/Translations/Russian/hover.json?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- JotunnModStub/Translations/Russian/hover.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/JotunnModStub/Translations/Russian/hover.json b/JotunnModStub/Translations/Russian/hover.json index b5fc367..bb109f8 100644 --- a/JotunnModStub/Translations/Russian/hover.json +++ b/JotunnModStub/Translations/Russian/hover.json @@ -16,7 +16,7 @@ "rov_hover_dvergar_read_ledger": "\n[$KEY_Use] Прочесть гроссбух", "rov_hover_dvergar_seal_worth_off": "\nваша печать дает скидку $1%", "rov_hover_dvergar_what_queen_left_behind_buys": "\n(оставленное Королевой позволит нанять еще два отряда)", - "rov_hover_fenrir_blood_thin_here_raises_no": "\nкровь здесь жидка - пока она не поднимет фенрира", + "rov_hover_fenrir_blood_thin_here_raises_no": "\nсила крови здесь слаба — фенрира ей пока не пробудить", "rov_hover_fenrir_fenrir": ", фенрир $1/$2", "rov_hover_fenrir_fill_with_meat": "\n[$KEY_Use] Заполнить мясом", "rov_hover_fenrir_meat_wolves_ulv": "мясо $1/$2\nволки $3/$4, ульвы $5/$6", @@ -26,7 +26,7 @@ "rov_hover_skeleton_bone_hand_buy_place_empty": "\n[$KEY_Use] Кость в руке — купить место, пустые руки — двинуть строй", "rov_hover_skeleton_bone_toward_next_places": "\nкостей $1/$2 для следующего из $3 мест", "rov_hover_skeleton_every_place_bought": "\nвсе места заняты", - "rov_hover_skeleton_melee_archers_rotten": "\nближний бой $1/$2 из $3\nлучники $4/$5 из $6\nгнилые $7/$8 из $9", + "rov_hover_skeleton_melee_archers_rotten": "\nближний бой $1/$2 из $3\nлучники $4/$5 из $6\nсгнившие $7/$8 из $9", "rov_hover_skeleton_needs_greater_cursed_skull": " (требуется большой проклятый череп)", "rov_hover_skeleton_next_rises_s": "\nследующий восстанет через $1 с", "rov_hover_sverm_beehives_taken_allowed_range_feed": "$1\n$2Ульев занято $3 из $4 доступных, $5 поблизости\n$6[$KEY_Use] Скормить стопку", From 3c86d48aad9d4434e393d333debaaa6fbe13f7bc Mon Sep 17 00:00:00 2001 From: Axibed Date: Thu, 8 Oct 2026 07:57:46 +0200 Subject: [PATCH 020/176] =?UTF-8?q?=D0=9E=D0=B1=D0=BD=D0=BE=D0=B2=D0=B8?= =?UTF-8?q?=D1=82=D1=8C=20JotunnModStub/Translations/Russian/merchants.jso?= =?UTF-8?q?n?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- JotunnModStub/Translations/Russian/merchants.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/JotunnModStub/Translations/Russian/merchants.json b/JotunnModStub/Translations/Russian/merchants.json index f554511..53129dd 100644 --- a/JotunnModStub/Translations/Russian/merchants.json +++ b/JotunnModStub/Translations/Russian/merchants.json @@ -110,7 +110,7 @@ "rov_sverm_refusal_stage_first": "Сначала гнездо должно развиться до стадии: $1.", "rov_sverm_refusal_working_m": "Улей все еще переваривает предыдущую порцию ($1 мин).", "rov_sverm_refusal_working_s": "Улей все еще переваривает предыдущую порцию ($1 с).", - "rov_sverm_stage_gorgedhive": "Обожравшийся улей", + "rov_sverm_stage_gorgedhive": "Насыщенный улей", "rov_sverm_stage_hivecitadel": "Цитадель улья", "rov_sverm_stage_nestingspire": "Гнездовой шпиль", "rov_troop_dvergar_ash_guard": "Пепельный страж", From 875024e649eca553c95a68905205e67395cbd6e8 Mon Sep 17 00:00:00 2001 From: Axibed Date: Thu, 8 Oct 2026 07:58:42 +0200 Subject: [PATCH 021/176] =?UTF-8?q?=D0=9E=D0=B1=D0=BD=D0=BE=D0=B2=D0=B8?= =?UTF-8?q?=D1=82=D1=8C=20JotunnModStub/Translations/Russian/messages.json?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- JotunnModStub/Translations/Russian/messages.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/JotunnModStub/Translations/Russian/messages.json b/JotunnModStub/Translations/Russian/messages.json index aaf65ef..001e5fe 100644 --- a/JotunnModStub/Translations/Russian/messages.json +++ b/JotunnModStub/Translations/Russian/messages.json @@ -180,7 +180,7 @@ "rov_msg_trenta_root_will_not_take_hold": "Корень не приживется для вас.", "rov_msg_trenta_still_growing_minutes": "Все еще растет. Осталось $1 мин.", "rov_msg_trenta_still_rotting_minutes": "Все еще перегнивает. Осталось $1 мин.", - "rov_msg_trenta_this_one_not_well_nothing": "Этому нездоровится. Ничто не ускорит это.", + "rov_msg_trenta_this_one_not_well_nothing": "Этому ростку нездоровится. Ничто не ускорит его рост.", "rov_msg_trenta_trenta_eat_only_what_grows": "Трента питается лишь тем, что рождено корнями и листвой: никакого мяса, рыбы, яиц или меда.", "rov_msg_trol_answers": "$1 откликается.", "rov_msg_trol_are_already_holding_log": "Вы уже держите бревно!", From a75655d3e5e5231c064416dd2a53bf8f1ddc6c1d Mon Sep 17 00:00:00 2001 From: Axibed Date: Thu, 8 Oct 2026 08:05:10 +0200 Subject: [PATCH 022/176] =?UTF-8?q?=D0=9E=D0=B1=D0=BD=D0=BE=D0=B2=D0=B8?= =?UTF-8?q?=D1=82=D1=8C=20JotunnModStub/Translations/Russian/messages.json?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- JotunnModStub/Translations/Russian/messages.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/JotunnModStub/Translations/Russian/messages.json b/JotunnModStub/Translations/Russian/messages.json index 001e5fe..2e70a33 100644 --- a/JotunnModStub/Translations/Russian/messages.json +++ b/JotunnModStub/Translations/Russian/messages.json @@ -35,7 +35,7 @@ "rov_msg_butler_servant_rises": "Слуга восстает.", "rov_msg_claws_they_are_part_hands": "Они — часть ваших рук.", "rov_msg_core_chose_path_aswid": "Вы избрали путь Асвида.", - "rov_msg_core_chose_path_draugh": "Вы избрали путь Драуга.", + "rov_msg_core_chose_path_draugh": "Вы избрали путь Драугра.", "rov_msg_core_chose_path_dvergar": "Вы избрали путь Дверга.", "rov_msg_core_chose_path_fenrir": "Вы избрали путь Фенрира.", "rov_msg_core_chose_path_furling": "Вы избрали путь Фурлинга.", From a1261af0f1fbbe598926ef1ff0713d5f9d7862b8 Mon Sep 17 00:00:00 2001 From: Axibed Date: Thu, 8 Oct 2026 08:12:25 +0200 Subject: [PATCH 023/176] =?UTF-8?q?=D0=9E=D0=B1=D0=BD=D0=BE=D0=B2=D0=B8?= =?UTF-8?q?=D1=82=D1=8C=20JotunnModStub/Translations/Russian/compendium.js?= =?UTF-8?q?on?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- JotunnModStub/Translations/Russian/compendium.json | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/JotunnModStub/Translations/Russian/compendium.json b/JotunnModStub/Translations/Russian/compendium.json index bc64748..6464233 100644 --- a/JotunnModStub/Translations/Russian/compendium.json +++ b/JotunnModStub/Translations/Russian/compendium.json @@ -2,19 +2,19 @@ "rov_compendium_aswid_always_active_every_form_with": "Активна всегда и в любом облике, не требует зажатия клавиши — только переключение вкл/выкл. Высасывает жизнь в радиусе $1 м днем и $2 м ночью, нанося магический урон, зависящий от навыка «Магия крови», и исцеляя вас на величину нанесенного урона. Враги с запасом здоровья $3% и ниже погибают мгновенно. В человеческом облике аура наносит половинный урон, в облике летучей мыши — полный, а в облике тумана — удвоенный. Аура не отличает торговцев от монстров, поэтому отключайте ее клавишей [I] перед разговором с Хальдором или Хильдир.\n", "rov_compendium_aswid_asmund_passive": "[Награда: Прародитель] Асмунд (Пассивное):", "rov_compendium_aswid_aswid_s_curse": "Проклятие Асвида\n", - "rov_compendium_aswid_bat_form_g_key_night": "[Награда: Эйктюр] Облик мыши (клавиша «G», только ночью): Примите облик летучей мыши.\n", - "rov_compendium_aswid_bat_form_now_answers_by": "[Награда: Древний] Облик мыши теперь доступен как ночью, так и днем.\n", + "rov_compendium_aswid_bat_form_g_key_night": "[Награда: Эйктюр] Облик летучей мыши (клавиша «G», только ночью): Примите облик летучей мыши.\n", + "rov_compendium_aswid_bat_form_now_answers_by": "[Награда: Древний] Облик летучей мыши теперь доступен как ночью, так и днем.\n", "rov_compendium_aswid_benedictus_et_afflictus": "[Базовое пассивное] Benedictus et Afflictus:", - "rov_compendium_aswid_claws_beast_s_grows_blackened": "[Базовое пассивное] Когти зверя ([K], $1 с): На ограниченное время отращивает черные когти вместо оружия. Удары кулаками наносят $2% от урона зрелых когтей (полностью рубящий урон), и их сила растет с каждым поверженным боссом. Если достать меч — когти спрячутся, убрать его — вернутся, пока не истечет таймер. Не занимают ячейку экипировки. Их нельзя выбросить, передать или украсть, пока они активны. В облике мыши или тумана когти недоступны, так как у вас нет рук.\n", + "rov_compendium_aswid_claws_beast_s_grows_blackened": "[Базовое пассивное] Когти зверя ([K], $1 с): На ограниченное время отращивает черные когти вместо оружия. Удары кулаками наносят $2% от урона зрелых когтей (полностью рубящий урон), и их сила растет с каждым поверженным боссом. Если достать меч — когти спрячутся, убрать его — вернутся, пока не истечет таймер. Не занимают ячейку экипировки. Их нельзя выбросить, передать или украсть, пока они активны. В облике летучей мыши или тумана когти недоступны, так как у вас нет рук.\n", "rov_compendium_aswid_dominate_native_interact_key": "[Награда: Яглут] Порабощение (клавиша взаимодействия):", "rov_compendium_aswid_eclipse_j_key_day_only": "[Награда: Яглут] Затмение (клавиша «J», только днем):", "rov_compendium_aswid_freezing_blood_passive": "[Награда: Матерь] Ледяная кровь (Пассивное):", - "rov_compendium_aswid_gain_permanent_immunity_freezing_status": "Вы получаете постоянный иммунитет к эффекту переохлаждения/замерзания (горы/снежные бури) и к урону от яда.\n", + "rov_compendium_aswid_gain_permanent_immunity_freezing_status": "Вы получаете постоянный иммунитет к эффекту «Замерзание» (горы/снежные бури) и к урону от яда.\n", "rov_compendium_aswid_hair_beard_turn_as_dark": "Ваши волосы и борода становятся черными, как бездна. Вы становитесь выше на 10% и получаете фиксированную прибавку +$1 к физическому урону.\n", "rov_compendium_aswid_second_cast_that_forces_night": "Сотворение в течение $1 с опускает ночную тьму вокруг вас на $2 с, позволяя получать ночные бонусы прямо под солнцем. Если уже наступила ночь, способность просто уйдет на перезарядку. Перезарядка: $3 мин.\n", "rov_compendium_aswid_sense_every_untamed_creature_within": "Вы чувствуете любое неприрученное существо в радиусе $1 м, подсвечивая его характерным свечением.\n", "rov_compendium_aswid_superhuman_senses_passive": "[Награда: Матерь] Сверхчеловеческие чувства (Пассивное):", - "rov_compendium_aswid_take_no_fall_damage_physical": "Вы не получаете урона от падения, а убийства в ближнем бою автоматически пожирают съедобных врагов (Vae Victis), принося опыт магии крови. Ваши физические характеристики растут с каждым убитым боссом: +$1 к броне, +$2 к урону, +$3% к скорости и прыжку, и +$4% вампиризма при физ. атаках. Все эти бонусы удваиваются ночью. Вы можете использовать предметы магии крови с бесконечным эйтром, а навык «Магия крови» качается в $5 раз быстрее.\n", + "rov_compendium_aswid_take_no_fall_damage_physical": "Вы не получаете урона от падения, а убийства в ближнем бою автоматически пожирают съедобных врагов (Vae Victis), принося опыт магии крови. Ваши физические характеристики растут с каждым убитым боссом: +$1 к броне, +$2 к урону, +$3% к скорости и прыжку, и +$4% вампиризма при физ. атаках. Все эти бонусы удваиваются ночью. Вы можете использовать предметы магии крови с бесконечным эйтром, а навык «Магия крови» растет в $5 раз быстрее.\n", "rov_compendium_aswid_tame_u_key_asksvin_join": "[Награда: Прародитель] Приручение (клавиша «U»): Пеплозавры добавляются в список доступных для приручения.\n", "rov_compendium_aswid_tame_u_key_lox_join": "[Награда: Яглут] Приручение (клавиша «U»): Быкоящеры добавляются в список доступных для приручения.\n", "rov_compendium_aswid_tame_u_key_tame_boar": "[Награда: Эйктюр] Приручение (клавиша «U»): Мгновенно приручает кабана под прицелом.\n", @@ -28,7 +28,7 @@ "rov_compendium_draugh_draugh_s_awakening": "Пробуждение Драугра\n", "rov_compendium_draugh_grave_chill_passive_parry_frost": "[Награда: Матерь] Могильный холод (Пассивное/Парирование): Мороз больше не может навредить вам. Успешное парирование также высвобождает волну холода, наносящую $1 урона от мороза и отталкивающую всё в радиусе $2 м от вас. У волны отдельная перезарядка в $3 с, независимая от всплеска яда «Гниющего клинка», который срабатывает при каждом парировании.\n", "rov_compendium_draugh_rotting_edge_passive_parry_physical": "[Награда: Древний] Гниющий клинок (Пассивное/Парирование): Ваши физические атаки пропитаны болотным тленом, добавляя урон ядом в размере $1% от нанесенного физ. урона. Успешное парирование также окатывает парированного врага $2 ед. урона ядом.\n", - "rov_compendium_draugh_slowly_we_rot_passive_being": "[Награда: Эйктюр] Slowly We Rot (Пассивное): Статус «Сырость» больше не снижает восстановление выносливости, а вместо этого исцеляет вас — здоровье восстанавливается на $1% быстрее, пока вы мокрые или плывете.\n", + "rov_compendium_draugh_slowly_we_rot_passive_being": "[Награда: Эйктюр] Slowly We Rot (Пассивное): Статус «Сырость» больше не снижает восстановление выносливости, а вместо этого исцеляет вас — здоровье восстанавливается на $1% быстрее, пока вы мокры или плывете.\n", "rov_compendium_draugh_steal_their_breath_execution_while": "[Награда: Прародитель] Steal Their Breath (Казнь): Находясь в призрачном состоянии выживания «Обряда зомби», нанесение смертельного удара любому врагу мгновенно восстановит $1% вашего максимального здоровья, остановит утечку эйтра и вернет вас к полноценной жизни.\n", "rov_compendium_draugh_swarm_terror_retaliation_whenever_are": "[Награда: Королева] Swarm of Terror (Возмездие): Каждый раз при получении удара в ближнем бою вы автоматически призываете $1 выводков искателя для защиты. Они живут $2 с. Перезарядка между призывами: $3 с.\n", "rov_compendium_draugh_title": "Тайны Драугра", @@ -37,7 +37,7 @@ "rov_compendium_dvergar_dvergar_s_craft": "Ремесло Дверга\n", "rov_compendium_dvergar_kin_traders_passive_haldor_hildir": "[Награда: Масса костей] Родня торговцев (Пассивное): Хальдор и Хильдир узнают сородича. Их цены для вас снижены на $1%, а выплата за ваши трофеи и охотничьи награды увеличена на $2%.\n", "rov_compendium_dvergar_mining_affinity_passive_pickaxe_answers": "[Награда: Эйктюр] Сродство с киркой (Пассивное): Кирка подчиняется вам беспрекословно. Рудные жилы поддаются быстрее, требуют меньше выносливости и порой дают больше руды, чем должны.\n", - "rov_compendium_dvergar_runic_overcharge_key_spend_eitr": "[Награда: Прародитель] Руническая перегрузка (клавиша «$1»): Потратьте $2 эйтра, чтобы зарядить руны. Ваш следующий удар излюбленным оружием нанесет урон с силой в $3x. Удерживайте заряд не дольше $4 с, иначе руны рассеются впустую.\n", + "rov_compendium_dvergar_runic_overcharge_key_spend_eitr": "[Награда: Прародитель] Руническая перегрузка (клавиша «$1»): Потратьте $2 эйтра, чтобы зарядить руны. Ваш следующий удар излюбленным оружием нанесет урон с $3-кратной силой. Удерживайте заряд не дольше $4 с, иначе руны рассеются впустую.\n", "rov_compendium_dvergar_runic_ping_key_spend_eitr": "[Награда: Яглут] Рунический эхолокатор (клавиша «$1»): Потратьте $2 эйтра, чтобы послать импульс сквозь толщу камня. На $3 с каждая рудная жила и каждый скрытый враг в радиусе $4 метров подсветятся только для вас.\n", "rov_compendium_dvergar_runic_spark_runes_blood_earth": "[Базовое пассивное] Руническая искра: Руны в вашей крови заземляются через каждую цель, по которой вы бьете. Каждый нанесенный удар несет +$1 урона молнией — этот бонус растет по мере гибели боссов.\n", "rov_compendium_dvergar_small_stubborn_stand_shorter_than": "[Базовое пассивное] Мал да удал: Вы на $1% ниже человека и обладаете базовым запасом здоровья на $2 ед. меньше. Капюшон дверга сросся с вами навечно — надевайте любой шлем и сохраняйте все его показатели защиты, но руны всегда будут выдавать в вас дитя глубин.\n", From d86609acef0a1c05df5ba808dc922207faad6598 Mon Sep 17 00:00:00 2001 From: Axibed Date: Thu, 8 Oct 2026 08:13:43 +0200 Subject: [PATCH 024/176] =?UTF-8?q?=D0=9E=D0=B1=D0=BD=D0=BE=D0=B2=D0=B8?= =?UTF-8?q?=D1=82=D1=8C=20JotunnModStub/Translations/Russian/hover.json?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- JotunnModStub/Translations/Russian/hover.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/JotunnModStub/Translations/Russian/hover.json b/JotunnModStub/Translations/Russian/hover.json index bb109f8..3ebe66d 100644 --- a/JotunnModStub/Translations/Russian/hover.json +++ b/JotunnModStub/Translations/Russian/hover.json @@ -26,7 +26,7 @@ "rov_hover_skeleton_bone_hand_buy_place_empty": "\n[$KEY_Use] Кость в руке — купить место, пустые руки — двинуть строй", "rov_hover_skeleton_bone_toward_next_places": "\nкостей $1/$2 для следующего из $3 мест", "rov_hover_skeleton_every_place_bought": "\nвсе места заняты", - "rov_hover_skeleton_melee_archers_rotten": "\nближний бой $1/$2 из $3\nлучники $4/$5 из $6\nсгнившие $7/$8 из $9", + "rov_hover_skeleton_melee_archers_rotten": "\nближний бой $1/$2 из $3\nлучники $4/$5 из $6\nсгнившие $7/$8 из $9", "rov_hover_skeleton_needs_greater_cursed_skull": " (требуется большой проклятый череп)", "rov_hover_skeleton_next_rises_s": "\nследующий восстанет через $1 с", "rov_hover_sverm_beehives_taken_allowed_range_feed": "$1\n$2Ульев занято $3 из $4 доступных, $5 поблизости\n$6[$KEY_Use] Скормить стопку", From f1fbebb8c7f7088079586bc45293a49235ce96ab Mon Sep 17 00:00:00 2001 From: Axibed Date: Thu, 8 Oct 2026 08:14:18 +0200 Subject: [PATCH 025/176] =?UTF-8?q?=D0=9E=D0=B1=D0=BD=D0=BE=D0=B2=D0=B8?= =?UTF-8?q?=D1=82=D1=8C=20JotunnModStub/Translations/Russian/items.json?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- JotunnModStub/Translations/Russian/items.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/JotunnModStub/Translations/Russian/items.json b/JotunnModStub/Translations/Russian/items.json index 7181215..c94f563 100644 --- a/JotunnModStub/Translations/Russian/items.json +++ b/JotunnModStub/Translations/Russian/items.json @@ -64,7 +64,7 @@ "rov_item_furling_tinflax_desc": "Лен, выросший на отравленной оловом почве и впитавший ее суть. Для ткани непригоден — измельчите и увидите сами.", "rov_item_furling_tinflax_name": "Оловянный лен", "rov_item_skadi_greaterfrostheart_desc": "Холод куда более древний, чем дыхание ледяных пиков. Культисты торгуют им, но не скажут, где ведут раскопки.", - "rov_item_skadi_greaterfrostheart_name": "Большое сердце холода", + "rov_item_skadi_greaterfrostheart_name": "Большое сердце мороза", "rov_item_skeleton_cursedskull_desc": "Череп, ведущий неустанный счет. Опустите его на землю, и мертвые отзовутся на зов.", "rov_item_skeleton_cursedskull_name": "Проклятый череп", "rov_item_skeleton_greatercursedskull_desc": "Старше прочих, и его счет куда длиннее. Куча останков с таким черепом поднимает и гниющих мертвецов.", From bb1ca579247ab86cd1f8a7287518777bf0c40b0a Mon Sep 17 00:00:00 2001 From: kanym Date: Tue, 13 Oct 2026 20:00:03 +0200 Subject: [PATCH 026/176] chore(release): v1.5.10 - Skeleton body switch for player model mods New client-side option Skeleton - Visuals -> Body Model Enabled. Off, a Skeleton takes the human branch of the VisEquipment postfix: vanilla body on, no bone meshes, eye glow, jaw correction or skull flame, and the helmet is left alone. Requested by players using EnhancedValheimVRM, where the bones floated around the replacement model. README: New in block for v1.5.10, changelog entry (also the Russian fixes since 1.5.9), and a line under the Skeleton features. --- JotunnModStub/Package/manifest.json | 2 +- JotunnModStub/RacesOfValheim.cs | 2 +- JotunnModStub/Skeleton/SkeletonConfig.cs | 3 +++ JotunnModStub/Skeleton/SkeletonJawFix.cs | 5 +++-- JotunnModStub/Skeleton/SkeletonPatches.cs | 4 +++- JotunnModStub/Skeleton/SkeletonRace.cs | 12 ++++++++---- JotunnModStub/Skeleton/SkeletonVisuals.cs | 10 ++++++++++ JotunnModStub/ZdoVisualSync.cs | 9 ++++++--- README.md | 9 +++++++-- manifest.json | 2 +- 10 files changed, 43 insertions(+), 15 deletions(-) diff --git a/JotunnModStub/Package/manifest.json b/JotunnModStub/Package/manifest.json index 8b25e6f..47424f1 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.5.9", + "version_number": "1.5.10", "website_url": "", "dependencies": [ "denikson-BepInExPack_Valheim-5.4.2333", diff --git a/JotunnModStub/RacesOfValheim.cs b/JotunnModStub/RacesOfValheim.cs index fe1cebb..6e826c6 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.5.9"; + public const string PluginVersion = "1.5.10"; private readonly Harmony harmony = new Harmony(PluginGUID); diff --git a/JotunnModStub/Skeleton/SkeletonConfig.cs b/JotunnModStub/Skeleton/SkeletonConfig.cs index a31f1a9..c6b8ba6 100644 --- a/JotunnModStub/Skeleton/SkeletonConfig.cs +++ b/JotunnModStub/Skeleton/SkeletonConfig.cs @@ -41,6 +41,7 @@ namespace RacesOfValheim // ─── Visuals ─────────────────────────────────────────────────────────── public static ConfigEntry HeadFireVFXEnabled; + public static ConfigEntry BodyModelEnabled; public static void Bind(ConfigFile config) { @@ -71,6 +72,8 @@ namespace RacesOfValheim const string visuals = "Skeleton - Visuals"; HeadFireVFXEnabled = config.Bind(visuals, "Head Fire VFX Enabled", true, new ConfigDescription("Whether the burning-skull effect (worn from tier 5+) renders at all. A client-side preference: disabling it stops you from seeing it on yourself and on every other skeleton you look at, but does not change what other players see.")); + BodyModelEnabled = config.Bind(visuals, "Body Model Enabled", true, + new ConfigDescription("Whether Skeleton players wear the skeleton body. Turn it off if you use a player model mod (EnhancedValheimVRM and the like): Skeletons then keep the vanilla viking body, so the replacement model shows without bones clipping through it. Abilities are unchanged. Client-side, like the option above: it applies to every Skeleton you see, yourself included, and changes nothing for other players.")); } } } diff --git a/JotunnModStub/Skeleton/SkeletonJawFix.cs b/JotunnModStub/Skeleton/SkeletonJawFix.cs index 8f9860d..d96c8c5 100644 --- a/JotunnModStub/Skeleton/SkeletonJawFix.cs +++ b/JotunnModStub/Skeleton/SkeletonJawFix.cs @@ -62,10 +62,11 @@ namespace RacesOfValheim Transform jaw = ResolveJaw(); if (jaw == null || jaw.parent == null) return; - if (!SkeletonVisuals.IsSkeletonPlayer(m_player)) + if (!SkeletonVisuals.ShowsSkeletonBody(m_player)) { // Nothing rewrites this bone on its own, so a player who stops being a Skeleton - // would otherwise keep wearing the correction on their human face. + // (or switches the skeleton body off) would otherwise keep wearing the correction + // on their human face. if (m_applied) { jaw.localPosition = m_baseLocalPosition; diff --git a/JotunnModStub/Skeleton/SkeletonPatches.cs b/JotunnModStub/Skeleton/SkeletonPatches.cs index 0937e37..461fa75 100644 --- a/JotunnModStub/Skeleton/SkeletonPatches.cs +++ b/JotunnModStub/Skeleton/SkeletonPatches.cs @@ -254,7 +254,9 @@ namespace RacesOfValheim // before it could find out it was looking at a Skeleton. string race = SkeletonVisuals.GetPlayerRace(p); - if (race == SkeletonVisuals.RaceId) + // With "Body Model Enabled" off a Skeleton takes the human branch below, the same + // as any other race, so the toggle also works live: the next refresh swaps back. + if (race == SkeletonVisuals.RaceId && SkeletonConfig.BodyModelEnabled.Value) { if (__instance.m_bodyModel != null) { diff --git a/JotunnModStub/Skeleton/SkeletonRace.cs b/JotunnModStub/Skeleton/SkeletonRace.cs index 78aebe6..1895ed5 100644 --- a/JotunnModStub/Skeleton/SkeletonRace.cs +++ b/JotunnModStub/Skeleton/SkeletonRace.cs @@ -323,9 +323,13 @@ namespace RacesOfValheim VisEquipment currentVis = Player.m_localPlayer.GetComponent(); if (currentVis != null) { - // Hide Helmets (Valheim uses singular GameObject for helmet) - var helmetObj = HarmonyLib.Traverse.Create(currentVis).Field("m_helmetItemInstance").Value; - SkeletonVisuals.SetEquipmentPieceHidden(helmetObj, true); + // Hide Helmets (Valheim uses singular GameObject for helmet). Only over a skull: + // a viking body wears its helmet, and the VisEquipment postfix puts it back. + if (SkeletonConfig.BodyModelEnabled.Value) + { + var helmetObj = HarmonyLib.Traverse.Create(currentVis).Field("m_helmetItemInstance").Value; + SkeletonVisuals.SetEquipmentPieceHidden(helmetObj, true); + } // Scale Body Armor (Chest, Legs, Shoulder) by 5% string[] armorFields = { "m_chestItemInstances", "m_legItemInstances", "m_shoulderItemInstances" }; @@ -440,7 +444,7 @@ namespace RacesOfValheim } // Flames on the skull, worn with the fire-tier model and nothing else. - headFlame.Apply(Player.m_localPlayer, SkeletonConfig.HeadFireVFXEnabled.Value && SkeletonVisuals.GetModel(Player.m_localPlayer, state) == SkeletonProgression.FireModel); + headFlame.Apply(Player.m_localPlayer, SkeletonConfig.HeadFireVFXEnabled.Value && SkeletonConfig.BodyModelEnabled.Value && SkeletonVisuals.GetModel(Player.m_localPlayer, state) == SkeletonProgression.FireModel); if (rules.FireAura) { diff --git a/JotunnModStub/Skeleton/SkeletonVisuals.cs b/JotunnModStub/Skeleton/SkeletonVisuals.cs index 18ada8b..e91963c 100644 --- a/JotunnModStub/Skeleton/SkeletonVisuals.cs +++ b/JotunnModStub/Skeleton/SkeletonVisuals.cs @@ -49,6 +49,16 @@ namespace RacesOfValheim public static bool IsSkeletonPlayer(Player player) => GetPlayerRace(player) == RaceId; + /// + /// Whether this client draws the skeleton's bones on this player. False for every + /// non-Skeleton, and for every Skeleton when "Body Model Enabled" is off: model-replacement + /// mods (EnhancedValheimVRM and the like) hide the vanilla body and draw their own, so the + /// borrowed bones ended up floating around the replacement model. With the option off the + /// Skeleton keeps every ability and only looks like a plain viking. + /// + public static bool ShowsSkeletonBody(Player player) => + SkeletonConfig.BodyModelEnabled.Value && IsSkeletonPlayer(player); + /// /// Fully hides (or restores) one equipped item instance - a helmet, typically. /// diff --git a/JotunnModStub/ZdoVisualSync.cs b/JotunnModStub/ZdoVisualSync.cs index 0df6988..4f1326f 100644 --- a/JotunnModStub/ZdoVisualSync.cs +++ b/JotunnModStub/ZdoVisualSync.cs @@ -128,8 +128,11 @@ namespace RacesOfValheim vis.SetBeardItem(0); // Hide Helmet - var helmetObj = HarmonyLib.Traverse.Create(vis).Field("m_helmetItemInstance").Value; - SkeletonVisuals.SetEquipmentPieceHidden(helmetObj, true); + if (SkeletonConfig.BodyModelEnabled.Value) + { + var helmetObj = HarmonyLib.Traverse.Create(vis).Field("m_helmetItemInstance").Value; + SkeletonVisuals.SetEquipmentPieceHidden(helmetObj, true); + } // Scale Body Armor string[] armorFields = { "m_chestItemInstances", "m_legItemInstances", "m_shoulderItemInstances" }; @@ -165,7 +168,7 @@ namespace RacesOfValheim // The burning skull, grown locally for whoever we are looking at. The tier is on the // ZDO, so this client can work out for itself whether they should be alight. - m_skeletonHeadFlame.Apply(m_player, SkeletonConfig.HeadFireVFXEnabled.Value && SkeletonVisuals.GetModel(m_player, state) == SkeletonProgression.FireModel); + m_skeletonHeadFlame.Apply(m_player, SkeletonConfig.HeadFireVFXEnabled.Value && SkeletonConfig.BodyModelEnabled.Value && SkeletonVisuals.GetModel(m_player, state) == SkeletonProgression.FireModel); // Apply Scale Vector3 targetScale = rules.ScaleMultiplier; diff --git a/README.md b/README.md index 39865d8..741c132 100644 --- a/README.md +++ b/README.md @@ -15,9 +15,9 @@ Support the mod: [Patreon — NandorTheModder](https://www.patreon.com/c/NandorT --- -## New in v1.5.9 +## New in v1.5.10 -Skeletons can laugh: type /evillaugh. The Furling's fire bonus now covers crossbow bolts, and a crossbow in hand no longer fires on every attack while you are transformed. Full details in the [changelog](#v159). +Using a player model mod such as EnhancedValheimVRM? Turn off `Skeleton - Visuals` → `Body Model Enabled` and Skeletons keep the vanilla body, so no bones clip through your model. Full details in the [changelog](#v1510). --- @@ -30,6 +30,7 @@ Skeletons can laugh: type /evillaugh. The Furling's fire bonus now covers crossb - **Stamina-less Combat:** Skeletons use no stamina and do not have a stamina bar. - **Undead Diet:** Cannot eat normal food. Max health increases automatically as you defeat bosses to make up for lack of food buffs. - **Lit Sockets:** Your skull carries the eye lights of the creature your tier is built from, in that creature's own colour — so they change as the body does. +- **Body Model switch:** with a player model mod (EnhancedValheimVRM and the like), set `Skeleton - Visuals` → `Body Model Enabled` to off and Skeletons keep the vanilla body. Abilities stay the same. ### 2. Skadi ![Skadi1](https://wiki.aledanidev.ovh/assets/images/skadi1.gif) @@ -447,6 +448,10 @@ Both halves have an off switch under `Factions` in Configuration Manager: **Fact ## Changelog +### v1.5.10 +- **New - Skeleton body switch for player model mods:** with EnhancedValheimVRM or another model replacer, the skeleton's bones stayed on screen and floated around the new model. Set `Skeleton - Visuals` → `Body Model Enabled` to off and Skeletons keep the vanilla body: no bones, eye lights or skull flames, and the helmet shows. Abilities don't change. The setting is client-side, so it applies to every Skeleton you see and changes nothing for other players. The race strips hair and beard, so the vanilla body is bald, and the auto-resurrection still shows the skeleton for the few seconds it climbs out of the ground. Thanks to the players who reported it and tested the fix. +- **Fix - Russian translation:** corrections to several Russian texts, by Axibed. + ### v1.5.9 - **New - /evillaugh (Skeleton):** the Skeleton throws its head back, clacks its jaw, shakes its shoulders and punches both fists into the air for four seconds. Everyone nearby sees it. - **Change - Furling fire bolts:** the Wickerman's fire damage now also applies to crossbow bolts, not only to arrows. diff --git a/manifest.json b/manifest.json index 8b25e6f..47424f1 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.5.9", + "version_number": "1.5.10", "website_url": "", "dependencies": [ "denikson-BepInExPack_Valheim-5.4.2333", From 65b488b5dc841592dc75bbecd8a4dea62587d80f Mon Sep 17 00:00:00 2001 From: kanym Date: Wed, 14 Oct 2026 14:12:50 +0200 Subject: [PATCH 027/176] feat(trol): skin and hair colour pickers in Trol - Appearance Two Color entries, Skin Color and Hair Color (hair and beard), defaulting to the old peacock blue and golden blonde so no Trol changes on update. Each Trol publishes its choice on its own ZDO and every client paints that player with it; a Trol on an older build publishes nothing and shows the defaults. The menu preview, with no ZDO, reads the local config. The section is kept local by ConfigSync. README: New in block, Trol features line and a 1.5.10 changelog entry. --- JotunnModStub/ConfigSync.cs | 1 + JotunnModStub/Trol/TrolConfig.cs | 15 +++++++++++ JotunnModStub/Trol/TrolPatches.cs | 45 +++++++++++++++++++++++++------ README.md | 4 ++- 4 files changed, 56 insertions(+), 9 deletions(-) diff --git a/JotunnModStub/ConfigSync.cs b/JotunnModStub/ConfigSync.cs index fb38b9c..996168a 100644 --- a/JotunnModStub/ConfigSync.cs +++ b/JotunnModStub/ConfigSync.cs @@ -31,6 +31,7 @@ namespace RacesOfValheim "Skeleton - Visuals", "Sverm - Dorsal Spines", "Sverm - Emberform", + "Trol - Appearance", "War Vulture - Model", "War Vulture - Interface", }; diff --git a/JotunnModStub/Trol/TrolConfig.cs b/JotunnModStub/Trol/TrolConfig.cs index ffca8af..2a152ae 100644 --- a/JotunnModStub/Trol/TrolConfig.cs +++ b/JotunnModStub/Trol/TrolConfig.cs @@ -59,8 +59,23 @@ namespace RacesOfValheim // ─── Farming ─────────────────────────────────────────────────────────── public static ConfigEntry UnarmedFarmingDamageBonusPerState; + // ─── Appearance ──────────────────────────────────────────────────────── + public static ConfigEntry SkinColor; + public static ConfigEntry HairColor; + + // The colours every Trol wore before these became settings. Also what a Trol on an older + // build of the mod shows as, since that build publishes no colour of its own. + public static readonly Color DefaultSkinColor = new Color(0.1f, 0.6f, 0.7f, 1f); + public static readonly Color DefaultHairColor = new Color(0.9f, 0.8f, 0.4f, 1f); + public static void Bind(ConfigFile config) { + const string appearance = "Trol - Appearance"; + SkinColor = config.Bind(appearance, "Skin Color", DefaultSkinColor, + new ConfigDescription("Your Trol's skin. Other players see it too. The game multiplies it with the skin texture, so it comes out a little darker than the swatch. For the look of Valheim's own trolls try 7FA8C9.")); + HairColor = config.Bind(appearance, "Hair Color", DefaultHairColor, + new ConfigDescription("Your Trol's hair and beard. Other players see it too.")); + const string keybinds = "Trol - Keybinds"; ThrowRockKey = config.Bind(keybinds, "Throw Rock", new KeyboardShortcut(KeyCode.G), new ConfigDescription("Throws a rock (or the log you're holding), tier 3+.")); diff --git a/JotunnModStub/Trol/TrolPatches.cs b/JotunnModStub/Trol/TrolPatches.cs index 68007df..0d9f5c2 100644 --- a/JotunnModStub/Trol/TrolPatches.cs +++ b/JotunnModStub/Trol/TrolPatches.cs @@ -6,8 +6,23 @@ namespace RacesOfValheim [HarmonyPatch(typeof(VisEquipment), "UpdateColors")] public static class TrolSkinColorPatch { - // Golden blonde hair - private static readonly Color HairColor = new Color(0.9f, 0.8f, 0.4f, 1f); + // Each Trol picks their own colours in Trol - Appearance and publishes them here (see + // Trol_PlayerUpdate_Patch), so everyone sees the colours that player chose. Stored without + // alpha: _SkinColor ignores it. + public const string SkinColorKey = "RacesOfValheim_TrolSkinColor"; + public const string HairColorKey = "RacesOfValheim_TrolHairColor"; + + private static Vector3 ToVec3(Color c) => new Vector3(c.r, c.g, c.b); + private static Color ToColor(Vector3 v) => new Color(v.x, v.y, v.z, 1f); + + /// Puts the local player's chosen colours on their ZDO. Only the owner writes. + public static void Publish(ZDO zdo) + { + Vector3 skin = ToVec3(TrolConfig.SkinColor.Value); + Vector3 hair = ToVec3(TrolConfig.HairColor.Value); + if (zdo.GetVec3(SkinColorKey, Vector3.negativeInfinity) != skin) zdo.Set(SkinColorKey, skin); + if (zdo.GetVec3(HairColorKey, Vector3.negativeInfinity) != hair) zdo.Set(HairColorKey, hair); + } public static void Postfix(VisEquipment __instance) { @@ -28,25 +43,38 @@ namespace RacesOfValheim if (race != "Trol") return; - // Apply skin, hair, beard colors here... + // The colours this Trol published. A Trol on an older build publishes none and keeps the + // defaults; with no ZDO at all (the main-menu preview) it is the local player's own + // character, so the local settings are the right answer. + Color skinColor, hairColor; + if (nview != null && nview.IsValid()) + { + ZDO zdo = nview.GetZDO(); + skinColor = ToColor(zdo.GetVec3(SkinColorKey, ToVec3(TrolConfig.DefaultSkinColor))); + hairColor = ToColor(zdo.GetVec3(HairColorKey, ToVec3(TrolConfig.DefaultHairColor))); + } + else + { + skinColor = TrolConfig.SkinColor.Value; + hairColor = TrolConfig.HairColor.Value; + } + if (__instance.m_bodyModel != null && __instance.m_bodyModel.material != null) { - // Peacock blue (deep greenish-blue) - Color trolColor = new Color(0.1f, 0.6f, 0.7f, 1f); - __instance.m_bodyModel.material.SetColor("_SkinColor", trolColor); + __instance.m_bodyModel.material.SetColor("_SkinColor", skinColor); } // Hair var hairInst = Traverse.Create(__instance).Field("m_hairItemInstance").GetValue(); if (hairInst != null) foreach (var r in hairInst.GetComponentsInChildren()) - if (r.material != null) r.material.SetColor("_SkinColor", HairColor); + if (r.material != null) r.material.SetColor("_SkinColor", hairColor); // Beard var beardInst = Traverse.Create(__instance).Field("m_beardItemInstance").GetValue(); if (beardInst != null) foreach (var r in beardInst.GetComponentsInChildren()) - if (r.material != null) r.material.SetColor("_SkinColor", HairColor); + if (r.material != null) r.material.SetColor("_SkinColor", hairColor); } } @@ -128,6 +156,7 @@ namespace RacesOfValheim { nview.GetZDO().Set(StateKey, state); nview.GetZDO().Set(TrueFormKey, isTrueFormActive); + if (race == "Trol") TrolSkinColorPatch.Publish(nview.GetZDO()); } } else diff --git a/README.md b/README.md index 741c132..68d1e8d 100644 --- a/README.md +++ b/README.md @@ -17,7 +17,7 @@ Support the mod: [Patreon — NandorTheModder](https://www.patreon.com/c/NandorT ## New in v1.5.10 -Using a player model mod such as EnhancedValheimVRM? Turn off `Skeleton - Visuals` → `Body Model Enabled` and Skeletons keep the vanilla body, so no bones clip through your model. Full details in the [changelog](#v1510). +Using a player model mod such as EnhancedValheimVRM? Turn off `Skeleton - Visuals` → `Body Model Enabled` and Skeletons keep the vanilla body, so no bones clip through your model. Trols can pick their own skin and hair colour under `Trol - Appearance`. Full details in the [changelog](#v1510). --- @@ -72,6 +72,7 @@ Using a player model mod such as EnhancedValheimVRM? Turn off `Skeleton - Visual - **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. +- **Your Own Colours:** pick your skin and hair colour under `Trol - Appearance`. Other players see them too. ### 7. Draugh - **Born Dead, Buried Alive:** Undead warrior: resistant to physical/poison, weak to fire/spirit. @@ -450,6 +451,7 @@ Both halves have an off switch under `Factions` in Configuration Manager: **Fact ### v1.5.10 - **New - Skeleton body switch for player model mods:** with EnhancedValheimVRM or another model replacer, the skeleton's bones stayed on screen and floated around the new model. Set `Skeleton - Visuals` → `Body Model Enabled` to off and Skeletons keep the vanilla body: no bones, eye lights or skull flames, and the helmet shows. Abilities don't change. The setting is client-side, so it applies to every Skeleton you see and changes nothing for other players. The race strips hair and beard, so the vanilla body is bald, and the auto-resurrection still shows the skeleton for the few seconds it climbs out of the ground. Thanks to the players who reported it and tested the fix. +- **New - Trol skin and hair colour:** `Trol - Appearance` has a colour picker for the skin and one for the hair and beard. Each Trol picks their own and every player sees them. The defaults are the old peacock blue and golden blonde, so nobody's Trol changes after the update. For the blue-grey of Valheim's own trolls, try `7FA8C9`. A Trol on an older version of the mod shows the defaults to everyone else. Thanks to the player who suggested it. - **Fix - Russian translation:** corrections to several Russian texts, by Axibed. ### v1.5.9 From d5c2d58636ae37167642310ee6fea0fa1fb31aa3 Mon Sep 17 00:00:00 2001 From: kanym Date: Wed, 14 Oct 2026 16:40:27 +0200 Subject: [PATCH 028/176] fix(resetrace): drop every form and every mod status effect on reset ResetRace now undoes each race's form on the spot before it touches status effects: Aswid bat and mist, Fenrir, Skadi drake, Trol True Form, Trenta Muspell and Sverm Ravager. Each race gets a HardResetForReset that stops the form's coroutine, so a transform caught mid-gesture can't finish after the reset and a revert can't hand out its cooldown after the sweep. The hand-written status effect list is gone. The reset now removes everything the mod registers through Jotunn (ModRegistry), which covers the True Form and its cooldowns, Bat and Mist Form, the Skeleton resurrect cooldown and Skadi's ability cooldowns. It also puts the player and the Visual back to scale 1, clears the Sverm's static Ravager cooldown and the Trol's wasTrueFormActive flag, and prints what it removed to the console and the BepInEx log. --- JotunnModStub/Aswid/AswidRace.cs | 71 ++++++++++++++++++++++--- JotunnModStub/Fenrir/FenrirRace.cs | 58 ++++++++++++++++++-- JotunnModStub/RacesOfValheim.cs | 61 +++++++++++++++------ JotunnModStub/Skadi/SkadiRace.cs | 57 ++++++++++++++++++-- JotunnModStub/Sverm/SvermRavagerForm.cs | 34 +++++++++++- JotunnModStub/Trenta/TrentaMuspell.cs | 47 ++++++++++++++-- JotunnModStub/Trol/TrolRace.cs | 45 +++++++++++++++- 7 files changed, 336 insertions(+), 37 deletions(-) diff --git a/JotunnModStub/Aswid/AswidRace.cs b/JotunnModStub/Aswid/AswidRace.cs index e8bb4c7..b95daff 100644 --- a/JotunnModStub/Aswid/AswidRace.cs +++ b/JotunnModStub/Aswid/AswidRace.cs @@ -463,7 +463,7 @@ namespace RacesOfValheim if (EnvMan.instance != null && EnvMan.IsDay() && !isTransformingSequence && Player.m_localPlayer.GetSEMan().HaveStatusEffect("SE_MistForm".GetStableHashCode())) { - StartCoroutine(RevertMistFormRoutine()); + RunFormRoutine(RevertMistFormRoutine()); } // Same rule for a night-only bat: a form the sun forbids cannot be kept through the @@ -474,7 +474,7 @@ namespace RacesOfValheim EnvMan.instance != null && EnvMan.IsDay()) { Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_aswid_morning_sun_drives_bat_back")); - StartCoroutine(RevertToHumanRoutine()); + RunFormRoutine(RevertToHumanRoutine()); } } @@ -565,7 +565,7 @@ namespace RacesOfValheim if (IsTransformed) { - StartCoroutine(RevertToHumanRoutine()); + RunFormRoutine(RevertToHumanRoutine()); return; } @@ -580,18 +580,73 @@ namespace RacesOfValheim return; } - StartCoroutine(TransformIntoBatRoutine(rules)); + RunFormRoutine(TransformIntoBatRoutine(rules)); + } + + // The one bat or mist routine in flight, if any. Kept so ResetRace can stop it: a + // TransformIntoBatRoutine left running through a reset finishes its 1.1s gesture and + // turns a freshly reset Human into a bat. + private Coroutine formRoutine; + + private void RunFormRoutine(System.Collections.IEnumerator routine) + { + formRoutine = StartCoroutine(routine); + } + + /// + /// Drops bat and mist form on the spot for ResetRace: no puff, no tween, nothing left + /// running. ForceRevert is no use there - it skips a form that is still mid-gesture, and + /// its coroutine would still be shrinking the body back after the reset has finished. + /// + /// True if there was a form to drop. + public bool HardResetForReset() + { + Player player = Player.m_localPlayer; + if (player == null) return false; + + if (formRoutine != null) + { + StopCoroutine(formRoutine); + formRoutine = null; + } + + bool hadMist = mistTransformation != null || player.GetSEMan().HaveStatusEffect("SE_MistForm".GetStableHashCode()); + bool hadBat = IsTransformed || isTransformingSequence; + + // Also clears isTransformingSequence and puts the transform back to scale 1, which + // covers a reset caught halfway through the bat's shrink. + HardResetBatForm(); + + if (hadMist) + { + if (mistTransformation != null) + { + Destroy(mistTransformation); + mistTransformation = null; + } + + Transform playerVisual = player.transform.Find("Visual"); + PlayerVisualHider.Show(playerVisual, "aswid-reset-mist"); + if (playerVisual != null) playerVisual.localScale = Vector3.one; + + player.GetSEMan().RemoveStatusEffect("SE_MistForm".GetStableHashCode(), true); + ZNetView nview = player.GetComponent(); + if (nview != null && nview.IsValid()) nview.GetZDO().Set("Aswid_IsMistForm", false); + } + + isTransformingSequence = false; + return hadBat || hadMist; } public void ForceRevert() { if (IsTransformed && !isTransformingSequence) { - StartCoroutine(RevertToHumanRoutine()); + RunFormRoutine(RevertToHumanRoutine()); } if (Player.m_localPlayer != null && Player.m_localPlayer.GetSEMan().HaveStatusEffect("SE_MistForm".GetStableHashCode()) && !isTransformingSequence) { - StartCoroutine(RevertMistFormRoutine()); + RunFormRoutine(RevertMistFormRoutine()); } } @@ -745,11 +800,11 @@ namespace RacesOfValheim if (Player.m_localPlayer.GetSEMan().HaveStatusEffect("SE_MistForm".GetStableHashCode())) { - StartCoroutine(RevertMistFormRoutine()); + RunFormRoutine(RevertMistFormRoutine()); } else { - StartCoroutine(TransformIntoMistRoutine()); + RunFormRoutine(TransformIntoMistRoutine()); } } diff --git a/JotunnModStub/Fenrir/FenrirRace.cs b/JotunnModStub/Fenrir/FenrirRace.cs index c1d7664..ee5cd5a 100644 --- a/JotunnModStub/Fenrir/FenrirRace.cs +++ b/JotunnModStub/Fenrir/FenrirRace.cs @@ -185,7 +185,7 @@ namespace RacesOfValheim { if (isTransformed) { - StartCoroutine(RevertToHumanRoutine()); + RunFormRoutine(RevertToHumanRoutine()); return; } @@ -213,7 +213,7 @@ namespace RacesOfValheim { } } - StartCoroutine(TransformIntoWolfRoutine(rules)); + RunFormRoutine(TransformIntoWolfRoutine(rules)); } /// @@ -256,11 +256,63 @@ namespace RacesOfValheim { return "$rov_msg_fenrir_formname_fenrir"; } + // The one transform or revert routine in flight, if any, so ResetRace can stop it. A + // revert left to finish on its own lands its cooldown after the reset has already swept + // the status effects, and the next Fenrir starts locked out. + private Coroutine formRoutine; + + private void RunFormRoutine(IEnumerator routine) + { + formRoutine = StartCoroutine(routine); + } + + /// + /// Drops whatever form is up, immediately, for ResetRace: no poof, no message, and no + /// cooldown - ExecuteReversion hands one out, which is right for a form running out and + /// wrong for a player leaving the race. + /// + /// True if there was a form to drop. + public bool HardResetForReset() + { + Player player = Player.m_localPlayer; + if (player == null) return false; + + if (formRoutine != null) + { + StopCoroutine(formRoutine); + formRoutine = null; + } + + bool hadForm = isTransformed || isTransformingSequence || currentTransformation != null; + if (hadForm) + { + if (currentTransformation != null) Destroy(currentTransformation); + currentTransformation = null; + DestroyAllForms(); + + ZNetView nview = player.GetComponent(); + if (nview != null && nview.IsValid()) nview.GetZDO().Set("RacesOfValheim_FenrirForm", ""); + + PlayerVisualHider.Show(player.transform.Find("Visual"), "fenrir-reset"); + + player.GetSEMan().RemoveStatusEffect("SE_FenrirForm".GetStableHashCode()); + player.GetSEMan().RemoveStatusEffect("SE_CultistForm".GetStableHashCode()); + player.GetSEMan().RemoveStatusEffect("SE_WolfForm".GetStableHashCode()); + } + + isTransformed = false; + isTransformingSequence = false; + activeRules = null; + revertMessage = null; + sunSicknessTimer = 0f; + return hadForm; + } + public void ForceRevert() { if (isTransformed && !isTransformingSequence) { - StartCoroutine(RevertToHumanRoutine()); + RunFormRoutine(RevertToHumanRoutine()); } } diff --git a/JotunnModStub/RacesOfValheim.cs b/JotunnModStub/RacesOfValheim.cs index 6e826c6..e6f8289 100644 --- a/JotunnModStub/RacesOfValheim.cs +++ b/JotunnModStub/RacesOfValheim.cs @@ -4,6 +4,7 @@ using HarmonyLib; using Jotunn.Configs; using Jotunn.Entities; using Jotunn.Managers; +using Jotunn.Utils; using UnityEngine; using UnityEngine.UI; // Added for UI @@ -99,6 +100,20 @@ namespace RacesOfValheim Player player = Player.m_localPlayer; if (player == null) return; + // What the reset actually took off, printed at the end so it can be read in the console. + var removed = new System.Collections.Generic.List(); + + // Forms first, before any status effect goes. Taking a form's effect away without + // undoing the form leaves the body hidden (bat, mist, drake, wolf, Muspell, Ravager) + // or oversized (True Form), and several races only ever look at their form from an + // Update that returns early for anyone who is not of that race any more. + if (AswidRace.Instance != null && AswidRace.Instance.HardResetForReset()) removed.Add("form: Aswid bat/mist"); + if (FenrirRace.Instance != null && FenrirRace.Instance.HardResetForReset()) removed.Add("form: Fenrir"); + if (SkadiRace.Instance != null && SkadiRace.Instance.HardResetForReset()) removed.Add("form: Skadi drake"); + if (TrolRace.Instance != null && TrolRace.Instance.HardResetForReset()) removed.Add("form: Trol True Form"); + if (TrentaMuspell.HardResetForReset(player)) removed.Add("form: Trenta Muspell"); + if (SvermRavagerForm.HardResetForReset(player)) removed.Add("form: Sverm Ravager"); + RemovePermanentRaceEquipment(player); player.m_customData.Remove("Race"); @@ -120,21 +135,23 @@ namespace RacesOfValheim } } - player.GetSEMan().RemoveStatusEffect("SE_FenrirCurse".GetStableHashCode()); - player.GetSEMan().RemoveStatusEffect("SE_AswidStats".GetStableHashCode()); - player.GetSEMan().RemoveStatusEffect("SE_SkeletonStats".GetStableHashCode()); - player.GetSEMan().RemoveStatusEffect("SE_SkadiStats".GetStableHashCode()); - player.GetSEMan().RemoveStatusEffect("SE_SkadiCooldown".GetStableHashCode()); - player.GetSEMan().RemoveStatusEffect(DvergarConfig.StatsSE.GetStableHashCode()); - player.GetSEMan().RemoveStatusEffect(DvergarConfig.OverchargeSE.GetStableHashCode()); - player.GetSEMan().RemoveStatusEffect(DvergarConfig.OverchargeCdSE.GetStableHashCode()); - player.GetSEMan().RemoveStatusEffect(DvergarConfig.RunicPingCdSE.GetStableHashCode()); - player.GetSEMan().RemoveStatusEffect(TrentaConfig.StatsSE.GetStableHashCode()); - player.GetSEMan().RemoveStatusEffect(TrentaConfig.PurpleRainCdSE.GetStableHashCode()); - player.GetSEMan().RemoveStatusEffect(TrentaConfig.PortalCdSE.GetStableHashCode()); - player.GetSEMan().RemoveStatusEffect(SvermConfig.StatsSE.GetStableHashCode()); - player.GetSEMan().RemoveStatusEffect(SvermConfig.RavagerSE.GetStableHashCode()); - player.GetSEMan().RemoveStatusEffect(SvermConfig.RavagerCdSE.GetStableHashCode()); + // Every status effect this mod registers, rather than a list kept by hand: the hand + // list was missing the True Form and both of its cooldowns, Bat and Mist Form, the + // Skeleton's resurrect cooldown and most of Skadi's, and the next effect anyone adds + // would have been missing too. The forms were dropped above, so taking their effects + // away here no longer leaves a body hidden or blown up. + SEMan seman = player.GetSEMan(); + foreach (CustomStatusEffect custom in ModRegistry.GetStatusEffects(PluginGUID)) + { + StatusEffect se = custom?.StatusEffect; + if (se == null) continue; + + int hash = se.name.GetStableHashCode(); + if (!seman.HaveStatusEffect(hash)) continue; + + seman.RemoveStatusEffect(hash, true); + removed.Add(se.name); + } // COLD, which is not one of ours at all - and that is exactly why it has to go. // @@ -161,9 +178,21 @@ namespace RacesOfValheim // Only after the ZDO above already says "Human" - see the class doc comment. RaceItemCleanup.PurgeForeignRaceItems(player); + // Normal size. The Trol, the Skeleton past Fader and the self-sizing races all scale + // either the player or its Visual, and each puts its own size back only from code that + // may not run again now the race has changed. The next race sets its own size anyway. + player.transform.localScale = Vector3.one; + GameObject visual = Traverse.Create(player).Field("m_visual").GetValue(); + if (visual != null) visual.transform.localScale = Vector3.one; + + string summary = removed.Count == 0 + ? "[ResetRace] Nothing race-specific was left on the player." + : "[ResetRace] Removed: " + string.Join(", ", removed); + Jotunn.Logger.LogInfo(summary); + if (Console.instance != null) Console.instance.Print(summary); + if (Instance != null) { - if (FenrirRace.Instance != null) FenrirRace.Instance.ForceRevert(); Instance.ShowRaceSelectionMenu(); } } diff --git a/JotunnModStub/Skadi/SkadiRace.cs b/JotunnModStub/Skadi/SkadiRace.cs index 573685d..27ea13e 100644 --- a/JotunnModStub/Skadi/SkadiRace.cs +++ b/JotunnModStub/Skadi/SkadiRace.cs @@ -247,7 +247,7 @@ namespace RacesOfValheim { formExpireTime = 0f; Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_skadi_dragon_form_fades")); - StartCoroutine(RevertToHumanRoutine()); + RunFormRoutine(RevertToHumanRoutine()); return; } @@ -687,7 +687,7 @@ namespace RacesOfValheim if (isTransformed) { - StartCoroutine(RevertToHumanRoutine()); + RunFormRoutine(RevertToHumanRoutine()); return; } @@ -707,7 +707,7 @@ namespace RacesOfValheim } activeRules = rules; - StartCoroutine(TransformRoutine(rules)); + RunFormRoutine(TransformRoutine(rules)); } private Vector3 GetFormScale(SkadiProgression.FormType form) @@ -914,6 +914,57 @@ namespace RacesOfValheim if (se != null) se.m_ttl = seconds; } + // The one transform or revert routine in flight, if any, so ResetRace can stop it. + private Coroutine formRoutine; + + private void RunFormRoutine(System.Collections.IEnumerator routine) + { + formRoutine = StartCoroutine(routine); + } + + /// + /// Drops the drake form on the spot for ResetRace. Update bails out on its first line for + /// anyone who is not a Skadi, so once the race changes nothing in this class ever looks at + /// the form again - a Skadi reset in drake form stayed a drake for good. No message and no + /// cooldown here, unlike ExecuteReversion. + /// + /// True if there was a form to drop. + public bool HardResetForReset() + { + Player player = Player.m_localPlayer; + if (player == null) return false; + + if (formRoutine != null) + { + StopCoroutine(formRoutine); + formRoutine = null; + } + + bool hadForm = isTransformed || isTransformingSequence || currentTransformation != null; + if (hadForm) + { + if (currentTransformation != null) Destroy(currentTransformation); + currentTransformation = null; + foreach (var f in player.GetComponentsInChildren(true)) Destroy(f.gameObject); + + ZNetView nview = player.GetComponent(); + if (nview != null && nview.IsValid()) + { + nview.GetZDO().Set("Skadi_Form", ""); + nview.GetZDO().Set("RacesOfValheim_SkadiForm", ""); + } + + PlayerVisualHider.Show(player.transform.Find("Visual"), "skadi-reset"); + player.GetSEMan().RemoveStatusEffect("SE_SkadiForm".GetStableHashCode(), true); + } + + isTransformed = false; + isTransformingSequence = false; + formExpireTime = 0f; + activeRules = null; + return hadForm; + } + private void ExecuteReversion() { Transform playerVisual = Player.m_localPlayer.transform.Find("Visual"); diff --git a/JotunnModStub/Sverm/SvermRavagerForm.cs b/JotunnModStub/Sverm/SvermRavagerForm.cs index b0e6497..f41b7f0 100644 --- a/JotunnModStub/Sverm/SvermRavagerForm.cs +++ b/JotunnModStub/Sverm/SvermRavagerForm.cs @@ -177,7 +177,7 @@ namespace RacesOfValheim if (SvermRace.Instance != null) { - SvermRace.Instance.StartCoroutine(EnterRoutine(player)); + formRoutine = SvermRace.Instance.StartCoroutine(EnterRoutine(player)); } else { @@ -342,12 +342,42 @@ namespace RacesOfValheim } } + // The enter or exit routine in flight, if any, so ResetRace can stop it. An ExitRoutine + // left running finishes with Exit(spendCooldown: true), which puts the cooldown back on + // after the reset has swept it. + private static Coroutine formRoutine; + + /// + /// Drops Ravager Strain on the spot for ResetRace, and forgets its cooldown: nextAllowedAt + /// is a static the status effect sweep never touches, so without this a player who left + /// the Sverm and came back stayed locked out of the form with no timer in the HUD. + /// + /// True if there was a form to drop. + public static bool HardResetForReset(Player player) + { + if (player == null) return false; + + if (formRoutine != null && SvermRace.Instance != null) + { + SvermRace.Instance.StopCoroutine(formRoutine); + } + formRoutine = null; + + bool hadForm = IsActive || transforming || exiting || model != null; + if (IsActive || model != null) Exit(player, spendCooldown: false); + + transforming = false; + exiting = false; + nextAllowedAt = 0f; + return hadForm; + } + /// Kicks off the graceful exit (shrink, then Exit) if there is a host to run it on. private static void RunExit(Player player, bool spendCooldown, string message) { if (SvermRace.Instance != null) { - SvermRace.Instance.StartCoroutine(ExitRoutine(player, spendCooldown, message)); + formRoutine = SvermRace.Instance.StartCoroutine(ExitRoutine(player, spendCooldown, message)); } else { diff --git a/JotunnModStub/Trenta/TrentaMuspell.cs b/JotunnModStub/Trenta/TrentaMuspell.cs index 4499faf..d3af9ef 100644 --- a/JotunnModStub/Trenta/TrentaMuspell.cs +++ b/JotunnModStub/Trenta/TrentaMuspell.cs @@ -53,11 +53,11 @@ namespace RacesOfValheim if (IsTransformed) { - TrentaRace.Instance.StartCoroutine(RevertRoutine(player)); + formRoutine = TrentaRace.Instance.StartCoroutine(RevertRoutine(player)); } else { - TrentaRace.Instance.StartCoroutine(TransformRoutine(player)); + formRoutine = TrentaRace.Instance.StartCoroutine(TransformRoutine(player)); } } @@ -68,10 +68,51 @@ namespace RacesOfValheim { if (IsTransformed && !isTransformingSequence) { - TrentaRace.Instance.StartCoroutine(RevertRoutine(player)); + formRoutine = TrentaRace.Instance.StartCoroutine(RevertRoutine(player)); } } + // The one transform or revert routine in flight, if any, so ResetRace can stop it. + private static Coroutine formRoutine; + + /// + /// Drops the Muspell on the spot for ResetRace. ForceRevert would get there too, from + /// TrentaRace.Update, but a frame and a half-second tween later - after ResetRace has + /// already reopened the menu - and not at all if the reset lands mid-gesture. + /// + /// True if there was a form to drop. + public static bool HardResetForReset(Player player) + { + if (player == null) return false; + + if (formRoutine != null && TrentaRace.Instance != null) + { + TrentaRace.Instance.StopCoroutine(formRoutine); + } + formRoutine = null; + + bool hadForm = IsTransformed || isTransformingSequence || currentTransformation != null; + if (hadForm) + { + if (currentTransformation != null) Object.Destroy(currentTransformation); + currentTransformation = null; + + ZNetView nview = player.GetComponent(); + if (nview != null && nview.IsValid()) nview.GetZDO().Set("RacesOfValheim_MuspellForm", false); + + Transform playerVisual = player.transform.Find("Visual"); + if (playerVisual != null) + { + playerVisual.localScale = Vector3.one; + playerVisual.gameObject.SetActive(true); + } + } + + IsTransformed = false; + isTransformingSequence = false; + return hadForm; + } + /// /// Called by Purple Rain instead of its usual staff_summon trigger whenever Muspell is /// active - The Elder's own root-summon gesture, played on the transformation clone's diff --git a/JotunnModStub/Trol/TrolRace.cs b/JotunnModStub/Trol/TrolRace.cs index e1894ec..e2d26c4 100644 --- a/JotunnModStub/Trol/TrolRace.cs +++ b/JotunnModStub/Trol/TrolRace.cs @@ -206,11 +206,52 @@ namespace RacesOfValheim bool isTrueFormActive = Player.m_localPlayer.GetSEMan().HaveStatusEffect("SE_TrolTrueForm".GetStableHashCode()); if (wasTrueFormActive && !isTrueFormActive && !isTransforming) { - StartCoroutine(RevertTrueFormRoutine()); + RunFormRoutine(RevertTrueFormRoutine()); } wasTrueFormActive = isTrueFormActive; } + // The one grow or shrink routine in flight, if any, so ResetRace can stop it. + private Coroutine formRoutine; + + private void RunFormRoutine(System.Collections.IEnumerator routine) + { + formRoutine = StartCoroutine(routine); + } + + /// + /// Drops True Form on the spot for ResetRace. Update returns on its first line for anyone + /// who is not a Trol, so its auto-revert never saw the form end. wasTrueFormActive is the + /// part that would bite later: left true, the next time this player picks Trol the first + /// Update reads it as a form that just ran out and hands out a True Form cooldown. + /// + /// True if there was a form to drop. + public bool HardResetForReset() + { + Player player = Player.m_localPlayer; + if (player == null) return false; + + if (formRoutine != null) + { + StopCoroutine(formRoutine); + formRoutine = null; + } + + int trueFormHash = "SE_TrolTrueForm".GetStableHashCode(); + bool hadForm = isTransforming || wasTrueFormActive || player.GetSEMan().HaveStatusEffect(trueFormHash); + if (hadForm) + { + player.GetSEMan().RemoveStatusEffect(trueFormHash, true); + + ZNetView nview = player.GetComponent(); + if (nview != null && nview.IsValid()) nview.GetZDO().Set(Trol_PlayerUpdate_Patch.TrueFormKey, false); + } + + isTransforming = false; + wasTrueFormActive = false; + return hadForm; + } + private void TryTrueForm() { if (BossProgressionManager.GetCurrentProgressionState() < 5) return; // Requires Moder @@ -239,7 +280,7 @@ namespace RacesOfValheim if (!isTransforming) { - StartCoroutine(TransformToTrueFormRoutine()); + RunFormRoutine(TransformToTrueFormRoutine()); } } From c64cb393c7ddbb1bed9108f0509616cec0f2ac94 Mon Sep 17 00:00:00 2001 From: kanym Date: Wed, 14 Oct 2026 16:56:34 +0200 Subject: [PATCH 029/176] feat(trol): True Form wears Valheim's own troll True Form now hides the Trol's body and puts the vanilla forest troll's model in its place, on the owner's client and on every other player's. The costume stands as tall as the old True Form did: it follows the Visual scale Trol_PlayerUpdate_Patch already grows and publishes, so the grow-in, the shrink back and the size others see come for free. It takes the Trol skin colour from Trol - Appearance. Weapons are out while it is up. Left click is the troll's punch, right click its ground slam, and with a log in hand they become its two log swings, which wear the log down per hit as a club swing did. Throw Rock plays the troll's throw. The attacks, their triggers and reach are read off the troll's own weapons at runtime, and each hit lands on the troll's OnAttackTrigger event rather than a fixed delay. Damage is a share of the troll's own (Troll Attack Damage, 0.5), scaled by the Clubs skill like a club and hit as Clubs, so the True Form and tier melee bonuses still add on top. Other players see the troll from the existing True Form ZDO flag, with attacks replayed from a new trigger key. New options in Trol - True Form: Troll Model (on/off), Troll Model Size, Troll Attack Damage. --- JotunnModStub/Trol/TrolConfig.cs | 9 + JotunnModStub/Trol/TrolRace.cs | 22 +- JotunnModStub/Trol/TrolTrueFormBehavior.cs | 399 ++++++++++++++++++++ JotunnModStub/Trol/TrolTrueFormModel.cs | 407 +++++++++++++++++++++ 4 files changed, 835 insertions(+), 2 deletions(-) create mode 100644 JotunnModStub/Trol/TrolTrueFormBehavior.cs create mode 100644 JotunnModStub/Trol/TrolTrueFormModel.cs diff --git a/JotunnModStub/Trol/TrolConfig.cs b/JotunnModStub/Trol/TrolConfig.cs index 2a152ae..eaecaae 100644 --- a/JotunnModStub/Trol/TrolConfig.cs +++ b/JotunnModStub/Trol/TrolConfig.cs @@ -51,6 +51,9 @@ namespace RacesOfValheim public static ConfigEntry TrueFormCooldown; public static ConfigEntry TrueFormScaleNormal; public static ConfigEntry TrueFormScaleAdvanced; + public static ConfigEntry TrueFormUseTrollModel; + public static ConfigEntry TrueFormModelSize; + public static ConfigEntry TrueFormTrollDamageShare; // ─── Log Weapon (tier 7+) ────────────────────────────────────────────── public static ConfigEntry LogWeaponMaxDurability; @@ -133,6 +136,12 @@ namespace RacesOfValheim new ConfigDescription("Model scale while in True Form, tier 5-6.", new AcceptableValueRange(1f, 4f))); TrueFormScaleAdvanced = config.Bind(trueForm, "Scale (Tier 7+)", 2.5f, new ConfigDescription("Model scale while in True Form, tier 7+.", new AcceptableValueRange(1f, 4f))); + TrueFormUseTrollModel = config.Bind(trueForm, "Troll Model", true, + new ConfigDescription("Wear Valheim's own troll in True Form, with its own punch and ground slam instead of your weapons. Off: the old True Form, a bigger Trol with weapons in hand.")); + TrueFormModelSize = config.Bind(trueForm, "Troll Model Size", 1f, + new ConfigDescription("How tall the troll stands, as a share of the True Form size set by Scale above. 1 = exactly as tall as the old True Form.", new AcceptableValueRange(0.5f, 2f))); + TrueFormTrollDamageShare = config.Bind(trueForm, "Troll Attack Damage", 0.5f, + new ConfigDescription("Share of a real troll's damage each troll attack deals. Your Clubs skill then scales it the way it scales a club, and the True Form Melee Bonus and tier bonuses add on top.", new AcceptableValueRange(0.1f, 2f))); const string logWeapon = "Trol - Log Weapon"; LogWeaponMaxDurability = config.Bind(logWeapon, "Max Durability", 6f, diff --git a/JotunnModStub/Trol/TrolRace.cs b/JotunnModStub/Trol/TrolRace.cs index e2d26c4..dd5e546 100644 --- a/JotunnModStub/Trol/TrolRace.cs +++ b/JotunnModStub/Trol/TrolRace.cs @@ -153,6 +153,10 @@ namespace RacesOfValheim private void Update() { + // Before the race check, on purpose: a race change or a death has to take the troll + // costume off, and nothing below the check runs for them any more. + TrolTrueFormModel.Tick(Player.m_localPlayer); + if (!IsTrol()) return; if (RaceInput.Allowed) @@ -247,6 +251,8 @@ namespace RacesOfValheim if (nview != null && nview.IsValid()) nview.GetZDO().Set(Trol_PlayerUpdate_Patch.TrueFormKey, false); } + if (TrolTrueFormModel.RemoveLocal(player)) hadForm = true; + isTransforming = false; wasTrueFormActive = false; return hadForm; @@ -402,8 +408,20 @@ namespace RacesOfValheim Player.m_localPlayer.GetInventory().RemoveItem(rightItem); } - // Wait a moment for the animation to reach the throw point - yield return new WaitForSeconds(0.4f); + // Wait a moment for the animation to reach the throw point. Wearing the troll, that is + // the troll's own throw, and the rock leaves the hand on its OnAttackTrigger. + TrolTrueFormBehavior troll = isTrueForm ? FindObjectOfType() : null; + int baseline = troll != null ? troll.PlayThrow() : -1; + if (baseline >= 0) + { + float started = Time.time; + while (TrolTrueFormModel.AttackEvents == baseline && Time.time - started < 1.5f) yield return null; + } + else + { + yield return new WaitForSeconds(0.4f); + } + if (Player.m_localPlayer == null) yield break; Vector3 spawnPos = Player.m_localPlayer.GetEyePoint() + Player.m_localPlayer.GetLookDir() * 1.5f; diff --git a/JotunnModStub/Trol/TrolTrueFormBehavior.cs b/JotunnModStub/Trol/TrolTrueFormBehavior.cs new file mode 100644 index 0000000..1e52a57 --- /dev/null +++ b/JotunnModStub/Trol/TrolTrueFormBehavior.cs @@ -0,0 +1,399 @@ +using System.Collections; +using System.Collections.Generic; +using HarmonyLib; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// Drives the local player's troll: its legs from the hidden player's Animator, its fists from + /// the mouse. FenrirFormBehavior in shape - a trigger on the costume's Animator, then a sweep for + /// whatever is in reach - with two differences. The hit waits for the troll's own OnAttackTrigger + /// (see TrolTrueFormModel) instead of a fixed delay, and the damage is the troll's own, scaled. + /// + /// Left click punches, right click slams the ground. With a log in hand they become the troll's + /// two log swings, and each one that lands wears the log down the way a club swing used to. + /// + public class TrolTrueFormBehavior : MonoBehaviour + { + // Longest a swing waits for the troll's own hit event before landing anyway: a clip with + // no event must not leave the player swinging at nothing. + private const float HitEventTimeout = 1.5f; + + private Animator anim; + private Animator playerAnim; + private readonly FormLocomotion locomotion = new FormLocomotion(); + private readonly HashSet triggers = new HashSet(); + + private bool isAttacking; + private float busySince = -1f; + + private GameObject heldLog; + private string heldLogName; + + public bool IsAttacking => isAttacking; + + private void Start() + { + anim = GetComponentInChildren(); + Transform visual = Player.m_localPlayer != null ? Player.m_localPlayer.transform.Find("Visual") : null; + if (visual != null) playerAnim = visual.GetComponent(); + + if (anim != null) + { + foreach (AnimatorControllerParameter p in anim.parameters) + { + if (p.type == AnimatorControllerParameterType.Trigger) triggers.Add(p.name); + } + } + } + + /// Re-hides the body every frame; see RavagerFormBehavior.LateUpdate for why a + /// timer is not enough. + private void LateUpdate() + { + Player player = Player.m_localPlayer; + if (player == null) return; + PlayerVisualHider.Hide(player.transform.Find("Visual"), "trol-trueform-local"); + } + + private void Update() + { + Player player = Player.m_localPlayer; + if (player == null || anim == null || playerAnim == null) return; + + transform.localScale = Vector3.one * TrolTrueFormModel.ScaleFor(player); + + ItemDrop.ItemData right = Traverse.Create(player).Field("m_rightItem").Value; + TrolTrueFormModel.UpdateHeldLog(gameObject, right?.m_dropPrefab, ref heldLog, ref heldLogName); + + if (FormAnimGuard.Stuck(isAttacking, ref busySince)) + { + StopAllCoroutines(); + isAttacking = false; + } + + if (isAttacking || player.IsDead()) return; + + bool grounded = locomotion.Mirror(anim, playerAnim, player.IsCrouching()); + if (!grounded || !RaceInput.Allowed) return; + + bool log = heldLogName != null; + if (RaceInput.AttackDown(0)) + { + Play(log ? TrolTrueFormModel.AttackKind.LogSwingH : TrolTrueFormModel.AttackKind.Punch); + } + else if (RaceInput.AttackDown(1)) + { + Play(log ? TrolTrueFormModel.AttackKind.LogSwingV : TrolTrueFormModel.AttackKind.Slam); + } + } + + private void Play(TrolTrueFormModel.AttackKind kind) + { + TrolTrueFormModel.Profile profile = TrolTrueFormModel.Get(kind); + // A log swing the troll does not have falls back on the fist, rather than doing nothing. + if (profile == null && kind == TrolTrueFormModel.AttackKind.LogSwingH) profile = TrolTrueFormModel.Get(TrolTrueFormModel.AttackKind.Punch); + if (profile == null && kind == TrolTrueFormModel.AttackKind.LogSwingV) profile = TrolTrueFormModel.Get(TrolTrueFormModel.AttackKind.Slam); + if (profile == null) return; + + bool log = kind == TrolTrueFormModel.AttackKind.LogSwingH || kind == TrolTrueFormModel.AttackKind.LogSwingV; + StartCoroutine(AttackRoutine(profile, log)); + } + + /// + /// Plays the troll's throw for TrolRace's Throw Rock and holds the troll still through it. + /// Returns the event count to wait on, or -1 if the troll has no throw to play. + /// + public int PlayThrow() + { + TrolTrueFormModel.Profile profile = TrolTrueFormModel.Get(TrolTrueFormModel.AttackKind.Throw); + if (profile == null || isAttacking) return -1; + + int baseline = TrolTrueFormModel.AttackEvents; + StartCoroutine(ThrowRoutine(profile)); + return baseline; + } + + private IEnumerator ThrowRoutine(TrolTrueFormModel.Profile profile) + { + isAttacking = true; + Fire(profile.Trigger); + yield return WaitForClip(); + isAttacking = false; + } + + private IEnumerator AttackRoutine(TrolTrueFormModel.Profile profile, bool log) + { + isAttacking = true; + Player player = Player.m_localPlayer; + + int baseline = TrolTrueFormModel.AttackEvents; + Fire(profile.Trigger); + profile.Shared.m_startEffect.Create(player.transform.position, player.transform.rotation, player.transform); + float started = Time.time; + + while (TrolTrueFormModel.AttackEvents == baseline && Time.time - started < HitEventTimeout) + { + yield return null; + } + + if (player != null && !player.IsDead()) + { + profile.Shared.m_triggerEffect.Create(player.transform.position, player.transform.rotation, player.transform); + int landed = TrolTrueFormHit.Sweep(player, profile, transform.localScale.x); + if (landed > 0) + { + player.RaiseSkill(Skills.SkillType.Clubs, 1f); + if (log) WearLog(player); + } + } + + yield return WaitForClip(Time.time - started); + isAttacking = false; + } + + private void Fire(string trigger) + { + if (anim == null || string.IsNullOrEmpty(trigger) || !triggers.Contains(trigger)) return; + + try { anim.SetFloat("forward_speed", 0f); } catch {} + try { anim.SetFloat("sideway_speed", 0f); } catch {} + anim.SetTrigger(trigger); + TrolTrueFormModel.PublishAttackTrigger(Player.m_localPlayer, trigger); + } + + /// + /// Holds the lock until the attack clip has played out. The clip is read off the Animator a + /// frame after the trigger, when the transition into it has started; the length is clamped + /// so a wrong guess can neither cut a swing short nor freeze the troll. + /// + private IEnumerator WaitForClip(float alreadySpent = 0f) + { + yield return null; + + float length = 1.2f; + if (anim != null) + { + AnimatorClipInfo[] clips = anim.IsInTransition(0) ? anim.GetNextAnimatorClipInfo(0) : anim.GetCurrentAnimatorClipInfo(0); + if (clips != null && clips.Length > 0 && clips[0].clip != null) length = clips[0].clip.length; + } + + float remaining = Mathf.Clamp(length, 0.6f, 3f) - alreadySpent; + if (remaining > 0f) yield return new WaitForSeconds(remaining); + } + + /// The same wear a club swing put on the log, per swing that lands. TrolRace.Update + /// breaks it once it reaches zero. + private static void WearLog(Player player) + { + ItemDrop.ItemData right = Traverse.Create(player).Field("m_rightItem").Value; + if (right == null || right.m_dropPrefab == null || !right.m_dropPrefab.name.StartsWith("TrolWeapon_")) return; + right.m_durability = Mathf.Max(0f, right.m_durability - TrolConfig.LogWeaponDurabilityDrainPerHit.Value); + } + } + + /// + /// One troll blow against whatever is in reach. FenrirFormBehavior.ExecuteClawDamage's shape and + /// cover test, with the reach taken off the troll's own weapon and multiplied by how big the + /// costume is - a troll's arm is a troll's arm, at whatever size it is worn. + /// + internal static class TrolTrueFormHit + { + private const string FormLabel = "Troll"; + + private static readonly int Mask = LayerMask.GetMask("Default", "static_solid", "Default_small", "piece", + "piece_nonsolid", "terrain", "character", "character_net", "character_ghost", "hitbox", + "character_noenv", "vehicle"); + + /// How many things the blow landed on. + public static int Sweep(Player player, TrolTrueFormModel.Profile profile, float costumeScale) + { + Vector3 pos = player.transform.position; + Vector3 forward = player.transform.forward; + float range = Mathf.Max(1.5f, profile.Range * costumeScale); + bool area = profile.Type == Attack.AttackType.Area; + + Vector3 center = area + ? pos + forward * (range * 0.3f) + Vector3.up + : pos + forward * (range * 0.5f) + Vector3.up * Mathf.Max(1f, profile.Height * costumeScale); + float radius = area ? range * 0.7f : range * 0.5f + 0.5f; + float halfAngle = area ? 180f : Mathf.Max(60f, profile.Angle * 0.5f); + + Collider[] hits = Physics.OverlapSphere(center, radius, Mask); + FormMelee.LogSwing(FormLabel, hits.Length); + + HitData.DamageTypes damage = TrolTrueFormModel.DamageFor(player, profile); + var done = new HashSet(); + int landed = 0; + + foreach (Collider hit in hits) + { + if (hit.gameObject == player.gameObject) continue; + if (hit.attachedRigidbody != null && hit.attachedRigidbody.gameObject == player.gameObject) continue; + + IDestructible target = hit.GetComponentInParent(); + if (target == null || (target is Character c && c == player)) continue; + + GameObject targetObj = (target as MonoBehaviour)?.gameObject; + if (targetObj != null && done.Contains(targetObj)) continue; + + Vector3 targetCenter = hit.bounds.center; + Vector3 flat = targetCenter - pos; + flat.y = 0f; + float angle = flat.sqrMagnitude > 0.0001f ? Vector3.Angle(forward, flat) : 0f; + if (angle > halfAngle) + { + FormMelee.LogMiss(FormLabel, hit, $"outside the swing arc ({angle:0} deg)"); + continue; + } + + Vector3 eye = player.GetEyePoint(); + if (!FormMelee.CanReach(eye, center, hit, target, out string cover)) + { + FormMelee.LogMiss(FormLabel, hit, "no clear line, blocked by '" + cover + "'"); + continue; + } + + HitData hitData = new HitData(); + hitData.m_damage = damage; + hitData.m_point = targetCenter; + hitData.m_dir = (targetCenter - pos).normalized; + hitData.m_pushForce = profile.PushForce; + hitData.m_skill = Skills.SkillType.Clubs; + hitData.m_toolTier = (short)profile.ToolTier; + hitData.m_dodgeable = true; + hitData.m_blockable = true; + hitData.m_hitType = HitData.HitType.PlayerHit; + hitData.SetAttacker(player); + + if (targetObj != null) done.Add(targetObj); + FormMelee.LogHit(FormLabel, target, damage.GetTotalDamage()); + target.Damage(hitData); + profile.Shared.m_hitEffect.Create(targetCenter, Quaternion.identity); + landed++; + } + + return landed; + } + } + + /// + /// The troll every other client sees. RemoteFenrirAnimator in shape: legs from the remote + /// player's own Animator, which ZSyncAnimation keeps fed over the network, and attacks replayed + /// from the trigger the owner publishes. Sized and given its log the same way as the owner's. + /// + public class RemoteTrolTrueFormAnimator : MonoBehaviour + { + private Player player; + private Animator anim; + private Animator playerAnim; + private ZNetView nview; + private string lastAttack; + private readonly FormLocomotion locomotion = new FormLocomotion(); + + private GameObject heldLog; + private string heldLogName; + + private void LateUpdate() + { + if (player == null) return; + PlayerVisualHider.Hide(player.transform.Find("Visual"), "trol-trueform-remote"); + } + + private void Update() + { + if (player == null) player = GetComponentInParent(); + if (player == null) return; + if (nview == null) nview = player.GetComponent(); + if (anim == null) anim = GetComponentInChildren(); + if (playerAnim == null) + { + Transform visual = player.transform.Find("Visual"); + if (visual != null) playerAnim = visual.GetComponent(); + } + if (anim == null || playerAnim == null || nview == null || !nview.IsValid()) return; + + transform.localScale = Vector3.one * TrolTrueFormModel.ScaleFor(player); + + int rightHash = nview.GetZDO().GetInt(ZDOVars.s_rightItem, 0); + GameObject rightPrefab = rightHash != 0 && ObjectDB.instance != null ? ObjectDB.instance.GetItemPrefab(rightHash) : null; + TrolTrueFormModel.UpdateHeldLog(gameObject, rightPrefab, ref heldLog, ref heldLogName); + + ReplayAttack(); + locomotion.Mirror(anim, playerAnim, player.IsCrouching()); + } + + private void ReplayAttack() + { + string current = nview.GetZDO().GetString(TrolTrueFormModel.AttackTriggerKey, ""); + + // The first look only records what is there, so a punch from an earlier True Form does + // not replay the moment this troll is built. + if (lastAttack == null) { lastAttack = current; return; } + if (string.IsNullOrEmpty(current) || current == lastAttack) return; + lastAttack = current; + + int seqAt = current.LastIndexOf('#'); + string trigger = seqAt >= 0 ? current.Substring(0, seqAt) : current; + + foreach (AnimatorControllerParameter p in anim.parameters) + { + if (p.type == AnimatorControllerParameterType.Trigger && p.name == trigger) + { + try { anim.SetFloat("forward_speed", 0f); } catch {} + anim.SetTrigger(trigger); + break; + } + } + } + } + + /// + /// Puts the troll on every other client, from the True Form flag Trol_PlayerUpdate_Patch already + /// publishes for sizing. Sverm_RavagerRemoteVisuals_Patch's arrangement. + /// + [HarmonyPatch(typeof(VisEquipment), "UpdateVisuals")] + public static class Trol_TrueFormRemoteVisuals_Patch + { + public static void Postfix(VisEquipment __instance) + { + if (__instance == null || !__instance.m_isPlayer) return; + + Player player = __instance.GetComponent(); + if (player == null || player.IsOwner()) return; // The owner's own troll: TrolTrueFormModel.Tick. + + ZNetView nview = player.GetComponent(); + if (nview == null || !nview.IsValid()) return; + + ZDO zdo = nview.GetZDO(); + bool active = TrolConfig.TrueFormUseTrollModel.Value && + !player.IsDead() && + zdo.GetString("RacesOfValheim_Race", "Human") == "Trol" && + zdo.GetBool(Trol_PlayerUpdate_Patch.TrueFormKey, false); + + Transform existing = player.transform.Find(TrolTrueFormModel.RemoteModelName); + Transform playerVisual = player.transform.Find("Visual"); + + if (!active) + { + if (existing != null) + { + existing.gameObject.SetActive(false); + Object.Destroy(existing.gameObject); + PlayerVisualHider.Show(playerVisual, "trol-trueform-remote-revert"); + } + return; + } + + if (existing == null) + { + GameObject model = TrolTrueFormModel.Spawn(player, TrolTrueFormModel.RemoteModelName); + if (model == null) return; + model.AddComponent(); + } + + PlayerVisualHider.Hide(playerVisual, "trol-trueform-remote"); + } + } +} diff --git a/JotunnModStub/Trol/TrolTrueFormModel.cs b/JotunnModStub/Trol/TrolTrueFormModel.cs new file mode 100644 index 0000000..9748bf8 --- /dev/null +++ b/JotunnModStub/Trol/TrolTrueFormModel.cs @@ -0,0 +1,407 @@ +using System.Collections.Generic; +using HarmonyLib; +using Jotunn.Managers; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// True Form wears Valheim's own forest troll instead of a scaled-up player. + /// + /// Built the way the Fenrir forms are, not the way the Sverm's Ravager is: the troll's Visual is + /// instantiated live under the player, CharacterAnimEvent and AnimationEffect included. That + /// costs a FormFootsteps.Detach, and in return the troll's own clips play their own sounds and, + /// more to the point here, fire OnAttackTrigger at the exact frame a fist lands. That event + /// resolves to the PLAYER (the first Character up the hierarchy), and + /// Trol_TrueFormAttackTrigger_Patch catches it there - so every hit lands on the troll's own + /// timing rather than on a delay somebody guessed. + /// + /// SIZE. The costume does not have a size of its own. Every frame it is sized to stand as tall as + /// the player's hidden Visual would - the same Visual Trol_PlayerUpdate_Patch already grows from + /// 1.2-1.3 to the True Form scale, on the owner's client and every onlooker's. So the grow-in, the + /// shrink back and the size other players see all come from code that already worked, and + /// "Scale" / "Scale (Tier 7+)" keep meaning what they meant: how many player heights tall. + /// + /// ATTACKS. Read once off the troll's own weapons (Humanoid.m_defaultItems and friends): the + /// trigger each one plays, its damage, its reach. Nothing is cloned or equipped. The damage is a + /// share of the troll's (Troll Attack Damage), scaled by the player's Clubs skill exactly the way + /// a weapon is, and hit as Clubs - so Trol_Character_ApplyDamage_Patch adds the True Form and tier + /// bonuses on top just as it did for a club in hand. + /// + public static class TrolTrueFormModel + { + public const string Creature = "Troll"; + public const string LocalModelName = "TrolTrueFormModel"; + public const string RemoteModelName = "TrolTrueFormRemoteModel"; + + // Published by the owner after every trigger it fires, with a running count so the same + // punch twice in a row still reads as two - see FenrirAttackSync. + public const string AttackTriggerKey = "RacesOfValheim_TrolTrueFormAttack"; + private static int attackSeq; + + private static readonly int TrueFormHash = "SE_TrolTrueForm".GetStableHashCode(); + + public enum AttackKind { Punch, Slam, Throw, LogSwingH, LogSwingV } + + public class Profile + { + public string Source; + public string Trigger; + public HitData.DamageTypes Damage; + public Attack.AttackType Type; + public float Range; + public float Height; + public float Angle; + public float PushForce; + public int ToolTier; + public ItemDrop.ItemData.SharedData Shared; + } + + private static readonly Dictionary profiles = new Dictionary(); + private static bool profilesRead; + + // Measured once off the prefab: how tall the troll stands at scale 1. + private static float trollHeight = -1f; + private static string rightHandPath; + + private static GameObject localModel; + private static int attackEvents; + + public static bool LocalActive => localModel != null; + + /// How many OnAttackTrigger events the local troll has fired. Attack routines + /// remember the count and wait for it to move. + public static int AttackEvents => attackEvents; + + public static void NotifyAttackTrigger() => attackEvents++; + + // ─── Lifecycle ─────────────────────────────────────────────────────── + + /// + /// Called every frame from TrolRace.Update, before its race check, so a race change, a death + /// or the form running out all take the costume off even though nothing else in TrolRace + /// looks at the player any more by then. + /// + public static void Tick(Player player) + { + if (player == null || player != Player.m_localPlayer) return; + + bool wanted = TrolConfig.TrueFormUseTrollModel.Value && + !player.IsDead() && + TrolRace.IsTrol() && + player.GetSEMan().HaveStatusEffect(TrueFormHash); + + if (wanted && localModel == null) SpawnLocal(player); + else if (!wanted && localModel != null) RemoveLocal(player); + } + + private static void SpawnLocal(Player player) + { + localModel = Spawn(player, LocalModelName); + if (localModel == null) return; + + localModel.AddComponent(); + PlayerVisualHider.Hide(player.transform.Find("Visual"), "trol-trueform-local"); + + GameObject smoke = PrefabManager.Cache.GetPrefab("vfx_corpse_destruction_medium"); + if (smoke != null) Object.Instantiate(smoke, player.transform.position + Vector3.up, Quaternion.identity); + } + + /// Takes the costume off and gives the body back. Safe to call when there is none. + public static bool RemoveLocal(Player player) + { + if (localModel == null) return false; + + // SetActive first: Destroy waits for the end of the frame, and the behaviour's + // LateUpdate would hide the body again after the Show below. Same trap + // SvermRavagerForm.Exit documents. + localModel.SetActive(false); + Object.Destroy(localModel); + localModel = null; + + if (player != null) PlayerVisualHider.Show(player.transform.Find("Visual"), "trol-trueform-revert"); + return true; + } + + /// + /// The troll's Visual, under the given player. Shared by the owner's copy and every + /// onlooker's, so both look alike; only the driving component differs. + /// + public static GameObject Spawn(Player player, string name) + { + GameObject prefab = PrefabManager.Cache.GetPrefab(Creature); + Transform source = prefab != null ? prefab.transform.Find("Visual") : null; + if (source == null) + { + Jotunn.Logger.LogWarning($"[Trol] No '{Creature}' Visual to build True Form from; staying in the old shape."); + return null; + } + + MeasureTroll(prefab); + + GameObject model = Object.Instantiate(source.gameObject, player.transform); + model.name = name; + model.transform.localPosition = Vector3.zero; + model.transform.localRotation = Quaternion.identity; + model.transform.localScale = Vector3.one * ScaleFor(player); + + FormFootsteps.Detach(model, Creature); + + Animator anim = model.GetComponentInChildren(true); + if (anim != null) + { + anim.cullingMode = AnimatorCullingMode.AlwaysAnimate; + if (anim.GetComponent("AnimationEffect") == null) anim.gameObject.AddComponent(); + } + + Tint(model, SkinColorOf(player)); + return model; + } + + /// + /// The costume's scale for this player right now: as tall as their Visual stands, in + /// player heights, times the Troll Model Size setting. + /// + public static float ScaleFor(Player player) + { + if (player == null || trollHeight <= 0f) return 1f; + + GameObject visual = Traverse.Create(player).Field("m_visual").GetValue(); + float visualScale = visual != null ? visual.transform.localScale.y : 1f; + + CapsuleCollider capsule = player.GetComponent(); + float playerHeight = capsule != null ? capsule.height : 1.85f; + + return playerHeight * visualScale / trollHeight * TrolConfig.TrueFormModelSize.Value; + } + + private static void MeasureTroll(GameObject prefab) + { + if (trollHeight > 0f) return; + + CapsuleCollider capsule = prefab.GetComponent(); + trollHeight = capsule != null ? capsule.height * prefab.transform.localScale.y : 0f; + if (trollHeight <= 0.5f) trollHeight = 4.5f; + + // Where the troll holds its log: VisEquipment knows, so ask it rather than guess bones. + VisEquipment vis = prefab.GetComponent(); + Transform hand = vis != null ? vis.m_rightHand : null; + Transform visualRoot = prefab.transform.Find("Visual"); + if (hand != null && visualRoot != null && hand.IsChildOf(visualRoot)) + { + rightHandPath = PathFrom(visualRoot, hand); + } + + Jotunn.Logger.LogInfo($"[Trol] True Form model: '{Creature}' stands {trollHeight:0.00} m at scale 1, " + + $"right hand '{rightHandPath ?? "not found"}'."); + } + + private static string PathFrom(Transform root, Transform child) + { + var parts = new List(); + for (Transform t = child; t != null && t != root; t = t.parent) parts.Insert(0, t.name); + return string.Join("/", parts); + } + + // ─── Looks ─────────────────────────────────────────────────────────── + + /// The colour this Trol picked in Trol - Appearance, as published on their ZDO. + public static Color SkinColorOf(Player player) + { + ZNetView nview = player != null ? player.GetComponent() : null; + if (nview != null && nview.IsValid()) + { + Vector3 v = nview.GetZDO().GetVec3(TrolSkinColorPatch.SkinColorKey, new Vector3(-1f, -1f, -1f)); + if (v.x >= 0f) return new Color(v.x, v.y, v.z, 1f); + } + return player == Player.m_localPlayer ? TrolConfig.SkinColor.Value : TrolConfig.DefaultSkinColor; + } + + /// + /// Multiplies the troll's own colour by the player's skin colour, brought up to full + /// brightness first: the troll's texture is already dark, and multiplying it by the swatch + /// as-is turned it nearly black. The hue is the player's, the shading stays the troll's. + /// + private static void Tint(GameObject model, Color skin) + { + float max = Mathf.Max(skin.r, Mathf.Max(skin.g, skin.b)); + if (max <= 0.001f) return; + Color tint = new Color(skin.r / max, skin.g / max, skin.b / max, 1f); + + foreach (Renderer r in model.GetComponentsInChildren(true)) + { + if (r is ParticleSystemRenderer) continue; + foreach (Material m in r.materials) + { + if (m != null && m.HasProperty("_Color")) m.SetColor("_Color", m.GetColor("_Color") * tint); + } + } + } + + /// + /// Puts a copy of the held Trol log in the troll's right hand, or takes it away. Called every + /// frame by both drivers with whatever the player has in their right hand. + /// + public static void UpdateHeldLog(GameObject model, GameObject itemPrefab, ref GameObject current, ref string currentName) + { + string wanted = itemPrefab != null && itemPrefab.name.StartsWith("TrolWeapon_") ? itemPrefab.name : null; + if (wanted == currentName) return; + + if (current != null) Object.Destroy(current); + current = null; + currentName = wanted; + if (wanted == null || rightHandPath == null) return; + + Transform hand = model.transform.Find(rightHandPath); + Transform attach = itemPrefab.transform.Find("attach"); + if (hand == null || attach == null) return; + + current = Object.Instantiate(attach.gameObject, hand); + current.name = "TrolTrueFormLog"; + current.transform.localPosition = Vector3.zero; + current.transform.localRotation = Quaternion.identity; + // Left at the attach's own scale: the hand bone already carries the costume's, so the + // log grows and shrinks with the troll. Whether it looks right in the fist is a thing + // only an eye can settle - this is the line to change if it does not. + current.transform.localScale = Vector3.one; + } + + // ─── Attacks ───────────────────────────────────────────────────────── + + public static Profile Get(AttackKind kind) + { + EnsureProfiles(); + profiles.TryGetValue(kind, out Profile p); + return p; + } + + private static void EnsureProfiles() + { + if (profilesRead) return; + GameObject prefab = PrefabManager.Cache.GetPrefab(Creature); + Humanoid humanoid = prefab != null ? prefab.GetComponent() : null; + if (humanoid == null) return; + profilesRead = true; + + var weapons = new List(); + if (humanoid.m_defaultItems != null) weapons.AddRange(humanoid.m_defaultItems); + if (humanoid.m_randomWeapon != null) weapons.AddRange(humanoid.m_randomWeapon); + if (humanoid.m_randomSets != null) + { + foreach (Humanoid.ItemSet set in humanoid.m_randomSets) + { + if (set?.m_items != null) weapons.AddRange(set.m_items); + } + } + + foreach (GameObject weapon in weapons) + { + ItemDrop drop = weapon != null ? weapon.GetComponent() : null; + ItemDrop.ItemData.SharedData shared = drop?.m_itemData?.m_shared; + if (shared?.m_attack == null || string.IsNullOrEmpty(shared.m_attack.m_attackAnimation)) continue; + + AttackKind? kind = Classify(weapon.name.ToLower(), shared); + if (kind == null || profiles.ContainsKey(kind.Value)) continue; + + Attack a = shared.m_attack; + Profile p = new Profile + { + Source = weapon.name, + Trigger = a.m_attackAnimation, + Damage = shared.m_damages, + Type = a.m_attackType, + Range = a.m_attackRange, + Height = a.m_attackHeight, + Angle = a.m_attackAngle, + PushForce = shared.m_attackForce, + ToolTier = shared.m_toolTier, + Shared = shared, + }; + profiles[kind.Value] = p; + + Jotunn.Logger.LogInfo($"[Trol] True Form {kind.Value} <- '{p.Source}': trigger '{p.Trigger}', {p.Type}, " + + $"range {p.Range:0.0}, blunt {p.Damage.m_blunt:0} slash {p.Damage.m_slash:0} " + + $"chop {p.Damage.m_chop:0} pickaxe {p.Damage.m_pickaxe:0}."); + } + + if (!profiles.ContainsKey(AttackKind.Punch)) + { + Jotunn.Logger.LogWarning($"[Trol] '{Creature}' carries no punch; True Form left click will do nothing."); + } + } + + private static AttackKind? Classify(string name, ItemDrop.ItemData.SharedData shared) + { + if (name.Contains("throw") || shared.m_attack.m_attackProjectile != null) return AttackKind.Throw; + if (name.Contains("log")) + { + return name.EndsWith("_v") || name.Contains("vertical") ? AttackKind.LogSwingV : AttackKind.LogSwingH; + } + if (name.Contains("slam") || shared.m_attack.m_attackType == Attack.AttackType.Area) return AttackKind.Slam; + if (name.Contains("punch")) return AttackKind.Punch; + return null; + } + + /// + /// The owner's side of a remote replay: records the trigger just fired, so + /// RemoteTrolTrueFormAnimator plays it on every other client's copy. + /// + public static void PublishAttackTrigger(Player player, string trigger) + { + ZNetView nview = player != null ? player.GetComponent() : null; + if (nview == null || !nview.IsValid()) return; + + attackSeq++; + nview.GetZDO().Set(AttackTriggerKey, trigger + "#" + attackSeq); + } + + /// + /// The damage a troll attack deals for this player right now: the troll's own numbers, times + /// Troll Attack Damage, times the same random Clubs factor a club would get. + /// + public static HitData.DamageTypes DamageFor(Player player, Profile profile) + { + HitData.DamageTypes damage = profile.Damage.Clone(); + float factor = TrolConfig.TrueFormTrollDamageShare.Value * player.GetRandomSkillFactor(Skills.SkillType.Clubs); + damage.Modify(factor); + return damage; + } + + // ─── Native attack loop, shut while the costume is on ──────────────── + + [HarmonyPatch(typeof(Humanoid), "StartAttack")] + public static class Trol_TrueFormBlockNativeAttack_Patch + { + public static bool Prefix(Humanoid __instance) + { + return __instance != Player.m_localPlayer || !LocalActive; + } + } + + /// Crossbow reload and draw live here; see Fenrir's BlockPlayerAttackInputPatch. + [HarmonyPatch(typeof(Player), "PlayerAttackInput")] + public static class Trol_TrueFormBlockAttackInput_Patch + { + public static bool Prefix(Player __instance) + { + return __instance != Player.m_localPlayer || !LocalActive; + } + } + + /// + /// The troll's own clips call OnAttackTrigger at the moment a blow lands, and it arrives on + /// the player. It is the hit cue for TrolTrueFormBehavior, and it must go no further: let + /// through, it fires whatever attack the human still has in hand. + /// + [HarmonyPatch(typeof(Humanoid), nameof(Humanoid.OnAttackTrigger))] + public static class Trol_TrueFormAttackTrigger_Patch + { + public static bool Prefix(Humanoid __instance) + { + if (__instance != Player.m_localPlayer || !LocalActive) return true; + NotifyAttackTrigger(); + return false; + } + } + } +} From db29f868ea8f5dbb80c152310b5998afde9ac113 Mon Sep 17 00:00:00 2001 From: kanym Date: Wed, 14 Oct 2026 17:08:20 +0200 Subject: [PATCH 030/176] fix(trol): True Form troll size, log, reach, root during attacks, slam The troll pulsed several times a second and stayed small because PlayerVisualHider.Hide put the hidden Visual back to scale 1 every frame while Trol_PlayerUpdate_Patch grew it back, and the troll follows that scale. Hide and Show take keepScale now, and the Trol calls pass it. The camera height, which reads the same scale, stops jumping too. The log in the troll's hand is the troll's own log model, hung the way VisEquipment does it, instead of the Trol's, which was built for a person's hand and came out huge and sideways. Punch and slam reach further and hit wider, with a new Troll Attack Reach option (1.3). The player is held still through every attack clip, throw included. The ground slam spawns the troll's own troll_groundslam_aoe with the player's damage, kept off friends, plus its trigger and terrain effects. It carries chop and pickaxe at least equal to its blunt, so it breaks trees and rocks, and with Ground Slam Crater on it digs into the terrain where it lands, never inside a ward without access. --- JotunnModStub/PlayerVisualHider.cs | 12 +- JotunnModStub/Trol/TrolConfig.cs | 6 + JotunnModStub/Trol/TrolTrueFormBehavior.cs | 150 ++++++++++++++++++--- JotunnModStub/Trol/TrolTrueFormModel.cs | 53 ++++++-- 4 files changed, 189 insertions(+), 32 deletions(-) diff --git a/JotunnModStub/PlayerVisualHider.cs b/JotunnModStub/PlayerVisualHider.cs index 0f92cbf..6e753e5 100644 --- a/JotunnModStub/PlayerVisualHider.cs +++ b/JotunnModStub/PlayerVisualHider.cs @@ -37,14 +37,18 @@ namespace RacesOfValheim private float m_nextLog; private string m_context = ""; - public static void Hide(Transform playerVisual, string context) + /// Leave the Visual's scale alone. For a body that is meant to be + /// sized while hidden: the Trol's True Form troll stands as tall as the Visual does, and + /// resetting it here every frame fought Trol_PlayerUpdate_Patch growing it back - the troll + /// pulsed several times a second and never reached full size. + public static void Hide(Transform playerVisual, string context, bool keepScale = false) { if (playerVisual == null) return; // Undo the two older ways this body could have been hidden, so a form entered right // after one of those code paths still starts from a sane state. if (!playerVisual.gameObject.activeSelf) playerVisual.gameObject.SetActive(true); - if (playerVisual.localScale != Vector3.one) playerVisual.localScale = Vector3.one; + if (!keepScale && playerVisual.localScale != Vector3.one) playerVisual.localScale = Vector3.one; // Belt and braces: if anything else ever does deactivate the Visual, at least keep the // animator from snapping back to its spawn state. @@ -68,12 +72,12 @@ namespace RacesOfValheim } } - public static void Show(Transform playerVisual, string context) + public static void Show(Transform playerVisual, string context, bool keepScale = false) { if (playerVisual == null) return; if (!playerVisual.gameObject.activeSelf) playerVisual.gameObject.SetActive(true); - if (playerVisual.localScale != Vector3.one) playerVisual.localScale = Vector3.one; + if (!keepScale && playerVisual.localScale != Vector3.one) playerVisual.localScale = Vector3.one; PlayerVisualHider hider = playerVisual.GetComponent(); if (hider == null || !hider.enabled) return; diff --git a/JotunnModStub/Trol/TrolConfig.cs b/JotunnModStub/Trol/TrolConfig.cs index eaecaae..2588e9a 100644 --- a/JotunnModStub/Trol/TrolConfig.cs +++ b/JotunnModStub/Trol/TrolConfig.cs @@ -54,6 +54,8 @@ namespace RacesOfValheim public static ConfigEntry TrueFormUseTrollModel; public static ConfigEntry TrueFormModelSize; public static ConfigEntry TrueFormTrollDamageShare; + public static ConfigEntry TrueFormAttackReach; + public static ConfigEntry TrueFormSlamCrater; // ─── Log Weapon (tier 7+) ────────────────────────────────────────────── public static ConfigEntry LogWeaponMaxDurability; @@ -142,6 +144,10 @@ namespace RacesOfValheim new ConfigDescription("How tall the troll stands, as a share of the True Form size set by Scale above. 1 = exactly as tall as the old True Form.", new AcceptableValueRange(0.5f, 2f))); TrueFormTrollDamageShare = config.Bind(trueForm, "Troll Attack Damage", 0.5f, new ConfigDescription("Share of a real troll's damage each troll attack deals. Your Clubs skill then scales it the way it scales a club, and the True Form Melee Bonus and tier bonuses add on top.", new AcceptableValueRange(0.1f, 2f))); + TrueFormAttackReach = config.Bind(trueForm, "Troll Attack Reach", 1.3f, + new ConfigDescription("Multiplies how far the troll's punch and slam reach and how wide they hit. 1 = a real troll's reach at the size you stand.", new AcceptableValueRange(0.5f, 3f))); + TrueFormSlamCrater = config.Bind(trueForm, "Ground Slam Crater", true, + new ConfigDescription("The ground slam digs into the ground where it lands, like a pickaxe blow. Never inside a ward you have no access to.")); const string logWeapon = "Trol - Log Weapon"; LogWeaponMaxDurability = config.Bind(logWeapon, "Max Durability", 6f, diff --git a/JotunnModStub/Trol/TrolTrueFormBehavior.cs b/JotunnModStub/Trol/TrolTrueFormBehavior.cs index 1e52a57..004f99c 100644 --- a/JotunnModStub/Trol/TrolTrueFormBehavior.cs +++ b/JotunnModStub/Trol/TrolTrueFormBehavior.cs @@ -33,6 +33,17 @@ namespace RacesOfValheim public bool IsAttacking => isAttacking; + private void SetAttacking(bool on) + { + isAttacking = on; + TrolTrueFormModel.LocalAttacking = on; + } + + private void OnDestroy() + { + TrolTrueFormModel.LocalAttacking = false; + } + private void Start() { anim = GetComponentInChildren(); @@ -54,7 +65,7 @@ namespace RacesOfValheim { Player player = Player.m_localPlayer; if (player == null) return; - PlayerVisualHider.Hide(player.transform.Find("Visual"), "trol-trueform-local"); + PlayerVisualHider.Hide(player.transform.Find("Visual"), "trol-trueform-local", keepScale: true); } private void Update() @@ -70,7 +81,7 @@ namespace RacesOfValheim if (FormAnimGuard.Stuck(isAttacking, ref busySince)) { StopAllCoroutines(); - isAttacking = false; + SetAttacking(false); } if (isAttacking || player.IsDead()) return; @@ -117,15 +128,15 @@ namespace RacesOfValheim private IEnumerator ThrowRoutine(TrolTrueFormModel.Profile profile) { - isAttacking = true; + SetAttacking(true); Fire(profile.Trigger); yield return WaitForClip(); - isAttacking = false; + SetAttacking(false); } private IEnumerator AttackRoutine(TrolTrueFormModel.Profile profile, bool log) { - isAttacking = true; + SetAttacking(true); Player player = Player.m_localPlayer; int baseline = TrolTrueFormModel.AttackEvents; @@ -140,8 +151,18 @@ namespace RacesOfValheim if (player != null && !player.IsDead()) { - profile.Shared.m_triggerEffect.Create(player.transform.position, player.transform.rotation, player.transform); - int landed = TrolTrueFormHit.Sweep(player, profile, transform.localScale.x); + float scale = transform.localScale.x; + int landed; + if (profile.Type == Attack.AttackType.Area) + { + landed = TrolTrueFormHit.Slam(player, profile, scale); + } + else + { + profile.Shared.m_triggerEffect.Create(player.transform.position, player.transform.rotation, player.transform); + landed = TrolTrueFormHit.Sweep(player, profile, scale); + } + if (landed > 0) { player.RaiseSkill(Skills.SkillType.Clubs, 1f); @@ -150,7 +171,7 @@ namespace RacesOfValheim } yield return WaitForClip(Time.time - started); - isAttacking = false; + SetAttacking(false); } private void Fire(string trigger) @@ -206,24 +227,115 @@ namespace RacesOfValheim "piece_nonsolid", "terrain", "character", "character_net", "character_ghost", "hitbox", "character_noenv", "vehicle"); + private const string SlamAoeFallback = "troll_groundslam_aoe"; + private const string CraterPrefab = "digg_v3"; + + private static readonly int GroundMask = LayerMask.GetMask("terrain", "Default", "static_solid", "piece"); + + /// + /// The ground slam, done the way the troll does it: its attack's own spawn-on-trigger, the + /// troll_groundslam_aoe that carries the dust and the area hit. Set up with this player's + /// damage instead of the troll's (m_useAttackSettings) and kept off friends. The first + /// version swept a sphere and spawned nothing, so a slam that hit no creature looked like + /// nothing had happened at all. + /// + /// It also breaks things: the slam's damage gets chop and pickaxe at least equal to its + /// blunt, so trees, rocks and ore around the fists take the blow. With Ground Slam Crater on, + /// the ground gives way too - a pickaxe's dig, which TerrainOp does not check against wards on + /// its own, so the ward check is done here. + /// + /// 1 if the slam went off, so the caller raises the skill; the AoE does its own hits. + public static int Slam(Player player, TrolTrueFormModel.Profile profile, float costumeScale) + { + float range = Mathf.Max(2f, profile.Range * costumeScale * TrolConfig.TrueFormAttackReach.Value); + Vector3 impact = player.transform.position + player.transform.forward * (range * 0.5f); + + // Down onto whatever is under the fists, so the dust and the crater sit on the ground. + bool onTerrain = false; + if (Physics.Raycast(impact + Vector3.up * 3f, Vector3.down, out RaycastHit ground, 8f, GroundMask)) + { + impact = ground.point; + onTerrain = ground.collider != null && ground.collider.GetComponent() != null; + } + + HitData.DamageTypes damage = TrolTrueFormModel.DamageFor(player, profile); + damage.m_chop = Mathf.Max(damage.m_chop, damage.m_blunt); + damage.m_pickaxe = Mathf.Max(damage.m_pickaxe, damage.m_blunt); + + HitData hitData = new HitData(); + hitData.m_damage = damage; + hitData.m_pushForce = profile.PushForce; + hitData.m_skill = Skills.SkillType.Clubs; + hitData.m_toolTier = (short)profile.ToolTier; + hitData.m_dodgeable = true; + hitData.m_blockable = true; + hitData.m_hitType = HitData.HitType.PlayerHit; + hitData.SetAttacker(player); + + profile.Shared.m_triggerEffect.Create(impact, player.transform.rotation); + profile.Shared.m_hitTerrainEffect.Create(impact, Quaternion.identity); + + GameObject aoePrefab = profile.Shared.m_attack.m_spawnOnTrigger; + if (aoePrefab == null) aoePrefab = Jotunn.Managers.PrefabManager.Cache.GetPrefab(SlamAoeFallback); + + bool spawned = false; + if (aoePrefab != null) + { + GameObject instance = Object.Instantiate(aoePrefab, impact, Quaternion.identity); + Aoe aoe = instance.GetComponent(); + if (aoe != null) + { + aoe.m_useAttackSettings = true; + aoe.m_hitFriendly = false; + aoe.m_hitOwner = false; + aoe.m_hitProps = true; + aoe.m_radius = Mathf.Max(aoe.m_radius, range * 0.6f); + aoe.Setup(player, player.transform.forward, -1f, hitData, null, null); + spawned = true; + } + else + { + Object.Destroy(instance); + } + } + + // No Aoe to borrow: the sphere, centred on the impact, so the slam still hits. + if (!spawned) SphereHit(player, impact + Vector3.up, range * 0.7f, 180f, damage, profile); + + if (TrolConfig.TrueFormSlamCrater.Value && onTerrain && PrivateArea.CheckAccess(impact, 0f, false)) + { + GameObject crater = Jotunn.Managers.PrefabManager.Cache.GetPrefab(CraterPrefab); + if (crater != null) Object.Instantiate(crater, impact, Quaternion.identity); + } + + Jotunn.Logger.LogInfo($"[Trol] Ground slam: aoe '{aoePrefab?.name ?? "none"}' spawned={spawned}, " + + $"range {range:0.0}, onTerrain={onTerrain}."); + return 1; + } + /// How many things the blow landed on. public static int Sweep(Player player, TrolTrueFormModel.Profile profile, float costumeScale) { Vector3 pos = player.transform.position; Vector3 forward = player.transform.forward; - float range = Mathf.Max(1.5f, profile.Range * costumeScale); - bool area = profile.Type == Attack.AttackType.Area; + float range = Mathf.Max(2f, profile.Range * costumeScale * TrolConfig.TrueFormAttackReach.Value); - Vector3 center = area - ? pos + forward * (range * 0.3f) + Vector3.up - : pos + forward * (range * 0.5f) + Vector3.up * Mathf.Max(1f, profile.Height * costumeScale); - float radius = area ? range * 0.7f : range * 0.5f + 0.5f; - float halfAngle = area ? 180f : Mathf.Max(60f, profile.Angle * 0.5f); + Vector3 center = pos + forward * (range * 0.55f) + Vector3.up * Mathf.Max(1f, profile.Height * costumeScale); + float radius = range * 0.6f + 0.75f; + float halfAngle = Mathf.Max(75f, profile.Angle * 0.5f); + + return SphereHit(player, center, radius, halfAngle, TrolTrueFormModel.DamageFor(player, profile), profile); + } + + private static int SphereHit(Player player, Vector3 center, float radius, float halfAngle, + HitData.DamageTypes damage, TrolTrueFormModel.Profile profile) + { + Vector3 pos = player.transform.position; + Vector3 forward = player.transform.forward; Collider[] hits = Physics.OverlapSphere(center, radius, Mask); FormMelee.LogSwing(FormLabel, hits.Length); - HitData.DamageTypes damage = TrolTrueFormModel.DamageFor(player, profile); var done = new HashSet(); int landed = 0; @@ -298,7 +410,7 @@ namespace RacesOfValheim private void LateUpdate() { if (player == null) return; - PlayerVisualHider.Hide(player.transform.Find("Visual"), "trol-trueform-remote"); + PlayerVisualHider.Hide(player.transform.Find("Visual"), "trol-trueform-remote", keepScale: true); } private void Update() @@ -381,7 +493,7 @@ namespace RacesOfValheim { existing.gameObject.SetActive(false); Object.Destroy(existing.gameObject); - PlayerVisualHider.Show(playerVisual, "trol-trueform-remote-revert"); + PlayerVisualHider.Show(playerVisual, "trol-trueform-remote-revert", keepScale: true); } return; } @@ -393,7 +505,7 @@ namespace RacesOfValheim model.AddComponent(); } - PlayerVisualHider.Hide(playerVisual, "trol-trueform-remote"); + PlayerVisualHider.Hide(playerVisual, "trol-trueform-remote", keepScale: true); } } } diff --git a/JotunnModStub/Trol/TrolTrueFormModel.cs b/JotunnModStub/Trol/TrolTrueFormModel.cs index 9748bf8..435d8f2 100644 --- a/JotunnModStub/Trol/TrolTrueFormModel.cs +++ b/JotunnModStub/Trol/TrolTrueFormModel.cs @@ -55,6 +55,10 @@ namespace RacesOfValheim public float PushForce; public int ToolTier; public ItemDrop.ItemData.SharedData Shared; + + // The weapon's own model, as VisEquipment would hang it in the troll's hand. Only the + // log swings have one worth showing. + public GameObject Attach; } private static readonly Dictionary profiles = new Dictionary(); @@ -69,6 +73,10 @@ namespace RacesOfValheim public static bool LocalActive => localModel != null; + /// True while the local troll is in the middle of a swing, a slam or a throw. + /// Trol_TrueFormHoldStill_Patch holds the player still for exactly that long. + public static bool LocalAttacking { get; set; } + /// How many OnAttackTrigger events the local troll has fired. Attack routines /// remember the count and wait for it to move. public static int AttackEvents => attackEvents; @@ -101,7 +109,7 @@ namespace RacesOfValheim if (localModel == null) return; localModel.AddComponent(); - PlayerVisualHider.Hide(player.transform.Find("Visual"), "trol-trueform-local"); + PlayerVisualHider.Hide(player.transform.Find("Visual"), "trol-trueform-local", keepScale: true); GameObject smoke = PrefabManager.Cache.GetPrefab("vfx_corpse_destruction_medium"); if (smoke != null) Object.Instantiate(smoke, player.transform.position + Vector3.up, Quaternion.identity); @@ -118,8 +126,9 @@ namespace RacesOfValheim localModel.SetActive(false); Object.Destroy(localModel); localModel = null; + LocalAttacking = false; - if (player != null) PlayerVisualHider.Show(player.transform.Find("Visual"), "trol-trueform-revert"); + if (player != null) PlayerVisualHider.Show(player.transform.Find("Visual"), "trol-trueform-revert", keepScale: true); return true; } @@ -253,17 +262,23 @@ namespace RacesOfValheim if (wanted == null || rightHandPath == null) return; Transform hand = model.transform.Find(rightHandPath); - Transform attach = itemPrefab.transform.Find("attach"); - if (hand == null || attach == null) return; + if (hand == null) return; - current = Object.Instantiate(attach.gameObject, hand); + // The troll's OWN log, not the Trol's. The Trol's was built for a person's hand - turned + // 90 degrees, pushed 1.5 m along it, scaled to 0.4 - and in the troll's fist that came + // out huge and pointing the wrong way. The troll's log weapon carries a model made for + // exactly this bone, and hanging it the way VisEquipment.AttachItem does (zero offset, + // no rotation, its own scale) puts it where vanilla puts it. + Profile log = Get(AttackKind.LogSwingH) ?? Get(AttackKind.LogSwingV); + GameObject source = log?.Attach; + if (source == null) return; + + current = Object.Instantiate(source, hand); current.name = "TrolTrueFormLog"; current.transform.localPosition = Vector3.zero; current.transform.localRotation = Quaternion.identity; - // Left at the attach's own scale: the hand bone already carries the costume's, so the - // log grows and shrinks with the troll. Whether it looks right in the fist is a thing - // only an eye can settle - this is the line to change if it does not. - current.transform.localScale = Vector3.one; + current.transform.localScale = source.transform.localScale; + foreach (Collider c in current.GetComponentsInChildren(true)) Object.Destroy(c); } // ─── Attacks ───────────────────────────────────────────────────────── @@ -316,6 +331,7 @@ namespace RacesOfValheim PushForce = shared.m_attackForce, ToolTier = shared.m_toolTier, Shared = shared, + Attach = weapon.transform.Find("attach")?.gameObject, }; profiles[kind.Value] = p; @@ -369,6 +385,25 @@ namespace RacesOfValheim // ─── Native attack loop, shut while the costume is on ──────────────── + /// + /// Holds the troll still through its own attack clips, the way vanilla roots a creature in + /// mid-swing. SkeletonRiseControlsPatch's arrangement: the move direction is the first + /// argument of SetControls, bound by position. + /// + [HarmonyPatch(typeof(Player), "SetControls")] + public static class Trol_TrueFormHoldStill_Patch + { + public static void Prefix(Player __instance, ref Vector3 __0, ref bool jump, ref bool crouch, ref bool dodge) + { + if (__instance != Player.m_localPlayer || !LocalActive || !LocalAttacking) return; + + __0 = Vector3.zero; + jump = false; + crouch = false; + dodge = false; + } + } + [HarmonyPatch(typeof(Humanoid), "StartAttack")] public static class Trol_TrueFormBlockNativeAttack_Patch { From a9e66aeeb7fd8122695fdab1d6817b815b7108ed Mon Sep 17 00:00:00 2001 From: kanym Date: Wed, 14 Oct 2026 17:17:20 +0200 Subject: [PATCH 031/176] fix(trol): True Form log visible, slam reaches the ground, skin tint The log in the troll's fist was there but switched off: an item's attach child is stored inactive in its prefab and VisEquipment turns it on after the Instantiate. It is now switched on, hung with the item's equipoffset, and sized to the costume, since AttachItem keeps an attach at its world size and the costume is not at scale 1. The slam never ran its slam code. troll_groundslam is a Vertical attack in vanilla, not Area, so asking the attack type sent every slam down the punch's sweep: damage, but no AoE, no dust and no crater. The slam now goes by the key that was pressed. The tint multiplied _Color, which the creature shader does not read. It now shifts _Hue, _Saturation and _Value, as LevelEffects does for starred creatures, by the distance from the vanilla troll's colour to the player's skin colour. --- JotunnModStub/Trol/TrolTrueFormBehavior.cs | 10 ++- JotunnModStub/Trol/TrolTrueFormModel.cs | 72 +++++++++++++++++++--- 2 files changed, 69 insertions(+), 13 deletions(-) diff --git a/JotunnModStub/Trol/TrolTrueFormBehavior.cs b/JotunnModStub/Trol/TrolTrueFormBehavior.cs index 004f99c..4cf4acd 100644 --- a/JotunnModStub/Trol/TrolTrueFormBehavior.cs +++ b/JotunnModStub/Trol/TrolTrueFormBehavior.cs @@ -109,7 +109,11 @@ namespace RacesOfValheim if (profile == null) return; bool log = kind == TrolTrueFormModel.AttackKind.LogSwingH || kind == TrolTrueFormModel.AttackKind.LogSwingV; - StartCoroutine(AttackRoutine(profile, log)); + // The slam goes by what the key means, not by the troll's attack type: troll_groundslam + // is a Vertical attack in vanilla, not an Area one, so asking the type sent every slam + // down the punch's sweep - no dust, no crater, only the damage. + bool slam = kind == TrolTrueFormModel.AttackKind.Slam && profile == TrolTrueFormModel.Get(TrolTrueFormModel.AttackKind.Slam); + StartCoroutine(AttackRoutine(profile, log, slam)); } /// @@ -134,7 +138,7 @@ namespace RacesOfValheim SetAttacking(false); } - private IEnumerator AttackRoutine(TrolTrueFormModel.Profile profile, bool log) + private IEnumerator AttackRoutine(TrolTrueFormModel.Profile profile, bool log, bool slam) { SetAttacking(true); Player player = Player.m_localPlayer; @@ -153,7 +157,7 @@ namespace RacesOfValheim { float scale = transform.localScale.x; int landed; - if (profile.Type == Attack.AttackType.Area) + if (slam) { landed = TrolTrueFormHit.Slam(player, profile, scale); } diff --git a/JotunnModStub/Trol/TrolTrueFormModel.cs b/JotunnModStub/Trol/TrolTrueFormModel.cs index 435d8f2..5437696 100644 --- a/JotunnModStub/Trol/TrolTrueFormModel.cs +++ b/JotunnModStub/Trol/TrolTrueFormModel.cs @@ -68,6 +68,8 @@ namespace RacesOfValheim private static float trollHeight = -1f; private static string rightHandPath; + private static readonly HashSet logged = new HashSet(); + private static GameObject localModel; private static int attackEvents; @@ -226,25 +228,48 @@ namespace RacesOfValheim return player == Player.m_localPlayer ? TrolConfig.SkinColor.Value : TrolConfig.DefaultSkinColor; } + // The vanilla forest troll's own colour, as near as a single swatch gets: the same value the + // Skin Color description recommends for "the look of Valheim's own trolls". + private static readonly Color VanillaTrollColor = new Color(0x7F / 255f, 0xA8 / 255f, 0xC9 / 255f, 1f); + /// - /// Multiplies the troll's own colour by the player's skin colour, brought up to full - /// brightness first: the troll's texture is already dark, and multiplying it by the swatch - /// as-is turned it nearly black. The hue is the player's, the shading stays the troll's. + /// Shifts the troll's colour toward the player's skin colour, the way Valheim recolours a + /// starred creature: LevelEffects writes _Hue, _Saturation and _Value on the creature + /// shader. The first version multiplied _Color, which this shader does not read, so the + /// troll stayed vanilla blue. The shift is the distance from the vanilla troll's colour to + /// the chosen one, so the default Trol skin gives a troll close to its own colour and the + /// texture's shading survives whatever hue is picked. /// private static void Tint(GameObject model, Color skin) { - float max = Mathf.Max(skin.r, Mathf.Max(skin.g, skin.b)); - if (max <= 0.001f) return; - Color tint = new Color(skin.r / max, skin.g / max, skin.b / max, 1f); + Color.RGBToHSV(VanillaTrollColor, out float baseH, out float baseS, out float baseV); + Color.RGBToHSV(skin, out float h, out float s, out float v); + float hue = Mathf.Repeat(h - baseH + 0.5f, 1f) - 0.5f; + float saturation = Mathf.Clamp(s - baseS, -1f, 1f); + // Value is halved: the swatch reads darker on the skin than it looks in the picker (the + // Skin Color description says as much), and a full shift took the troll to near black. + float value = Mathf.Clamp((v - baseV) * 0.5f, -1f, 1f); + + int tinted = 0; foreach (Renderer r in model.GetComponentsInChildren(true)) { if (r is ParticleSystemRenderer) continue; foreach (Material m in r.materials) { - if (m != null && m.HasProperty("_Color")) m.SetColor("_Color", m.GetColor("_Color") * tint); + if (m == null || !m.HasProperty("_Hue")) continue; + m.SetFloat("_Hue", hue); + if (m.HasProperty("_Saturation")) m.SetFloat("_Saturation", saturation); + if (m.HasProperty("_Value")) m.SetFloat("_Value", value); + tinted++; } } + + if (logged.Add("tint/" + model.name)) + { + Jotunn.Logger.LogInfo($"[Trol] True Form tint: hue {hue:+0.00;-0.00}, saturation {saturation:+0.00;-0.00}, " + + $"value {value:+0.00;-0.00} on {tinted} material(s)."); + } } /// @@ -273,12 +298,39 @@ namespace RacesOfValheim GameObject source = log?.Attach; if (source == null) return; - current = Object.Instantiate(source, hand); + // An item's "attach" child is stored INACTIVE in its prefab; VisEquipment.AttachItem + // switches it on after the Instantiate. Copied as it was, the log hung in the fist + // switched off - invisible, and it looked as if the Trol held nothing. + current = Object.Instantiate(source); + current.SetActive(true); current.name = "TrolTrueFormLog"; + foreach (Collider c in current.GetComponentsInChildren(true)) Object.Destroy(c); + + // Hung the way AttachItem hangs it: on the joint at zero, then the item's equipoffset. + current.transform.SetParent(hand, false); current.transform.localPosition = Vector3.zero; current.transform.localRotation = Quaternion.identity; - current.transform.localScale = source.transform.localScale; - foreach (Collider c in current.GetComponentsInChildren(true)) Object.Destroy(c); + Transform offset = source.transform.parent != null ? source.transform.parent.Find("equipoffset") : null; + if (offset != null) + { + current.transform.localPosition += offset.position; + current.transform.localRotation *= offset.rotation; + } + + // AttachItem keeps the attach at its own WORLD size, and a vanilla troll stands at scale 1. + // This one is worn smaller or bigger, so the log takes the costume's share on top. Once + // set, the hand carries it through the grow and shrink like any child. + float handScale = hand.lossyScale.x; + float costume = model.transform.localScale.x; + current.transform.localScale = handScale > 0.0001f + ? source.transform.localScale * (costume / handScale) + : source.transform.localScale; + + if (logged.Add("log/" + source.name)) + { + Jotunn.Logger.LogInfo($"[Trol] True Form log '{log.Source}' in hand: hand scale {handScale:0.###}, " + + $"costume {costume:0.###}, offset {(offset != null ? "yes" : "no")}."); + } } // ─── Attacks ───────────────────────────────────────────────────────── From b2346c1437e44794b6e68cbc414553452a026c3b Mon Sep 17 00:00:00 2001 From: kanym Date: Sat, 17 Oct 2026 15:32:06 +0200 Subject: [PATCH 032/176] feat(trol): Legacy True Form switch, chosen per player The Troll Model option becomes Legacy True Form, off by default. On, True Form is the old one: the player's own Trol grown bigger, weapons in hand, body untouched, which player model mods such as VRM need. It is a local preference, not a synced one, so a server cannot force the troll costume on a VRM user. The owner publishes the choice on the ZDO and every other client reads it from there, so onlookers see each Trol the way that Trol's owner picked. --- JotunnModStub/ConfigSync.cs | 3 +++ JotunnModStub/Trol/TrolConfig.cs | 6 +++--- JotunnModStub/Trol/TrolTrueFormBehavior.cs | 3 ++- JotunnModStub/Trol/TrolTrueFormModel.cs | 13 ++++++++++++- 4 files changed, 20 insertions(+), 5 deletions(-) diff --git a/JotunnModStub/ConfigSync.cs b/JotunnModStub/ConfigSync.cs index 996168a..f743b4c 100644 --- a/JotunnModStub/ConfigSync.cs +++ b/JotunnModStub/ConfigSync.cs @@ -40,6 +40,9 @@ namespace RacesOfValheim private static readonly string[] LocalKeyParts = { "marker light", "tint", "colour", "color", "glow", "swarm scale", "log rounds", "debug", + // Each player picks their own True Form: a player model mod (VRM and the like) breaks + // under the troll costume, so a server cannot be allowed to force the costume on. + "legacy true form", }; public static void Apply(ConfigFile config) diff --git a/JotunnModStub/Trol/TrolConfig.cs b/JotunnModStub/Trol/TrolConfig.cs index 2588e9a..5521be7 100644 --- a/JotunnModStub/Trol/TrolConfig.cs +++ b/JotunnModStub/Trol/TrolConfig.cs @@ -51,7 +51,7 @@ namespace RacesOfValheim public static ConfigEntry TrueFormCooldown; public static ConfigEntry TrueFormScaleNormal; public static ConfigEntry TrueFormScaleAdvanced; - public static ConfigEntry TrueFormUseTrollModel; + public static ConfigEntry TrueFormLegacy; public static ConfigEntry TrueFormModelSize; public static ConfigEntry TrueFormTrollDamageShare; public static ConfigEntry TrueFormAttackReach; @@ -138,8 +138,8 @@ namespace RacesOfValheim new ConfigDescription("Model scale while in True Form, tier 5-6.", new AcceptableValueRange(1f, 4f))); TrueFormScaleAdvanced = config.Bind(trueForm, "Scale (Tier 7+)", 2.5f, new ConfigDescription("Model scale while in True Form, tier 7+.", new AcceptableValueRange(1f, 4f))); - TrueFormUseTrollModel = config.Bind(trueForm, "Troll Model", true, - new ConfigDescription("Wear Valheim's own troll in True Form, with its own punch and ground slam instead of your weapons. Off: the old True Form, a bigger Trol with weapons in hand.")); + TrueFormLegacy = config.Bind(trueForm, "Legacy True Form", false, + new ConfigDescription("Off: True Form wears Valheim's own troll, with its punch and ground slam instead of your weapons. On: the old True Form, your own Trol grown bigger with weapons in hand. Turn it on if you use a player model mod such as VRM, which needs the player's body to stay visible. Your own choice: other players see you the way you picked.")); TrueFormModelSize = config.Bind(trueForm, "Troll Model Size", 1f, new ConfigDescription("How tall the troll stands, as a share of the True Form size set by Scale above. 1 = exactly as tall as the old True Form.", new AcceptableValueRange(0.5f, 2f))); TrueFormTrollDamageShare = config.Bind(trueForm, "Troll Attack Damage", 0.5f, diff --git a/JotunnModStub/Trol/TrolTrueFormBehavior.cs b/JotunnModStub/Trol/TrolTrueFormBehavior.cs index 4cf4acd..4e17311 100644 --- a/JotunnModStub/Trol/TrolTrueFormBehavior.cs +++ b/JotunnModStub/Trol/TrolTrueFormBehavior.cs @@ -483,7 +483,8 @@ namespace RacesOfValheim if (nview == null || !nview.IsValid()) return; ZDO zdo = nview.GetZDO(); - bool active = TrolConfig.TrueFormUseTrollModel.Value && + // The owner's choice, not this client's: see TrolTrueFormModel.LegacyKey. + bool active = !zdo.GetBool(TrolTrueFormModel.LegacyKey, false) && !player.IsDead() && zdo.GetString("RacesOfValheim_Race", "Human") == "Trol" && zdo.GetBool(Trol_PlayerUpdate_Patch.TrueFormKey, false); diff --git a/JotunnModStub/Trol/TrolTrueFormModel.cs b/JotunnModStub/Trol/TrolTrueFormModel.cs index 5437696..ef02c33 100644 --- a/JotunnModStub/Trol/TrolTrueFormModel.cs +++ b/JotunnModStub/Trol/TrolTrueFormModel.cs @@ -37,6 +37,10 @@ namespace RacesOfValheim // Published by the owner after every trigger it fires, with a running count so the same // punch twice in a row still reads as two - see FenrirAttackSync. public const string AttackTriggerKey = "RacesOfValheim_TrolTrueFormAttack"; + + // The owner's Legacy True Form choice, so every other client draws this Trol the way its + // owner picked rather than the way the onlooker's own setting says. + public const string LegacyKey = "RacesOfValheim_TrolTrueFormLegacy"; private static int attackSeq; private static readonly int TrueFormHash = "SE_TrolTrueForm".GetStableHashCode(); @@ -96,7 +100,14 @@ namespace RacesOfValheim { if (player == null || player != Player.m_localPlayer) return; - bool wanted = TrolConfig.TrueFormUseTrollModel.Value && + bool legacy = TrolConfig.TrueFormLegacy.Value; + ZNetView nview = player.GetComponent(); + if (nview != null && nview.IsValid() && nview.GetZDO().GetBool(LegacyKey, false) != legacy) + { + nview.GetZDO().Set(LegacyKey, legacy); + } + + bool wanted = !legacy && !player.IsDead() && TrolRace.IsTrol() && player.GetSEMan().HaveStatusEffect(TrueFormHash); From b566adbfb9a84f31025b3009fc8899d18c91c1ee Mon Sep 17 00:00:00 2001 From: kanym Date: Sat, 17 Oct 2026 15:50:41 +0200 Subject: [PATCH 033/176] fix(factions): allied mobs spare a race's buildings with nobody home FactionStaticTargetPatch only vetoed a mob's piece target while an allied player stood within 100 m. Inside a troll cave that was the collapse bug: the Trol walks out, the resident Troll (its prefab has m_attackPlayerObjects) finds nobody to stop it, and the cooking station built there is in pieces when the Trol comes back. Every piece now carries the race of its builder on its ZDO, stamped in Piece.SetCreator at placement, and in Piece.Awake for older pieces the first time their builder loads them, so no timer and no scan. An allied mob of that race can't pick the piece as a target and its blows do it no damage, which also covers a swing at a foreign wall that would have hit the Trol's workbench next to it. A mob holding a grudge against the builder gets no such truce. --- .../Factions/FactionHostilityPatch.cs | 8 ++ JotunnModStub/Factions/FactionPieceTruce.cs | 120 ++++++++++++++++++ 2 files changed, 128 insertions(+) create mode 100644 JotunnModStub/Factions/FactionPieceTruce.cs diff --git a/JotunnModStub/Factions/FactionHostilityPatch.cs b/JotunnModStub/Factions/FactionHostilityPatch.cs index f8f873f..b445dbe 100644 --- a/JotunnModStub/Factions/FactionHostilityPatch.cs +++ b/JotunnModStub/Factions/FactionHostilityPatch.cs @@ -212,6 +212,14 @@ namespace RacesOfValheim Character monster = Traverse.Create(__instance).Field("m_character").Value; if (monster == null) return; + // A piece an allied race built is never a target, with or without anyone around. + // See FactionPieceTruce. + if (targetStatic.GetValue() is Component target && FactionPieceTruce.Protects(target.gameObject, monster)) + { + targetStatic.SetValue(null); + return; + } + foreach (Player player in Player.GetAllPlayers()) { if (Vector3.Distance(player.transform.position, monster.transform.position) > FactionCheckRange) continue; diff --git a/JotunnModStub/Factions/FactionPieceTruce.cs b/JotunnModStub/Factions/FactionPieceTruce.cs new file mode 100644 index 0000000..76321aa --- /dev/null +++ b/JotunnModStub/Factions/FactionPieceTruce.cs @@ -0,0 +1,120 @@ +using HarmonyLib; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// Allied mobs leave a race's buildings alone whether or not anyone is home. + /// + /// FactionStaticTargetPatch only spares a base while an allied player stands within 100 m of + /// the mob. That left the troll cave bug: a Trol builds a cooking station inside a troll cave, + /// walks out, and the cave's resident Troll - m_attackPlayerObjects is true on its prefab - finds + /// nobody to stop it and smashes the station. The player came back to the materials on the floor. + /// + /// So every piece remembers the race of whoever built it (BuilderRaceKey on its ZDO), and an + /// allied mob of that race can neither pick it as a target nor damage it. The damage veto is + /// for the blows meant for something else: a Troll swinging at a Dvergar's wall must not take + /// the Trol's workbench next to it down too. The target veto is what keeps the Troll from + /// standing there forever: it never picks an allied piece, so once the foreign one is gone it + /// has nothing to swing at. + /// + /// A piece built before this existed carries no race. It gets one the next time its builder + /// loads it, from Piece.Awake, which runs anyway for every piece in a zone as it loads - so + /// there is no timer and no scan. Until then it is protected only the old way. + /// + public static class FactionPieceTruce + { + public const string BuilderRaceKey = "RacesOfValheim_BuilderRace"; + + /// True if this piece was built by a race whose ally is, + /// and the monster holds no grudge against the builder. + public static bool Protects(GameObject pieceObject, Character monster) + { + if (!FactionsConfig.Hostility || pieceObject == null || monster == null) return false; + if (monster.IsPlayer() || monster.IsTamed()) return false; + + ZNetView nview = pieceObject.GetComponentInParent(); + if (nview == null || !nview.IsValid()) return false; + + string race = nview.GetZDO().GetString(BuilderRaceKey, ""); + if (string.IsNullOrEmpty(race)) return false; + if (!FactionHostilityPatch.IsAlliedMob(race, monster.gameObject.name)) return false; + + // A mob fighting the builder right now is no ally of the builder's house either. + long creator = nview.GetZDO().GetLong(ZDOVars.s_creator, 0L); + if (creator != 0L) + { + foreach (Player player in Player.GetAllPlayers()) + { + if (player.GetPlayerID() == creator && RaceGrudge.Holds(monster, player)) return false; + } + } + return true; + } + + private static void Stamp(ZNetView nview) + { + Player local = Player.m_localPlayer; + if (local == null) return; + + string race = FactionHostilityPatch.GetPlayerRace(local); + if (string.IsNullOrEmpty(race)) return; + + nview.GetZDO().Set(BuilderRaceKey, race); + } + + /// A new piece: stamped by its builder the moment it is placed. + [HarmonyPatch(typeof(Piece), nameof(Piece.SetCreator))] + public static class Faction_PieceSetCreator_Patch + { + public static void Postfix(Piece __instance, long uid) + { + if (__instance == null || Player.m_localPlayer == null) return; + if (uid != Player.m_localPlayer.GetPlayerID()) return; + + ZNetView nview = __instance.GetComponent(); + if (nview == null || !nview.IsValid() || !nview.IsOwner()) return; + Stamp(nview); + } + } + + /// + /// An old piece: stamped by its builder the first time it loads for them. Only the ZDO's + /// owner writes, as everywhere else in the mod; a piece some other player owns right now + /// gets its race on a later load. + /// + [HarmonyPatch(typeof(Piece), "Awake")] + public static class Faction_PieceAwake_Patch + { + public static void Postfix(Piece __instance) + { + Player local = Player.m_localPlayer; + if (__instance == null || local == null) return; + + ZNetView nview = __instance.GetComponent(); + if (nview == null || !nview.IsValid() || !nview.IsOwner()) return; + + ZDO zdo = nview.GetZDO(); + if (zdo.GetLong(ZDOVars.s_creator, 0L) != local.GetPlayerID()) return; + if (!string.IsNullOrEmpty(zdo.GetString(BuilderRaceKey, ""))) return; + + Stamp(nview); + } + } + + /// + /// Blows from an allied mob land on nothing. Patched on Damage, the attacker's side, where + /// the mob is a live object; RPC_Damage runs on the piece's owner, who may not have it. + /// + [HarmonyPatch(typeof(WearNTear), nameof(WearNTear.Damage))] + public static class Faction_PieceDamage_Patch + { + public static bool Prefix(WearNTear __instance, HitData hit) + { + if (hit == null) return true; + Character attacker = hit.GetAttacker(); + return !Protects(__instance.gameObject, attacker); + } + } + } +} From 87d0f2642c98894fdae50d9083eb97a8d74fbc92 Mon Sep 17 00:00:00 2001 From: kanym Date: Sat, 17 Oct 2026 15:51:53 +0200 Subject: [PATCH 034/176] fix(texts): four messages showed as [msg_...] Four tokens the mod printed exist in no vanilla table (checked on Valheim 1.0.20) and were never registered by the mod, so players saw the raw name in brackets. - $msg_eatanother (Trol, a food still being digested): vanilla's $msg_nomore, "You can't eat more $1", called as Player.CanEat calls it. - $msg_canteatanymore (Trol, every stomach full): vanilla's $msg_isfull. - $msg_ate (Aswid, Vae Victis): vanilla's $msg_consumed. - $msg_notenoughmoney (Dvergar bank, Trol totem): a new mod text, rov_msg_not_enough_coins, in English, Italian and Russian. --- JotunnModStub/Aswid/AswidRace.cs | 3 ++- JotunnModStub/Dvergar/DvergarBancoBehaviour.cs | 2 +- JotunnModStub/Translations/English/messages.json | 1 + JotunnModStub/Translations/Italian/messages.json | 1 + JotunnModStub/Translations/Russian/messages.json | 1 + JotunnModStub/Trol/TrolFoodPatches.cs | 10 ++++++---- JotunnModStub/Trol/TrolTotemBehaviour.cs | 2 +- 7 files changed, 13 insertions(+), 7 deletions(-) diff --git a/JotunnModStub/Aswid/AswidRace.cs b/JotunnModStub/Aswid/AswidRace.cs index b95daff..fb949a3 100644 --- a/JotunnModStub/Aswid/AswidRace.cs +++ b/JotunnModStub/Aswid/AswidRace.cs @@ -1258,7 +1258,8 @@ namespace RacesOfValheim { // Show the Vae Victis message in the center of the screen Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_aswid_vae_victis")); - Player.m_localPlayer.Message(MessageHud.MessageType.TopLeft, "$msg_ate " + addedItem.m_shared.m_name); + // "$msg_ate" exists in no vanilla table and players saw [msg_ate]; vanilla's "Consumed" reads the same. + Player.m_localPlayer.Message(MessageHud.MessageType.TopLeft, "$msg_consumed " + addedItem.m_shared.m_name); // Vae Victis XP logic - similar to Dead Raiser Player.m_localPlayer.RaiseSkill(Skills.SkillType.BloodMagic, 1f); diff --git a/JotunnModStub/Dvergar/DvergarBancoBehaviour.cs b/JotunnModStub/Dvergar/DvergarBancoBehaviour.cs index 444b065..fcdd94d 100644 --- a/JotunnModStub/Dvergar/DvergarBancoBehaviour.cs +++ b/JotunnModStub/Dvergar/DvergarBancoBehaviour.cs @@ -157,7 +157,7 @@ namespace RacesOfValheim if (CountCoins(inventory) < price) { - player.Message(MessageHud.MessageType.Center, "$msg_notenoughmoney"); + player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_not_enough_coins")); return; } diff --git a/JotunnModStub/Translations/English/messages.json b/JotunnModStub/Translations/English/messages.json index 6e6ee1e..8f7c7fa 100644 --- a/JotunnModStub/Translations/English/messages.json +++ b/JotunnModStub/Translations/English/messages.json @@ -106,6 +106,7 @@ "rov_msg_fenrir_trough_takes_line_runs_deeper": "The trough takes it. The line runs deeper now.", "rov_msg_fenrir_wants_meat_any_meat": "It wants meat. Any meat.", "rov_msg_fenrir_wants_what_yagluth_left_behind": "It wants what Yagluth left behind.", + "rov_msg_not_enough_coins": "Not enough coins", "rov_msg_skadi_are_drake": "You are a Drake!", "rov_msg_skadi_are_fader": "You are Fader!", "rov_msg_skadi_are_moder": "You are Moder!", diff --git a/JotunnModStub/Translations/Italian/messages.json b/JotunnModStub/Translations/Italian/messages.json index 6d3cb6f..f0e20bb 100644 --- a/JotunnModStub/Translations/Italian/messages.json +++ b/JotunnModStub/Translations/Italian/messages.json @@ -106,6 +106,7 @@ "rov_msg_fenrir_trough_takes_line_runs_deeper": "La mangiatoia lo accetta. Ora la discendenza va più a fondo.", "rov_msg_fenrir_wants_meat_any_meat": "Vuole carne. Qualsiasi carne.", "rov_msg_fenrir_wants_what_yagluth_left_behind": "Vuole ciò che Yagluth ha lasciato.", + "rov_msg_not_enough_coins": "Monete insufficienti", "rov_msg_skadi_are_drake": "Sei un Drake!", "rov_msg_skadi_are_fader": "Sei Fader!", "rov_msg_skadi_are_moder": "Sei Moder!", diff --git a/JotunnModStub/Translations/Russian/messages.json b/JotunnModStub/Translations/Russian/messages.json index 2e70a33..3ef6918 100644 --- a/JotunnModStub/Translations/Russian/messages.json +++ b/JotunnModStub/Translations/Russian/messages.json @@ -106,6 +106,7 @@ "rov_msg_fenrir_trough_takes_line_runs_deeper": "Кормушка принимает жертву. Родословная стаи крепнет.", "rov_msg_fenrir_wants_meat_any_meat": "Требуется мясо. Любое мясо.", "rov_msg_fenrir_wants_what_yagluth_left_behind": "Требуется то, что осталось после падения Яглута.", + "rov_msg_not_enough_coins": "Недостаточно монет", "rov_msg_skadi_are_drake": "Вы — Дрейк!", "rov_msg_skadi_are_fader": "Вы — Прародитель!", "rov_msg_skadi_are_moder": "Вы — Матерь!", diff --git a/JotunnModStub/Trol/TrolFoodPatches.cs b/JotunnModStub/Trol/TrolFoodPatches.cs index b0d452d..97232bb 100644 --- a/JotunnModStub/Trol/TrolFoodPatches.cs +++ b/JotunnModStub/Trol/TrolFoodPatches.cs @@ -90,7 +90,7 @@ namespace RacesOfValheim if (f.m_item.m_shared.m_name != item.m_shared.m_name) continue; if (f.CanEatAgain()) return true; - __instance.Message(MessageHud.MessageType.Center, "$msg_eatanother"); + __instance.Message(MessageHud.MessageType.Center, Localization.instance.Localize("$msg_nomore", item.m_shared.m_name)); __result = false; return false; } @@ -110,12 +110,12 @@ namespace RacesOfValheim if (has4 && food4.m_item.m_shared.m_name == item.m_shared.m_name) { if (canEat4) { TrolFoodManager.SetExtraFood(__instance, item); ConsumeItemEffect(__instance, item); __result = true; return false; } - else { __instance.Message(MessageHud.MessageType.Center, "$msg_eatanother"); __result = false; return false; } + else { __instance.Message(MessageHud.MessageType.Center, Localization.instance.Localize("$msg_nomore", item.m_shared.m_name)); __result = false; return false; } } if (has5 && food5.m_item.m_shared.m_name == item.m_shared.m_name) { if (state5 && canEat5) { TrolFoodManager.SetExtraFood5(__instance, item); ConsumeItemEffect(__instance, item); __result = true; return false; } - else { __instance.Message(MessageHud.MessageType.Center, "$msg_eatanother"); __result = false; return false; } + else { __instance.Message(MessageHud.MessageType.Center, Localization.instance.Localize("$msg_nomore", item.m_shared.m_name)); __result = false; return false; } } // 3. A free vanilla slot takes it the vanilla way. @@ -137,7 +137,9 @@ namespace RacesOfValheim return false; } - __instance.Message(MessageHud.MessageType.Center, "$msg_canteatanymore"); + // Vanilla's own "You are full already", the line Player.CanEat shows for a full stomach. + // "$msg_canteatanymore" was never a vanilla token, so players saw [msg_canteatanymore]. + __instance.Message(MessageHud.MessageType.Center, "$msg_isfull"); __result = false; return false; } diff --git a/JotunnModStub/Trol/TrolTotemBehaviour.cs b/JotunnModStub/Trol/TrolTotemBehaviour.cs index cf040b6..d43f028 100644 --- a/JotunnModStub/Trol/TrolTotemBehaviour.cs +++ b/JotunnModStub/Trol/TrolTotemBehaviour.cs @@ -157,7 +157,7 @@ namespace RacesOfValheim if (CountCoins(inventory) < troop.Price) { - player.Message(MessageHud.MessageType.Center, "$msg_notenoughmoney"); + player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_not_enough_coins")); return; } From 916ba5bd6f853973bc1c125d537bc4c1ed287bbd Mon Sep 17 00:00:00 2001 From: kanym Date: Sat, 17 Oct 2026 15:59:08 +0200 Subject: [PATCH 035/176] fix(pieces): placement ghost vanished off terrain for most stations Eleven pieces set m_groundPiece. Player.UpdatePlacementGhost switches the ghost off outright and returns whenever the aim is not on a Heightmap, which vanilla means for hoe and cultivator pieces. Floors, rocks and a troll cave's mesh floor are not a Heightmap, so players saw no ghost at all there, and with either flag Valheim never shows the blue placement marker. Reported for the Trol War Totem. m_groundPiece is off everywhere now. The stations (War Totem, Cursed Body Pile, Dvergar Bank, Rune Barrel, Pack Trough, Skadi Golem, Bone Servants) drop m_groundOnly too and go on floors, foundations and in caves, like the Bone Pile since 1.5.8. The living pieces (Furling bushes, Sverm nest and Hive Market, Trenta Elder Root) keep m_groundOnly: terrain only, and the ghost shows red elsewhere. --- JotunnModStub/Butler/BoneServant.cs | 8 ++++++-- JotunnModStub/Draugh/DraughSpawner.cs | 8 ++++++-- JotunnModStub/Dvergar/DvergarBanco.cs | 8 ++++++-- JotunnModStub/Dvergar/DvergarBotte.cs | 8 ++++++-- JotunnModStub/Fenrir/FenrirMangiatoia.cs | 8 ++++++-- JotunnModStub/Furling/FurlingCrops.cs | 5 ++++- JotunnModStub/Skadi/SkadiGolem.cs | 8 ++++++-- JotunnModStub/Sverm/SvermHive.cs | 5 ++++- JotunnModStub/Sverm/SvermHiveStore.cs | 5 ++++- JotunnModStub/Trenta/TrentaElderRoot.cs | 5 ++++- JotunnModStub/Trol/TrolTotem.cs | 8 ++++++-- 11 files changed, 58 insertions(+), 18 deletions(-) diff --git a/JotunnModStub/Butler/BoneServant.cs b/JotunnModStub/Butler/BoneServant.cs index 6126d1d..714016f 100644 --- a/JotunnModStub/Butler/BoneServant.cs +++ b/JotunnModStub/Butler/BoneServant.cs @@ -233,8 +233,12 @@ namespace RacesOfValheim piece.m_resources = new Piece.Requirement[0]; piece.m_name = displayName; piece.m_canBeRemoved = true; - piece.m_groundPiece = true; - piece.m_groundOnly = true; + // Neither flag, like the Bone Pile. m_groundPiece made Player.UpdatePlacementGhost switch + // the ghost off outright wherever the aim was not terrain - floors, rocks, a troll cave's + // mesh floor - so players saw no ghost at all and could not tell why. A station belongs + // in a house or a cave as much as outside. + piece.m_groundPiece = false; + piece.m_groundOnly = false; piece.m_icon = icon; Piece template = PrefabManager.Cache.GetPrefab("piece_workbench"); diff --git a/JotunnModStub/Draugh/DraughSpawner.cs b/JotunnModStub/Draugh/DraughSpawner.cs index a2604b2..61ea53d 100644 --- a/JotunnModStub/Draugh/DraughSpawner.cs +++ b/JotunnModStub/Draugh/DraughSpawner.cs @@ -251,8 +251,12 @@ namespace RacesOfValheim piece.m_resources = new Piece.Requirement[0]; piece.m_name = PieceDisplayName; piece.m_canBeRemoved = true; - piece.m_groundPiece = true; - piece.m_groundOnly = true; + // Neither flag, like the Bone Pile. m_groundPiece made Player.UpdatePlacementGhost switch + // the ghost off outright wherever the aim was not terrain - floors, rocks, a troll cave's + // mesh floor - so players saw no ghost at all and could not tell why. A station belongs + // in a house or a cave as much as outside. + piece.m_groundPiece = false; + piece.m_groundOnly = false; piece.m_icon = BorrowIcon(TrophyDraugr); // Learned on the Furling's bushes: a Piece added to world scenery is born with no icon diff --git a/JotunnModStub/Dvergar/DvergarBanco.cs b/JotunnModStub/Dvergar/DvergarBanco.cs index 34ab389..a912a2d 100644 --- a/JotunnModStub/Dvergar/DvergarBanco.cs +++ b/JotunnModStub/Dvergar/DvergarBanco.cs @@ -335,8 +335,12 @@ namespace RacesOfValheim piece.m_resources = new Piece.Requirement[0]; piece.m_name = PieceDisplayName; piece.m_canBeRemoved = true; - piece.m_groundPiece = true; - piece.m_groundOnly = true; + // Neither flag, like the Bone Pile. m_groundPiece made Player.UpdatePlacementGhost switch + // the ghost off outright wherever the aim was not terrain - floors, rocks, a troll cave's + // mesh floor - so players saw no ghost at all and could not tell why. A station belongs + // in a house or a cave as much as outside. + piece.m_groundPiece = false; + piece.m_groundOnly = false; piece.m_icon = BorrowIcon("TrophyDvergr"); Piece template = PrefabManager.Cache.GetPrefab("piece_workbench"); diff --git a/JotunnModStub/Dvergar/DvergarBotte.cs b/JotunnModStub/Dvergar/DvergarBotte.cs index e0a7953..69f30bf 100644 --- a/JotunnModStub/Dvergar/DvergarBotte.cs +++ b/JotunnModStub/Dvergar/DvergarBotte.cs @@ -90,8 +90,12 @@ namespace RacesOfValheim piece.m_resources = new Piece.Requirement[0]; piece.m_name = PieceDisplayName; piece.m_canBeRemoved = true; - piece.m_groundPiece = true; - piece.m_groundOnly = true; + // Neither flag, like the Bone Pile. m_groundPiece made Player.UpdatePlacementGhost switch + // the ghost off outright wherever the aim was not terrain - floors, rocks, a troll cave's + // mesh floor - so players saw no ghost at all and could not tell why. A station belongs + // in a house or a cave as much as outside. + piece.m_groundPiece = false; + piece.m_groundOnly = false; piece.m_icon = BorrowIcon("MeadHealthMinor") ?? BorrowIcon("TrophyDvergr"); Piece template = PrefabManager.Cache.GetPrefab("piece_workbench"); diff --git a/JotunnModStub/Fenrir/FenrirMangiatoia.cs b/JotunnModStub/Fenrir/FenrirMangiatoia.cs index 8280607..93e2e67 100644 --- a/JotunnModStub/Fenrir/FenrirMangiatoia.cs +++ b/JotunnModStub/Fenrir/FenrirMangiatoia.cs @@ -326,8 +326,12 @@ namespace RacesOfValheim piece.m_resources = new Piece.Requirement[0]; piece.m_name = PieceDisplayName; piece.m_canBeRemoved = true; - piece.m_groundPiece = true; - piece.m_groundOnly = true; + // Neither flag, like the Bone Pile. m_groundPiece made Player.UpdatePlacementGhost switch + // the ghost off outright wherever the aim was not terrain - floors, rocks, a troll cave's + // mesh floor - so players saw no ghost at all and could not tell why. A station belongs + // in a house or a cave as much as outside. + piece.m_groundPiece = false; + piece.m_groundOnly = false; piece.m_icon = BorrowIcon("TrophyFenring"); Piece template = PrefabManager.Cache.GetPrefab("piece_workbench"); diff --git a/JotunnModStub/Furling/FurlingCrops.cs b/JotunnModStub/Furling/FurlingCrops.cs index 79cf5c9..4a55b8b 100644 --- a/JotunnModStub/Furling/FurlingCrops.cs +++ b/JotunnModStub/Furling/FurlingCrops.cs @@ -381,7 +381,10 @@ namespace RacesOfValheim piece.m_craftingStation = null; piece.m_resources = new Piece.Requirement[0]; piece.m_canBeRemoved = true; - piece.m_groundPiece = true; + // Terrain only, as a living thing should be - but through m_groundOnly alone, which shows + // the ghost red off the terrain. m_groundPiece switched the ghost off outright there + // (Player.UpdatePlacementGhost), and players saw nothing at all. + piece.m_groundPiece = false; piece.m_groundOnly = true; piece.m_cultivatedGroundOnly = false; // a bush of rocks does not want tilled soil piece.m_icon = BorrowIcon(berry.YieldPrefab); diff --git a/JotunnModStub/Skadi/SkadiGolem.cs b/JotunnModStub/Skadi/SkadiGolem.cs index 99fca6a..1f14080 100644 --- a/JotunnModStub/Skadi/SkadiGolem.cs +++ b/JotunnModStub/Skadi/SkadiGolem.cs @@ -264,8 +264,12 @@ namespace RacesOfValheim piece.m_resources = new Piece.Requirement[0]; piece.m_name = DisplayName; piece.m_canBeRemoved = true; - piece.m_groundPiece = true; - piece.m_groundOnly = true; + // Neither flag, like the Bone Pile. m_groundPiece made Player.UpdatePlacementGhost switch + // the ghost off outright wherever the aim was not terrain - floors, rocks, a troll cave's + // mesh floor - so players saw no ghost at all and could not tell why. A station belongs + // in a house or a cave as much as outside. + piece.m_groundPiece = false; + piece.m_groundOnly = false; piece.m_icon = BorrowIcon(CrystalItem); PieceManager.Instance.AddPiece(new CustomPiece(prefab, fixReference: false, new PieceConfig diff --git a/JotunnModStub/Sverm/SvermHive.cs b/JotunnModStub/Sverm/SvermHive.cs index cc30a09..6116fab 100644 --- a/JotunnModStub/Sverm/SvermHive.cs +++ b/JotunnModStub/Sverm/SvermHive.cs @@ -96,7 +96,10 @@ namespace RacesOfValheim Piece piece = prefab.GetComponent() ?? prefab.AddComponent(); piece.m_name = DisplayName; piece.m_description = "$rov_piece_sverm_broodmound_desc"; - piece.m_groundPiece = true; + // Terrain only, as a living thing should be - but through m_groundOnly alone, which shows + // the ghost red off the terrain. m_groundPiece switched the ghost off outright there + // (Player.UpdatePlacementGhost), and players saw nothing at all. + piece.m_groundPiece = false; piece.m_groundOnly = true; piece.m_cultivatedGroundOnly = false; piece.m_canBeRemoved = true; diff --git a/JotunnModStub/Sverm/SvermHiveStore.cs b/JotunnModStub/Sverm/SvermHiveStore.cs index ef96cc7..0699fda 100644 --- a/JotunnModStub/Sverm/SvermHiveStore.cs +++ b/JotunnModStub/Sverm/SvermHiveStore.cs @@ -324,7 +324,10 @@ namespace RacesOfValheim piece.m_resources = new Piece.Requirement[0]; piece.m_name = DisplayName; piece.m_description = "$rov_piece_sverm_hivemarket_desc"; - piece.m_groundPiece = true; + // Terrain only, as a living thing should be - but through m_groundOnly alone, which shows + // the ghost red off the terrain. m_groundPiece switched the ghost off outright there + // (Player.UpdatePlacementGhost), and players saw nothing at all. + piece.m_groundPiece = false; piece.m_groundOnly = true; piece.m_canBeRemoved = true; diff --git a/JotunnModStub/Trenta/TrentaElderRoot.cs b/JotunnModStub/Trenta/TrentaElderRoot.cs index ba21936..8e8e421 100644 --- a/JotunnModStub/Trenta/TrentaElderRoot.cs +++ b/JotunnModStub/Trenta/TrentaElderRoot.cs @@ -83,7 +83,10 @@ namespace RacesOfValheim piece.m_resources = new Piece.Requirement[0]; piece.m_name = TrentaConfig.ElderRootDisplayName; piece.m_canBeRemoved = true; - piece.m_groundPiece = true; + // Terrain only, as a living thing should be - but through m_groundOnly alone, which shows + // the ghost red off the terrain. m_groundPiece switched the ghost off outright there + // (Player.UpdatePlacementGhost), and players saw nothing at all. + piece.m_groundPiece = false; piece.m_groundOnly = true; piece.m_icon = icon; diff --git a/JotunnModStub/Trol/TrolTotem.cs b/JotunnModStub/Trol/TrolTotem.cs index 99f94c9..5bd38f8 100644 --- a/JotunnModStub/Trol/TrolTotem.cs +++ b/JotunnModStub/Trol/TrolTotem.cs @@ -303,8 +303,12 @@ namespace RacesOfValheim piece.m_resources = new Piece.Requirement[0]; piece.m_name = PieceDisplayName; piece.m_canBeRemoved = true; - piece.m_groundPiece = true; - piece.m_groundOnly = true; + // Neither flag, like the Bone Pile. m_groundPiece made Player.UpdatePlacementGhost switch + // the ghost off outright wherever the aim was not terrain - floors, rocks, a troll cave's + // mesh floor - so players saw no ghost at all and could not tell why. A station belongs + // in a house or a cave as much as outside. + piece.m_groundPiece = false; + piece.m_groundOnly = false; piece.m_icon = BorrowIcon(TrollHead); Piece template = PrefabManager.Cache.GetPrefab("piece_workbench"); From edc7fd33b7ee1aa567ddc4c84cd888a1efb2f0b4 Mon Sep 17 00:00:00 2001 From: kanym Date: Sat, 17 Oct 2026 16:11:16 +0200 Subject: [PATCH 036/176] debug: F8 dumps the build ghost and the placement ray (temporary) --- JotunnModStub/PlacementGhostDebug.cs | 70 ++++++++++++++++++++++++++++ JotunnModStub/RacesOfValheim.cs | 2 + 2 files changed, 72 insertions(+) create mode 100644 JotunnModStub/PlacementGhostDebug.cs diff --git a/JotunnModStub/PlacementGhostDebug.cs b/JotunnModStub/PlacementGhostDebug.cs new file mode 100644 index 0000000..17fd667 --- /dev/null +++ b/JotunnModStub/PlacementGhostDebug.cs @@ -0,0 +1,70 @@ +using System.Text; +using HarmonyLib; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// TEMPORARY DEBUG. F8 dumps the build ghost in hand and what the placement ray hits, to the + /// console and the BepInEx log - for the Trol War Totem, whose ghost stays invisible where every + /// other station's now shows. Remove once that is fixed. + /// + public class PlacementGhostDebug : MonoBehaviour + { + private void Update() + { + if (!Input.GetKeyDown(KeyCode.F8)) return; + + Player player = Player.m_localPlayer; + if (player == null) return; + + var sb = new StringBuilder(); + GameObject ghost = Traverse.Create(player).Field("m_placementGhost").Value; + sb.AppendLine($"[GhostDebug] status={Traverse.Create(player).Field("m_placementStatus").GetValue()} ghost={(ghost != null ? ghost.name : "none")}"); + + Camera cam = GameCamera.instance != null ? GameCamera.instance.GetComponent() : null; + if (GameCamera.instance != null && Physics.Raycast(GameCamera.instance.transform.position, GameCamera.instance.transform.forward, out RaycastHit hit, 50f)) + { + sb.AppendLine($"[GhostDebug] ray hit '{hit.collider.name}' layer={LayerMask.LayerToName(hit.collider.gameObject.layer)} " + + $"dist={hit.distance:0.0} heightmap={(hit.collider.GetComponent() != null)} rigidbody={(hit.collider.attachedRigidbody != null)}"); + } + + if (ghost != null) + { + sb.AppendLine($"[GhostDebug] ghost active={ghost.activeInHierarchy} pos={ghost.transform.position} scale={ghost.transform.lossyScale} " + + $"layer={LayerMask.LayerToName(ghost.layer)} cameraMask has ghost layer={(cam != null && (cam.cullingMask & (1 << ghost.layer)) != 0)}"); + + foreach (LODGroup lod in ghost.GetComponentsInChildren(true)) + { + sb.AppendLine($"[GhostDebug] LODGroup on '{lod.name}' enabled={lod.enabled} active={lod.gameObject.activeInHierarchy} lods={lod.lodCount}"); + } + + foreach (Renderer r in ghost.GetComponentsInChildren(true)) + { + Material m = r.sharedMaterial; + sb.AppendLine($"[GhostDebug] renderer '{PathOf(r.transform, ghost.transform)}' {r.GetType().Name} enabled={r.enabled} " + + $"forceOff={r.forceRenderingOff} active={r.gameObject.activeInHierarchy} visible={r.isVisible} " + + $"layer={LayerMask.LayerToName(r.gameObject.layer)} bounds={r.bounds.size} " + + $"shader={(m != null && m.shader != null ? m.shader.name : "none")}"); + } + } + + string text = sb.ToString(); + Jotunn.Logger.LogInfo(text); + if (Console.instance != null) + { + foreach (string line in text.Split('\n')) + { + if (!string.IsNullOrWhiteSpace(line)) Console.instance.Print(line.TrimEnd()); + } + } + } + + private static string PathOf(Transform t, Transform root) + { + string path = t.name; + for (Transform p = t.parent; p != null && p != root; p = p.parent) path = p.name + "/" + path; + return path; + } + } +} diff --git a/JotunnModStub/RacesOfValheim.cs b/JotunnModStub/RacesOfValheim.cs index e6f8289..6bb439d 100644 --- a/JotunnModStub/RacesOfValheim.cs +++ b/JotunnModStub/RacesOfValheim.cs @@ -69,6 +69,8 @@ namespace RacesOfValheim // Not a race: a perk two races share (Skadi and Trol build inside troll caves), so it // gets its own component rather than living inside either one's Update. gameObject.AddComponent(); + // TEMPORARY DEBUG: F8 dumps the build ghost (Trol War Totem ghost investigation). + gameObject.AddComponent(); PrefabManager.OnVanillaPrefabsAvailable += CreateAllModAssets; CommandManager.Instance.AddConsoleCommand(new ResetRaceCommand()); CommandManager.Instance.AddConsoleCommand(new CheckProgressionCommand()); From e1bd3b66e16e6fc4d2782ac0dda7ea5aa50a555b Mon Sep 17 00:00:00 2001 From: kanym Date: Sat, 17 Oct 2026 16:19:03 +0200 Subject: [PATCH 037/176] fix(trol): War Totem ghost invisible everywhere The totem borrowed its look from the GoblinTotem item, whose root holds a ParticleSystem while the mesh sits in its attach child. Player.SetupPlacementGhost switches off every GameObject with a ParticleSystem, so it took the root and the mesh with it: the F8 dump showed TotemModel/model/attach/model active=False on the ghost. The Yagluth head (TrophyGoblinKing) is built the same way. Both now borrow the item's attach child, which is the mesh itself. ModelBorrow switches the copy on, since an item's attach is stored inactive in its prefab. --- JotunnModStub/ModelBorrow.cs | 5 +++++ JotunnModStub/Trol/TrolTotem.cs | 19 +++++++++++++++++-- 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/JotunnModStub/ModelBorrow.cs b/JotunnModStub/ModelBorrow.cs index b064361..20b2ded 100644 --- a/JotunnModStub/ModelBorrow.cs +++ b/JotunnModStub/ModelBorrow.cs @@ -89,6 +89,11 @@ namespace RacesOfValheim copy.transform.localRotation = localRotation; copy.transform.localScale = Vector3.one; + // An item's "attach" child is stored switched off in its prefab (VisEquipment turns it on + // when it is worn), so a copy of one comes out switched off too. The holder above is still + // inactive, so turning the copy on wakes nothing. + if (!copy.activeSelf) copy.SetActive(true); + // Everything that is not a Renderer or a Transform. Order matters for the same reason it did // on the Aswid's lights: behaviours first, then the things they hold references to. foreach (MonoBehaviour behaviour in copy.GetComponentsInChildren(true)) diff --git a/JotunnModStub/Trol/TrolTotem.cs b/JotunnModStub/Trol/TrolTotem.cs index 5bd38f8..f3d567f 100644 --- a/JotunnModStub/Trol/TrolTotem.cs +++ b/JotunnModStub/Trol/TrolTotem.cs @@ -239,7 +239,7 @@ namespace RacesOfValheim // The look the player asked for: the totem itself, not a log with a head on it. Grounded on // its own base, so Vector3.zero really is "standing on the spot the hammer picked". - GameObject totemModel = ModelBorrow.Attach(prefab.transform, "TotemModel", "GoblinTotem", + GameObject totemModel = ModelBorrow.Attach(prefab.transform, "TotemModel", ItemMesh("GoblinTotem"), Vector3.zero, Quaternion.identity, TotemHeight, "Trol"); TrolTotemBehaviour totem = prefab.AddComponent(); @@ -293,7 +293,7 @@ namespace RacesOfValheim Jotunn.Logger.LogInfo($"[Trol] Totem crown measured at {crown:0.##} m; the king's head is " + $"{HeadSize} m across and sunk {HeadSize * HeadSink:0.##} m into it."); - totem.m_yagluthHead = ModelBorrow.Attach(prefab.transform, "TotemHeadYagluth", YagluthHead, + totem.m_yagluthHead = ModelBorrow.Attach(prefab.transform, "TotemHeadYagluth", ItemMesh(YagluthHead), new Vector3(0f, crown - HeadSize * HeadSink, 0f), HeadTilt, HeadSize, "Trol"); totem.m_yagluthHead.SetActive(false); @@ -329,6 +329,21 @@ namespace RacesOfValheim })); } + /// + /// The part of an item that IS the item: its "attach" child, which holds the mesh, rather than + /// the whole prefab. GoblinTotem carries a ParticleSystem on its root, and + /// Player.SetupPlacementGhost switches off every GameObject that has one - taking the root and, + /// with it, the mesh underneath. That is why the War Totem showed no ghost anywhere while every + /// other station did. TrophyGoblinKing is built the same way. Falls back to the whole prefab + /// for an item without an attach. + /// + private static GameObject ItemMesh(string itemPrefab) + { + GameObject source = PrefabManager.Cache.GetPrefab(itemPrefab); + Transform attach = source != null ? source.transform.Find("attach") : null; + return attach != null ? attach.gameObject : source; + } + public static void EnsureKnown(Player player) { if (player == null) return; From 0cc10b437e41642f6e6f35de1009ee8ada314dd5 Mon Sep 17 00:00:00 2001 From: kanym Date: Sat, 17 Oct 2026 16:21:50 +0200 Subject: [PATCH 038/176] Revert "debug: F8 dumps the build ghost and the placement ray (temporary)" This reverts commit edc7fd33b7ee1aa567ddc4c84cd888a1efb2f0b4. --- JotunnModStub/PlacementGhostDebug.cs | 70 ---------------------------- JotunnModStub/RacesOfValheim.cs | 2 - 2 files changed, 72 deletions(-) delete mode 100644 JotunnModStub/PlacementGhostDebug.cs diff --git a/JotunnModStub/PlacementGhostDebug.cs b/JotunnModStub/PlacementGhostDebug.cs deleted file mode 100644 index 17fd667..0000000 --- a/JotunnModStub/PlacementGhostDebug.cs +++ /dev/null @@ -1,70 +0,0 @@ -using System.Text; -using HarmonyLib; -using UnityEngine; - -namespace RacesOfValheim -{ - /// - /// TEMPORARY DEBUG. F8 dumps the build ghost in hand and what the placement ray hits, to the - /// console and the BepInEx log - for the Trol War Totem, whose ghost stays invisible where every - /// other station's now shows. Remove once that is fixed. - /// - public class PlacementGhostDebug : MonoBehaviour - { - private void Update() - { - if (!Input.GetKeyDown(KeyCode.F8)) return; - - Player player = Player.m_localPlayer; - if (player == null) return; - - var sb = new StringBuilder(); - GameObject ghost = Traverse.Create(player).Field("m_placementGhost").Value; - sb.AppendLine($"[GhostDebug] status={Traverse.Create(player).Field("m_placementStatus").GetValue()} ghost={(ghost != null ? ghost.name : "none")}"); - - Camera cam = GameCamera.instance != null ? GameCamera.instance.GetComponent() : null; - if (GameCamera.instance != null && Physics.Raycast(GameCamera.instance.transform.position, GameCamera.instance.transform.forward, out RaycastHit hit, 50f)) - { - sb.AppendLine($"[GhostDebug] ray hit '{hit.collider.name}' layer={LayerMask.LayerToName(hit.collider.gameObject.layer)} " + - $"dist={hit.distance:0.0} heightmap={(hit.collider.GetComponent() != null)} rigidbody={(hit.collider.attachedRigidbody != null)}"); - } - - if (ghost != null) - { - sb.AppendLine($"[GhostDebug] ghost active={ghost.activeInHierarchy} pos={ghost.transform.position} scale={ghost.transform.lossyScale} " + - $"layer={LayerMask.LayerToName(ghost.layer)} cameraMask has ghost layer={(cam != null && (cam.cullingMask & (1 << ghost.layer)) != 0)}"); - - foreach (LODGroup lod in ghost.GetComponentsInChildren(true)) - { - sb.AppendLine($"[GhostDebug] LODGroup on '{lod.name}' enabled={lod.enabled} active={lod.gameObject.activeInHierarchy} lods={lod.lodCount}"); - } - - foreach (Renderer r in ghost.GetComponentsInChildren(true)) - { - Material m = r.sharedMaterial; - sb.AppendLine($"[GhostDebug] renderer '{PathOf(r.transform, ghost.transform)}' {r.GetType().Name} enabled={r.enabled} " + - $"forceOff={r.forceRenderingOff} active={r.gameObject.activeInHierarchy} visible={r.isVisible} " + - $"layer={LayerMask.LayerToName(r.gameObject.layer)} bounds={r.bounds.size} " + - $"shader={(m != null && m.shader != null ? m.shader.name : "none")}"); - } - } - - string text = sb.ToString(); - Jotunn.Logger.LogInfo(text); - if (Console.instance != null) - { - foreach (string line in text.Split('\n')) - { - if (!string.IsNullOrWhiteSpace(line)) Console.instance.Print(line.TrimEnd()); - } - } - } - - private static string PathOf(Transform t, Transform root) - { - string path = t.name; - for (Transform p = t.parent; p != null && p != root; p = p.parent) path = p.name + "/" + path; - return path; - } - } -} diff --git a/JotunnModStub/RacesOfValheim.cs b/JotunnModStub/RacesOfValheim.cs index 6bb439d..e6f8289 100644 --- a/JotunnModStub/RacesOfValheim.cs +++ b/JotunnModStub/RacesOfValheim.cs @@ -69,8 +69,6 @@ namespace RacesOfValheim // Not a race: a perk two races share (Skadi and Trol build inside troll caves), so it // gets its own component rather than living inside either one's Update. gameObject.AddComponent(); - // TEMPORARY DEBUG: F8 dumps the build ghost (Trol War Totem ghost investigation). - gameObject.AddComponent(); PrefabManager.OnVanillaPrefabsAvailable += CreateAllModAssets; CommandManager.Instance.AddConsoleCommand(new ResetRaceCommand()); CommandManager.Instance.AddConsoleCommand(new CheckProgressionCommand()); From 5b2e5f4f86ac2df15e346f83fa8fdf32bbaa030f Mon Sep 17 00:00:00 2001 From: kanym Date: Sat, 17 Oct 2026 16:24:09 +0200 Subject: [PATCH 039/176] feat(stations): the race is a build requirement, shown in the panel Every race station is listed in RaceStationLock with the race (or races) that may build it. The build panel shows it in the requirement row after the materials and the crafting station, with the race's icon from the race menu and its translated name, blinking red when the player is not of that race, the way vanilla flags a missing station. Player.HaveRequirements answers false for CanBuild, so the piece is greyed and a click gets vanilla's "Missing requirements". IsKnown and CanAlmostBuild stay vanilla, so every station is still listed. Seven stations had no race lock at all and are now locked too: Cursed Body Pile, Pack Trough, Bone Pile, Bound Sentry, Blood Refinery, Composter and Heartwood Grove. The stations' own placement gates stay for their boss-tier checks and for no-cost debug building. --- JotunnModStub/RaceStationLock.cs | 131 +++++++++++++++++++++++++++++++ JotunnModStub/RacesOfValheim.cs | 22 ++++++ 2 files changed, 153 insertions(+) create mode 100644 JotunnModStub/RaceStationLock.cs diff --git a/JotunnModStub/RaceStationLock.cs b/JotunnModStub/RaceStationLock.cs new file mode 100644 index 0000000..ba84346 --- /dev/null +++ b/JotunnModStub/RaceStationLock.cs @@ -0,0 +1,131 @@ +using System.Collections.Generic; +using System.Linq; +using HarmonyLib; +using TMPro; +using UnityEngine; +using UnityEngine.UI; + +namespace RacesOfValheim +{ + /// + /// A race station asks for its race the way a piece asks for wood: as a requirement. + /// + /// Each station used to have its own lock, or none. Nine refused at placement with a message of + /// their own (PieceDensityLimit gates, the Trol totem, the Dvergar bank and barrel, the Trenta + /// root); seven - the Cursed Body Pile, the Pack Trough, the Bone Pile and Sentry, the Blood + /// Refinery, the Composter and the Heartwood Grove - anybody could build. And none of them said so + /// before the click: the build panel listed the wood and the trophy and nothing else. + /// + /// Now every one of them is listed here with its race, and two things follow. The build panel + /// shows the race in the requirement row, with the race's icon and name, blinking red when the + /// player is not of it - the same row and the same blink vanilla uses for a missing crafting + /// station. And Player.HaveRequirements answers false for CanBuild, so the piece is greyed in the + /// menu and a click gets vanilla's "Missing requirements", exactly as for a missing item. IsKnown + /// and CanAlmostBuild are left alone, so the station stays in the menu for everyone to read. + /// + /// The stations' own gates stay: they also check boss tiers, and they still catch a build in + /// no-cost debug mode, which skips HaveRequirements altogether. + /// + public static class RaceStationLock + { + private static readonly Dictionary Races = new Dictionary + { + { TrolTotem.PieceName, new[] { TrolTotem.RaceId } }, + { DraughSpawner.PieceName, new[] { DraughVisuals.RaceId } }, + { DvergarBanco.PieceName, new[] { DvergarConfig.RaceId } }, + { DvergarBotte.PieceName, new[] { DvergarConfig.RaceId } }, + { FenrirMangiatoia.PieceName, new[] { FenrirMangiatoia.RaceId } }, + { SkadiGolem.SeedPieceName, new[] { "Skadi" } }, + { BoneServant.SmithTableName, new[] { SkeletonVisuals.RaceId, "Skadi" } }, + { BoneServant.CookTableName, new[] { "Skadi" } }, + { SkeletonBonePile.PieceName, new[] { SkeletonVisuals.RaceId } }, + { SkeletonSentry.SeedPieceName, new[] { SkeletonVisuals.RaceId } }, + { SvermHive.PieceName, new[] { SvermConfig.RaceId } }, + { SvermHiveMarketPiece.PieceName, new[] { SvermConfig.RaceId } }, + { TrentaConfig.ElderRootPieceName, new[] { TrentaConfig.RaceId } }, + { TrentaConfig.ComposterPieceName, new[] { TrentaConfig.RaceId } }, + { TrentaConfig.GrovePieceName, new[] { TrentaConfig.RaceId } }, + { AswidBloodRefinery.PieceName, new[] { "Aswid" } }, + }; + + /// The races allowed to build this piece, or null for a piece anyone builds. + public static string[] For(Piece piece) + { + if (piece == null) return null; + return Races.TryGetValue(Utils.GetPrefabName(piece.gameObject), out string[] races) ? races : null; + } + + public static bool Allows(Player player, string[] races) + { + if (races == null) return true; + if (player == null) return false; + string race = FactionHostilityPatch.GetPlayerRace(player); + return race != null && races.Contains(race); + } + + public static string NameOf(string race) => ModText.Get("rov_race_" + race.ToLowerInvariant() + "_name"); + + /// CanBuild only: see the class doc for why IsKnown and CanAlmostBuild stay vanilla. + [HarmonyPatch(typeof(Player), nameof(Player.HaveRequirements), new[] { typeof(Piece), typeof(Player.RequirementMode) })] + public static class RaceStation_HaveRequirements_Patch + { + public static void Postfix(Player __instance, Piece piece, Player.RequirementMode mode, ref bool __result) + { + if (!__result || mode != Player.RequirementMode.CanBuild) return; + if (!Allows(__instance, For(piece))) __result = false; + } + } + + /// + /// The race in the build panel's requirement row, in the first slot after the materials and + /// the crafting station - the slots Hud.SetupPieceInfo has just filled or switched off. + /// + [HarmonyPatch(typeof(Hud), "SetupPieceInfo")] + public static class RaceStation_PieceInfo_Patch + { + // Vanilla never sets the name's colour, so a row this patch left red would stay red for + // whatever item the next piece puts in it. + public static void Prefix(Hud __instance) + { + if (__instance.m_requirementItems == null) return; + foreach (GameObject row in __instance.m_requirementItems) + { + TMP_Text name = row != null ? row.transform.Find("res_name")?.GetComponent() : null; + if (name != null) name.color = Color.white; + } + } + + public static void Postfix(Hud __instance, Piece piece) + { + string[] races = For(piece); + if (races == null || races.Length == 0 || __instance.m_requirementItems == null) return; + + int slot = piece.m_resources.Length + (piece.m_craftingStation != null ? 1 : 0); + if (slot >= __instance.m_requirementItems.Length) return; + + GameObject row = __instance.m_requirementItems[slot]; + Image icon = row.transform.Find("res_icon")?.GetComponent(); + TMP_Text name = row.transform.Find("res_name")?.GetComponent(); + TMP_Text amount = row.transform.Find("res_amount")?.GetComponent(); + UITooltip tooltip = row.GetComponent(); + if (icon == null || name == null || amount == null) return; + + row.SetActive(true); + icon.gameObject.SetActive(true); + name.gameObject.SetActive(true); + amount.gameObject.SetActive(true); + + string label = string.Join(" / ", races.Select(NameOf)); + icon.sprite = RacesOfValheim.RaceIcon(races[0]); + name.text = label; + if (tooltip != null) tooltip.m_text = label; + amount.text = ""; + + bool ok = Allows(Player.m_localPlayer, races); + icon.color = ok ? Color.white : Color.gray; + // Vanilla's blink for a missing crafting station, on the name since there is no number. + name.color = ok || Mathf.Sin(Time.time * 10f) <= 0f ? Color.white : Color.red; + } + } + } +} diff --git a/JotunnModStub/RacesOfValheim.cs b/JotunnModStub/RacesOfValheim.cs index e6f8289..0702646 100644 --- a/JotunnModStub/RacesOfValheim.cs +++ b/JotunnModStub/RacesOfValheim.cs @@ -451,6 +451,28 @@ namespace RacesOfValheim GUIManager.BlockInput(true); } + /// + /// The icon the race menu shows for a race, for anything else that names a race - the race + /// requirement in the build panel (RaceStationLock). One source, so the two never disagree. + /// + public static Sprite RaceIcon(string race) + { + if (Instance == null || string.IsNullOrEmpty(race)) return null; + switch (race) + { + case "Fenrir": return Instance.GetFenrirIcon(); + case "Skadi": return Instance.GetSkadiIcon(); + case SkeletonVisuals.RaceId: return Instance.GetSkeletonIcon(); + case "Aswid": return Instance.GetAswidIcon(); + case "Furling": return Instance.GetFurlingIcon(); + case "Trol": return Instance.GetTrolIcon(); + case DvergarConfig.RaceId: return Instance.GetDvergarIcon(); + case TrentaConfig.RaceId: return Instance.GetTrentaIcon(); + case SvermConfig.RaceId: return Instance.GetSvermIcon(); + } + return race == DraughVisuals.RaceId ? Instance.GetDraughIcon() : Instance.GetHumanIcon(); + } + private Sprite GetHumanIcon() { GameObject clubPrefab = PrefabManager.Cache.GetPrefab("Club")?.gameObject; From 7647b66aa051553a6d44c1fcb52602726a635358 Mon Sep 17 00:00:00 2001 From: kanym Date: Sat, 17 Oct 2026 16:39:56 +0200 Subject: [PATCH 040/176] fix(stations): the race requirement comes first in the build panel The race took the first free row after the materials and the crafting station. Each of those rows now moves one to the right and the race takes row 0: it decides whether the rest matters at all. --- JotunnModStub/RaceStationLock.cs | 42 ++++++++++++++++++++++++++++---- 1 file changed, 37 insertions(+), 5 deletions(-) diff --git a/JotunnModStub/RaceStationLock.cs b/JotunnModStub/RaceStationLock.cs index ba84346..b7eaab6 100644 --- a/JotunnModStub/RaceStationLock.cs +++ b/JotunnModStub/RaceStationLock.cs @@ -77,8 +77,9 @@ namespace RacesOfValheim } /// - /// The race in the build panel's requirement row, in the first slot after the materials and - /// the crafting station - the slots Hud.SetupPieceInfo has just filled or switched off. + /// The race in the build panel's requirement row, FIRST: the race decides whether the rest + /// matters at all. Hud.SetupPieceInfo has just filled one row per material and one for the + /// crafting station; each of those is moved one row to the right, and the race takes row 0. /// [HarmonyPatch(typeof(Hud), "SetupPieceInfo")] public static class RaceStation_PieceInfo_Patch @@ -100,10 +101,13 @@ namespace RacesOfValheim string[] races = For(piece); if (races == null || races.Length == 0 || __instance.m_requirementItems == null) return; - int slot = piece.m_resources.Length + (piece.m_craftingStation != null ? 1 : 0); - if (slot >= __instance.m_requirementItems.Length) return; + GameObject[] rows = __instance.m_requirementItems; + int used = piece.m_resources.Length + (piece.m_craftingStation != null ? 1 : 0); + if (used >= rows.Length) return; - GameObject row = __instance.m_requirementItems[slot]; + for (int i = used; i > 0; i--) CopyRow(rows[i - 1], rows[i]); + + GameObject row = rows[0]; Image icon = row.transform.Find("res_icon")?.GetComponent(); TMP_Text name = row.transform.Find("res_name")?.GetComponent(); TMP_Text amount = row.transform.Find("res_amount")?.GetComponent(); @@ -126,6 +130,34 @@ namespace RacesOfValheim // Vanilla's blink for a missing crafting station, on the name since there is no number. name.color = ok || Mathf.Sin(Time.time * 10f) <= 0f ? Color.white : Color.red; } + + /// Everything SetupRequirement and the station row write, from one row to the next. + private static void CopyRow(GameObject from, GameObject to) + { + to.SetActive(from.activeSelf); + foreach (string child in new[] { "res_icon", "res_name", "res_amount" }) + { + Transform a = from.transform.Find(child); + Transform b = to.transform.Find(child); + if (a == null || b == null) continue; + b.gameObject.SetActive(a.gameObject.activeSelf); + } + + Image fromIcon = from.transform.Find("res_icon")?.GetComponent(); + Image toIcon = to.transform.Find("res_icon")?.GetComponent(); + if (fromIcon != null && toIcon != null) { toIcon.sprite = fromIcon.sprite; toIcon.color = fromIcon.color; } + + foreach (string child in new[] { "res_name", "res_amount" }) + { + TMP_Text a = from.transform.Find(child)?.GetComponent(); + TMP_Text b = to.transform.Find(child)?.GetComponent(); + if (a != null && b != null) { b.text = a.text; b.color = a.color; } + } + + UITooltip fromTip = from.GetComponent(); + UITooltip toTip = to.GetComponent(); + if (fromTip != null && toTip != null) toTip.m_text = fromTip.m_text; + } } } } From 580ef6d4684906ba82714dc1dd890d541cf6fd65 Mon Sep 17 00:00:00 2001 From: kanym Date: Sat, 17 Oct 2026 18:51:14 +0200 Subject: [PATCH 041/176] feat(fenrir): forms sneak at a walk and sleep when the player sits FormLocomotion zeroed the speed whenever the player crouched, so a sneaking form slid across the ground in its idle pose. Only airborne reads as still now: crouched, the player moves at sneaking speed and the creature's controller picks its walk. Sitting sets the "sleeping" bool the creature's own MonsterAI uses, when its controller has one; the log says once per controller which do. IsSitting reads the replicated animator state, so onlookers' copies sleep too. Covers every Fenrir form, local and remote, and the True Form troll, which share FormLocomotion. Mirror now takes the Player. Requested by a player on Discord. --- JotunnModStub/Fenrir/FenrirBehaviors.cs | 10 +++--- JotunnModStub/Fenrir/FenrirFormShared.cs | 42 ++++++++++++++++++---- JotunnModStub/Trol/TrolTrueFormBehavior.cs | 4 +-- 3 files changed, 42 insertions(+), 14 deletions(-) diff --git a/JotunnModStub/Fenrir/FenrirBehaviors.cs b/JotunnModStub/Fenrir/FenrirBehaviors.cs index abe0846..dfbbaeb 100644 --- a/JotunnModStub/Fenrir/FenrirBehaviors.cs +++ b/JotunnModStub/Fenrir/FenrirBehaviors.cs @@ -422,7 +422,7 @@ namespace RacesOfValheim // The same helper the local behaviours use, so both views of the same wolf agree. // Player.IsCrouching answers off the animator's current state, which is replicated, so // it is true here too. - locomotion.Mirror(formAnim, playerAnim, player.IsCrouching()); + locomotion.Mirror(formAnim, playerAnim, player); } // Written every frame while the flag is set, and only when the controller has the bool: a @@ -539,7 +539,7 @@ namespace RacesOfValheim // Meglio continuare a sincronizzare i movimenti base. if (!isAttacking) { - bool isGrounded = locomotion.Mirror(fenrirAnim, playerAnim, Player.m_localPlayer.IsCrouching()); + bool isGrounded = locomotion.Mirror(fenrirAnim, playerAnim, Player.m_localPlayer); if (isGrounded && RaceInput.Allowed) { @@ -790,7 +790,7 @@ namespace RacesOfValheim if (!isAttacking) { // Se tiene premuto Ctrl (Crouch), ferma il movimento per preparare l'attacco - bool isGrounded = locomotion.Mirror(cultistAnim, playerAnim, Player.m_localPlayer.IsCrouching()); + bool isGrounded = locomotion.Mirror(cultistAnim, playerAnim, Player.m_localPlayer); if (isGrounded) { @@ -1172,7 +1172,7 @@ namespace RacesOfValheim if (!isAttacking) { - bool isGrounded = locomotion.Mirror(wolfAnim, playerAnim, Player.m_localPlayer.IsCrouching()); + bool isGrounded = locomotion.Mirror(wolfAnim, playerAnim, Player.m_localPlayer); if (isGrounded && RaceInput.Allowed) { @@ -1384,7 +1384,7 @@ namespace RacesOfValheim if (!isAttacking) { - bool isGrounded = locomotion.Mirror(ulvAnim, playerAnim, Player.m_localPlayer.IsCrouching()); + bool isGrounded = locomotion.Mirror(ulvAnim, playerAnim, Player.m_localPlayer); if (isGrounded && RaceInput.Allowed) { diff --git a/JotunnModStub/Fenrir/FenrirFormShared.cs b/JotunnModStub/Fenrir/FenrirFormShared.cs index 4bb14e4..e74407c 100644 --- a/JotunnModStub/Fenrir/FenrirFormShared.cs +++ b/JotunnModStub/Fenrir/FenrirFormShared.cs @@ -40,22 +40,50 @@ namespace RacesOfValheim private float airborneFor; + // Whether this form's controller has a "sleeping" bool, asked once per Animator: MonsterAI + // drives the creature's own sleep through it, and not every creature has one. + private Animator sleepChecked; + private bool hasSleeping; + private static readonly System.Collections.Generic.HashSet sleepLogged = new System.Collections.Generic.HashSet(); + /// Copies the movement parameters, and says whether the form counts as grounded. - public bool Mirror(Animator form, Animator player, bool crouching) + public bool Mirror(Animator form, Animator playerAnim, Player player) { - bool touching = player.GetBool("onGround"); + bool touching = playerAnim.GetBool("onGround"); airborneFor = touching ? 0f : airborneFor + Time.deltaTime; bool grounded = airborneFor <= AirborneGrace; // try/catch as the behaviours always did it: a controller missing one of these must not // throw once per frame. try { form.SetBool("onGround", grounded); } catch {} - try { form.SetBool("inWater", player.GetBool("inWater")); } catch {} + try { form.SetBool("inWater", playerAnim.GetBool("inWater")); } catch {} - // Airborne and crouching both read as standing still, as before. - bool still = !grounded || crouching; - try { form.SetFloat("forward_speed", still ? 0f : player.GetFloat("forward_speed")); } catch {} - try { form.SetFloat("sideway_speed", still ? 0f : player.GetFloat("sideway_speed")); } catch {} + // Only airborne reads as standing still now. Crouching used to as well, so a player + // sneaking in a form slid across the ground in the idle pose. Crouched, the player moves + // at sneaking speed, and the creature's controller picks its walk for a speed that low: + // the sneak a player asked for, from animations the creature already has. + try { form.SetFloat("forward_speed", grounded ? playerAnim.GetFloat("forward_speed") : 0f); } catch {} + try { form.SetFloat("sideway_speed", grounded ? playerAnim.GetFloat("sideway_speed") : 0f); } catch {} + + // Sitting puts the creature to sleep, on the "sleeping" bool its own MonsterAI uses - the + // Ulv curls up. IsSitting reads the animator's state, which is replicated, so it is right + // for an onlooker's copy too. + if (sleepChecked != form) + { + sleepChecked = form; + hasSleeping = false; + foreach (AnimatorControllerParameter p in form.parameters) + { + if (p.type == AnimatorControllerParameterType.Bool && p.name == "sleeping") { hasSleeping = true; break; } + } + string controller = form.runtimeAnimatorController != null ? form.runtimeAnimatorController.name : form.name; + if (sleepLogged.Add(controller)) + { + Jotunn.Logger.LogInfo($"[FenrirForm] '{controller}' {(hasSleeping ? "has" : "has no")} sleeping animation; " + + (hasSleeping ? "sitting puts it to sleep." : "sitting keeps it idle.")); + } + } + if (hasSleeping) form.SetBool("sleeping", player != null && player.IsSitting()); return grounded; } diff --git a/JotunnModStub/Trol/TrolTrueFormBehavior.cs b/JotunnModStub/Trol/TrolTrueFormBehavior.cs index 4e17311..65ef184 100644 --- a/JotunnModStub/Trol/TrolTrueFormBehavior.cs +++ b/JotunnModStub/Trol/TrolTrueFormBehavior.cs @@ -86,7 +86,7 @@ namespace RacesOfValheim if (isAttacking || player.IsDead()) return; - bool grounded = locomotion.Mirror(anim, playerAnim, player.IsCrouching()); + bool grounded = locomotion.Mirror(anim, playerAnim, player); if (!grounded || !RaceInput.Allowed) return; bool log = heldLogName != null; @@ -437,7 +437,7 @@ namespace RacesOfValheim TrolTrueFormModel.UpdateHeldLog(gameObject, rightPrefab, ref heldLog, ref heldLogName); ReplayAttack(); - locomotion.Mirror(anim, playerAnim, player.IsCrouching()); + locomotion.Mirror(anim, playerAnim, player); } private void ReplayAttack() From 96dc8e4158530409466b4f64860e433f109dbcef Mon Sep 17 00:00:00 2001 From: kanym Date: Sat, 17 Oct 2026 19:01:03 +0200 Subject: [PATCH 042/176] fix(fenrir): Ulv sleeps on the sit key; forms stand still to attack Humanoid.IsSitting asks about the "sitting" animator tag, which belongs to chairs. The sit key is an emote that Player.StartEmote writes on the ZDO as "sit", so the Ulv never saw the player sit down. FormLocomotion now reads the ZDO emote too, which every client sees. Of the four forms only ulv_animator has a sleeping state. The hidden player kept walking under the form through an attack, so a bite slid toward whatever WASD held. Each form's isAttacking now also sets FenrirForms.LocalAttacking, and a SetControls prefix holds the player still while it is set, as the True Form troll does. The leaps move the body directly and are untouched. Cleared on every revert. --- JotunnModStub/Fenrir/FenrirBehaviors.cs | 20 ++++++++--- JotunnModStub/Fenrir/FenrirFormShared.cs | 45 +++++++++++++++++++++++- JotunnModStub/Fenrir/FenrirRace.cs | 2 ++ 3 files changed, 62 insertions(+), 5 deletions(-) diff --git a/JotunnModStub/Fenrir/FenrirBehaviors.cs b/JotunnModStub/Fenrir/FenrirBehaviors.cs index dfbbaeb..2b0783d 100644 --- a/JotunnModStub/Fenrir/FenrirBehaviors.cs +++ b/JotunnModStub/Fenrir/FenrirBehaviors.cs @@ -514,7 +514,10 @@ namespace RacesOfValheim private readonly FormLocomotion locomotion = new FormLocomotion(); private float busySince = -1f; - private bool isAttacking = false; + // A property so every form tells FenrirForms.LocalAttacking too: Fenrir_FormHoldStill_Patch + // holds the player still for exactly as long as an attack clip runs. + private bool attacking; + private bool isAttacking { get => attacking; set { attacking = value; FenrirForms.LocalAttacking = value; } } void Start() { @@ -766,7 +769,10 @@ namespace RacesOfValheim private readonly FormLocomotion locomotion = new FormLocomotion(); private float busySince = -1f; - private bool isAttacking = false; + // A property so every form tells FenrirForms.LocalAttacking too: Fenrir_FormHoldStill_Patch + // holds the player still for exactly as long as an attack clip runs. + private bool attacking; + private bool isAttacking { get => attacking; set { attacking = value; FenrirForms.LocalAttacking = value; } } private bool isShootingFire = false; private float fireTimer = 0f; @@ -1150,7 +1156,10 @@ namespace RacesOfValheim private Animator wolfAnim; private readonly FormLocomotion locomotion = new FormLocomotion(); private float busySince = -1f; - private bool isAttacking = false; + // A property so every form tells FenrirForms.LocalAttacking too: Fenrir_FormHoldStill_Patch + // holds the player still for exactly as long as an attack clip runs. + private bool attacking; + private bool isAttacking { get => attacking; set { attacking = value; FenrirForms.LocalAttacking = value; } } void Start() { @@ -1363,7 +1372,10 @@ namespace RacesOfValheim private readonly FormLocomotion locomotion = new FormLocomotion(); private float busySince = -1f; - private bool isAttacking = false; + // A property so every form tells FenrirForms.LocalAttacking too: Fenrir_FormHoldStill_Patch + // holds the player still for exactly as long as an attack clip runs. + private bool attacking; + private bool isAttacking { get => attacking; set { attacking = value; FenrirForms.LocalAttacking = value; } } void Start() { diff --git a/JotunnModStub/Fenrir/FenrirFormShared.cs b/JotunnModStub/Fenrir/FenrirFormShared.cs index e74407c..f412620 100644 --- a/JotunnModStub/Fenrir/FenrirFormShared.cs +++ b/JotunnModStub/Fenrir/FenrirFormShared.cs @@ -14,6 +14,10 @@ namespace RacesOfValheim /// SE_FenrirForm and the Cultist SE_CultistForm. Checking only SE_FenrirForm, as the attack /// block used to, left three of the four forms out. /// + /// True while the local form is inside an attack, a howl or a breath. Cleared by the + /// form's own routines, and on every revert. + public static bool LocalAttacking { get; set; } + public static bool LocalInForm(Character character) { if (character == null || character != Player.m_localPlayer) return false; @@ -83,10 +87,25 @@ namespace RacesOfValheim (hasSleeping ? "sitting puts it to sleep." : "sitting keeps it idle.")); } } - if (hasSleeping) form.SetBool("sleeping", player != null && player.IsSitting()); + if (hasSleeping) form.SetBool("sleeping", IsSitting(player)); return grounded; } + + /// + /// The sit key, or a chair. The sit key is an EMOTE, not the "sitting" animator tag that + /// Humanoid.IsSitting asks about - that tag belongs to chairs and benches - so IsSitting alone + /// never saw it and the Ulv stayed on its feet. Player.StartEmote writes the emote's name on the + /// ZDO, which every client reads, so this is right for an onlooker's copy as well. + /// + private static bool IsSitting(Player player) + { + if (player == null) return false; + if (player.IsSitting()) return true; + + ZNetView nview = player.GetComponent(); + return nview != null && nview.IsValid() && nview.GetZDO().GetString(ZDOVars.s_emote, "") == "sit"; + } } /// @@ -215,4 +234,28 @@ namespace RacesOfValheim Jotunn.Logger.LogInfo($"[FenrirForm] {form} swing: {candidates} collider(s) in reach."); } } + /// + /// Holds the player still through a form's attack clips, the way a human stands to swing. The + /// hidden player kept walking under the creature, so the bite slid toward whatever WASD held. + /// SkeletonRiseControlsPatch's arrangement: the move direction is SetControls' first argument, + /// bound by position. The Fenring's and the Ulv's leaps move the body directly and are untouched. + /// + [HarmonyLib.HarmonyPatch(typeof(Player), "SetControls")] + public static class Fenrir_FormHoldStill_Patch + { + public static void Prefix(Player __instance, ref Vector3 __0, ref bool jump, ref bool crouch, ref bool dodge) + { + if (__instance != Player.m_localPlayer || !FenrirForms.LocalAttacking) return; + if (!FenrirForms.LocalInForm(__instance)) + { + FenrirForms.LocalAttacking = false; + return; + } + + __0 = Vector3.zero; + jump = false; + crouch = false; + dodge = false; + } + } } diff --git a/JotunnModStub/Fenrir/FenrirRace.cs b/JotunnModStub/Fenrir/FenrirRace.cs index ee5cd5a..655cb86 100644 --- a/JotunnModStub/Fenrir/FenrirRace.cs +++ b/JotunnModStub/Fenrir/FenrirRace.cs @@ -300,6 +300,7 @@ namespace RacesOfValheim { player.GetSEMan().RemoveStatusEffect("SE_WolfForm".GetStableHashCode()); } + FenrirForms.LocalAttacking = false; isTransformed = false; isTransformingSequence = false; activeRules = null; @@ -575,6 +576,7 @@ namespace RacesOfValheim { Player.m_localPlayer.GetSEMan().RemoveStatusEffect("SE_CultistForm".GetStableHashCode()); Player.m_localPlayer.GetSEMan().RemoveStatusEffect("SE_WolfForm".GetStableHashCode()); + FenrirForms.LocalAttacking = false; isTransformed = false; Player.m_localPlayer.Message(MessageHud.MessageType.Center, revertMessage ?? ModText.Get("rov_msg_fenrir_returned_human_form")); revertMessage = null; From 2df8264c42279f941d0aae6ef31f27271ccd6009 Mon Sep 17 00:00:00 2001 From: kanym Date: Sat, 17 Oct 2026 19:06:08 +0200 Subject: [PATCH 043/176] debug: log the Ulv's sleep state while the player sits (temporary) --- JotunnModStub/Fenrir/FenrirFormShared.cs | 29 +++++++++++++++++++++++- 1 file changed, 28 insertions(+), 1 deletion(-) diff --git a/JotunnModStub/Fenrir/FenrirFormShared.cs b/JotunnModStub/Fenrir/FenrirFormShared.cs index f412620..e1a8b72 100644 --- a/JotunnModStub/Fenrir/FenrirFormShared.cs +++ b/JotunnModStub/Fenrir/FenrirFormShared.cs @@ -87,7 +87,9 @@ namespace RacesOfValheim (hasSleeping ? "sitting puts it to sleep." : "sitting keeps it idle.")); } } - if (hasSleeping) form.SetBool("sleeping", IsSitting(player)); + bool sitting = IsSitting(player); + if (hasSleeping) form.SetBool("sleeping", sitting); + DebugSleep(form, player, sitting); return grounded; } @@ -98,6 +100,31 @@ namespace RacesOfValheim /// never saw it and the Ulv stayed on its feet. Player.StartEmote writes the emote's name on the /// ZDO, which every client reads, so this is right for an onlooker's copy as well. /// + // TEMPORARY DEBUG for the Ulv that will not sleep. Remove with the fix. + private bool lastSitting; + private float nextSleepLog; + private void DebugSleep(Animator form, Player player, bool sitting) + { + if (player == null || player != Player.m_localPlayer) return; + ZNetView nview = player.GetComponent(); + string emote = nview != null && nview.IsValid() ? nview.GetZDO().GetString(ZDOVars.s_emote, "") : "?"; + if (sitting != lastSitting) + { + lastSitting = sitting; + Jotunn.Logger.LogInfo($"[SleepDebug] sitting={sitting} IsSitting={player.IsSitting()} emote='{emote}' hasSleeping={hasSleeping}"); + } + if (!sitting && emote != "sit") return; + if (Time.time < nextSleepLog) return; + nextSleepLog = Time.time + 1f; + string clip = "?"; + var clips = form.GetCurrentAnimatorClipInfo(0); + if (clips.Length > 0 && clips[0].clip != null) clip = clips[0].clip.name; + bool sleepingNow = false; + try { sleepingNow = form.GetBool("sleeping"); } catch {} + Jotunn.Logger.LogInfo($"[SleepDebug] sitting={sitting} emote='{emote}' sleepingBool={sleepingNow} clip='{clip}' " + + $"inTransition={form.IsInTransition(0)} enabled={form.enabled} speed={form.speed}"); + } + private static bool IsSitting(Player player) { if (player == null) return false; From 4cb6da801bf669e49a2002fb848b50fff33b0dd9 Mon Sep 17 00:00:00 2001 From: kanym Date: Sat, 17 Oct 2026 19:09:38 +0200 Subject: [PATCH 044/176] Revert "debug: log the Ulv's sleep state while the player sits (temporary)" This reverts commit 2df8264c42279f941d0aae6ef31f27271ccd6009. --- JotunnModStub/Fenrir/FenrirFormShared.cs | 29 +----------------------- 1 file changed, 1 insertion(+), 28 deletions(-) diff --git a/JotunnModStub/Fenrir/FenrirFormShared.cs b/JotunnModStub/Fenrir/FenrirFormShared.cs index e1a8b72..f412620 100644 --- a/JotunnModStub/Fenrir/FenrirFormShared.cs +++ b/JotunnModStub/Fenrir/FenrirFormShared.cs @@ -87,9 +87,7 @@ namespace RacesOfValheim (hasSleeping ? "sitting puts it to sleep." : "sitting keeps it idle.")); } } - bool sitting = IsSitting(player); - if (hasSleeping) form.SetBool("sleeping", sitting); - DebugSleep(form, player, sitting); + if (hasSleeping) form.SetBool("sleeping", IsSitting(player)); return grounded; } @@ -100,31 +98,6 @@ namespace RacesOfValheim /// never saw it and the Ulv stayed on its feet. Player.StartEmote writes the emote's name on the /// ZDO, which every client reads, so this is right for an onlooker's copy as well. /// - // TEMPORARY DEBUG for the Ulv that will not sleep. Remove with the fix. - private bool lastSitting; - private float nextSleepLog; - private void DebugSleep(Animator form, Player player, bool sitting) - { - if (player == null || player != Player.m_localPlayer) return; - ZNetView nview = player.GetComponent(); - string emote = nview != null && nview.IsValid() ? nview.GetZDO().GetString(ZDOVars.s_emote, "") : "?"; - if (sitting != lastSitting) - { - lastSitting = sitting; - Jotunn.Logger.LogInfo($"[SleepDebug] sitting={sitting} IsSitting={player.IsSitting()} emote='{emote}' hasSleeping={hasSleeping}"); - } - if (!sitting && emote != "sit") return; - if (Time.time < nextSleepLog) return; - nextSleepLog = Time.time + 1f; - string clip = "?"; - var clips = form.GetCurrentAnimatorClipInfo(0); - if (clips.Length > 0 && clips[0].clip != null) clip = clips[0].clip.name; - bool sleepingNow = false; - try { sleepingNow = form.GetBool("sleeping"); } catch {} - Jotunn.Logger.LogInfo($"[SleepDebug] sitting={sitting} emote='{emote}' sleepingBool={sleepingNow} clip='{clip}' " + - $"inTransition={form.IsInTransition(0)} enabled={form.enabled} speed={form.speed}"); - } - private static bool IsSitting(Player player) { if (player == null) return false; From 9cf3f5386c7e413ca38690cbe1591e0bfc90f702 Mon Sep 17 00:00:00 2001 From: kanym Date: Sat, 17 Oct 2026 19:09:50 +0200 Subject: [PATCH 045/176] fix(fenrir): the Ulv sleeps when the player sits Sitting now zeroes the form's speed. The seated player's Animator keeps a forward_speed above zero, which kept the Ulv in its Walk clip on the spot and out of reach of its Sleep state, which leaves from idle. The debug log showed it: sitting, sleeping=true, clip 'Walk'. --- JotunnModStub/Fenrir/FenrirFormShared.cs | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/JotunnModStub/Fenrir/FenrirFormShared.cs b/JotunnModStub/Fenrir/FenrirFormShared.cs index f412620..3922be6 100644 --- a/JotunnModStub/Fenrir/FenrirFormShared.cs +++ b/JotunnModStub/Fenrir/FenrirFormShared.cs @@ -66,8 +66,15 @@ namespace RacesOfValheim // sneaking in a form slid across the ground in the idle pose. Crouched, the player moves // at sneaking speed, and the creature's controller picks its walk for a speed that low: // the sneak a player asked for, from animations the creature already has. - try { form.SetFloat("forward_speed", grounded ? playerAnim.GetFloat("forward_speed") : 0f); } catch {} - try { form.SetFloat("sideway_speed", grounded ? playerAnim.GetFloat("sideway_speed") : 0f); } catch {} + // + // Sitting reads as still too. The seated player's own Animator keeps a forward_speed that + // is not zero, and passed through it kept the Ulv in its Walk clip - on the spot, and out + // of reach of its Sleep state, which only leaves from idle. Seen in the log: sitting, + // sleeping=true, clip 'Walk'. + bool sitting = IsSitting(player); + bool still = !grounded || sitting; + try { form.SetFloat("forward_speed", still ? 0f : playerAnim.GetFloat("forward_speed")); } catch {} + try { form.SetFloat("sideway_speed", still ? 0f : playerAnim.GetFloat("sideway_speed")); } catch {} // Sitting puts the creature to sleep, on the "sleeping" bool its own MonsterAI uses - the // Ulv curls up. IsSitting reads the animator's state, which is replicated, so it is right @@ -87,7 +94,7 @@ namespace RacesOfValheim (hasSleeping ? "sitting puts it to sleep." : "sitting keeps it idle.")); } } - if (hasSleeping) form.SetBool("sleeping", IsSitting(player)); + if (hasSleeping) form.SetBool("sleeping", sitting); return grounded; } From fb354c2387dc760e71058197388906d88e4ceb66 Mon Sep 17 00:00:00 2001 From: kanym Date: Sat, 17 Oct 2026 19:13:47 +0200 Subject: [PATCH 046/176] fix(fenrir): enter the Ulv's Sleep state by hand when the player sits A vanilla Ulv is born asleep: its controller only knows the way out of Sleep, so setting the bool from Idle did nothing. The state is now cross-faded into when the player sits; standing drops the bool and the controller's own 'Sleep to Idle' plays. The log names the state found. --- JotunnModStub/Fenrir/FenrirFormShared.cs | 34 ++++++++++++++++++++++-- 1 file changed, 32 insertions(+), 2 deletions(-) diff --git a/JotunnModStub/Fenrir/FenrirFormShared.cs b/JotunnModStub/Fenrir/FenrirFormShared.cs index 3922be6..5ee2233 100644 --- a/JotunnModStub/Fenrir/FenrirFormShared.cs +++ b/JotunnModStub/Fenrir/FenrirFormShared.cs @@ -48,6 +48,9 @@ namespace RacesOfValheim // drives the creature's own sleep through it, and not every creature has one. private Animator sleepChecked; private bool hasSleeping; + private int sleepState; + private bool wasSitting; + private static readonly string[] SleepStateNames = { "Sleep", "sleep", "Sleeping", "sleeping" }; private static readonly System.Collections.Generic.HashSet sleepLogged = new System.Collections.Generic.HashSet(); /// Copies the movement parameters, and says whether the form counts as grounded. @@ -87,14 +90,41 @@ namespace RacesOfValheim { if (p.type == AnimatorControllerParameterType.Bool && p.name == "sleeping") { hasSleeping = true; break; } } + + // The state's name is not readable at runtime, only testable: the clip is 'Sleep', and + // the state is most likely named after it. + sleepState = 0; + string found = "none"; + if (hasSleeping) + { + foreach (string candidate in SleepStateNames) + { + int hash = Animator.StringToHash(candidate); + if (!form.HasState(0, hash)) continue; + sleepState = hash; + found = candidate; + break; + } + } string controller = form.runtimeAnimatorController != null ? form.runtimeAnimatorController.name : form.name; if (sleepLogged.Add(controller)) { Jotunn.Logger.LogInfo($"[FenrirForm] '{controller}' {(hasSleeping ? "has" : "has no")} sleeping animation; " + - (hasSleeping ? "sitting puts it to sleep." : "sitting keeps it idle.")); + (hasSleeping ? $"sitting puts it to sleep (state '{found}')." : "sitting keeps it idle.")); } } - if (hasSleeping) form.SetBool("sleeping", sitting); + if (hasSleeping) + { + form.SetBool("sleeping", sitting); + + // The bool alone never put the Ulv to sleep. A vanilla Ulv is BORN asleep: its + // controller enters Sleep from the start and only knows the way out (Sleep, then + // 'Sleep to Idle' once the bool drops). Nothing leads from Idle back into Sleep, so + // the state is entered by hand when the player sits; standing up drops the bool and + // the controller's own wake-up plays. + if (sitting && !wasSitting && sleepState != 0) form.CrossFadeInFixedTime(sleepState, 0.4f, 0); + } + wasSitting = sitting; return grounded; } From e83c3c5d74757a951343d36d0a4bbce6e224f44e Mon Sep 17 00:00:00 2001 From: kanym Date: Sat, 17 Oct 2026 19:22:24 +0200 Subject: [PATCH 047/176] fix(fenrir): enter the Ulv's sleep by its real state path scripts/dump_controller.py reads an AnimatorController's states and transitions offline from Valheim's bundles with UnityPy. On ulv_animator it shows the entry state "check sleeping" picks Sleep only at start-up and Movement has no way back into it, so the bool alone could never work. The cross-fade now targets "Base Layer.Sleep". --- JotunnModStub/Fenrir/FenrirFormShared.cs | 9 +- scripts/dump_controller.py | 105 +++++++++++++++++++++++ 2 files changed, 111 insertions(+), 3 deletions(-) create mode 100644 scripts/dump_controller.py diff --git a/JotunnModStub/Fenrir/FenrirFormShared.cs b/JotunnModStub/Fenrir/FenrirFormShared.cs index 5ee2233..a6eb382 100644 --- a/JotunnModStub/Fenrir/FenrirFormShared.cs +++ b/JotunnModStub/Fenrir/FenrirFormShared.cs @@ -50,7 +50,10 @@ namespace RacesOfValheim private bool hasSleeping; private int sleepState; private bool wasSitting; - private static readonly string[] SleepStateNames = { "Sleep", "sleep", "Sleeping", "sleeping" }; + // Read off ulv_animator with scripts/dump_controller.py: the entry state "check sleeping" goes + // to Sleep only at start-up, and Movement has no way back into it. "Base Layer.Sleep" is the + // real path; the short name stays as a fallback for another creature built the same way. + private static readonly string[] SleepStateNames = { "Base Layer.Sleep", "Sleep" }; private static readonly System.Collections.Generic.HashSet sleepLogged = new System.Collections.Generic.HashSet(); /// Copies the movement parameters, and says whether the form counts as grounded. @@ -91,8 +94,8 @@ namespace RacesOfValheim if (p.type == AnimatorControllerParameterType.Bool && p.name == "sleeping") { hasSleeping = true; break; } } - // The state's name is not readable at runtime, only testable: the clip is 'Sleep', and - // the state is most likely named after it. + // The state's name is not readable at runtime, only testable - but it is readable offline, + // see SleepStateNames. sleepState = 0; string found = "none"; if (hasSleeping) diff --git a/scripts/dump_controller.py b/scripts/dump_controller.py new file mode 100644 index 0000000..07b9274 --- /dev/null +++ b/scripts/dump_controller.py @@ -0,0 +1,105 @@ +r"""Dump a Unity AnimatorController's parameters, states and transitions from Valheim's own files. + +Reads the game's asset files offline, so animator state and parameter names are read, not guessed. + +Setup, once (UnityPy into a folder of your choice, not into the repo): + python -m pip install --target C:\path o\pylib UnityPy + +Usage (Windows paths: a Git Bash "/c/..." path does not resolve for a Windows Python): + python -I scripts/dump_controller.py C:\path o\pylib " alheim_Data" ulv_animator wolf_animator + +Pass valheim_Data to search everything (slow, a few minutes), or a single bundle file to read +only that one. Creature animators live in valheim_Data\StreamingAssets\SoftRef\Bundles; the +Fenrir forms' four (wolf, ulv, fenring, fenring_cultist) are all in bundle c4210710 as of 1.0.20. +A controller's name is the one dumpanim prints ("controller 'ulv_animator'"). +""" +import os, sys, json + +sys.path.insert(0, sys.argv[1]) +import UnityPy # noqa: E402 + +data_dir = sys.argv[2] +wanted = set(sys.argv[3:]) + +candidates = [data_dir] if os.path.isfile(data_dir) else [] +for root, _, files in ([] if os.path.isfile(data_dir) else os.walk(data_dir)): + for f in files: + p = os.path.join(root, f) + if f.endswith(('.resS', '.resource', '.manifest', '.json', '.dll', '.csv', '.txt', '.info', '.config')): + continue + if os.path.getsize(p) < 1024: + continue + candidates.append(p) + +found = {} +for path in candidates: + try: + env = UnityPy.load(path) + except Exception: + continue + for obj in env.objects: + if obj.type.name != 'AnimatorController': + continue + try: + name = obj.peek_name() + except Exception: + name = None + if name is None: + try: + name = obj.read().m_Name + except Exception: + continue + if name not in wanted or name in found: + continue + tree = obj.read_typetree() + found[name] = (path, tree) + if len(found) == len(wanted): + break + +for name, (path, tree) in found.items(): + print(f'=== {name} ({os.path.basename(path)})') + tos = {int(k): v for k, v in tree.get('m_TOS', [])} + print('m_TOS (hash -> name):') + for h, v in sorted(tos.items(), key=lambda kv: kv[1]): + print(f' {h:>12} {v}') + + ctrl = tree.get('m_Controller', {}) + params = ctrl.get('m_Values', {}).get('data', {}).get('m_ValueArray', []) + print('parameters:') + for p in params: + print(f" {tos.get(p.get('m_ID'), p.get('m_ID'))} type={p.get('m_Type')}") + + for sm_i, sm in enumerate(ctrl.get('m_StateMachineArray', [])): + sm = sm.get('data', sm) + states = sm.get('m_StateConstantArray', []) + print(f'state machine {sm_i}: {len(states)} states, default index {sm.get("m_DefaultState")}') + any_tr = sm.get('m_AnyStateTransitionConstantArray', []) + + def describe(tr): + tr = tr.get('data', tr) + conds = [] + for c in tr.get('m_ConditionConstantArray', []): + c = c.get('data', c) + conds.append(f"{tos.get(c.get('m_EventID'), c.get('m_EventID'))} mode={c.get('m_ConditionMode')} th={c.get('m_EventThreshold')}") + dest = tr.get('m_DestinationState') + return dest, conds + + names = [] + for st in states: + st = st.get('data', st) + names.append(tos.get(st.get('m_NameID'), st.get('m_NameID'))) + for i, st in enumerate(states): + st = st.get('data', st) + print(f' [{i}] state "{names[i]}" fullPath="{tos.get(st.get("m_FullPathID"), st.get("m_FullPathID"))}" tag="{tos.get(st.get("m_TagID"), st.get("m_TagID"))}"') + for tr in st.get('m_TransitionConstantArray', []): + dest, conds = describe(tr) + dname = names[dest] if isinstance(dest, int) and 0 <= dest < len(names) else dest + print(f' -> {dname} when {conds}') + for tr in any_tr: + dest, conds = describe(tr) + dname = names[dest] if isinstance(dest, int) and 0 <= dest < len(names) else dest + print(f' AnyState -> {dname} when {conds}') + +missing = wanted - set(found) +if missing: + print('not found:', ', '.join(sorted(missing))) From 5c0f092c89e19d5e83899eaeff4612edf706c212 Mon Sep 17 00:00:00 2001 From: kanym Date: Sat, 17 Oct 2026 19:28:42 +0200 Subject: [PATCH 048/176] fix(fenrir): a form on a chair settles in front of the seat On a chair the player sits on the seat, and the form stood inside the chair at seat height. The form's root now goes 0.5 m in front of the seat, on whatever is under that point, skipping the seat's own colliders. The seat is found by a short raycast under the player, so it works for onlookers too, who have no attach point. Back to zero on standing up; the sit key is untouched. --- JotunnModStub/Fenrir/FenrirFormShared.cs | 66 ++++++++++++++++++++++++ 1 file changed, 66 insertions(+) diff --git a/JotunnModStub/Fenrir/FenrirFormShared.cs b/JotunnModStub/Fenrir/FenrirFormShared.cs index a6eb382..3d33ddf 100644 --- a/JotunnModStub/Fenrir/FenrirFormShared.cs +++ b/JotunnModStub/Fenrir/FenrirFormShared.cs @@ -129,9 +129,75 @@ namespace RacesOfValheim } wasSitting = sitting; + PlaceOnChair(form, player); + return grounded; } + // How far in front of the seat a creature on a chair settles, in metres. + private const float ChairForward = 0.5f; + private static readonly int ChairGroundMask = LayerMask.GetMask("Default", "static_solid", "terrain", "piece", "vehicle"); + private static readonly RaycastHit[] chairHits = new RaycastHit[16]; + private Transform placedRoot; + + /// + /// On a chair the player sits on the seat itself, and a creature there stood inside the chair, + /// at seat height. It goes half a metre in front of the seat instead, standing on whatever is + /// under that point. Moves the form's own root (the child of the player), never the player. + /// The sit key is left alone: the player is on the ground already. + /// + private void PlaceOnChair(Animator form, Player player) + { + Transform root = RootUnder(form.transform, player != null ? player.transform : null); + if (root == null) return; + + bool onChair = player.IsSitting(); + if (!onChair) + { + if (placedRoot == root && root.localPosition != Vector3.zero) root.localPosition = Vector3.zero; + return; + } + placedRoot = root; + + Transform body = player.transform; + Piece seat = SeatUnder(body.position); + Vector3 target = body.position + body.forward * ChairForward; + + float groundY = target.y; + int count = Physics.RaycastNonAlloc(target + Vector3.up * 1.5f, Vector3.down, chairHits, 4f, ChairGroundMask); + float best = float.MaxValue; + for (int i = 0; i < count; i++) + { + Collider c = chairHits[i].collider; + if (c == null || c.transform.IsChildOf(body)) continue; + if (seat != null && c.GetComponentInParent() == seat) continue; + if (chairHits[i].distance < best) { best = chairHits[i].distance; groundY = chairHits[i].point.y; } + } + + root.localPosition = body.InverseTransformPoint(new Vector3(target.x, groundY, target.z)); + } + + /// The chair or bench the player sits on: the first piece straight under them. + private static Piece SeatUnder(Vector3 position) + { + int count = Physics.RaycastNonAlloc(position + Vector3.up * 0.3f, Vector3.down, chairHits, 1.5f, ChairGroundMask); + Piece seat = null; + float best = float.MaxValue; + for (int i = 0; i < count; i++) + { + Piece piece = chairHits[i].collider != null ? chairHits[i].collider.GetComponentInParent() : null; + if (piece != null && chairHits[i].distance < best) { best = chairHits[i].distance; seat = piece; } + } + return seat; + } + + private static Transform RootUnder(Transform t, Transform player) + { + if (player == null) return null; + while (t != null && t.parent != player) t = t.parent; + return t; + } + /// /// The sit key, or a chair. The sit key is an EMOTE, not the "sitting" animator tag that /// Humanoid.IsSitting asks about - that tag belongs to chairs and benches - so IsSitting alone From ba7f56550d84e7e6bb16661cf8367d0fb41f89ca Mon Sep 17 00:00:00 2001 From: kanym Date: Sat, 17 Oct 2026 19:34:51 +0200 Subject: [PATCH 049/176] fix(forms): no form attacks in build mode; chair pose 1 m out, turned RaceInput.AttackDown and AttackHeld now return false while the player is in place mode (hammer, hoe, cultivator). Right click removes a piece there and middle click picks a snap point, and every form read both as its own attacks. Allowed only covered the piece selection panel. Every form reads the mouse through RaceInput, so all of them are covered. On a chair the form now settles 1 m in front of the seat and turns a quarter counter-clockwise, at the player's request after the first try. --- JotunnModStub/Fenrir/FenrirFormShared.cs | 13 +++++++++++-- JotunnModStub/RaceInput.cs | 11 +++++++++-- 2 files changed, 20 insertions(+), 4 deletions(-) diff --git a/JotunnModStub/Fenrir/FenrirFormShared.cs b/JotunnModStub/Fenrir/FenrirFormShared.cs index 3d33ddf..6fafc2e 100644 --- a/JotunnModStub/Fenrir/FenrirFormShared.cs +++ b/JotunnModStub/Fenrir/FenrirFormShared.cs @@ -135,7 +135,11 @@ namespace RacesOfValheim } // How far in front of the seat a creature on a chair settles, in metres. - private const float ChairForward = 0.5f; + private const float ChairForward = 1f; + + // And turned a quarter left, counter-clockwise seen from above, so it lies across the front + // of the seat rather than facing out of it. + private static readonly Quaternion ChairTurn = Quaternion.Euler(0f, -90f, 0f); private static readonly int ChairGroundMask = LayerMask.GetMask("Default", "static_solid", "terrain", "piece", "vehicle"); private static readonly RaycastHit[] chairHits = new RaycastHit[16]; private Transform placedRoot; @@ -154,7 +158,11 @@ namespace RacesOfValheim bool onChair = player.IsSitting(); if (!onChair) { - if (placedRoot == root && root.localPosition != Vector3.zero) root.localPosition = Vector3.zero; + if (placedRoot == root) + { + if (root.localPosition != Vector3.zero) root.localPosition = Vector3.zero; + if (root.localRotation != Quaternion.identity) root.localRotation = Quaternion.identity; + } return; } placedRoot = root; @@ -175,6 +183,7 @@ namespace RacesOfValheim } root.localPosition = body.InverseTransformPoint(new Vector3(target.x, groundY, target.z)); + root.localRotation = ChairTurn; } /// The chair or bench the player sits on: the first piece straight under them. diff --git a/JotunnModStub/RaceInput.cs b/JotunnModStub/RaceInput.cs index 283b34e..c045f2c 100644 --- a/JotunnModStub/RaceInput.cs +++ b/JotunnModStub/RaceInput.cs @@ -31,6 +31,13 @@ namespace RacesOfValheim // Not public on Player, hence the reflection; resolved once rather than per frame. private static readonly MethodInfo TakeInputMethod = AccessTools.Method(typeof(Player), "TakeInput"); + /// + /// Hammer, hoe or cultivator in hand. Right click removes a piece there and middle click picks + /// a snap point, and a form read both as its own attacks: an Ulv building a wall bit the air + /// on every click. Allowed only covered the piece selection panel, not the build mode itself. + /// + private static bool InBuildMode => Player.m_localPlayer != null && Player.m_localPlayer.InPlaceMode(); + public static bool Allowed { get @@ -156,14 +163,14 @@ namespace RacesOfValheim /// public static bool AttackDown(int mouseButton) { - if (RadialOpen) return false; + if (RadialOpen || InBuildMode) return false; return Input.GetMouseButtonDown(mouseButton) || PadAttackDown(mouseButton); } /// Held-down counterpart of . public static bool AttackHeld(int mouseButton) { - if (RadialOpen) return false; + if (RadialOpen || InBuildMode) return false; return Input.GetMouseButton(mouseButton) || PadAttackHeld(mouseButton); } From 5cf1ae7fb0a4e30a8a30027821c09b3aa33e5c63 Mon Sep 17 00:00:00 2001 From: kanym Date: Sat, 17 Oct 2026 19:42:14 +0200 Subject: [PATCH 050/176] fix(sverm): the Ravager costume no longer keeps a live Humanoid The BepInEx log showed "Can't remove Humanoid (Script) because CharacterDrop (Script) depends on it" right after the Ravager template was built from SeekerBrute. The strip was one pass in component order, and Unity refuses to destroy a component another still requires, so the Brute's Humanoid survived on the costume and on every copy a player wore: the leftover that once broke the hammer for every piece. ModelBorrow.StripBehaviours destroys only what nothing remaining requires through [RequireComponent], round after round, and logs any survivor by name. Used by the Ravager template, by ModelBorrow.Attach and by the Skeleton's rise costume, which had the same single pass. --- JotunnModStub/ModelBorrow.cs | 66 +++++++++++++++++++++++-- JotunnModStub/Skeleton/SkeletonRise.cs | 6 +-- JotunnModStub/Sverm/SvermRavagerForm.cs | 7 ++- 3 files changed, 67 insertions(+), 12 deletions(-) diff --git a/JotunnModStub/ModelBorrow.cs b/JotunnModStub/ModelBorrow.cs index 20b2ded..1bd8fd2 100644 --- a/JotunnModStub/ModelBorrow.cs +++ b/JotunnModStub/ModelBorrow.cs @@ -96,10 +96,7 @@ namespace RacesOfValheim // Everything that is not a Renderer or a Transform. Order matters for the same reason it did // on the Aswid's lights: behaviours first, then the things they hold references to. - foreach (MonoBehaviour behaviour in copy.GetComponentsInChildren(true)) - { - if (behaviour != null) Object.DestroyImmediate(behaviour); - } + StripBehaviours(copy, label); foreach (Collider collider in copy.GetComponentsInChildren(true)) { if (collider != null) Object.DestroyImmediate(collider); @@ -119,6 +116,67 @@ namespace RacesOfValheim return holder; } + /// + /// Destroys every MonoBehaviour under , dependents first. + /// + /// A single pass in component order is not enough, and the log said so: "Can't remove Humanoid + /// (Script) because CharacterDrop (Script) depends on it". Unity refuses to destroy a component + /// another one still requires through [RequireComponent], so the pass that reached Humanoid + /// before CharacterDrop left a live Humanoid on the Sverm's Ravager costume - on every player + /// wearing it - which is the leftover that once broke the hammer for every piece (see + /// SvermHive.MouthCandidates). Each round here destroys only what nothing remaining requires, + /// and rounds repeat until nothing is left or nothing more can go. + /// + public static void StripBehaviours(GameObject root, string label) + { + if (root == null) return; + + for (int round = 0; round < 16; round++) + { + MonoBehaviour[] left = root.GetComponentsInChildren(true); + if (left.Length == 0) return; + + int destroyed = 0; + foreach (MonoBehaviour behaviour in left) + { + if (behaviour == null || IsRequired(behaviour)) continue; + Object.DestroyImmediate(behaviour); + destroyed++; + } + if (destroyed == 0) break; + } + + foreach (MonoBehaviour survivor in root.GetComponentsInChildren(true)) + { + if (survivor != null) + { + Jotunn.Logger.LogWarning($"[{label}] '{survivor.GetType().Name}' on '{survivor.name}' could not be stripped from a borrowed model."); + } + } + } + + /// True if another component on the same GameObject names this one's type in a + /// [RequireComponent]. + private static bool IsRequired(Component target) + { + System.Type type = target.GetType(); + foreach (Component other in target.GetComponents()) + { + if (other == null || other == target) continue; + foreach (object attribute in other.GetType().GetCustomAttributes(typeof(RequireComponent), true)) + { + RequireComponent require = (RequireComponent)attribute; + if (Requires(require.m_Type0, type) || Requires(require.m_Type1, type) || Requires(require.m_Type2, type)) + { + return true; + } + } + } + return false; + } + + private static bool Requires(System.Type required, System.Type type) => required != null && required.IsAssignableFrom(type); + /// /// How tall the borrowed model actually turned out, in the holder's parent's space. Used to stack /// one borrowed model on top of another without a magic offset. diff --git a/JotunnModStub/Skeleton/SkeletonRise.cs b/JotunnModStub/Skeleton/SkeletonRise.cs index d44cd75..7e9827b 100644 --- a/JotunnModStub/Skeleton/SkeletonRise.cs +++ b/JotunnModStub/Skeleton/SkeletonRise.cs @@ -125,10 +125,8 @@ namespace RacesOfValheim // Everything that is not a Renderer, a Transform or the Animator. Animator is a Behaviour, // not a MonoBehaviour, so the first loop never touches it. - foreach (MonoBehaviour behaviour in copy.GetComponentsInChildren(true)) - { - if (behaviour != null) Object.DestroyImmediate(behaviour); - } + // Dependents first, so a Humanoid held down by CharacterDrop cannot survive on the copy. + ModelBorrow.StripBehaviours(copy, "Skeleton"); foreach (Collider collider in copy.GetComponentsInChildren(true)) { if (collider != null) Object.DestroyImmediate(collider); diff --git a/JotunnModStub/Sverm/SvermRavagerForm.cs b/JotunnModStub/Sverm/SvermRavagerForm.cs index f41b7f0..d9b21a7 100644 --- a/JotunnModStub/Sverm/SvermRavagerForm.cs +++ b/JotunnModStub/Sverm/SvermRavagerForm.cs @@ -103,10 +103,9 @@ namespace RacesOfValheim // Everything that is not a Renderer or a Transform. Animator is a Behaviour, not a // MonoBehaviour, so it is never touched by the first loop and survives on purpose - // it is the one live thing this costume is allowed to keep. - foreach (MonoBehaviour behaviour in copy.GetComponentsInChildren(true)) - { - if (behaviour != null) Object.DestroyImmediate(behaviour); - } + // Dependents first: a single pass left the Brute's Humanoid on the costume, because + // CharacterDrop requires it and came later. See ModelBorrow.StripBehaviours. + ModelBorrow.StripBehaviours(copy, "Sverm"); foreach (Collider collider in copy.GetComponentsInChildren(true)) { if (collider != null) Object.DestroyImmediate(collider); From 1c2da77603fd619e1c69d57c7a2ee0c621c65bb5 Mon Sep 17 00:00:00 2001 From: kanym Date: Sat, 17 Oct 2026 19:51:33 +0200 Subject: [PATCH 051/176] fix(sverm): the Ravager stands still to attack and its slam digs The hidden player kept walking under the costume, so every swing slid toward whatever WASD held. A SetControls prefix holds it still while an attack runs, as Fenrir and the True Form troll do. The middle-click slam now digs a crater on bare terrain (digg_v3), never inside a ward without access, behind a new Ground Slam Crater option. --- JotunnModStub/Sverm/SvermConfigManagement.cs | 6 ++ JotunnModStub/Sverm/SvermRavagerForm.cs | 63 ++++++++++++++++++-- 2 files changed, 64 insertions(+), 5 deletions(-) diff --git a/JotunnModStub/Sverm/SvermConfigManagement.cs b/JotunnModStub/Sverm/SvermConfigManagement.cs index a2627f8..a25aec9 100644 --- a/JotunnModStub/Sverm/SvermConfigManagement.cs +++ b/JotunnModStub/Sverm/SvermConfigManagement.cs @@ -45,6 +45,7 @@ namespace RacesOfValheim public static ConfigEntry RavagerScaleMultiplier; public static ConfigEntry RavagerYawDegrees; public static ConfigEntry RavagerAttackOffsetValue; + public static ConfigEntry RavagerSlamCraterValue; // ─── Colony caps ───────────────────────────────────────────────────── // Every ceiling on how many things the colony can have alive at once, in one section, so @@ -226,6 +227,10 @@ namespace RacesOfValheim "Raise it if a swing visibly connects short of the model's mouth/claws; lower it " + "if it connects well past them."); + RavagerSlamCraterValue = config.Bind(ravager, "Ground Slam Crater", true, + "The middle-click slam digs into the ground where it lands, like a pickaxe blow. " + + "Never inside a ward you have no access to."); + EmberGlowStrength = config.Bind(ember, "Glow Strength", SvermConfig.EmberGlowStrength, "How hot the chitin burns at Fader. This multiplies an HDR colour and it is applied " + "to the chest, the legs and the helmet at once, so it goes a very long way. Settled " + @@ -358,6 +363,7 @@ namespace RacesOfValheim public static float RavagerScale => RavagerScaleMultiplier?.Value ?? 1f; public static float RavagerYaw => RavagerYawDegrees?.Value ?? 0f; public static float RavagerAttackOffset => RavagerAttackOffsetValue?.Value ?? 1.5f; + public static bool RavagerSlamCrater => RavagerSlamCraterValue?.Value ?? true; public static bool Spines => SpinesEnabled?.Value ?? false; public static float SizeSmall => SpineSizeSmall?.Value ?? SvermConfig.SpineSizeSmall; diff --git a/JotunnModStub/Sverm/SvermRavagerForm.cs b/JotunnModStub/Sverm/SvermRavagerForm.cs index d9b21a7..68caf14 100644 --- a/JotunnModStub/Sverm/SvermRavagerForm.cs +++ b/JotunnModStub/Sverm/SvermRavagerForm.cs @@ -28,6 +28,10 @@ namespace RacesOfValheim { public static bool IsActive { get; private set; } + /// True while the local Brute is inside a swing or the roar. + /// Sverm_RavagerHoldStill_Patch holds the player still for exactly that long. + public static bool LocalAttacking { get; set; } + // Read by Sverm_RavagerRemoteVisuals_Patch (SvermPatches.cs) so every other client can // tell the form is up at all - without this the whole thing was local-only, exactly like // DrakeFormBehavior's flight flag and Fenrir's own form key, and other players saw nothing @@ -302,6 +306,7 @@ namespace RacesOfValheim private static void Exit(Player player, bool spendCooldown) { IsActive = false; + LocalAttacking = false; ZNetView exitNview = player.GetComponent(); if (exitNview != null && exitNview.IsValid()) exitNview.GetZDO().Set(ActiveKey, false); @@ -471,6 +476,30 @@ namespace RacesOfValheim /// equipped never swings and never deals damage while this is up; RavagerFormBehavior's /// own coroutines are the only thing that can land a hit. /// + /// + /// Holds the Brute still through its attack clips, the way Fenrir_FormHoldStill_Patch and + /// Trol_TrueFormHoldStill_Patch do for their forms. The hidden player kept walking under the + /// costume, so a bite or a slam slid toward whatever WASD held. + /// + [HarmonyPatch(typeof(Player), "SetControls")] + public static class Sverm_RavagerHoldStill_Patch + { + public static void Prefix(Player __instance, ref Vector3 __0, ref bool jump, ref bool crouch, ref bool dodge) + { + if (__instance != Player.m_localPlayer || !LocalAttacking) return; + if (!IsActive) + { + LocalAttacking = false; + return; + } + + __0 = Vector3.zero; + jump = false; + crouch = false; + dodge = false; + } + } + [HarmonyPatch(typeof(Humanoid), "StartAttack")] public static class Sverm_RavagerBlockNativeAttack_Patch { @@ -545,7 +574,8 @@ namespace RacesOfValheim // gate FenrirFormBehavior's own isAttacking flag uses, and the direct answer to "the // animation has to finish before the Brute can move": nothing here can start moving the // model again, or start a second attack, until the coroutine below clears it. - private bool isAttacking; + private bool isAttacking { get => attacking; set { attacking = value; SvermRavagerForm.LocalAttacking = value; } } + private bool attacking; // The taunt's own cooldown - short, and tracked separately from the other three, which // have no cooldown of their own beyond their own lock duration. @@ -655,15 +685,15 @@ namespace RacesOfValheim // be the only reliable option. if (RaceInput.AttackDown(1)) { - StartCoroutine(AttackRoutine(SvermRavagerAttacks.Ram, 2f, 0.3f, 0.7f)); + StartCoroutine(AttackRoutine(SvermRavagerAttacks.Ram, 2f, 0.3f, 0.7f, false)); } else if (RaceInput.AttackDown(0)) { - StartCoroutine(AttackRoutine(SvermRavagerAttacks.Bite, 2f, 0.3f, 0.6f)); + StartCoroutine(AttackRoutine(SvermRavagerAttacks.Bite, 2f, 0.3f, 0.6f, false)); } else if (RaceInput.AttackDown(2)) { - StartCoroutine(AttackRoutine(SvermRavagerAttacks.Slam, 1.2f, 0.4f, 1.0f)); + StartCoroutine(AttackRoutine(SvermRavagerAttacks.Slam, 1.2f, 0.4f, 1.0f, true)); } else if ((SvermConfigManagement.RavagerKey.Value.IsDown() || RaceInput.ConsumePress(SvermConfigManagement.RavagerKey.Value)) && Time.time >= nextTauntAt) @@ -680,7 +710,7 @@ namespace RacesOfValheim /// (SvermRavagerAttacks) instead of one tuned float. /// private System.Collections.IEnumerator AttackRoutine(SvermRavagerAttacks.Profile profile, float radius, - float hitDelay, float lockDuration) + float hitDelay, float lockDuration, bool digs) { isAttacking = true; @@ -695,6 +725,7 @@ namespace RacesOfValheim yield return new WaitForSeconds(hitDelay); ExecuteDamage(profile, radius); + if (digs) DigCrater(); float remaining = lockDuration - hitDelay; if (remaining > 0f) yield return new WaitForSeconds(remaining); @@ -768,6 +799,28 @@ namespace RacesOfValheim ApplyDamageInSphere(attackPoint, radius, profile.Damage); } + private const string CraterPrefab = "digg_v3"; + private static readonly int GroundMask = LayerMask.GetMask("terrain", "Default", "static_solid", "piece"); + + /// + /// The slam digs where it lands, the way the True Form troll's does (TrolTrueFormBehavior.Slam): + /// a pickaxe's dig on bare terrain only. TerrainOp does not check wards on its own, so the + /// ward check is done here. + /// + private static void DigCrater() + { + Player player = Player.m_localPlayer; + if (player == null || !SvermConfigManagement.RavagerSlamCrater) return; + + Vector3 impact = player.transform.position + player.transform.forward * SvermConfigManagement.RavagerAttackOffset; + if (!Physics.Raycast(impact + Vector3.up * 3f, Vector3.down, out RaycastHit ground, 8f, GroundMask)) return; + if (ground.collider == null || ground.collider.GetComponent() == null) return; + if (!PrivateArea.CheckAccess(ground.point, 0f, false)) return; + + GameObject crater = Jotunn.Managers.PrefabManager.Cache.GetPrefab(CraterPrefab); + if (crater != null) Object.Instantiate(crater, ground.point, Quaternion.identity); + } + /// /// The actual sweep, shared by every attack this form has (the three forward swings and /// the taunt's own AoE) - only the sphere's centre and radius differ between them. From 61a74320c5bfccf7b6e5bfc1c94be1055d28aed7 Mon Sep 17 00:00:00 2001 From: kanym Date: Sat, 17 Oct 2026 20:05:36 +0200 Subject: [PATCH 052/176] fix(sverm): Ravager attacks follow the Brute's clips; the slam hits once per claw Hits land on the clip's own Hit events and the hold-still lasts until the animator leaves the attack state, instead of fixed delays. The slam has two Hit events, one per claw: each one hits and digs under the claw that came down. --- JotunnModStub/Sverm/SvermRavagerForm.cs | 219 +++++++++++++++++++----- 1 file changed, 176 insertions(+), 43 deletions(-) diff --git a/JotunnModStub/Sverm/SvermRavagerForm.cs b/JotunnModStub/Sverm/SvermRavagerForm.cs index 68caf14..01ad562 100644 --- a/JotunnModStub/Sverm/SvermRavagerForm.cs +++ b/JotunnModStub/Sverm/SvermRavagerForm.cs @@ -585,8 +585,19 @@ namespace RacesOfValheim // present, so PlayAttack does not pass a name to SetTrigger the controller cannot use. private readonly System.Collections.Generic.HashSet knownTriggers = new System.Collections.Generic.HashSet(); + // The two front claws (bone names read from the SeekerBrute prefab with UnityPy). The slam + // brings one down, then the other; each Hit lands under whichever claw just came down. + private Transform leftClaw; + private Transform rightClaw; + private void Start() { + foreach (Transform bone in GetComponentsInChildren(true)) + { + if (bone.name == "l.frontfoot") leftClaw = bone; + else if (bone.name == "r.frontfoot") rightClaw = bone; + } + anim = GetComponentInChildren(); if (anim == null || anim.runtimeAnimatorController == null) return; @@ -685,15 +696,15 @@ namespace RacesOfValheim // be the only reliable option. if (RaceInput.AttackDown(1)) { - StartCoroutine(AttackRoutine(SvermRavagerAttacks.Ram, 2f, 0.3f, 0.7f, false)); + StartCoroutine(AttackRoutine(SvermRavagerAttacks.Ram, "Attack Ram", 2f, false)); } else if (RaceInput.AttackDown(0)) { - StartCoroutine(AttackRoutine(SvermRavagerAttacks.Bite, 2f, 0.3f, 0.6f, false)); + StartCoroutine(AttackRoutine(SvermRavagerAttacks.Bite, "Attack Bite", 2f, false)); } else if (RaceInput.AttackDown(2)) { - StartCoroutine(AttackRoutine(SvermRavagerAttacks.Slam, 1.2f, 0.4f, 1.0f, true)); + StartCoroutine(AttackRoutine(SvermRavagerAttacks.Slam, "Attack Slam", 1.2f, true)); } else if ((SvermConfigManagement.RavagerKey.Value.IsDown() || RaceInput.ConsumePress(SvermConfigManagement.RavagerKey.Value)) && Time.time >= nextTauntAt) @@ -704,31 +715,33 @@ namespace RacesOfValheim } /// - /// One swing: play the clip, wait for the moment it should land, hit whatever is there, - /// then hold isAttacking until the swing is fully spent. FenrirFormBehavior.ClawRoutine in - /// every particular except the damage itself, which here is the Brute's own real numbers - /// (SvermRavagerAttacks) instead of one tuned float. + /// One swing, timed by the clip itself instead of by fixed delays. Each "Hit" animation + /// event in the clip is a hit here, at the same point of the clip (the bite and the ram + /// have one, the slam has two, one per claw). The player is held still until the + /// animator starts blending out of the attack state, which is when the real Brute can + /// move again. /// - private System.Collections.IEnumerator AttackRoutine(SvermRavagerAttacks.Profile profile, float radius, - float hitDelay, float lockDuration, bool digs) + private System.Collections.IEnumerator AttackRoutine(SvermRavagerAttacks.Profile profile, string stateName, + float radius, bool slam) { isAttacking = true; + bool played = StartAttackState(profile); - if (hasForwardSpeed) anim.SetFloat("forward_speed", 0f); + int dropSamples = 0; + float[] leftY = new float[ClawHistory]; + float[] rightY = new float[ClawHistory]; - if (!string.IsNullOrEmpty(profile.Trigger) && knownTriggers.Contains(profile.Trigger)) + yield return FollowAttackState(stateName, played, 0f, () => { - anim.SetTrigger(profile.Trigger); - SvermRavagerForm.PublishAttackTrigger(Player.m_localPlayer, profile.Trigger); - } - - yield return new WaitForSeconds(hitDelay); - - ExecuteDamage(profile, radius); - if (digs) DigCrater(); - - float remaining = lockDuration - hitDelay; - if (remaining > 0f) yield return new WaitForSeconds(remaining); + if (slam) Slam(profile, radius, leftY, rightY, dropSamples); + else ExecuteDamage(profile, radius); + }, () => + { + if (leftClaw == null || rightClaw == null) return; + leftY[dropSamples % ClawHistory] = leftClaw.position.y; + rightY[dropSamples % ClawHistory] = rightClaw.position.y; + dropSamples++; + }); isAttacking = false; } @@ -738,37 +751,159 @@ namespace RacesOfValheim /// swing - the roar reaches out in every direction, so the sphere is centred on the /// player instead of offset ahead of them the way AttackRoutine's three do. Deliberately /// silent: no message, no status effect, nothing in a corner of the screen - just the - /// animation, the sound if one resolves, and the hit. + /// animation, the sound if one resolves, and the hit. The clip has no Hit event, so the + /// roar lands at TauntHitPoint of the clip. /// private System.Collections.IEnumerator TauntRoutine() { isAttacking = true; SvermRavagerAttacks.Profile profile = SvermRavagerAttacks.Taunt; - - if (hasForwardSpeed) anim.SetFloat("forward_speed", 0f); - - if (!string.IsNullOrEmpty(profile.Trigger) && knownTriggers.Contains(profile.Trigger)) - { - anim.SetTrigger(profile.Trigger); - SvermRavagerForm.PublishAttackTrigger(Player.m_localPlayer, profile.Trigger); - } + bool played = StartAttackState(profile); PlaySound(SvermConfig.RavagerTauntSoundEffects); - yield return new WaitForSeconds(0.3f); - - Player player = Player.m_localPlayer; - if (player != null) + yield return FollowAttackState("Taunt", played, TauntHitPoint, () => { - ApplyDamageInSphere(player.transform.position + Vector3.up, SvermConfig.RavagerTauntRadius, profile.Damage); - } - - yield return new WaitForSeconds(0.4f); + Player player = Player.m_localPlayer; + if (player != null) + ApplyDamageInSphere(player.transform.position + Vector3.up, SvermConfig.RavagerTauntRadius, profile.Damage); + }, null); isAttacking = false; } + // 0.3 s into the 2.67 s taunt clip, where the old fixed delay put the roar's hit. + private const float TauntHitPoint = 0.11f; + + // Frames of claw height kept to tell which claw just came down (about 0.2 s at 60 fps). + private const int ClawHistory = 12; + + private bool StartAttackState(SvermRavagerAttacks.Profile profile) + { + if (hasForwardSpeed) anim.SetFloat("forward_speed", 0f); + + if (string.IsNullOrEmpty(profile.Trigger) || !knownTriggers.Contains(profile.Trigger)) return false; + + anim.SetTrigger(profile.Trigger); + SvermRavagerForm.PublishAttackTrigger(Player.m_localPlayer, profile.Trigger); + return true; + } + + /// + /// Waits out one attack state frame by frame. Calls onHit at every Hit event of the + /// state's clip (or once at fallbackHit, a 0-1 point of the clip, when the clip has + /// none), and returns once the animator starts leaving the state. If the state never + /// starts (trigger missing), it hits once and returns, so the attack still works. + /// + private System.Collections.IEnumerator FollowAttackState(string stateName, bool played, float fallbackHit, + System.Action onHit, System.Action eachFrame) + { + float startedAt = Time.time; + bool entered = false; + float[] hits = null; + int nextHit = 0; + + while (played && Time.time - startedAt < 8f) + { + eachFrame?.Invoke(); + + AnimatorStateInfo state; + AnimatorClipInfo[] clips; + bool leaving; + if (!TryGetAttackState(stateName, out state, out clips, out leaving)) + { + if (entered || Time.time - startedAt > 0.5f) break; + yield return null; + continue; + } + + entered = true; + if (hits == null) hits = ReadHitPoints(clips, fallbackHit); + + while (nextHit < hits.Length && state.normalizedTime >= hits[nextHit]) + { + onHit(); + nextHit++; + } + + if (leaving) break; + yield return null; + } + + if (!entered) onHit(); + } + + private bool TryGetAttackState(string stateName, out AnimatorStateInfo state, out AnimatorClipInfo[] clips, out bool leaving) + { + state = anim.GetCurrentAnimatorStateInfo(0); + if (state.IsName(stateName)) + { + clips = anim.GetCurrentAnimatorClipInfo(0); + leaving = anim.IsInTransition(0); + return true; + } + + leaving = false; + if (anim.IsInTransition(0)) + { + state = anim.GetNextAnimatorStateInfo(0); + if (state.IsName(stateName)) + { + clips = anim.GetNextAnimatorClipInfo(0); + return true; + } + } + + clips = null; + return false; + } + + private static float[] ReadHitPoints(AnimatorClipInfo[] clips, float fallbackHit) + { + var points = new System.Collections.Generic.List(); + if (clips != null && clips.Length > 0 && clips[0].clip != null && clips[0].clip.length > 0f) + { + AnimationClip clip = clips[0].clip; + foreach (AnimationEvent ev in clip.events) + if (ev.functionName == "Hit") points.Add(ev.time / clip.length); + } + + if (points.Count == 0) points.Add(fallbackHit); + points.Sort(); + return points.ToArray(); + } + + /// + /// One claw of the slam landing: the claw that dropped the most over the last few frames + /// is the one that just struck. Damage and crater go under it, not at a fixed point ahead. + /// + private void Slam(SvermRavagerAttacks.Profile profile, float radius, float[] leftY, float[] rightY, int samples) + { + Transform claw = StrikingClaw(leftY, rightY, samples); + if (claw == null) + { + ExecuteDamage(profile, radius); + Player player = Player.m_localPlayer; + if (player != null) + DigCrater(player.transform.position + player.transform.forward * SvermConfigManagement.RavagerAttackOffset); + return; + } + + ApplyDamageInSphere(claw.position + Vector3.up * 0.5f, radius, profile.Damage); + DigCrater(claw.position); + } + + private Transform StrikingClaw(float[] leftY, float[] rightY, int samples) + { + if (leftClaw == null || rightClaw == null || samples == 0) return null; + + int oldest = samples < ClawHistory ? 0 : samples % ClawHistory; + float leftDrop = leftY[oldest] - leftClaw.position.y; + float rightDrop = rightY[oldest] - rightClaw.position.y; + return leftDrop >= rightDrop ? leftClaw : rightClaw; + } + /// Tries each candidate in order and plays the first that resolves, same as SvermRavagerForm.PlayEffect. private static void PlaySound(string[] candidates) { @@ -807,12 +942,10 @@ namespace RacesOfValheim /// a pickaxe's dig on bare terrain only. TerrainOp does not check wards on its own, so the /// ward check is done here. /// - private static void DigCrater() + private static void DigCrater(Vector3 impact) { - Player player = Player.m_localPlayer; - if (player == null || !SvermConfigManagement.RavagerSlamCrater) return; + if (Player.m_localPlayer == null || !SvermConfigManagement.RavagerSlamCrater) return; - Vector3 impact = player.transform.position + player.transform.forward * SvermConfigManagement.RavagerAttackOffset; if (!Physics.Raycast(impact + Vector3.up * 3f, Vector3.down, out RaycastHit ground, 8f, GroundMask)) return; if (ground.collider == null || ground.collider.GetComponent() == null) return; if (!PrivateArea.CheckAccess(ground.point, 0f, false)) return; From d05cea7f083ef7482afa8056935ff8ce56f3d916 Mon Sep 17 00:00:00 2001 From: kanym Date: Sat, 17 Oct 2026 20:24:43 +0200 Subject: [PATCH 053/176] fix(warvulture): strip dependents first, no more Can't remove Humanoid at startup The startup error came from WarVultureVisual.BuildTemplate, not from the Ravager costume: its passes tried Humanoid before CharacterDrop. Components another one still requires now wait for a later pass. --- JotunnModStub/ModelBorrow.cs | 2 +- JotunnModStub/WarVulture/WarVultureItem.cs | 1 + JotunnModStub/WarVulture/WarVultureVisual.cs | 9 +++++++++ 3 files changed, 11 insertions(+), 1 deletion(-) diff --git a/JotunnModStub/ModelBorrow.cs b/JotunnModStub/ModelBorrow.cs index 1bd8fd2..08a777b 100644 --- a/JotunnModStub/ModelBorrow.cs +++ b/JotunnModStub/ModelBorrow.cs @@ -157,7 +157,7 @@ namespace RacesOfValheim /// True if another component on the same GameObject names this one's type in a /// [RequireComponent]. - private static bool IsRequired(Component target) + public static bool IsRequired(Component target) { System.Type type = target.GetType(); foreach (Component other in target.GetComponents()) diff --git a/JotunnModStub/WarVulture/WarVultureItem.cs b/JotunnModStub/WarVulture/WarVultureItem.cs index 7b735fa..74fc487 100644 --- a/JotunnModStub/WarVulture/WarVultureItem.cs +++ b/JotunnModStub/WarVulture/WarVultureItem.cs @@ -229,6 +229,7 @@ namespace RacesOfValheim if (component is MeshFilter) continue; if (component is MeshRenderer) continue; if (component is SkinnedMeshRenderer) continue; + if (ModelBorrow.IsRequired(component)) continue; // a later pass, once its dependent is gone Object.DestroyImmediate(component); diff --git a/JotunnModStub/WarVulture/WarVultureVisual.cs b/JotunnModStub/WarVulture/WarVultureVisual.cs index cf42a91..1a944f9 100644 --- a/JotunnModStub/WarVulture/WarVultureVisual.cs +++ b/JotunnModStub/WarVulture/WarVultureVisual.cs @@ -118,6 +118,15 @@ namespace RacesOfValheim if (component == null) continue; if (IsKept(component)) continue; + // Not yet if something still requires it: Unity would refuse and log an error + // ("Can't remove Humanoid because CharacterDrop depends on it"). It goes on a + // later pass, once its dependent is gone. + if (ModelBorrow.IsRequired(component)) + { + stubborn++; + continue; + } + Object.DestroyImmediate(component); if (component == null) destroyedSomething = true; From 63e252d9e94e08ffe2a6468fca01a7e0efd9f376 Mon Sep 17 00:00:00 2001 From: kanym Date: Sat, 17 Oct 2026 20:24:43 +0200 Subject: [PATCH 054/176] feat(sverm): the Ravager's ram lunges with the clip's root motion Vanilla only takes root motion during a native attack, which this form never starts, so a relay on the costume's Animator collects it and a prefix on Character.ApplyRootMotion applies it to the player the same way (x55). --- JotunnModStub/Sverm/SvermRavagerForm.cs | 69 +++++++++++++++++++++++-- 1 file changed, 64 insertions(+), 5 deletions(-) diff --git a/JotunnModStub/Sverm/SvermRavagerForm.cs b/JotunnModStub/Sverm/SvermRavagerForm.cs index 01ad562..bee58bb 100644 --- a/JotunnModStub/Sverm/SvermRavagerForm.cs +++ b/JotunnModStub/Sverm/SvermRavagerForm.cs @@ -500,6 +500,37 @@ namespace RacesOfValheim } } + /// The ram clip's own forward motion, collected by RavagerRootMotionRelay and + /// spent by Sverm_RavagerRootMotion_Patch. + public static Vector3 PendingRootMotion; + + /// + /// Moves the player by the ram clip's root motion, the way vanilla moves a charging Brute. + /// Vanilla's own path (CharacterAnimEvent.OnAnimatorMove into Character.AddRootMotion) only + /// takes motion while Character.InAttack(), and this form never starts a native attack, so + /// the motion comes in here instead and is applied exactly as Character.ApplyRootMotion + /// applies it: delta times 55, used when it is faster than the walk velocity. + /// + [HarmonyPatch(typeof(Character), "ApplyRootMotion")] + public static class Sverm_RavagerRootMotion_Patch + { + public static void Prefix(Character __instance, ref Vector3 vel) + { + if (__instance != Player.m_localPlayer) return; + + Vector3 motion = PendingRootMotion; + PendingRootMotion = Vector3.zero; + if (!IsActive || !LocalAttacking) return; + + Vector3 push = motion * 55f; + push.y = 0f; + if (push.magnitude > new Vector3(vel.x, 0f, vel.z).magnitude) + { + vel = new Vector3(push.x, vel.y, push.z); + } + } + } + [HarmonyPatch(typeof(Humanoid), "StartAttack")] public static class Sverm_RavagerBlockNativeAttack_Patch { @@ -546,6 +577,23 @@ namespace RacesOfValheim } } + /// + /// Sits on the costume's Animator object. Unity calls OnAnimatorMove there instead of moving + /// the costume itself; while Active (the ram), the clip's motion is handed to the player + /// through SvermRavagerForm.PendingRootMotion. Otherwise it is dropped, so the costume stays + /// where the player is. + /// + public class RavagerRootMotionRelay : MonoBehaviour + { + public Animator Animator; + public bool Active; + + private void OnAnimatorMove() + { + if (Active && Animator != null) SvermRavagerForm.PendingRootMotion += Animator.deltaPosition; + } + } + /// /// Locomotion AND combat, both held on every frame while the form is up - built on the same /// method FenrirFormBehavior and DrakeFormBehavior already use for their own transformations, @@ -590,6 +638,8 @@ namespace RacesOfValheim private Transform leftClaw; private Transform rightClaw; + private RavagerRootMotionRelay rootMotion; + private void Start() { foreach (Transform bone in GetComponentsInChildren(true)) @@ -615,6 +665,13 @@ namespace RacesOfValheim anim.fireEvents = false; anim.cullingMode = AnimatorCullingMode.AlwaysAnimate; + // The ram is the exception: its clip's motion moves the PLAYER (see + // Sverm_RavagerRootMotion_Patch). With an OnAnimatorMove receiver on the Animator's + // object, Unity computes the motion and hands it over instead of moving the costume. + rootMotion = anim.gameObject.AddComponent(); + rootMotion.Animator = anim; + anim.applyRootMotion = true; + foreach (AnimatorControllerParameter param in anim.parameters) { if (param.type == AnimatorControllerParameterType.Float && param.name == "forward_speed") @@ -696,15 +753,15 @@ namespace RacesOfValheim // be the only reliable option. if (RaceInput.AttackDown(1)) { - StartCoroutine(AttackRoutine(SvermRavagerAttacks.Ram, "Attack Ram", 2f, false)); + StartCoroutine(AttackRoutine(SvermRavagerAttacks.Ram, "Attack Ram", 2f, false, true)); } else if (RaceInput.AttackDown(0)) { - StartCoroutine(AttackRoutine(SvermRavagerAttacks.Bite, "Attack Bite", 2f, false)); + StartCoroutine(AttackRoutine(SvermRavagerAttacks.Bite, "Attack Bite", 2f, false, false)); } else if (RaceInput.AttackDown(2)) { - StartCoroutine(AttackRoutine(SvermRavagerAttacks.Slam, "Attack Slam", 1.2f, true)); + StartCoroutine(AttackRoutine(SvermRavagerAttacks.Slam, "Attack Slam", 1.2f, true, false)); } else if ((SvermConfigManagement.RavagerKey.Value.IsDown() || RaceInput.ConsumePress(SvermConfigManagement.RavagerKey.Value)) && Time.time >= nextTauntAt) @@ -719,13 +776,14 @@ namespace RacesOfValheim /// event in the clip is a hit here, at the same point of the clip (the bite and the ram /// have one, the slam has two, one per claw). The player is held still until the /// animator starts blending out of the attack state, which is when the real Brute can - /// move again. + /// move again. With lunge, the clip's own root motion carries the player forward (the ram). /// private System.Collections.IEnumerator AttackRoutine(SvermRavagerAttacks.Profile profile, string stateName, - float radius, bool slam) + float radius, bool slam, bool lunge) { isAttacking = true; bool played = StartAttackState(profile); + if (rootMotion != null) rootMotion.Active = lunge; int dropSamples = 0; float[] leftY = new float[ClawHistory]; @@ -743,6 +801,7 @@ namespace RacesOfValheim dropSamples++; }); + if (rootMotion != null) rootMotion.Active = false; isAttacking = false; } From f1d00f6eff46470b58295394fcb30ac26fc0ed98 Mon Sep 17 00:00:00 2001 From: kanym Date: Sat, 17 Oct 2026 20:30:37 +0200 Subject: [PATCH 055/176] chore(release): v1.5.11 - True Form troll, race stations, Ravager attacks Trol True Form wears the vanilla forest troll, with a per-player Legacy switch for model mods. Race stations show and require their race and go on floors and in caves. Fenrir forms sneak and stand still to attack; the Ulv sleeps when the player sits. The Ravager attacks on the Brute's own clips. Fixes: ResetRace, troll cave collapse, [msg_] texts, build-mode attacks, War Vulture startup error. README: New in block, changelog entry, Trol/Fenrir/Sverm feature lines and the stations section. --- JotunnModStub/Package/manifest.json | 2 +- JotunnModStub/RacesOfValheim.cs | 2 +- README.md | 27 +++++++++++++++++++++------ manifest.json | 2 +- 4 files changed, 24 insertions(+), 9 deletions(-) diff --git a/JotunnModStub/Package/manifest.json b/JotunnModStub/Package/manifest.json index 47424f1..0c5a46e 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.5.10", + "version_number": "1.5.11", "website_url": "", "dependencies": [ "denikson-BepInExPack_Valheim-5.4.2333", diff --git a/JotunnModStub/RacesOfValheim.cs b/JotunnModStub/RacesOfValheim.cs index 0702646..2a6b881 100644 --- a/JotunnModStub/RacesOfValheim.cs +++ b/JotunnModStub/RacesOfValheim.cs @@ -16,7 +16,7 @@ namespace RacesOfValheim { public const string PluginGUID = "com.nandor.racesofvalheim"; public const string PluginName = "Races Of Valheim"; - public const string PluginVersion = "1.5.10"; + public const string PluginVersion = "1.5.11"; private readonly Harmony harmony = new Harmony(PluginGUID); diff --git a/README.md b/README.md index 68d1e8d..ee6039c 100644 --- a/README.md +++ b/README.md @@ -15,9 +15,9 @@ Support the mod: [Patreon — NandorTheModder](https://www.patreon.com/c/NandorT --- -## New in v1.5.10 +## New in v1.5.11 -Using a player model mod such as EnhancedValheimVRM? Turn off `Skeleton - Visuals` → `Body Model Enabled` and Skeletons keep the vanilla body, so no bones clip through your model. Trols can pick their own skin and hair colour under `Trol - Appearance`. Full details in the [changelog](#v1510). +The Trol's True Form now wears Valheim's own forest troll, with its punches, ground slam and log swings; players with a model mod can keep the old True Form with `Trol - True Form` → `Legacy True Form`. The Sverm's Ravager attacks on the Seeker Brute's own animations: the ram lunges and the slam strikes with both claws. Race stations show and require their race in the build panel, and most of them now go on floors and inside caves. The Ulv sleeps when you sit. Full details in the [changelog](#v1511). --- @@ -47,6 +47,7 @@ Using a player model mod such as EnhancedValheimVRM? Turn off `Skeleton - Visual - **Beast Form:** Transform into a wolf-like beast. - **Cultist Form:** Transform into a Cultist. Its claws cost nothing, but the **fire breath (hold Right Mouse) runs on eitr** — 12.5 per second — and eitr comes from the Mistlands, so the form unlocks at Yagluth with its flames still out of reach. Holding the button with an empty pool now says so. - **Cursed Claws:** The wolf's hands, kept on in the man's shape — see [Claws](#claws). +- **Sneak and Sleep:** Forms sneak at a walk when you crouch and stand still to attack. Sit down as an Ulv and it curls up asleep. - **A Pack of Your Own:** The Pack Trough keeps a standing pack of wolves, ulvs and, late, fenrir — see [Race Stations](#race-stations--companions). - **Progression:** Forms grow as you defeat bosses, unlocking new powers and reducing cooldowns. Immune to fall damage. @@ -71,7 +72,7 @@ Using a player model mod such as EnhancedValheimVRM? Turn off `Skeleton - Visual - **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. +- **True Form:** From Moder, become a forest troll: punch, slam the ground, and from the Queen swing or throw a log. Using a player model mod? `Trol - True Form` → `Legacy True Form` keeps your own Trol, grown huge, with weapons in hand. - **Your Own Colours:** pick your skin and hair colour under `Trol - Appearance`. Other players see them too. ### 7. Draugh @@ -102,7 +103,7 @@ Using a player model mod such as EnhancedValheimVRM? Turn off `Skeleton - Visual - **Hive Pheromones:** No invertebrate attacks you — leeches, ticks, deathsquitos, seekers and bees all ignore you, from tier zero. - **Toxin Immunity:** Poison cannot touch you. Blunt and fire hit you 40% harder — until Fader, when the fire weakness burns out and comes back as a resistance. - **The Colony:** After the Elder, a Brood Mound, a Hive Market and a roster of insect troops bought with digested biomass. -- **Ravager Strain:** After Yagluth, become a Seeker Brute — the claws keep fighting, and the carapace is worth double. +- **Ravager Strain:** After Yagluth, become a Seeker Brute, with its own bite, lunging ram and two-claw ground slam that digs the earth. The carapace is worth double. --- @@ -293,10 +294,10 @@ Build a **Brood Mound** with the hammer — no more than two within its density ## Race Stations & Companions -Every race has a buildable station of its own, gated by a reagent bought from its faction's merchant. Stations of the same kind cannot be packed on top of each other — each has its own minimum spacing. Servants raised at any of them share one system: they follow when asked, walk home when dismissed, carry no loot on death, and knit their own wounds shut (ten seconds unhurt, then 2% a second). +Every race has a buildable station of its own, gated by a reagent bought from its faction's merchant. Each one needs its race: the build panel lists the race first and greys the station for anyone else. All of them go on floors, foundations and inside caves, except the living ones (Furling bushes, the Sverm nest and Hive Market, the Trenta's Elder Root), which need bare ground. Stations of the same kind cannot be packed on top of each other — each has its own minimum spacing. Servants raised at any of them share one system: they follow when asked, walk home when dismissed, carry no loot on death, and knit their own wounds shut (ten seconds unhurt, then 2% a second). - **Aswid — Blood Refinery:** refines Blood Essence, Superior Blood Essence and Blood Core. -- **Draugh — Cursed Body Pile:** eats raw flesh and answers with tamed draugr; Draugr and Elite trophies are worth a whole batch. Anyone can build it, but only a Draugh gives the draugr orders — for everyone else it is a grave that defends its own ten meters. +- **Draugh — Cursed Body Pile:** eats raw flesh and answers with tamed draugr; Draugr and Elite trophies are worth a whole batch. Draugh only. - **Furling — Five crops:** Copper, Tin and Iron Flax grow metal out of poisoned soil; Stoneberry and Flintberry bushes give stone and flint. - **Skadi — Crystal Golem & Bone Cook:** a stonecutter-bound guardian on a leash. Skadi (and Trol) may also build inside any troll cave in the world. The Cook is Skadi's own half of the [Bone Servants](#skeleton--skadi--bone-servants). - **Skeleton — Bound Bone Pile, Bound Sentry & Bone Smith:** pay once per slot and that slot refills itself forever, because an army you re-buy after every fight is one nobody takes out of the house. Both the pile and the Sentry can be built on the ground, on floors and on foundations. The Sentry is a bound archer that cannot walk, regenerates when left alone, and hands its parts back when it falls. The Smith is Skeleton and Skadi's shared half of the [Bone Servants](#skeleton--skadi--bone-servants). @@ -449,6 +450,20 @@ Both halves have an off switch under `Factions` in Configuration Manager: **Fact ## Changelog +### v1.5.11 +- **New - Trol True Form wears a real troll:** True Form hides your Trol and puts Valheim's own forest troll in its place, as tall as the old True Form, in your Trol's skin colour. Every player sees it. Weapons are put away while it lasts: left click punches, right click slams the ground, and with a log in hand they become the troll's two log swings. The slam breaks trees and rocks around it and digs into the ground, never inside a ward you have no access to. Throw Rock plays the troll's own throw. You stand still through every attack. Damage is half a real troll's, scaled by your Clubs skill like a club, and the True Form and tier melee bonuses still add on top. New options under `Trol - True Form`: `Troll Model Size`, `Troll Attack Damage`, `Troll Attack Reach`, `Ground Slam Crater`. +- **New - Legacy True Form:** prefer the old True Form, your own Trol grown bigger with weapons in hand? Turn on `Trol - True Form` → `Legacy True Form`. Use it with EnhancedValheimVRM or another player model mod, which needs the player's body to stay visible. Each player picks their own and other players see you the way you picked; a server cannot force it. Thanks to the players who answered the Discord poll. +- **New - race stations ask for their race:** the build panel lists the race a station needs first, before its materials, with the race's icon and name, and it blinks red if you are not of that race, like a missing crafting station. The station is greyed in the menu and a click says the requirements are missing. Seven stations anyone could build before now need their race too: the Cursed Body Pile (Draugh), the Pack Trough (Fenrir), the Bone Pile and Bound Sentry (Skeleton), the Blood Refinery (Aswid), the Composter and the Heartwood Grove (Trenta). Stations already built stay where they are. +- **Change - Fenrir forms sneak and stand still to attack:** crouching in a form no longer slides the creature across the ground in its idle pose: it walks, at sneaking speed. Attacks hold you still the way a human's swing does, instead of sliding toward the direction you hold; the leaps still leap. The True Form troll sneaks the same way. Thanks to the player who suggested it. +- **New - the Ulv sleeps when you sit:** sit down in Ulv form, with the sit key or on a chair, and the Ulv curls up asleep; stand up and it wakes. Every player nearby sees it. On a chair or a bench, every form now settles on the floor in front of the seat instead of standing inside it. The Wolf, the Fenring and the Cultist have no sleeping animation in the game and stay on their feet. +- **Fix - forms attacked while building:** with the hammer, hoe or cultivator in hand, right click (remove) and middle click (snap point) also fired the form's attacks. They no longer do. +- **Fix - forms and cooldowns survived a race reset:** resetting your race (console or Race Menu Ward) while in a form or with a cooldown running could carry it onto the new race: a Trol stayed huge in True Form, a Skadi stayed a drake, an Aswid stayed a bat or mist, and some cooldowns came back with no timer in the bar. The reset now drops every form at once, removes every status effect of the mod, and puts you back at normal size. The console prints what it removed. +- **Fix - pieces built in a troll cave broke while you were away:** the cave's own Troll spared your buildings only while you stood nearby. Walk out and it smashed them, and you came back to the materials on the floor. Creatures of your race's faction now leave alone anything your race built, whether you are home or not, and a blow aimed at something else no longer damages your pieces beside it. Pieces built before the update are covered the next time you load them. A creature you have attacked holds a grudge and does not spare your buildings until it passes. +- **Fix - four messages showed as [msg_...]:** the Trol's "already digesting" and "stomach full" lines, the Aswid's Vae Victis meal and the "not enough coins" line at the Dvergar bank and the Trol totem. The first three now use Valheim's own texts, the last is translated. +- **Fix - no placement ghost for most race stations:** aim anywhere but bare terrain (a floor, a rock, the floor of a troll cave) and the Trol War Totem showed no ghost at all, so you could not tell why it would not go down. The same held for the Cursed Body Pile, the Dvergar Bank, the Rune Barrel, the Pack Trough, the Skadi Golem and the Bone Servants. All of them now show their ghost everywhere and can be built on floors, foundations and inside caves, like the Bone Pile. The living pieces (Furling bushes, the Sverm nest and Hive Market, the Trenta Elder Root) still go on terrain only; elsewhere their ghost now shows red instead of vanishing. The War Totem had a second problem of its own: its ghost was invisible everywhere, terrain included, and now shows like the others. Thanks to the players who reported it. +- **Change - the Ravager's attacks follow its animations:** in Ravager Strain the Brute slid toward whatever direction you held while it bit, rammed, slammed or roared, and its hits landed on fixed timers that didn't match the clips. Each attack now hits at the moment the Seeker Brute's own animation strikes, and the Brute stands still until the animation ends, like the Fenrir forms and the True Form troll. Attacks take as long as the real Brute's: the bite about 1.5 s, the ram about 2.5 s, the slam about 4 s. The right-click ram now lunges a few metres forward, carried by the Seeker Brute's own charge animation. The middle-click slam brings down one claw and then the other, so it hits twice, as the Seeker Brute's does. Each claw digs into the ground where it lands, like the troll's slam, never inside a ward you have no access to. Turn the digging off with `Sverm - Ravager Strain` → `Ground Slam Crater`. **Tell us on Discord** how the new timing, the lunge and the two-claw slam feel. +- **Fix - error at game start:** the BepInEx log showed `Can't remove Humanoid (Script) because CharacterDrop (Script) depends on it` while the mod prepared the War Vulture's model. It was harmless, since the model came out clean on the next pass, but it looked like a crash in every log you sent us. It no longer appears. + ### v1.5.10 - **New - Skeleton body switch for player model mods:** with EnhancedValheimVRM or another model replacer, the skeleton's bones stayed on screen and floated around the new model. Set `Skeleton - Visuals` → `Body Model Enabled` to off and Skeletons keep the vanilla body: no bones, eye lights or skull flames, and the helmet shows. Abilities don't change. The setting is client-side, so it applies to every Skeleton you see and changes nothing for other players. The race strips hair and beard, so the vanilla body is bald, and the auto-resurrection still shows the skeleton for the few seconds it climbs out of the ground. Thanks to the players who reported it and tested the fix. - **New - Trol skin and hair colour:** `Trol - Appearance` has a colour picker for the skin and one for the hair and beard. Each Trol picks their own and every player sees them. The defaults are the old peacock blue and golden blonde, so nobody's Trol changes after the update. For the blue-grey of Valheim's own trolls, try `7FA8C9`. A Trol on an older version of the mod shows the defaults to everyone else. Thanks to the player who suggested it. diff --git a/manifest.json b/manifest.json index 47424f1..0c5a46e 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.5.10", + "version_number": "1.5.11", "website_url": "", "dependencies": [ "denikson-BepInExPack_Valheim-5.4.2333", From 5dff5e1b8426e83ef8eab859fdc74d2166c48934 Mon Sep 17 00:00:00 2001 From: kanym Date: Sun, 18 Oct 2026 00:09:14 +0200 Subject: [PATCH 056/176] fix(forms): hair comes back after a form with Valkyr Valkyr sets its hair's forceRenderingOff on every visual update. The hider read that flag as "not hidden yet", recorded the hair a second time with enabled already false, and the revert left it off. Track hidden renderers in a set instead of trusting the flag. --- JotunnModStub/PlayerVisualHider.cs | 20 +++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/JotunnModStub/PlayerVisualHider.cs b/JotunnModStub/PlayerVisualHider.cs index 6e753e5..d1cda5a 100644 --- a/JotunnModStub/PlayerVisualHider.cs +++ b/JotunnModStub/PlayerVisualHider.cs @@ -33,6 +33,11 @@ namespace RacesOfValheim } private readonly List m_hidden = new List(); + + // What we hid, kept apart from forceRenderingOff. Other mods write that flag too: Valkyr + // sets its hair's forceRenderingOff on every visual update, so the flag alone made the + // rescan record the hair a second time, already disabled, and the revert left it off. + private readonly HashSet m_tracked = new HashSet(); private float m_nextRescan; private float m_nextLog; private string m_context = ""; @@ -107,8 +112,20 @@ namespace RacesOfValheim // the cape along with the body mesh itself. foreach (Renderer r in GetComponentsInChildren(true)) { - if (r == null || r.forceRenderingOff) continue; // already ours + if (r == null) continue; + if (m_tracked.Contains(r)) + { + // Already ours: re-assert in case another mod cleared the flag. + r.forceRenderingOff = true; + continue; + } + + // Hidden by someone else (Valkyr hides the vanilla body and hair this way): leave + // it to them, or the revert would show it. + if (r.forceRenderingOff) continue; + + m_tracked.Add(r); m_hidden.Add(new HiddenRenderer { Renderer = r, WasEnabled = r.enabled }); r.enabled = false; r.forceRenderingOff = true; @@ -132,6 +149,7 @@ namespace RacesOfValheim } m_hidden.Clear(); + m_tracked.Clear(); enabled = false; return restored; } From 9d459fbc996da397b1474380e8c056fc62723d88 Mon Sep 17 00:00:00 2001 From: kanym Date: Sun, 18 Oct 2026 00:18:36 +0200 Subject: [PATCH 057/176] chore(release): v1.5.12 - hair back after a form with Valkyr With the Valkyr body replacer, leaving any monster form brought the body back without its hair. Fixed in PlayerVisualHider. README: New in block and changelog entry. --- JotunnModStub/Package/manifest.json | 2 +- JotunnModStub/RacesOfValheim.cs | 2 +- README.md | 7 +++++-- manifest.json | 2 +- 4 files changed, 8 insertions(+), 5 deletions(-) diff --git a/JotunnModStub/Package/manifest.json b/JotunnModStub/Package/manifest.json index 0c5a46e..6211ee9 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.5.11", + "version_number": "1.5.12", "website_url": "", "dependencies": [ "denikson-BepInExPack_Valheim-5.4.2333", diff --git a/JotunnModStub/RacesOfValheim.cs b/JotunnModStub/RacesOfValheim.cs index 2a6b881..2505de8 100644 --- a/JotunnModStub/RacesOfValheim.cs +++ b/JotunnModStub/RacesOfValheim.cs @@ -16,7 +16,7 @@ namespace RacesOfValheim { public const string PluginGUID = "com.nandor.racesofvalheim"; public const string PluginName = "Races Of Valheim"; - public const string PluginVersion = "1.5.11"; + public const string PluginVersion = "1.5.12"; private readonly Harmony harmony = new Harmony(PluginGUID); diff --git a/README.md b/README.md index ee6039c..0c572e8 100644 --- a/README.md +++ b/README.md @@ -15,9 +15,9 @@ Support the mod: [Patreon — NandorTheModder](https://www.patreon.com/c/NandorT --- -## New in v1.5.11 +## New in v1.5.12 -The Trol's True Form now wears Valheim's own forest troll, with its punches, ground slam and log swings; players with a model mod can keep the old True Form with `Trol - True Form` → `Legacy True Form`. The Sverm's Ravager attacks on the Seeker Brute's own animations: the ram lunges and the slam strikes with both claws. Race stations show and require their race in the build panel, and most of them now go on floors and inside caves. The Ulv sleeps when you sit. Full details in the [changelog](#v1511). +Compatibility fix for Valkyr (female body replacer): your hair no longer disappears when you leave a monster form. Full details in the [changelog](#v1512). --- @@ -450,6 +450,9 @@ Both halves have an off switch under `Factions` in Configuration Manager: **Fact ## Changelog +### v1.5.12 +- **Fix - hair gone after a form with Valkyr:** with the Valkyr body replacer, leaving a monster form (Skadi drake, Aswid bat or mist, Fenrir forms, Sverm Ravager, Trol True Form) brought the body back without its hair. Valkyr hides and shows its own hair, and the mod mistook that for a part it still had to hide, so it never turned the hair back on. Your hair now returns with the rest of the body. Thanks to BoredLizard for the report. + ### v1.5.11 - **New - Trol True Form wears a real troll:** True Form hides your Trol and puts Valheim's own forest troll in its place, as tall as the old True Form, in your Trol's skin colour. Every player sees it. Weapons are put away while it lasts: left click punches, right click slams the ground, and with a log in hand they become the troll's two log swings. The slam breaks trees and rocks around it and digs into the ground, never inside a ward you have no access to. Throw Rock plays the troll's own throw. You stand still through every attack. Damage is half a real troll's, scaled by your Clubs skill like a club, and the True Form and tier melee bonuses still add on top. New options under `Trol - True Form`: `Troll Model Size`, `Troll Attack Damage`, `Troll Attack Reach`, `Ground Slam Crater`. - **New - Legacy True Form:** prefer the old True Form, your own Trol grown bigger with weapons in hand? Turn on `Trol - True Form` → `Legacy True Form`. Use it with EnhancedValheimVRM or another player model mod, which needs the player's body to stay visible. Each player picks their own and other players see you the way you picked; a server cannot force it. Thanks to the players who answered the Discord poll. diff --git a/manifest.json b/manifest.json index 0c5a46e..6211ee9 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.5.11", + "version_number": "1.5.12", "website_url": "", "dependencies": [ "denikson-BepInExPack_Valheim-5.4.2333", From 6d9f07217e371d243e2a29bb79e3b3503627d496 Mon Sep 17 00:00:00 2001 From: kanym Date: Sun, 18 Oct 2026 13:33:21 +0200 Subject: [PATCH 058/176] fix(factions): no AI freeze when a targeted piece is destroyed FactionStaticTargetPatch read m_targetStatic as a boxed object, so the null check missed Unity's destroyed-object state. A piece destroyed while a mob targeted it passed the check, and reading its gameObject threw. The throw escaped into MonoUpdaters.FixedUpdate and stopped every AI after that mob, every frame, until the field changed. Cast to Component and use Unity's null check; clear a dead target. --- JotunnModStub/Factions/FactionHostilityPatch.cs | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/JotunnModStub/Factions/FactionHostilityPatch.cs b/JotunnModStub/Factions/FactionHostilityPatch.cs index b445dbe..7fee617 100644 --- a/JotunnModStub/Factions/FactionHostilityPatch.cs +++ b/JotunnModStub/Factions/FactionHostilityPatch.cs @@ -207,14 +207,23 @@ namespace RacesOfValheim { if (!FactionsConfig.Hostility) return; Traverse targetStatic = Traverse.Create(__instance).Field("m_targetStatic"); - if (targetStatic.GetValue() == null) return; + // GetValue() hands back a plain object, and object == null skips Unity's destroyed + // check: a piece smashed or removed while targeted stays non-null here, and touching + // its gameObject throws. That throw escapes into MonoUpdaters.FixedUpdate and stops + // every AI after this one for the frame, every frame, until the field changes. + Component target = targetStatic.GetValue() as Component; + if (target == null) + { + if (targetStatic.GetValue() != null) targetStatic.SetValue(null); + return; + } Character monster = Traverse.Create(__instance).Field("m_character").Value; if (monster == null) return; // A piece an allied race built is never a target, with or without anyone around. // See FactionPieceTruce. - if (targetStatic.GetValue() is Component target && FactionPieceTruce.Protects(target.gameObject, monster)) + if (FactionPieceTruce.Protects(target.gameObject, monster)) { targetStatic.SetValue(null); return; From 32c49a8af05e4199801abd245f955941d4a677bb Mon Sep 17 00:00:00 2001 From: kanym Date: Mon, 19 Oct 2026 14:20:28 +0200 Subject: [PATCH 059/176] fix(dvergar): build pieces accept the smithing discount The build menu showed the discounted metal cost, but Player.HaveRequirements(Piece) read m_amount directly, so placing a piece still needed the full vanilla amount. It now goes through GetAmount like the rest of the cost path. Piece.DropResources also read m_amount, which would have refunded 10 tin for a cauldron that cost 6. A piece placed by a Dvergar now stores the discount paid, and dismantling it drops that amount. --- JotunnModStub/Dvergar/DvergarPatches.cs | 144 +++++++++++++++++++++--- 1 file changed, 130 insertions(+), 14 deletions(-) diff --git a/JotunnModStub/Dvergar/DvergarPatches.cs b/JotunnModStub/Dvergar/DvergarPatches.cs index de75252..c29fdb0 100644 --- a/JotunnModStub/Dvergar/DvergarPatches.cs +++ b/JotunnModStub/Dvergar/DvergarPatches.cs @@ -1,5 +1,6 @@ using System.Collections.Generic; using System.Reflection; +using System.Reflection.Emit; using HarmonyLib; using UnityEngine; @@ -220,9 +221,13 @@ namespace RacesOfValheim // ─── Smithing and jewelry ──────────────────────────────────────────── /// - /// Metal saved when crafting and upgrading. Requirement.GetAmount is the single point both - /// the crafting panel and Player.ConsumeResources go through, so the figure the player is - /// quoted and the figure they are charged can never drift apart. + /// Metal saved when crafting, upgrading and building. Requirement.GetAmount is what the + /// crafting panel, the build menu and Player.ConsumeResources all read, so the figure the + /// player is quoted and the figure they are charged can never drift apart. + /// + /// Two vanilla paths read m_amount directly and skip GetAmount, both for build pieces: + /// Player.HaveRequirements(Piece) and Piece.DropResources. The two transpilers below route + /// them through the discount too. /// /// Scoped to the metals and gems in DvergarConfig.DiscountedResourceNames, which is what /// keeps this a smithing perk rather than a blanket discount on every wooden wall. @@ -232,26 +237,137 @@ namespace RacesOfValheim { public static void Postfix(Piece.Requirement __instance, ref int __result) { - if (__result <= 1 || Player.m_localPlayer == null) return; + if (Player.m_localPlayer == null) return; + if (!DvergarRace.IsDvergar()) return; + + __result = DiscountedAmount(__instance, __result, DvergarProgression.Current.SmithingDiscount); + } + } + + /// + /// The single rounding rule for the smithing discount. The price a Dvergar pays and the + /// refund their piece drops both go through here, so they can't end up one ingot apart. + /// + internal static int DiscountedAmount(Piece.Requirement requirement, int amount, float discount) + { + if (amount <= 1 || discount <= 0f) return amount; + if (requirement == null || requirement.m_resItem == null) return amount; + if (!IsDiscounted(requirement.m_resItem.gameObject.name)) return amount; + + return Mathf.Max(1, Mathf.RoundToInt(amount * (1f - discount))); + } + + private static bool IsDiscounted(string prefabName) + { + string lower = prefabName.ToLower(); + foreach (string resource in DvergarConfig.DiscountedResourceNames) + { + if (lower == resource || lower.Contains(resource)) return true; + } + return false; + } + + private static readonly FieldInfo RequirementAmountField = + AccessTools.Field(typeof(Piece.Requirement), nameof(Piece.Requirement.m_amount)); + + /// + /// The build check. Vanilla compares the inventory against requirement.m_amount here, so + /// the menu quoted 6 tin for a cauldron while the hammer still refused to place it with + /// fewer than 10. Every m_amount read becomes GetAmount(1), which returns m_amount for + /// everyone else and the discounted figure for a Dvergar. + /// + [HarmonyPatch(typeof(Player), nameof(Player.HaveRequirements), typeof(Piece), typeof(Player.RequirementMode))] + public static class Dvergar_HaveRequirements_Piece_Patch + { + private static readonly MethodInfo GetAmountMethod = + AccessTools.Method(typeof(Piece.Requirement), nameof(Piece.Requirement.GetAmount)); + + public static IEnumerable Transpiler(IEnumerable instructions) + { + int replaced = 0; + foreach (CodeInstruction instruction in instructions) + { + if (instruction.LoadsField(RequirementAmountField)) + { + replaced++; + yield return new CodeInstruction(OpCodes.Ldc_I4_1).MoveLabelsFrom(instruction); + yield return new CodeInstruction(OpCodes.Callvirt, GetAmountMethod); + continue; + } + yield return instruction; + } + if (replaced == 0) + Jotunn.Logger.LogWarning("[Dvergar] HaveRequirements(Piece) no longer reads m_amount; build discount check not patched."); + } + } + + /// + /// ZDO key holding the discount a Dvergar paid for a piece. Stored rather than read off + /// the builder at teardown, because anyone can smash the piece and the builder's discount + /// grows with progression. + /// + private const string PaidDiscountKey = "Dvergar_PaidDiscount"; + + /// + /// Stamps the discount on a piece the local Dvergar just placed. Player.PlacePiece calls + /// SetCreator on the new instance right after spawning it, and ConsumeResources charges + /// the discounted price straight after. + /// + [HarmonyPatch(typeof(Piece), nameof(Piece.SetCreator))] + public static class Dvergar_Piece_SetCreator_Patch + { + public static void Postfix(Piece __instance, long uid) + { + Player player = Player.m_localPlayer; + if (player == null || uid != player.GetPlayerID()) return; if (!DvergarRace.IsDvergar()) return; float discount = DvergarProgression.Current.SmithingDiscount; if (discount <= 0f) return; - if (__instance == null || __instance.m_resItem == null) return; - if (!IsDiscounted(__instance.m_resItem.gameObject.name)) return; + ZNetView nview = __instance.GetComponent(); + if (nview == null || !nview.IsValid() || !nview.IsOwner()) return; + nview.GetZDO().Set(PaidDiscountKey, discount); + } + } - __result = Mathf.Max(1, Mathf.RoundToInt(__result * (1f - discount))); + /// + /// The refund. Vanilla drops requirement.m_amount when a piece is removed or destroyed, + /// which handed a Dvergar back 10 tin for a cauldron that cost 6: build, smash, repeat. + /// The drop now uses the discount stamped on the piece, so it returns what was paid. + /// + [HarmonyPatch(typeof(Piece), nameof(Piece.DropResources))] + public static class Dvergar_Piece_DropResources_Patch + { + private static readonly MethodInfo PaidAmountMethod = + AccessTools.Method(typeof(Dvergar_Piece_DropResources_Patch), nameof(PaidAmount)); + + public static IEnumerable Transpiler(IEnumerable instructions) + { + int replaced = 0; + foreach (CodeInstruction instruction in instructions) + { + if (instruction.LoadsField(RequirementAmountField)) + { + replaced++; + yield return new CodeInstruction(OpCodes.Ldarg_0).MoveLabelsFrom(instruction); + yield return new CodeInstruction(OpCodes.Call, PaidAmountMethod); + continue; + } + yield return instruction; + } + if (replaced == 0) + Jotunn.Logger.LogWarning("[Dvergar] DropResources no longer reads m_amount; build discount refund not patched."); } - private static bool IsDiscounted(string prefabName) + public static int PaidAmount(Piece.Requirement requirement, Piece piece) { - string lower = prefabName.ToLower(); - foreach (string resource in DvergarConfig.DiscountedResourceNames) - { - if (lower == resource || lower.Contains(resource)) return true; - } - return false; + int amount = requirement.m_amount; + ZNetView nview = piece.GetComponent(); + if (nview == null || !nview.IsValid()) return amount; + + float discount = nview.GetZDO().GetFloat(PaidDiscountKey, 0f); + return DiscountedAmount(requirement, amount, discount); } } From 9dd6600287c029ff2a993046f2b73aacfaedc5ab Mon Sep 17 00:00:00 2001 From: kanym Date: Mon, 19 Oct 2026 14:30:35 +0200 Subject: [PATCH 060/176] chore(release): v1.5.13 - no faction AI freeze, Dvergar build discount With factions on, destroying a piece a mob was targeting froze every AI in the area on servers. Dvergar pieces now build at the discounted metal cost the menu shows, and refund what was paid. README: New in block and changelog entry. Compendium: the Dvergar smithing discount also covers building, in English, Italian and Russian. --- JotunnModStub/Package/manifest.json | 2 +- JotunnModStub/RacesOfValheim.cs | 2 +- JotunnModStub/Translations/English/compendium.json | 2 +- JotunnModStub/Translations/Italian/compendium.json | 2 +- JotunnModStub/Translations/Russian/compendium.json | 2 +- README.md | 8 ++++++-- manifest.json | 2 +- 7 files changed, 12 insertions(+), 8 deletions(-) diff --git a/JotunnModStub/Package/manifest.json b/JotunnModStub/Package/manifest.json index 6211ee9..8b1a0cf 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.5.12", + "version_number": "1.5.13", "website_url": "", "dependencies": [ "denikson-BepInExPack_Valheim-5.4.2333", diff --git a/JotunnModStub/RacesOfValheim.cs b/JotunnModStub/RacesOfValheim.cs index 2505de8..1bd1c2b 100644 --- a/JotunnModStub/RacesOfValheim.cs +++ b/JotunnModStub/RacesOfValheim.cs @@ -16,7 +16,7 @@ namespace RacesOfValheim { public const string PluginGUID = "com.nandor.racesofvalheim"; public const string PluginName = "Races Of Valheim"; - public const string PluginVersion = "1.5.12"; + public const string PluginVersion = "1.5.13"; private readonly Harmony harmony = new Harmony(PluginGUID); diff --git a/JotunnModStub/Translations/English/compendium.json b/JotunnModStub/Translations/English/compendium.json index 0b27389..96d652b 100644 --- a/JotunnModStub/Translations/English/compendium.json +++ b/JotunnModStub/Translations/English/compendium.json @@ -41,7 +41,7 @@ "rov_compendium_dvergar_runic_ping_key_spend_eitr": "[Yagluth Unlock] Runic Ping ('$1' Key): Spend $2 eitr to send a pulse through the stone. For $3 seconds every ore vein and every hidden enemy within $4 meters is lit for you alone.\n", "rov_compendium_dvergar_runic_spark_runes_blood_earth": "[Base Passive] Runic Spark: The runes in your blood earth themselves through whatever you strike. Every blow you land carries +$1 Lightning damage - a bonus that grows as each boss falls.\n", "rov_compendium_dvergar_small_stubborn_stand_shorter_than": "[Base Passive] Small and Stubborn: You stand $1% shorter than a human and carry $2 less health for it. The dvergr hood never leaves your head - wear whatever helm you please and keep every point of its protection, but the runes will always show you as one of the deep folk.\n", - "rov_compendium_dvergar_smithing_jewelry_passive_waste_nothing": "[Bonemass Unlock] Smithing and Jewelry (Passive): You waste nothing at the anvil. Metal and gems cost you $1% less when crafting and upgrading.\n", + "rov_compendium_dvergar_smithing_jewelry_passive_waste_nothing": "[Bonemass Unlock] Smithing and Jewelry (Passive): You waste nothing at the anvil. Metal and gems cost you $1% less when crafting, upgrading and building.\n", "rov_compendium_dvergar_title": "Dvergar Secrets", "rov_compendium_dvergar_weapon_affinity_passive_blows_struck": "Weapon Affinity (Passive): $1. Blows struck with these land harder and cost less stamina. The saving never grows - a tier only ever hands you another weapon to feel at home with - and your skill rises no faster than anyone else's.\n", "rov_compendium_dvergar_weapon_axe": "Axe", diff --git a/JotunnModStub/Translations/Italian/compendium.json b/JotunnModStub/Translations/Italian/compendium.json index c1c5a56..c761af4 100644 --- a/JotunnModStub/Translations/Italian/compendium.json +++ b/JotunnModStub/Translations/Italian/compendium.json @@ -41,7 +41,7 @@ "rov_compendium_dvergar_runic_ping_key_spend_eitr": "[Sblocco Yagluth] Richiamo runico (tasto '$1'): spendi $2 di eitr per mandare un impulso attraverso la pietra. Per $3 secondi ogni vena di minerale e ogni nemico nascosto entro $4 metri si illumina, solo per te.\n", "rov_compendium_dvergar_runic_spark_runes_blood_earth": "[Passiva base] Scintilla runica: le rune nel tuo sangue si scaricano a terra attraverso ciò che colpisci. Ogni colpo che metti a segno porta +$1 danni da fulmine, un bonus che cresce con la caduta di ogni boss.\n", "rov_compendium_dvergar_small_stubborn_stand_shorter_than": "[Passiva base] Piccolo e testardo: sei il $1% più basso di un umano e per questo hai $2 di salute in meno. Il cappuccio dvergr non ti lascia mai la testa: indossa l'elmo che vuoi e mantieni ogni punto della sua protezione, ma le rune ti mostreranno sempre come uno del popolo del profondo.\n", - "rov_compendium_dvergar_smithing_jewelry_passive_waste_nothing": "[Sblocco Massa d'ossa] Forgia e gioielleria (passiva): all'incudine non sprechi niente. Metalli e gemme ti costano il $1% in meno quando crei e migliori oggetti.\n", + "rov_compendium_dvergar_smithing_jewelry_passive_waste_nothing": "[Sblocco Massa d'ossa] Forgia e gioielleria (passiva): all'incudine non sprechi niente. Metalli e gemme ti costano il $1% in meno quando crei, migliori oggetti e costruisci.\n", "rov_compendium_dvergar_title": "Segreti dei Dvergar", "rov_compendium_dvergar_weapon_affinity_passive_blows_struck": "Affinità con le armi (passiva): $1. I colpi inferti con queste armi arrivano più forti e costano meno stamina. Il risparmio non cresce mai: un tier ti dà solo un'altra arma con cui sentirti a casa, e la tua abilità non sale più in fretta di quella di chiunque altro.\n", "rov_compendium_dvergar_weapon_axe": "Ascia", diff --git a/JotunnModStub/Translations/Russian/compendium.json b/JotunnModStub/Translations/Russian/compendium.json index 6464233..6f11d10 100644 --- a/JotunnModStub/Translations/Russian/compendium.json +++ b/JotunnModStub/Translations/Russian/compendium.json @@ -41,7 +41,7 @@ "rov_compendium_dvergar_runic_ping_key_spend_eitr": "[Награда: Яглут] Рунический эхолокатор (клавиша «$1»): Потратьте $2 эйтра, чтобы послать импульс сквозь толщу камня. На $3 с каждая рудная жила и каждый скрытый враг в радиусе $4 метров подсветятся только для вас.\n", "rov_compendium_dvergar_runic_spark_runes_blood_earth": "[Базовое пассивное] Руническая искра: Руны в вашей крови заземляются через каждую цель, по которой вы бьете. Каждый нанесенный удар несет +$1 урона молнией — этот бонус растет по мере гибели боссов.\n", "rov_compendium_dvergar_small_stubborn_stand_shorter_than": "[Базовое пассивное] Мал да удал: Вы на $1% ниже человека и обладаете базовым запасом здоровья на $2 ед. меньше. Капюшон дверга сросся с вами навечно — надевайте любой шлем и сохраняйте все его показатели защиты, но руны всегда будут выдавать в вас дитя глубин.\n", - "rov_compendium_dvergar_smithing_jewelry_passive_waste_nothing": "[Награда: Масса костей] Кузнечное и ювелирное дело (Пассивное): В вашей наковальне ни крупицы не пропадет даром. Металлы и самоцветы тратятся на $1% экономнее при создании и улучшении предметов.\n", + "rov_compendium_dvergar_smithing_jewelry_passive_waste_nothing": "[Награда: Масса костей] Кузнечное и ювелирное дело (Пассивное): В вашей наковальне ни крупицы не пропадет даром. Металлы и самоцветы тратятся на $1% экономнее при создании и улучшении предметов, а также при строительстве.\n", "rov_compendium_dvergar_title": "Тайны Дверга", "rov_compendium_dvergar_weapon_affinity_passive_blows_struck": "Владение оружием (Пассивное): $1. Удары этим оружием бьют сильнее и расходуют меньше выносливости. Экономия выносливости не увеличивается — открытие уровней лишь расширяет список доступного вам родного оружия, а сам навык растет с обычной скоростью.\n", "rov_compendium_dvergar_weapon_axe": "Топор", diff --git a/README.md b/README.md index 0c572e8..8c1b542 100644 --- a/README.md +++ b/README.md @@ -15,9 +15,9 @@ Support the mod: [Patreon — NandorTheModder](https://www.patreon.com/c/NandorT --- -## New in v1.5.12 +## New in v1.5.13 -Compatibility fix for Valkyr (female body replacer): your hair no longer disappears when you leave a monster form. Full details in the [changelog](#v1512). +Fixes a freeze on servers with factions on: when a building a mob was attacking got destroyed, every creature in the area stopped moving and players slid on the ground. Dvergar now pay the discounted metal cost the build menu shows. Full details in the [changelog](#v1513). --- @@ -450,6 +450,10 @@ Both halves have an off switch under `Factions` in Configuration Manager: **Fact ## Changelog +### v1.5.13 +- **Fix - world freezes with factions on:** since v1.5.11, if a mob was targeting a building piece and the piece got destroyed or removed, the faction check threw an error every frame. On a server this stopped the AI of every creature in the area: players slid on the ground, enemies stood still, and characters sometimes turned invisible. The check now drops the dead target and moves on. Thanks to SCRIMSHAW and GaoVN for the reports, and to SCRIMSHAW for testing the fix on their server. +- **Fix - Dvergar build discount:** the build menu showed the discounted metal cost (a cauldron for 6 tin instead of 10), but the hammer still refused to place the piece unless you carried the full vanilla amount. Pieces now build at the price shown. Dismantling or destroying a piece a Dvergar built returns the metal they paid, not the vanilla amount. Thanks to Balmarog for the report. + ### v1.5.12 - **Fix - hair gone after a form with Valkyr:** with the Valkyr body replacer, leaving a monster form (Skadi drake, Aswid bat or mist, Fenrir forms, Sverm Ravager, Trol True Form) brought the body back without its hair. Valkyr hides and shows its own hair, and the mod mistook that for a part it still had to hide, so it never turned the hair back on. Your hair now returns with the rest of the body. Thanks to BoredLizard for the report. diff --git a/manifest.json b/manifest.json index 6211ee9..8b1a0cf 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.5.12", + "version_number": "1.5.13", "website_url": "", "dependencies": [ "denikson-BepInExPack_Valheim-5.4.2333", From 691ccc211b666b76dfa2d7af8665d56defc7fe14 Mon Sep 17 00:00:00 2001 From: kanym Date: Tue, 20 Oct 2026 03:17:08 +0200 Subject: [PATCH 061/176] fix(visuals): a resized player's weapon hits as far as it is drawn Attack.DoMeleeAttack and DoAreaAttack measure range and ray width from the unscaled root, so a Legacy True Form Trol at 2.5 still hit at a human's 2 m while the drawn mace reached five. Both now grow by the Visual's world scale (never below 1), the factor HeldItemScaleFix sizes the weapon by. Height stays at the feet so a flat swing does not pass over small enemies. F8 toggles an in-game readout of the stretched numbers and what a cast straight ahead passes through. --- JotunnModStub/RaceMeleeReach.cs | 129 ++++++++++++++++++++++++++++++++ 1 file changed, 129 insertions(+) create mode 100644 JotunnModStub/RaceMeleeReach.cs diff --git a/JotunnModStub/RaceMeleeReach.cs b/JotunnModStub/RaceMeleeReach.cs new file mode 100644 index 0000000..4b2d66b --- /dev/null +++ b/JotunnModStub/RaceMeleeReach.cs @@ -0,0 +1,129 @@ +using System.Collections.Generic; +using HarmonyLib; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// Makes a resized player's weapon hit as far as the weapon is drawn. + /// + /// Vanilla's melee check (Attack.DoMeleeAttack) fans sphere casts out from the player's ROOT, + /// m_attackHeight above the feet and m_attackRange long, and none of those numbers know the + /// model was resized. Races resize the "Visual" child, never the root (see RaceEyeHeight), so a + /// Legacy True Form Trol at 2.5 swung a mace whose head landed five metres out while the hit + /// still stopped at a human's 2 m. Testers saw it as "hits the first few, then 50/50": the + /// targets close in were inside the human reach, the rest only stood under the drawn weapon. + /// The area attack (sledges, DoAreaAttack) has the same blind spot: its sphere sits a human's + /// range ahead with a human's radius. + /// + /// Range and ray width grow by the model's size, the world scale of the Visual - the same factor + /// HeldItemScaleFix sizes the weapon by, so the hit follows the weapon through tiers, True Form + /// and the grow animation. Never below 1: a Furling or a Dvergar keeps the vanilla reach, for + /// the same reason RaceEyeHeight never shrinks the interact range. + /// + /// The height is left alone on purpose. A horizontal swing is one flat fan at that height, and + /// raised to 2.5 m it passed clean over a Greydwarf's head. Kept at the feet, the wider sphere + /// still covers from the ground to above a human's head, and a troll stands up into it anyway. + /// + /// The troll-model True Form does not swing weapons at all (TrolTrueFormBehavior does its own + /// hits), and a player inside a borrowed form keeps the Visual at 1, so both read as 1 here. + /// Fields are put back in a finalizer: the Attack is a clone per swing, but a throw halfway + /// through must not leave a stretched one behind for the next hit of a chain. + /// + [HarmonyPatch] + internal static class RaceMeleeReach + { + private struct Saved + { + public bool Active; + public float Range; + public float RayWidth; + public float RayWidthCharExtra; + } + + private static IEnumerable TargetMethods() + { + yield return AccessTools.Method(typeof(Attack), "DoMeleeAttack"); + yield return AccessTools.Method(typeof(Attack), "DoAreaAttack"); + } + + private static void Prefix(Attack __instance, Humanoid ___m_character, out Saved __state) + { + __state = default; + if (!(___m_character is Player player)) return; + + float scale = ModelScale(player); + if (scale <= 1.001f) return; + + __state = new Saved + { + Active = true, + Range = __instance.m_attackRange, + RayWidth = __instance.m_attackRayWidth, + RayWidthCharExtra = __instance.m_attackRayWidthCharExtra + }; + __instance.m_attackRange *= scale; + __instance.m_attackRayWidth *= scale; + __instance.m_attackRayWidthCharExtra *= scale; + + if (DebugOn && player == Player.m_localPlayer) Report(__instance, player, scale, __state); + } + + private static void Finalizer(Attack __instance, Saved __state) + { + if (!__state.Active) return; + __instance.m_attackRange = __state.Range; + __instance.m_attackRayWidth = __state.RayWidth; + __instance.m_attackRayWidthCharExtra = __state.RayWidthCharExtra; + } + + private static float ModelScale(Player player) + { + GameObject visual = Traverse.Create(player).Field("m_visual").GetValue(); + if (visual == null) return 1f; + return Mathf.Max(1f, visual.transform.lossyScale.y); + } + + // ---- F8 debug: what the stretched swing reaches, read in game ---- + + internal static bool DebugOn; + + /// One sphere cast straight ahead with the stretched numbers, listing every + /// character it passes through and how far out, next to the vanilla range it replaced. + private static void Report(Attack attack, Player player, float scale, Saved before) + { + Vector3 origin = player.transform.position + Vector3.up * attack.m_attackHeight; + Vector3 dir = player.transform.forward; + float width = Mathf.Max(0.05f, attack.m_attackRayWidth); + RaycastHit[] hits = Physics.SphereCastAll(origin, width, dir, Mathf.Max(0f, attack.m_attackRange - width), + LayerMask.GetMask("character", "character_net", "character_ghost", "hitbox", "character_noenv"), + QueryTriggerInteraction.Ignore); + + var names = new List(); + foreach (RaycastHit hit in hits) + { + GameObject go = Projectile.FindHitObject(hit.collider); + if (go == null || go == player.gameObject) continue; + names.Add($"{go.name.Replace("(Clone)", "")} {hit.distance:0.0}m"); + } + + string line = $"[RoV reach] x{scale:0.00} {attack.m_attackType} range {before.Range:0.0}->{attack.m_attackRange:0.0} " + + $"width {before.RayWidth:0.00}->{attack.m_attackRayWidth:0.00} height {attack.m_attackHeight:0.0} | " + + (names.Count > 0 ? string.Join(", ", names) : "no character ahead"); + Debug.Log(line); + player.Message(MessageHud.MessageType.TopLeft, line); + } + } + + /// F8 turns the reach readout on and off. + [HarmonyPatch(typeof(Player), "Update")] + internal static class RaceMeleeReachDebugKey + { + private static void Postfix(Player __instance) + { + if (__instance != Player.m_localPlayer || !Input.GetKeyDown(KeyCode.F8)) return; + RaceMeleeReach.DebugOn = !RaceMeleeReach.DebugOn; + __instance.Message(MessageHud.MessageType.TopLeft, $"[RoV reach] debug {(RaceMeleeReach.DebugOn ? "on" : "off")}"); + } + } +} From 95c8a7b1b621dbf447df1d87ff3ac64e26589128 Mon Sep 17 00:00:00 2001 From: kanym Date: Fri, 23 Oct 2026 19:03:58 +0200 Subject: [PATCH 062/176] fix(furling): other players see a Furling at Furling size The 0.81 scale was applied from a Player.Update postfix that returned for anyone but the local player and read the race from the local m_customData. Scale is not replicated, so a Furling was small only on their own screen. The postfix now sizes every player, with the race read off the ZDO the way the Dvergar and the Trol already do it. --- JotunnModStub/Furling/FurlingPatches.cs | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/JotunnModStub/Furling/FurlingPatches.cs b/JotunnModStub/Furling/FurlingPatches.cs index 01bb0d3..7efb827 100644 --- a/JotunnModStub/Furling/FurlingPatches.cs +++ b/JotunnModStub/Furling/FurlingPatches.cs @@ -11,9 +11,13 @@ namespace RacesOfValheim { public static void Postfix(Player __instance) { - if (__instance == null || __instance != Player.m_localPlayer) return; - - if (FurlingRace.IsFurling()) + if (__instance == null) return; + + // Every player, not only the local one, with the race read off the ZDO. Scale is not + // replicated: each client sizes the characters it draws. When this sized only the + // local player from its own m_customData, a Furling was small on their own screen + // and full height on everybody else's. + if (DvergarVisuals.GetPlayerRace(__instance) == "Furling") { // Scale player visuals down by 19% (0.9 * 0.9 = 0.81) GameObject visual = Traverse.Create(__instance).Field("m_visual").GetValue(); From eba537fa0739d1cd7429b7ca56d33a1f5a519ba0 Mon Sep 17 00:00:00 2001 From: kanym Date: Fri, 23 Oct 2026 19:18:53 +0200 Subject: [PATCH 063/176] fix(food): race foods replace a worn-down meal when the stomach is full Trenta seeds, Draugh raw flesh and Aswid meals each go through an EatFood prefix that, with three slots full and none holding the same food, answered false. Vanilla would replace the most depleted meal past half its time. The UseItem callers also never showed why: EatFood says nothing on a refusal, so the click did nothing at all. That is the Reddit report of a Trenta who could not eat any seeds. The prefixes now hand that case to native EatFood, the Aswid's CanConsumeItem postfix keeps vanilla's answer instead of forcing false, and the Trenta and Draugh callers ask CanEat(item, true) for vanilla's own message when a meal is refused. --- JotunnModStub/Aswid/AswidPatches.cs | 19 ++++++++----------- JotunnModStub/Draugh/DraughFoodPatches.cs | 12 +++++++++--- JotunnModStub/Trenta/TrentaFoodPatches.cs | 13 +++++++++++-- 3 files changed, 28 insertions(+), 16 deletions(-) diff --git a/JotunnModStub/Aswid/AswidPatches.cs b/JotunnModStub/Aswid/AswidPatches.cs index 6931d80..6e1609e 100644 --- a/JotunnModStub/Aswid/AswidPatches.cs +++ b/JotunnModStub/Aswid/AswidPatches.cs @@ -341,14 +341,11 @@ namespace RacesOfValheim } } - if (canRefresh) - { - __result = true; - } - else - { - __result = false; // Nessuno spazio disponibile, cibo si disintegra - } + // Otherwise vanilla's answer stands: it already allows replacing the + // most depleted meal past half its time, and already showed its "too + // full" message when it refused. Forcing false here used to block + // that replacement, silently. + if (canRefresh) __result = true; } } else @@ -426,9 +423,9 @@ namespace RacesOfValheim return false; } - // Se pieno e senza 4° slot disponibile, fallisce e disintegra - __result = false; - return false; + // Full, no fourth slot free, no slot holding this meal. Native EatFood + // replaces the most depleted meal past half its time, or refuses. + return true; } else { diff --git a/JotunnModStub/Draugh/DraughFoodPatches.cs b/JotunnModStub/Draugh/DraughFoodPatches.cs index f4a9ce2..ea56d5c 100644 --- a/JotunnModStub/Draugh/DraughFoodPatches.cs +++ b/JotunnModStub/Draugh/DraughFoodPatches.cs @@ -90,6 +90,11 @@ namespace RacesOfValheim var zanim = Traverse.Create(player).Field("m_zanim").GetValue(); if (zanim != null) zanim.SetTrigger("eat"); } + else + { + // Vanilla's refusal message, which EatFood never shows by itself + player.CanEat(customItemDrop.m_itemData, true); + } return false; // Skip native UseItem } } @@ -154,9 +159,10 @@ namespace RacesOfValheim return false; // Skip native EatFood } - // Inventory full - __result = false; - return false; + // Full, and no slot holds this flesh. Native EatFood replaces the most + // depleted meal past half its time, or refuses - vanilla's own rule. This + // used to refuse outright, with no message. + return true; } else { diff --git a/JotunnModStub/Trenta/TrentaFoodPatches.cs b/JotunnModStub/Trenta/TrentaFoodPatches.cs index bc17d19..43bd5c5 100644 --- a/JotunnModStub/Trenta/TrentaFoodPatches.cs +++ b/JotunnModStub/Trenta/TrentaFoodPatches.cs @@ -71,6 +71,12 @@ namespace RacesOfValheim var zanim = Traverse.Create(player).Field("m_zanim").GetValue(); if (zanim != null) zanim.SetTrigger("eat"); } + else + { + // Vanilla's "can't eat more" / "too full" message, from vanilla's own + // check. EatFood itself never says why it refused. + player.CanEat(customDrop.m_itemData, true); + } return false; // Skip native UseItem either way } @@ -172,8 +178,11 @@ namespace RacesOfValheim } } - __result = false; // Full, and nothing in it worth topping up: the seed stays. - return false; + // Full, and no slot holds this seed. Native EatFood takes it from here with + // vanilla's own rule: it replaces the most depleted meal past half its time, + // or refuses. This used to refuse outright, so a Trenta with three meals going + // could not eat a seed at all, and saw no message saying why. + return true; } // Temporarily hide any existing slot with the same name to force native EatFood From f1597dd6462a7049753643929b769dbba13eca04 Mon Sep 17 00:00:00 2001 From: kanym Date: Fri, 23 Oct 2026 19:22:31 +0200 Subject: [PATCH 064/176] fix(hud): the stamina bar comes back after leaving the Aswid or the Draugh Both races hide the stamina bar root from a Hud.UpdateStamina prefix. Vanilla activates that root once, when the HUD is built, so after a race change the bar stayed hidden until relog. The prefix now switches it back on for every other race. --- JotunnModStub/Aswid/AswidPatches.cs | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/JotunnModStub/Aswid/AswidPatches.cs b/JotunnModStub/Aswid/AswidPatches.cs index 6931d80..58ea170 100644 --- a/JotunnModStub/Aswid/AswidPatches.cs +++ b/JotunnModStub/Aswid/AswidPatches.cs @@ -508,6 +508,14 @@ namespace RacesOfValheim } return false; } + + // Vanilla switches the bar on once, when the HUD is built, and never again. Without + // this a player who left the Aswid or the Draugh had no stamina bar until relog. + if (player == Player.m_localPlayer && __instance.m_staminaBar2Root != null + && !__instance.m_staminaBar2Root.gameObject.activeSelf) + { + __instance.m_staminaBar2Root.gameObject.SetActive(true); + } return true; } } From d1f328a496c5e84b968df63d755114149fdc2027 Mon Sep 17 00:00:00 2001 From: kanym Date: Fri, 23 Oct 2026 19:33:00 +0200 Subject: [PATCH 065/176] feat(fenrir): eyes glow at night, bright when a form is ready A community suggestion: an indicator on the character instead of the "
is Ready!" text. FenrirVisuals borrows the Skeleton's eye_l and eye_r the way AswidVisuals does, with the Aswid's playtested placement, and tints them with the Fenring's own emission colour (2.0, 0.372, 0), read from bundle c4210710. Dark by day and in a beast form. At night they glow faintly, and brightly while one of the three keys would transform. That uses the same gates as TryTransformWithRules: tier, night, sun sickness, cooldown. The owner writes it to the ZDO only on a change, so remote players see the same. New local section "Fenrir - Appearance": Ready Message (on by default), Eye Glow, and the night and ready strengths. --- JotunnModStub/ConfigSync.cs | 1 + JotunnModStub/Fenrir/FenrirConfig.cs | 17 ++ JotunnModStub/Fenrir/FenrirRace.cs | 29 +++ JotunnModStub/Fenrir/FenrirStatusEffects.cs | 2 +- JotunnModStub/Fenrir/FenrirVisuals.cs | 256 ++++++++++++++++++++ 5 files changed, 304 insertions(+), 1 deletion(-) create mode 100644 JotunnModStub/Fenrir/FenrirVisuals.cs diff --git a/JotunnModStub/ConfigSync.cs b/JotunnModStub/ConfigSync.cs index f743b4c..0281af6 100644 --- a/JotunnModStub/ConfigSync.cs +++ b/JotunnModStub/ConfigSync.cs @@ -28,6 +28,7 @@ namespace RacesOfValheim { "Aswid - Claws", "Aswid - Eyes", + "Fenrir - Appearance", "Skeleton - Visuals", "Sverm - Dorsal Spines", "Sverm - Emberform", diff --git a/JotunnModStub/Fenrir/FenrirConfig.cs b/JotunnModStub/Fenrir/FenrirConfig.cs index 74795e5..68e9a97 100644 --- a/JotunnModStub/Fenrir/FenrirConfig.cs +++ b/JotunnModStub/Fenrir/FenrirConfig.cs @@ -85,6 +85,12 @@ namespace RacesOfValheim // ─── Debug ───────────────────────────────────────────────────────────── public static ConfigEntry DebugFormHits; + // ─── Appearance (per player, never synced) ────────────────────────────── + public static ConfigEntry ReadyMessage; + public static ConfigEntry EyeGlow; + public static ConfigEntry EyeNightStrength; + public static ConfigEntry EyeReadyStrength; + public static void Bind(ConfigFile config) { const string keybinds = "Fenrir - Keybinds"; @@ -188,6 +194,17 @@ namespace RacesOfValheim UlvPushForce = config.Bind(ulv, "Push Force", 25f, new ConfigDescription("Knockback applied on a hit.", new AcceptableValueRange(0f, 100f))); + // The whole section stays local - see ConfigSync.LocalSections. + const string appearance = "Fenrir - Appearance"; + ReadyMessage = config.Bind(appearance, "Ready Message", true, + new ConfigDescription("Shows \" is Ready!\" when a form's cooldown ends. The eyes say the same thing; turn this off if they are enough.")); + EyeGlow = config.Bind(appearance, "Eye Glow", true, + new ConfigDescription("Fenrir eyes glow at night in the Fenring's own orange: faint while no form can be taken, bright when one can. Off hides them on every Fenrir you see.")); + EyeNightStrength = config.Bind(appearance, "Eye Night Strength", 0.35f, + new ConfigDescription("Glow at night while no form is ready.", new AcceptableValueRange(0f, 3f))); + EyeReadyStrength = config.Bind(appearance, "Eye Ready Strength", 1.2f, + new ConfigDescription("Glow at night while a form is ready.", new AcceptableValueRange(0f, 3f))); + // "debug" in the key keeps it local - see ConfigSync. DebugFormHits = config.Bind("Fenrir - Debug", "Debug: Log Form Hits", false, new ConfigDescription("Writes one log line per claw or bite: what was in reach, what it hit, and why anything was skipped. For bug reports about attacks that do no damage.")); diff --git a/JotunnModStub/Fenrir/FenrirRace.cs b/JotunnModStub/Fenrir/FenrirRace.cs index 655cb86..9feeb51 100644 --- a/JotunnModStub/Fenrir/FenrirRace.cs +++ b/JotunnModStub/Fenrir/FenrirRace.cs @@ -150,6 +150,8 @@ namespace RacesOfValheim { } wasNight = isNight; + FenrirVisuals.SetReady(Player.m_localPlayer, CanTakeAnyForm()); + if (isTransformed) { bool hasAnyForm = Player.m_localPlayer.GetSEMan().HaveStatusEffect("SE_FenrirForm".GetStableHashCode()) || @@ -171,6 +173,33 @@ namespace RacesOfValheim { if (FenrirConfig.CultistFormKey.Value.IsDownIgnoringHeldKeys()) { TryTransformWithRules(FenrirProgression.GetJKeyRules(state)); return; } } + /// + /// Whether one of the three keys would transform right now. The same gates as + /// TryTransformWithRules below, without its messages: this feeds the eye glow. + /// + private bool CanTakeAnyForm() + { + if (isTransformed) return false; + + int state = BossProgressionManager.GetCurrentProgressionState(); + return CanTake(FenrirProgression.GetGKeyRules(state)) + || CanTake(FenrirProgression.GetHKeyRules(state)) + || CanTake(FenrirProgression.GetJKeyRules(state)); + } + + private bool CanTake(FenrirProgression.FormRules rules) + { + if (rules == null || rules.Form == FenrirProgression.FormType.None) return false; + if (rules.NeedsNight && (sunSicknessTimer > 0f || !EnvMan.IsNight())) return false; + + if (rules.CooldownMinutes > 0) + { + string cdName = rules.Form == FenrirProgression.FormType.Cultist ? "SE_CultistCooldown" : "SE_FenrirCooldown"; + if (Player.m_localPlayer.GetSEMan().HaveStatusEffect(cdName.GetStableHashCode())) return false; + } + return true; + } + private void TryTransformWithRules(FenrirProgression.FormRules rules) { if (rules == null || rules.Form == FenrirProgression.FormType.None) return; diff --git a/JotunnModStub/Fenrir/FenrirStatusEffects.cs b/JotunnModStub/Fenrir/FenrirStatusEffects.cs index 43de139..f08ae33 100644 --- a/JotunnModStub/Fenrir/FenrirStatusEffects.cs +++ b/JotunnModStub/Fenrir/FenrirStatusEffects.cs @@ -15,7 +15,7 @@ namespace RacesOfValheim public override void Stop() { base.Stop(); - if (Player.m_localPlayer != null) + if (Player.m_localPlayer != null && FenrirConfig.ReadyMessage.Value) { Player.m_localPlayer.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_fenrir_ready", m_name)); } diff --git a/JotunnModStub/Fenrir/FenrirVisuals.cs b/JotunnModStub/Fenrir/FenrirVisuals.cs new file mode 100644 index 0000000..7b901c0 --- /dev/null +++ b/JotunnModStub/Fenrir/FenrirVisuals.cs @@ -0,0 +1,256 @@ +using System.Collections.Generic; +using HarmonyLib; +using Jotunn.Managers; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// The Fenrir's eyes catch the light at night, the way a wolf's do: a faint glow while no form + /// can be taken, a bright one when a key would transform right now. Dark by day and while in a + /// beast form, whose own eyes take over. A community suggestion (lexsonn), meant to say what + /// the "Ready!" text says without the text. + /// + /// Built the way AswidVisuals builds the Aswid's eyes, which is where the long story lives: the + /// vanilla Skeleton's eye_l/eye_r borrowed for mesh and material, placed on the head bone the + /// body mesh is skinned to, sized from the source's world scale. The placement numbers are the + /// Aswid's playtested defaults, fixed here rather than exposed again. + /// + /// The colour is the Fenring's own: its body material's _EmissionColor, (2.0, 0.372, 0.0) in + /// bundle c4210710, read offline with UnityPy rather than picked by eye. + /// + /// Runs for remote players too. Night is the same for everyone; whether a form is ready is + /// only known to the owner, who writes it to the ZDO (SetReady) for everyone else to read. + /// + public static class FenrirVisuals + { + public const string RaceId = "Fenrir"; + public const string ReadyKey = "RacesOfValheim_FenrirReady"; + private const string FormKey = "RacesOfValheim_FenrirForm"; + private const string EyesName = "FenrirEyes"; + private const string SourceModel = "Skeleton"; + private static readonly string[] SourceEyeNames = { "eye_l", "eye_r" }; + + private static readonly Color FenringGlow = new Color(2.0f, 0.372f, 0f, 1f); + + // AswidVisuals' base placement plus its Configuration Manager defaults, which are what + // playtesting settled on for this same pair of eyes on this same rig. + private const float EyeForward = 0.081f + 0.013f; + private const float EyeHeight = 0.181f + 0.004f; + private const float EyeSeparation = 0.032f + 0.007f; + private const float EyeSize = 1.1f; + private const float EyeYaw = 22.068f; + private const float EyeRoll = -180f; + + /// Owner only, and only on a change: one ZDO write per transition, not per frame. + public static void SetReady(Player player, bool ready) + { + ZNetView nview = player != null ? player.GetComponent() : null; + if (nview == null || !nview.IsValid() || !nview.IsOwner()) return; + + ZDO zdo = nview.GetZDO(); + if (zdo.GetBool(ReadyKey, false) != ready) zdo.Set(ReadyKey, ready); + } + + /// + /// Keeps the eyes on a living Fenrir and takes them off anyone else. Called from + /// VisEquipment.UpdateColors, which is what notices a race change; the ticker below then + /// follows night, readiness and forms frame by frame. + /// + public static void ApplyEyes(Player player) + { + if (player == null) return; + + Transform headBone = FindHeadBone(player); + if (headBone == null) return; // rig not up yet; the ticker or the next refresh retries + + Transform eyes = headBone.Find(EyesName); + + if (DvergarVisuals.GetPlayerRace(player) != RaceId || player.IsDead()) + { + if (eyes != null) + { + // Renamed first: Destroy waits for the end of the frame. + eyes.name = EyesName + "_Removed"; + Object.Destroy(eyes.gameObject); + } + EyeTicker ticker = player.GetComponent(); + if (ticker != null) Object.Destroy(ticker); + return; + } + + if (player.GetComponent() == null) player.gameObject.AddComponent(); + + float strength = GetGlowStrength(player); + if (strength <= 0f) + { + if (eyes != null && eyes.gameObject.activeSelf) eyes.gameObject.SetActive(false); + return; + } + + if (eyes == null) + { + // The skull's facing is measured once, at build time. A head turned by sitting, + // an attack or sleep would measure wrong; see AswidVisuals.ApplyEyes. + if (player.IsAttached() || player.IsAttachedToShip() || player.InAttack() || player.IsSleeping()) return; + eyes = BuildEyes(player, headBone); + if (eyes == null) return; + } + + if (!eyes.gameObject.activeSelf) eyes.gameObject.SetActive(true); + PaintEyes(eyes, FenringGlow * strength); + } + + /// 0 means dark: day, a beast form, or the viewer turned the glow off. + private static float GetGlowStrength(Player player) + { + if (!FenrirConfig.EyeGlow.Value) return 0f; + if (EnvMan.instance == null || !EnvMan.IsNight()) return 0f; + + ZNetView nview = player.GetComponent(); + if (nview == null || !nview.IsValid()) return 0f; + + ZDO zdo = nview.GetZDO(); + if (!string.IsNullOrEmpty(zdo.GetString(FormKey, ""))) return 0f; + + return zdo.GetBool(ReadyKey, false) + ? FenrirConfig.EyeReadyStrength.Value + : FenrirConfig.EyeNightStrength.Value; + } + + public class EyeTicker : MonoBehaviour + { + private Player m_player; + + private void Awake() => m_player = GetComponent(); + + private void LateUpdate() + { + if (m_player == null) { Destroy(this); return; } + ApplyEyes(m_player); + } + } + + /// The body mesh's own Head bone, never the Animator's. See AswidVisuals.FindHeadBone. + private static Transform FindHeadBone(Player player) + { + VisEquipment visEq = player.GetComponent(); + if (visEq == null || visEq.m_bodyModel == null || visEq.m_bodyModel.bones == null) return null; + + foreach (Transform bone in visEq.m_bodyModel.bones) + { + if (bone != null && bone.name == AswidVisuals.PlayerHeadBoneName) return bone; + } + return null; + } + + private static Transform BuildEyes(Player player, Transform headBone) + { + List sources = FindSourceEyes(); + if (sources.Count == 0) return null; + + float lossy = headBone.lossyScale.x; + if (Mathf.Abs(lossy) < 0.0001f) return null; // rig still coming up + float toLocal = 1f / lossy; + + GameObject holder = new GameObject(EyesName); + holder.transform.SetParent(headBone, false); + + RigBindPose.MeasureHeadFrame(player, headBone, RaceId, + out Vector3 forward, out Vector3 up, out Vector3 right); + Quaternion facing = Quaternion.LookRotation(forward, up); + + // The player's own scale cancels the rig's, as in AswidVisuals.PlaceEyes. + float scale = player.transform.localScale.x * toLocal; + + foreach (Transform source in sources) + { + GameObject eye = Object.Instantiate(source.gameObject, holder.transform); + eye.name = source.name; + + float side = source.name.ToLowerInvariant().Contains("_l") ? -1f : 1f; + + eye.transform.localPosition = forward * (EyeForward * scale) + + up * (EyeHeight * scale) + + right * (side * EyeSeparation * scale); + // Yaw mirrored per eye so the pair turns in towards the nose together. + eye.transform.localRotation = Quaternion.Euler(0f, EyeYaw * side, EyeRoll) * facing; + eye.transform.localScale = source.lossyScale * toLocal * EyeSize; + + // Allowlist: whatever else rode along on the skeleton goes. + foreach (Component comp in eye.GetComponentsInChildren(true)) + { + if (comp is Transform || comp is MeshRenderer || comp is MeshFilter) continue; + if (comp is ParticleSystem || comp is ParticleSystemRenderer) + { + // The skeleton's eye smoke, on a child of the eye: too loud for a reflection. + if (comp.gameObject != eye) comp.gameObject.SetActive(false); + continue; + } + Object.Destroy(comp); + } + + foreach (Renderer renderer in eye.GetComponentsInChildren(true)) + { + renderer.enabled = true; + renderer.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off; + renderer.receiveShadows = false; + } + + eye.SetActive(true); + } + + return holder.transform; + } + + /// Every colour property the borrowed material has; see AswidVisuals.PaintEyes. + private static void PaintEyes(Transform holder, Color glow) + { + glow.a = 1f; + foreach (Renderer renderer in holder.GetComponentsInChildren(true)) + { + Material material = renderer.material; + if (material == null) continue; + + if (material.HasProperty("_Color")) material.SetColor("_Color", glow); + if (material.HasProperty("_TintColor")) material.SetColor("_TintColor", glow); + if (material.HasProperty("_BaseColor")) material.SetColor("_BaseColor", glow); + if (material.HasProperty("_EmissionColor")) material.SetColor("_EmissionColor", glow); + } + } + + private static bool warnedSource; + + private static List FindSourceEyes() + { + List found = new List(); + + GameObject prefab = PrefabManager.Cache.GetPrefab(SourceModel); + if (prefab != null) + { + foreach (Transform t in prefab.GetComponentsInChildren(true)) + { + string lower = t.name.ToLower(); + if (lower == SourceEyeNames[0] || lower == SourceEyeNames[1]) found.Add(t); + } + } + + if (found.Count == 0 && !warnedSource) + { + warnedSource = true; + Jotunn.Logger.LogWarning($"[Fenrir] No eye_l/eye_r found on '{SourceModel}' - the eyes stay dark."); + } + return found; + } + } + + [HarmonyPatch(typeof(VisEquipment), "UpdateColors")] + public static class FenrirEyesPatch + { + public static void Postfix(VisEquipment __instance) + { + if (!__instance.m_isPlayer) return; + FenrirVisuals.ApplyEyes(__instance.GetComponent()); + } + } +} From 2becb81b6ffe2e44950cd906bfdb62ea349697f7 Mon Sep 17 00:00:00 2001 From: kanym Date: Fri, 23 Oct 2026 19:58:35 +0200 Subject: [PATCH 066/176] fix(fenrir): the faint night glow is bright enough to see At 0.35 the red channel stayed under 1, so bloom never picked it up and a Fenrir with no form ready looked like it had no glow at all. 0.6 puts it just over. --- JotunnModStub/Fenrir/FenrirConfig.cs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/JotunnModStub/Fenrir/FenrirConfig.cs b/JotunnModStub/Fenrir/FenrirConfig.cs index 68e9a97..67f695a 100644 --- a/JotunnModStub/Fenrir/FenrirConfig.cs +++ b/JotunnModStub/Fenrir/FenrirConfig.cs @@ -200,7 +200,9 @@ namespace RacesOfValheim new ConfigDescription("Shows \" is Ready!\" when a form's cooldown ends. The eyes say the same thing; turn this off if they are enough.")); EyeGlow = config.Bind(appearance, "Eye Glow", true, new ConfigDescription("Fenrir eyes glow at night in the Fenring's own orange: faint while no form can be taken, bright when one can. Off hides them on every Fenrir you see.")); - EyeNightStrength = config.Bind(appearance, "Eye Night Strength", 0.35f, + // Above 0.5 so the red channel (2.0 x strength) passes 1 and the bloom pass picks it + // up: at 0.35 the faint state read as no glow at all. + EyeNightStrength = config.Bind(appearance, "Eye Night Strength", 0.6f, new ConfigDescription("Glow at night while no form is ready.", new AcceptableValueRange(0f, 3f))); EyeReadyStrength = config.Bind(appearance, "Eye Ready Strength", 1.2f, new ConfigDescription("Glow at night while a form is ready.", new AcceptableValueRange(0f, 3f))); From c2bc73b3a095f738d94e15997699e4fa7881812d Mon Sep 17 00:00:00 2001 From: kanym Date: Fri, 23 Oct 2026 20:06:49 +0200 Subject: [PATCH 067/176] feat(fenrir): eyes turn the Cultist's yellow when it is back from cooldown The ready flag becomes an int: none, a form, or the Cultist. The Cultist wins only while its rules give it a cooldown (Yagluth and Queen), since that is the one return worth announcing. Its body shares the Fenring's material and its breath is white flame tinted by texture, so the colour comes from its death effect: FlameRoundYellowParticle's emission, (2.691, 1.797, 0.455), bundle c4210710. --- JotunnModStub/Fenrir/FenrirConfig.cs | 2 +- JotunnModStub/Fenrir/FenrirRace.cs | 23 ++++++++++----- JotunnModStub/Fenrir/FenrirVisuals.cs | 41 ++++++++++++++++++++------- 3 files changed, 48 insertions(+), 18 deletions(-) diff --git a/JotunnModStub/Fenrir/FenrirConfig.cs b/JotunnModStub/Fenrir/FenrirConfig.cs index 67f695a..17a26cd 100644 --- a/JotunnModStub/Fenrir/FenrirConfig.cs +++ b/JotunnModStub/Fenrir/FenrirConfig.cs @@ -199,7 +199,7 @@ namespace RacesOfValheim ReadyMessage = config.Bind(appearance, "Ready Message", true, new ConfigDescription("Shows \" is Ready!\" when a form's cooldown ends. The eyes say the same thing; turn this off if they are enough.")); EyeGlow = config.Bind(appearance, "Eye Glow", true, - new ConfigDescription("Fenrir eyes glow at night in the Fenring's own orange: faint while no form can be taken, bright when one can. Off hides them on every Fenrir you see.")); + new ConfigDescription("Fenrir eyes glow at night in the Fenring's own orange: faint while no form can be taken, bright when one can, yellow when the Cultist is back from its cooldown. Off hides them on every Fenrir you see.")); // Above 0.5 so the red channel (2.0 x strength) passes 1 and the bloom pass picks it // up: at 0.35 the faint state read as no glow at all. EyeNightStrength = config.Bind(appearance, "Eye Night Strength", 0.6f, diff --git a/JotunnModStub/Fenrir/FenrirRace.cs b/JotunnModStub/Fenrir/FenrirRace.cs index 9feeb51..963737b 100644 --- a/JotunnModStub/Fenrir/FenrirRace.cs +++ b/JotunnModStub/Fenrir/FenrirRace.cs @@ -150,7 +150,7 @@ namespace RacesOfValheim { } wasNight = isNight; - FenrirVisuals.SetReady(Player.m_localPlayer, CanTakeAnyForm()); + FenrirVisuals.SetReady(Player.m_localPlayer, GetReadyState()); if (isTransformed) { @@ -174,17 +174,26 @@ namespace RacesOfValheim { } /// - /// Whether one of the three keys would transform right now. The same gates as - /// TryTransformWithRules below, without its messages: this feeds the eye glow. + /// What the eyes should say right now, using the same gates as TryTransformWithRules + /// below without its messages. The Cultist wins over the other forms only while its rules + /// give it a cooldown: that is the one form whose return is worth announcing. /// - private bool CanTakeAnyForm() + private FenrirVisuals.ReadyState GetReadyState() { - if (isTransformed) return false; + if (isTransformed) return FenrirVisuals.ReadyState.None; int state = BossProgressionManager.GetCurrentProgressionState(); - return CanTake(FenrirProgression.GetGKeyRules(state)) + FenrirProgression.FormRules cultist = FenrirProgression.GetJKeyRules(state); + + if (CanTake(cultist) && cultist.CooldownMinutes > 0) return FenrirVisuals.ReadyState.Cultist; + + if (CanTake(FenrirProgression.GetGKeyRules(state)) || CanTake(FenrirProgression.GetHKeyRules(state)) - || CanTake(FenrirProgression.GetJKeyRules(state)); + || CanTake(cultist)) + { + return FenrirVisuals.ReadyState.Form; + } + return FenrirVisuals.ReadyState.None; } private bool CanTake(FenrirProgression.FormRules rules) diff --git a/JotunnModStub/Fenrir/FenrirVisuals.cs b/JotunnModStub/Fenrir/FenrirVisuals.cs index 7b901c0..fd0836b 100644 --- a/JotunnModStub/Fenrir/FenrirVisuals.cs +++ b/JotunnModStub/Fenrir/FenrirVisuals.cs @@ -7,7 +7,8 @@ namespace RacesOfValheim { /// /// The Fenrir's eyes catch the light at night, the way a wolf's do: a faint glow while no form - /// can be taken, a bright one when a key would transform right now. Dark by day and while in a + /// can be taken, a bright one when a key would transform right now, and the Cultist's yellow + /// when that form is back from its cooldown. Dark by day and while in a /// beast form, whose own eyes take over. A community suggestion (lexsonn), meant to say what /// the "Ready!" text says without the text. /// @@ -26,6 +27,14 @@ namespace RacesOfValheim { public const string RaceId = "Fenrir"; public const string ReadyKey = "RacesOfValheim_FenrirReady"; + + /// Written to the ZDO as an int, so the values are part of the network contract. + public enum ReadyState + { + None = 0, + Form = 1, + Cultist = 2, + } private const string FormKey = "RacesOfValheim_FenrirForm"; private const string EyesName = "FenrirEyes"; private const string SourceModel = "Skeleton"; @@ -33,6 +42,11 @@ namespace RacesOfValheim private static readonly Color FenringGlow = new Color(2.0f, 0.372f, 0f, 1f); + // The Cultist's body is the Fenring's material and its breath is white flame tinted by + // texture, so neither tells it apart. Its own death effect (vfx_fenring_cultist_death) + // does: FlameRoundYellowParticle's _EmissionColor, same bundle. + private static readonly Color CultistGlow = new Color(2.691f, 1.797f, 0.455f, 1f); + // AswidVisuals' base placement plus its Configuration Manager defaults, which are what // playtesting settled on for this same pair of eyes on this same rig. private const float EyeForward = 0.081f + 0.013f; @@ -43,13 +57,13 @@ namespace RacesOfValheim private const float EyeRoll = -180f; /// Owner only, and only on a change: one ZDO write per transition, not per frame. - public static void SetReady(Player player, bool ready) + public static void SetReady(Player player, ReadyState ready) { ZNetView nview = player != null ? player.GetComponent() : null; if (nview == null || !nview.IsValid() || !nview.IsOwner()) return; ZDO zdo = nview.GetZDO(); - if (zdo.GetBool(ReadyKey, false) != ready) zdo.Set(ReadyKey, ready); + if (zdo.GetInt(ReadyKey, 0) != (int)ready) zdo.Set(ReadyKey, (int)ready); } /// @@ -81,7 +95,7 @@ namespace RacesOfValheim if (player.GetComponent() == null) player.gameObject.AddComponent(); - float strength = GetGlowStrength(player); + float strength = GetGlowStrength(player, out Color hue); if (strength <= 0f) { if (eyes != null && eyes.gameObject.activeSelf) eyes.gameObject.SetActive(false); @@ -98,12 +112,17 @@ namespace RacesOfValheim } if (!eyes.gameObject.activeSelf) eyes.gameObject.SetActive(true); - PaintEyes(eyes, FenringGlow * strength); + PaintEyes(eyes, hue * strength); } - /// 0 means dark: day, a beast form, or the viewer turned the glow off. - private static float GetGlowStrength(Player player) + /// + /// 0 means dark: day, a beast form, or the viewer turned the glow off. Otherwise faint + /// orange with nothing ready, bright orange with a form ready, bright yellow when the + /// Cultist is back from its cooldown. + /// + private static float GetGlowStrength(Player player, out Color hue) { + hue = FenringGlow; if (!FenrirConfig.EyeGlow.Value) return 0f; if (EnvMan.instance == null || !EnvMan.IsNight()) return 0f; @@ -113,9 +132,11 @@ namespace RacesOfValheim ZDO zdo = nview.GetZDO(); if (!string.IsNullOrEmpty(zdo.GetString(FormKey, ""))) return 0f; - return zdo.GetBool(ReadyKey, false) - ? FenrirConfig.EyeReadyStrength.Value - : FenrirConfig.EyeNightStrength.Value; + ReadyState ready = (ReadyState)zdo.GetInt(ReadyKey, 0); + if (ready == ReadyState.None) return FenrirConfig.EyeNightStrength.Value; + + if (ready == ReadyState.Cultist) hue = CultistGlow; + return FenrirConfig.EyeReadyStrength.Value; } public class EyeTicker : MonoBehaviour From 418d2462bdb34c7394c8f1de59b1dc81eecb6e88 Mon Sep 17 00:00:00 2001 From: kanym Date: Fri, 23 Oct 2026 20:12:30 +0200 Subject: [PATCH 068/176] fix(fenrir): a softer ready glow 1.2 read too strong in game; 0.9 by default. The faint glow stays at 0.6. --- JotunnModStub/Fenrir/FenrirConfig.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/JotunnModStub/Fenrir/FenrirConfig.cs b/JotunnModStub/Fenrir/FenrirConfig.cs index 17a26cd..4a95c89 100644 --- a/JotunnModStub/Fenrir/FenrirConfig.cs +++ b/JotunnModStub/Fenrir/FenrirConfig.cs @@ -204,7 +204,8 @@ namespace RacesOfValheim // up: at 0.35 the faint state read as no glow at all. EyeNightStrength = config.Bind(appearance, "Eye Night Strength", 0.6f, new ConfigDescription("Glow at night while no form is ready.", new AcceptableValueRange(0f, 3f))); - EyeReadyStrength = config.Bind(appearance, "Eye Ready Strength", 1.2f, + // Tried at 1.2 in game: the orange was too strong. + EyeReadyStrength = config.Bind(appearance, "Eye Ready Strength", 0.9f, new ConfigDescription("Glow at night while a form is ready.", new AcceptableValueRange(0f, 3f))); // "debug" in the key keeps it local - see ConfigSync. From 8b7e88e0770502b4adb1151435a738987b3feb7c Mon Sep 17 00:00:00 2001 From: kanym Date: Fri, 23 Oct 2026 22:08:05 +0200 Subject: [PATCH 069/176] fix(fenrir): faint night glow at 0.675, as tuned in game --- JotunnModStub/Fenrir/FenrirConfig.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/JotunnModStub/Fenrir/FenrirConfig.cs b/JotunnModStub/Fenrir/FenrirConfig.cs index 4a95c89..e9dd6e5 100644 --- a/JotunnModStub/Fenrir/FenrirConfig.cs +++ b/JotunnModStub/Fenrir/FenrirConfig.cs @@ -201,10 +201,10 @@ namespace RacesOfValheim EyeGlow = config.Bind(appearance, "Eye Glow", true, new ConfigDescription("Fenrir eyes glow at night in the Fenring's own orange: faint while no form can be taken, bright when one can, yellow when the Cultist is back from its cooldown. Off hides them on every Fenrir you see.")); // Above 0.5 so the red channel (2.0 x strength) passes 1 and the bloom pass picks it - // up: at 0.35 the faint state read as no glow at all. - EyeNightStrength = config.Bind(appearance, "Eye Night Strength", 0.6f, + // up: at 0.35 the faint state read as no glow at all. 0.675 is what looked right in game. + EyeNightStrength = config.Bind(appearance, "Eye Night Strength", 0.675f, new ConfigDescription("Glow at night while no form is ready.", new AcceptableValueRange(0f, 3f))); - // Tried at 1.2 in game: the orange was too strong. + // Tried at 1.2 in game: the orange was too strong. 0.9 checked and kept. EyeReadyStrength = config.Bind(appearance, "Eye Ready Strength", 0.9f, new ConfigDescription("Glow at night while a form is ready.", new AcceptableValueRange(0f, 3f))); From d8dcecb573381e4b8b5fe603a62adeb3970bc085 Mon Sep 17 00:00:00 2001 From: kanym Date: Fri, 23 Oct 2026 22:17:17 +0200 Subject: [PATCH 070/176] fix(fenrir): form hits build adrenaline like a weapon hit Vanilla grants a hit's adrenaline inside Attack. The forms skip Attack and call Damage directly, so only the stagger bonus in Character.Damage reached the player: meadow mobs, quick to stagger, filled the bar, while Lox, Tar, Brutes and Furlings gave nothing until staggered. FormMelee.GrantAdrenaline adds the player's unarmed attack adrenaline times the target's multiplier after each claw or bite, and a fifth of it per 0.2s tick of the Cultist's fire. --- JotunnModStub/Fenrir/FenrirBehaviors.cs | 5 +++++ JotunnModStub/Fenrir/FenrirFormShared.cs | 20 ++++++++++++++++++++ 2 files changed, 25 insertions(+) diff --git a/JotunnModStub/Fenrir/FenrirBehaviors.cs b/JotunnModStub/Fenrir/FenrirBehaviors.cs index 2b0783d..e1df615 100644 --- a/JotunnModStub/Fenrir/FenrirBehaviors.cs +++ b/JotunnModStub/Fenrir/FenrirBehaviors.cs @@ -752,6 +752,7 @@ namespace RacesOfValheim if (targetObj != null) hitObjects.Add(targetObj); FormMelee.LogHit(FormLabel, target, totalDamage); target.Damage(hitData); + FormMelee.GrantAdrenaline(target); } } } @@ -1012,6 +1013,7 @@ namespace RacesOfValheim if (targetObj != null) hitObjects.Add(targetObj); FormMelee.LogHit(FormLabel, target, totalDamage); target.Damage(hitData); + FormMelee.GrantAdrenaline(target, 0.2f); // one 0.2s tick: a full hit per second of breath if (ZNetScene.instance != null) { @@ -1141,6 +1143,7 @@ namespace RacesOfValheim if (targetObj != null) hitObjects.Add(targetObj); FormMelee.LogHit(FormLabel, target, totalDamage); target.Damage(hitData); + FormMelee.GrantAdrenaline(target); } } } @@ -1355,6 +1358,7 @@ namespace RacesOfValheim if (targetObj != null) hitObjects.Add(targetObj); FormMelee.LogHit(FormLabel, target, totalDamage); target.Damage(hitData); + FormMelee.GrantAdrenaline(target); } } } @@ -1562,6 +1566,7 @@ namespace RacesOfValheim if (targetObj != null) hitObjects.Add(targetObj); FormMelee.LogHit(FormLabel, target, totalDamage); target.Damage(hitData); + FormMelee.GrantAdrenaline(target); } } } diff --git a/JotunnModStub/Fenrir/FenrirFormShared.cs b/JotunnModStub/Fenrir/FenrirFormShared.cs index 6fafc2e..84dc78a 100644 --- a/JotunnModStub/Fenrir/FenrirFormShared.cs +++ b/JotunnModStub/Fenrir/FenrirFormShared.cs @@ -336,6 +336,26 @@ namespace RacesOfValheim Jotunn.Logger.LogInfo($"[FenrirForm] {form} swing skipped '{hit.name}' (layer {LayerMask.LayerToName(hit.gameObject.layer)}): {reason}."); } + /// + /// The adrenaline vanilla gives for a weapon hit, which a form's hit never got. Vanilla + /// grants it inside Attack (m_attackAdrenaline x the enemy's m_enemyAdrenalineMultiplier); + /// the forms skip Attack and call Damage directly, so only the stagger bonus inside + /// Character.Damage reached the player. That is the report: easy-to-stagger meadow mobs + /// filled the bar, Lox, Tar, Brutes and Furlings only did when staggered. + /// + /// The per-hit amount is the player's own unarmed attack's, since the forms fight + /// unarmed. scale lets a damage-over-time tick pay a fraction of a hit. + /// + public static void GrantAdrenaline(IDestructible target, float scale = 1f) + { + Player player = Player.m_localPlayer; + if (player == null || !(target is Character character) || character == player) return; + + ItemDrop unarmed = player.m_unarmedWeapon; + float perHit = unarmed != null ? unarmed.m_itemData.m_shared.m_attack.m_attackAdrenaline : 1f; + player.AddAdrenaline(perHit * character.m_enemyAdrenalineMultiplier * scale); + } + public static void LogHit(string form, IDestructible target, float damage) { if (!FenrirConfig.DebugFormHits.Value) return; From 7411680553abdba17a0ccea4afcd0cb0b35caa5a Mon Sep 17 00:00:00 2001 From: kanym Date: Fri, 23 Oct 2026 22:27:26 +0200 Subject: [PATCH 071/176] chore(release): v1.5.14 - Fenrir night eyes, form adrenaline, full-stomach eating Fenrir eyes glow at night, brighter when a form is ready and yellow when the Cultist is back. Form hits build adrenaline like a weapon hit. Race foods replace a worn-down meal when the stomach is full. The stamina bar comes back after leaving Aswid or Draugh. Other players see a Furling at Furling size, and a Legacy True Form Trol hits as far as it reaches. README: New in block, Fenrir night eyes, changelog entry, new Discord link (also in the old JotunnModStub README). --- JotunnModStub/Package/manifest.json | 2 +- JotunnModStub/README.md | 2 +- JotunnModStub/RacesOfValheim.cs | 2 +- README.md | 16 +++++++++++++--- manifest.json | 2 +- 5 files changed, 17 insertions(+), 7 deletions(-) diff --git a/JotunnModStub/Package/manifest.json b/JotunnModStub/Package/manifest.json index 8b1a0cf..6c5a7ef 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.5.13", + "version_number": "1.5.14", "website_url": "", "dependencies": [ "denikson-BepInExPack_Valheim-5.4.2333", diff --git a/JotunnModStub/README.md b/JotunnModStub/README.md index e9389e3..343bba3 100644 --- a/JotunnModStub/README.md +++ b/JotunnModStub/README.md @@ -109,7 +109,7 @@ This mod currently introduces 6 custom races: This is a stable release of Races of Valheim, but the mod is actively in development! We plan to add more races, gameplay elements, and refine the mechanics in future updates. Any feedback, bug reports, or suggestions for new features are more than welcome. -Please write to us on my Discord server: **https://discord.gg/gbBEK2VTE** +Please write to us on my Discord server: **https://discord.gg/dW72ch6Sw5** ## Changelog diff --git a/JotunnModStub/RacesOfValheim.cs b/JotunnModStub/RacesOfValheim.cs index 1bd1c2b..4ff8ec9 100644 --- a/JotunnModStub/RacesOfValheim.cs +++ b/JotunnModStub/RacesOfValheim.cs @@ -16,7 +16,7 @@ namespace RacesOfValheim { public const string PluginGUID = "com.nandor.racesofvalheim"; public const string PluginName = "Races Of Valheim"; - public const string PluginVersion = "1.5.13"; + public const string PluginVersion = "1.5.14"; private readonly Harmony harmony = new Harmony(PluginGUID); diff --git a/README.md b/README.md index 8c1b542..9e09880 100644 --- a/README.md +++ b/README.md @@ -10,14 +10,14 @@ A comprehensive Valheim mod allowing you to play as unique races, each providing This is a stable release, but more races and refinements are planned! Wiki: [https://wiki.aledanidev.ovh/](https://wiki.aledanidev.ovh/) -Bug reports, feedback, ideas: [https://discord.gg/jJzuKBZNC](https://discord.gg/jJzuKBZNC) +Bug reports, feedback, ideas: [https://discord.gg/dW72ch6Sw5](https://discord.gg/dW72ch6Sw5) Support the mod: [Patreon — NandorTheModder](https://www.patreon.com/c/NandorTheModder) --- -## New in v1.5.13 +## New in v1.5.14 -Fixes a freeze on servers with factions on: when a building a mob was attacking got destroyed, every creature in the area stopped moving and players slid on the ground. Dvergar now pay the discounted metal cost the build menu shows. Full details in the [changelog](#v1513). +A Fenrir's eyes now glow at night, brighter when a form is ready and yellow when the Cultist is back. Fenrir forms build adrenaline on every hit, Trenta can eat seeds with a full stomach, and the stamina bar comes back after leaving Aswid or Draugh. Full details in the [changelog](#v1514). --- @@ -47,6 +47,7 @@ Fixes a freeze on servers with factions on: when a building a mob was attacking - **Beast Form:** Transform into a wolf-like beast. - **Cultist Form:** Transform into a Cultist. Its claws cost nothing, but the **fire breath (hold Right Mouse) runs on eitr** — 12.5 per second — and eitr comes from the Mistlands, so the form unlocks at Yagluth with its flames still out of reach. Holding the button with an empty pool now says so. - **Cursed Claws:** The wolf's hands, kept on in the man's shape — see [Claws](#claws). +- **Night Eyes:** At night your eyes glow in the Fenring's orange: faintly while no form is ready, brightly when one is, and yellow when the Cultist is back from its cooldown. Other players see it too. Turn it off, or the "Ready!" message, under `Fenrir - Appearance`. - **Sneak and Sleep:** Forms sneak at a walk when you crouch and stand still to attack. Sit down as an Ulv and it curls up asleep. - **A Pack of Your Own:** The Pack Trough keeps a standing pack of wolves, ulvs and, late, fenrir — see [Race Stations](#race-stations--companions). - **Progression:** Forms grow as you defeat bosses, unlocking new powers and reducing cooldowns. Immune to fall damage. @@ -450,6 +451,15 @@ Both halves have an off switch under `Factions` in Configuration Manager: **Fact ## Changelog +### v1.5.14 +- **New - Fenrir night eyes:** at night a Fenrir's eyes glow in the Fenring's orange, the way a wolf's eyes catch the light. Faint while no form is ready, bright when one is, and yellow when the Cultist is back from its cooldown. Other players see it too. Under `Fenrir - Appearance` each player can turn off the glow or the "Ready!" message for themselves. Thanks to lexsonn for the idea. +- **Fix - Fenrir forms and adrenaline:** in Wolf, Ulv, Fenring and Cultist form, hits now build adrenaline the way a weapon does. Before, only staggering an enemy did, so Lox, Tar, Brutes and Furlings gave almost none. The Cultist's fire breath builds it too, about one hit's worth per second. Thanks to lexsonn for the report. +- **Fix - eating with a full stomach:** with all three food slots full, a Trenta couldn't eat seeds, and a Draugh's raw flesh or an Aswid's meals could get stuck the same way. Nothing happened and no message said why. They now follow the normal rule: they replace the meal that has worn down the most, once it's past half its time, and otherwise show the usual "too full" message. Thanks to ExpensiveMouse1700 for the report. +- **Fix - stamina bar after Aswid or Draugh:** switching from Aswid or Draugh to a race with stamina no longer leaves you without a stamina bar until you log out. Thanks to frogneel for the report. +- **Fix - Furling size for other players:** other players now see a Furling at Furling size. The shrink was only applied on the Furling's own screen, so everyone else saw them at full height. +- **Fix - Legacy True Form reach:** a big Trol's weapons now hit as far as they reach. Vanilla measured every swing at a human's range, so in Legacy True Form only the closest targets got hit. Melee range and swing width now grow with the model's size, for every race that grows. +- **Change - new Discord link:** [https://discord.gg/dW72ch6Sw5](https://discord.gg/dW72ch6Sw5). + ### v1.5.13 - **Fix - world freezes with factions on:** since v1.5.11, if a mob was targeting a building piece and the piece got destroyed or removed, the faction check threw an error every frame. On a server this stopped the AI of every creature in the area: players slid on the ground, enemies stood still, and characters sometimes turned invisible. The check now drops the dead target and moves on. Thanks to SCRIMSHAW and GaoVN for the reports, and to SCRIMSHAW for testing the fix on their server. - **Fix - Dvergar build discount:** the build menu showed the discounted metal cost (a cauldron for 6 tin instead of 10), but the hammer still refused to place the piece unless you carried the full vanilla amount. Pieces now build at the price shown. Dismantling or destroying a piece a Dvergar built returns the metal they paid, not the vanilla amount. Thanks to Balmarog for the report. diff --git a/manifest.json b/manifest.json index 8b1a0cf..6c5a7ef 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.5.13", + "version_number": "1.5.14", "website_url": "", "dependencies": [ "denikson-BepInExPack_Valheim-5.4.2333", From 53f6fb71a2dee8427da8f8e96accd2b765e34be3 Mon Sep 17 00:00:00 2001 From: kanym Date: Sat, 24 Oct 2026 15:28:04 +0200 Subject: [PATCH 072/176] fix(skeleton): Auto-Resurrect on the real deathblow; Summon on Kill toggle Auto-Resurrect was decided in the Character.Damage prefix on the raw hit: before armour, blocking and resistances, with poison and fire counted in full. With good armour it fired on almost any hit. Damage also runs on the attacker's owner, so on a dedicated server a mob owned by the server or another player skipped the check entirely. It now runs in an ApplyDamage prefix, on the victim's own client, against the damage that is about to land. The rising-from-the-ground immunity is checked there too. Summon on Kill gets a toggle key (G, Skeleton - Keybinds) and a gamepad radial entry. The choice is saved on the character, on by default. A "Raise the Dead" status icon with the Dead Raiser's picture shows while it is on. Texts in English, Italian and Russian. --- JotunnModStub/RaceRadial.cs | 3 + JotunnModStub/Skeleton/SkeletonConfig.cs | 9 ++ JotunnModStub/Skeleton/SkeletonPatches.cs | 84 ++++++++++++------- JotunnModStub/Skeleton/SkeletonRace.cs | 70 ++++++++++++++++ .../Translations/English/messages.json | 5 +- .../Translations/English/status_effects.json | 4 +- .../Translations/Italian/messages.json | 5 +- .../Translations/Italian/status_effects.json | 4 +- .../Translations/Russian/messages.json | 5 +- .../Translations/Russian/status_effects.json | 4 +- 10 files changed, 158 insertions(+), 35 deletions(-) diff --git a/JotunnModStub/RaceRadial.cs b/JotunnModStub/RaceRadial.cs index 3e4e0da..a3dfc6b 100644 --- a/JotunnModStub/RaceRadial.cs +++ b/JotunnModStub/RaceRadial.cs @@ -72,6 +72,9 @@ namespace RacesOfValheim new Entry { Race = "Sverm", Label = "Ravager Strain", Key = () => SvermConfigManagement.RavagerKey, Icon = "TrophySeekerBrute" }, + new Entry { Race = "Skeleton", Label = "Summon on Kill", Key = () => SkeletonConfig.SummonToggleKey, Icon = "StaffSkeleton", + Available = player => SkeletonProgression.GetRules(BossProgressionManager.GetCurrentProgressionState()).SummonOnKill }, + // Any race: shown to whoever RaceClawSet has claws for. new Entry { Race = null, Label = "Grow Claws", Key = () => RaceClawsConfig.ActivateKey, Icon = "TrophyWolf", Available = player => RaceClawSet.For(player) != null }, diff --git a/JotunnModStub/Skeleton/SkeletonConfig.cs b/JotunnModStub/Skeleton/SkeletonConfig.cs index c6b8ba6..c5a9abf 100644 --- a/JotunnModStub/Skeleton/SkeletonConfig.cs +++ b/JotunnModStub/Skeleton/SkeletonConfig.cs @@ -1,4 +1,5 @@ using BepInEx.Configuration; +using UnityEngine; namespace RacesOfValheim { @@ -39,6 +40,9 @@ namespace RacesOfValheim // ─── Resurrection (tier 6+) ──────────────────────────────────────────── public static ConfigEntry ResurrectionCooldown; + // ─── Keybinds ────────────────────────────────────────────────────────── + public static ConfigEntry SummonToggleKey; + // ─── Visuals ─────────────────────────────────────────────────────────── public static ConfigEntry HeadFireVFXEnabled; public static ConfigEntry BodyModelEnabled; @@ -65,6 +69,11 @@ namespace RacesOfValheim FireAuraTickInterval = config.Bind(aura, "Tick Interval", 1f, new ConfigDescription("Seconds between aura damage ticks.", new AcceptableValueRange(0.1f, 5f))); + // G is the first ability key of every race that has one; the Skeleton had none. + const string keybinds = "Skeleton - Keybinds"; + SummonToggleKey = config.Bind(keybinds, "Toggle Summon on Kill", new KeyboardShortcut(KeyCode.G), + "Turns raising a skeleton from each kill on and off (The Queen and later). The Dead Raiser icon shows while it is on."); + const string resurrection = "Skeleton - Resurrection"; ResurrectionCooldown = config.Bind(resurrection, "Cooldown", 300f, new ConfigDescription("Seconds between auto-resurrections, tier 6+.", new AcceptableValueRange(0f, 3600f))); diff --git a/JotunnModStub/Skeleton/SkeletonPatches.cs b/JotunnModStub/Skeleton/SkeletonPatches.cs index 461fa75..8bfab05 100644 --- a/JotunnModStub/Skeleton/SkeletonPatches.cs +++ b/JotunnModStub/Skeleton/SkeletonPatches.cs @@ -597,6 +597,58 @@ namespace RacesOfValheim } } + /// + /// Auto-Resurrect, decided on the hit that would actually kill. + /// + /// It used to be decided in the Character.Damage prefix below, on hit.GetTotalDamage(), + /// and that number is the raw hit: before armour, blocking and resistances, and with the + /// hit's poison and fire counted in full although vanilla splits those off and lands them + /// over time. Any hit whose raw size beat the current health raised the Skeleton, so with + /// good armour it fired on "just about any damage" (akira's report). Damage also runs on + /// whoever owns the attacker, so on a dedicated server a mob owned by the server or by + /// another player never reached this check at all, and a real deathblow went through. + /// + /// ApplyDamage is what RPC_Damage calls on the victim's owner, after armour, blocking and + /// resistances, with poison, fire and spirit already moved out into their status effects. + /// Those effects come back through here on each tick, so a lethal tick still counts. The + /// one scaling left inside ApplyDamage for a player is the damage-taken rate. + /// + [HarmonyPatch(typeof(Character), nameof(Character.ApplyDamage))] + public static class Skeleton_ApplyDamage_Patch + { + private static readonly int CooldownHash = "SE_SkeletonResurrectCooldown".GetStableHashCode(); + + public static bool Prefix(Character __instance, HitData hit) + { + Player player = Player.m_localPlayer; + if (player == null || __instance != player) return true; + + // Here as well as in the Damage prefix, which only sees hits thrown from this client. + if (SkeletonRise.IsRising(player)) return false; + + if (!SkeletonRace.IsSkeleton() || player.IsDead()) return true; + if (!SkeletonProgression.GetRules(BossProgressionManager.GetCurrentProgressionState()).AutoResurrect) return true; + + float damage = hit.GetTotalDamage() * Game.m_localDamgeTakenRate; + if (damage < player.GetHealth()) return true; + if (player.GetSEMan().HaveStatusEffect(CooldownHash)) return true; + + player.Heal(player.GetMaxHealth(), true); + player.GetSEMan().AddStatusEffect(CooldownHash, true); + + // Confirmed real via 'listprefabs'; see SummonOnKill below. + GameObject vfx = PrefabManager.Cache.GetPrefab("fx_summon_skeleton_spawn") ?? + PrefabManager.Cache.GetPrefab("fx_summon_skeleton"); + if (vfx != null) UnityEngine.Object.Instantiate(vfx, player.transform.position, Quaternion.identity); + + // The body climbs out of the ground the way a crypt skeleton does. + SkeletonRise.Begin(player); + + player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_skeleton_have_been_resurrected_by_dark")); + return false; // the lethal hit never lands + } + } + [HarmonyPatch(typeof(Character), "Damage")] public static class Character_Damage_Patch { @@ -624,34 +676,8 @@ namespace RacesOfValheim // 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("fx_summon_skeleton_spawn") ?? - PrefabManager.Cache.GetPrefab("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 - } - } - } + // The Auto-Resurrect check used to live here and is now in + // Skeleton_ApplyDamage_Patch below; see there for why. // Outgoing damage (Lifesteal, Poison, Stun) Character attacker = hit.GetAttacker(); @@ -740,7 +766,7 @@ namespace RacesOfValheim int state = BossProgressionManager.GetCurrentProgressionState(); var rules = SkeletonProgression.GetRules(state); - if (rules.SummonOnKill && !string.IsNullOrEmpty(rules.SummonPrefab)) + if (rules.SummonOnKill && SkeletonRace.SummonOnKillEnabled && !string.IsNullOrEmpty(rules.SummonPrefab)) { // Clean up dead minions activeMinions.RemoveAll(m => m == null || m.IsDead()); diff --git a/JotunnModStub/Skeleton/SkeletonRace.cs b/JotunnModStub/Skeleton/SkeletonRace.cs index 1895ed5..8a80c7e 100644 --- a/JotunnModStub/Skeleton/SkeletonRace.cs +++ b/JotunnModStub/Skeleton/SkeletonRace.cs @@ -48,6 +48,73 @@ namespace RacesOfValheim resurrectSE.name = "SE_SkeletonResurrectCooldown"; CustomStatusEffect customResurrectSE = new CustomStatusEffect(resurrectSE, fixReference: false); ItemManager.Instance.AddStatusEffect(customResurrectSE); + + // The "Summon on Kill is on" icon. The Dead Raiser's, since the Skeleton trophy is + // already Undead Fortitude's and this is the staff that raises skeletons in vanilla. + var raiseSE = ScriptableObject.CreateInstance(); + raiseSE.name = RaiseDeadEffectName; + raiseSE.m_name = "$rov_se_skeleton_raisedead_name"; + raiseSE.m_tooltip = "$rov_se_skeleton_raisedead_tooltip"; + raiseSE.m_icon = PrefabManager.Cache.GetPrefab("StaffSkeleton")?.m_itemData.GetIcon() + ?? PrefabManager.Cache.GetPrefab("TrophySkeleton")?.m_itemData.GetIcon(); + ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(raiseSE, fixReference: false)); + } + + // ─── Summon on Kill switch ────────────────────────────────────────── + + private const string RaiseDeadEffectName = "SE_SkeletonRaiseDead"; + private static readonly int RaiseDeadEffectHash = RaiseDeadEffectName.GetStableHashCode(); + + // Stored as "off" on the character, so a character that never pressed the key - every + // existing one - keeps the perk on. + private const string SummonOffKey = "RacesOfValheim_SkeletonSummonOff"; + + /// Whether this character wants a skeleton raised from each kill. Per character, saved with it. + public static bool SummonOnKillEnabled + { + get + { + Player player = Player.m_localPlayer; + return player == null || player.m_customData == null || !player.m_customData.ContainsKey(SummonOffKey); + } + set + { + Player player = Player.m_localPlayer; + if (player == null || player.m_customData == null) return; + if (value) player.m_customData.Remove(SummonOffKey); + else player.m_customData[SummonOffKey] = "1"; + } + } + + /// + /// The toggle key, and the icon that says the perk is on. The icon is put back whenever it + /// is missing, because status effects do not survive death or a relog. + /// + private static void TickSummonToggle(Player player, SkeletonProgression.SkeletonRules rules) + { + if (RaceInput.Allowed && SkeletonConfig.SummonToggleKey.Value.IsDownIgnoringHeldKeys()) + { + if (!rules.SummonOnKill) + { + player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_skeleton_summon_locked")); + } + else + { + SummonOnKillEnabled = !SummonOnKillEnabled; + player.Message(MessageHud.MessageType.Center, + ModText.Get(SummonOnKillEnabled ? "rov_msg_skeleton_summon_on" : "rov_msg_skeleton_summon_off")); + } + } + + SetRaiseDeadIcon(player, rules.SummonOnKill && SummonOnKillEnabled); + } + + private static void SetRaiseDeadIcon(Player player, bool on) + { + SEMan seman = player.GetSEMan(); + bool has = seman.HaveStatusEffect(RaiseDeadEffectHash); + if (on && !has) seman.AddStatusEffect(RaiseDeadEffectHash, true); + else if (!on && has) seman.RemoveStatusEffect(RaiseDeadEffectHash, true); } public static bool IsSkeleton() @@ -272,6 +339,7 @@ namespace RacesOfValheim SkeletonVisuals.EnsureFireAura(Player.m_localPlayer, false, ref fireAuraVFX); headFlame.Apply(Player.m_localPlayer, false); RestoreJawBone(); + SetRaiseDeadIcon(Player.m_localPlayer, false); if (Player.m_localPlayer.transform.localScale != Vector3.one) { @@ -319,6 +387,8 @@ namespace RacesOfValheim int state = BossProgressionManager.GetCurrentProgressionState(); var rules = SkeletonProgression.GetRules(state); + TickSummonToggle(Player.m_localPlayer, rules); + // Continuously adjust equipment VisEquipment currentVis = Player.m_localPlayer.GetComponent(); if (currentVis != null) diff --git a/JotunnModStub/Translations/English/messages.json b/JotunnModStub/Translations/English/messages.json index 8f7c7fa..92fd052 100644 --- a/JotunnModStub/Translations/English/messages.json +++ b/JotunnModStub/Translations/English/messages.json @@ -202,5 +202,8 @@ "rov_msg_warvulture_vulture_settles_into_glide": "The vulture settles into a glide.", "rov_msg_warvulture_vulture_spirals_down": "The vulture spirals down.", "rov_msg_boneship_no_shore": "No shore in reach. They stay at the oars.", - "rov_msg_boneship_sunk": "The ship goes down, and $1 go with it." + "rov_msg_boneship_sunk": "The ship goes down, and $1 go with it.", + "rov_msg_skeleton_summon_on": "Summon on Kill: on. The dead will rise for you.", + "rov_msg_skeleton_summon_off": "Summon on Kill: off. The dead stay down.", + "rov_msg_skeleton_summon_locked": "Summon on Kill awakens once The Queen falls." } diff --git a/JotunnModStub/Translations/English/status_effects.json b/JotunnModStub/Translations/English/status_effects.json index ba0b959..dd86c98 100644 --- a/JotunnModStub/Translations/English/status_effects.json +++ b/JotunnModStub/Translations/English/status_effects.json @@ -58,5 +58,7 @@ "rov_se_trol_trueform_name": "True Form", "rov_se_trol_trueform_tooltip": "You have unleashed your inner troll!", "rov_se_trol_trueformcd_name": "True Form Cooldown", - "rov_se_trol_trueformcd_tooltip": "You are exhausted from your True Form." + "rov_se_trol_trueformcd_tooltip": "You are exhausted from your True Form.", + "rov_se_skeleton_raisedead_name": "Raise the Dead", + "rov_se_skeleton_raisedead_tooltip": "Each kill raises a skeleton to fight for you. Press the Summon on Kill key to turn it off." } diff --git a/JotunnModStub/Translations/Italian/messages.json b/JotunnModStub/Translations/Italian/messages.json index f0e20bb..1e1ee27 100644 --- a/JotunnModStub/Translations/Italian/messages.json +++ b/JotunnModStub/Translations/Italian/messages.json @@ -202,5 +202,8 @@ "rov_msg_warvulture_vulture_settles_into_glide": "L'avvoltoio si mette a planare.", "rov_msg_warvulture_vulture_spirals_down": "L'avvoltoio scende a spirale.", "rov_msg_boneship_no_shore": "Nessuna riva a portata. Restano ai remi.", - "rov_msg_boneship_sunk": "La nave affonda, e con lei $1." + "rov_msg_boneship_sunk": "La nave affonda, e con lei $1.", + "rov_msg_skeleton_summon_on": "Evoca all'uccisione: attiva. I morti si alzeranno per te.", + "rov_msg_skeleton_summon_off": "Evoca all'uccisione: disattiva. I morti restano a terra.", + "rov_msg_skeleton_summon_locked": "Evoca all'uccisione si risveglia quando cade la Regina." } diff --git a/JotunnModStub/Translations/Italian/status_effects.json b/JotunnModStub/Translations/Italian/status_effects.json index e4e391c..ed8a813 100644 --- a/JotunnModStub/Translations/Italian/status_effects.json +++ b/JotunnModStub/Translations/Italian/status_effects.json @@ -58,5 +58,7 @@ "rov_se_trol_trueform_name": "Vera forma", "rov_se_trol_trueform_tooltip": "Hai scatenato il troll che è in te!", "rov_se_trol_trueformcd_name": "Ricarica vera forma", - "rov_se_trol_trueformcd_tooltip": "Sei esausto dopo la tua vera forma." + "rov_se_trol_trueformcd_tooltip": "Sei esausto dopo la tua vera forma.", + "rov_se_skeleton_raisedead_name": "Risveglio dei morti", + "rov_se_skeleton_raisedead_tooltip": "Ogni uccisione fa risorgere uno scheletro che combatte per te. Premi il tasto di Evoca all'uccisione per disattivarlo." } diff --git a/JotunnModStub/Translations/Russian/messages.json b/JotunnModStub/Translations/Russian/messages.json index 3ef6918..128bd9a 100644 --- a/JotunnModStub/Translations/Russian/messages.json +++ b/JotunnModStub/Translations/Russian/messages.json @@ -202,5 +202,8 @@ "rov_msg_warvulture_vulture_settles_into_glide": "Стервятник переходит в планирующий полет.", "rov_msg_warvulture_vulture_spirals_down": "Стервятник кружит, спускаясь по спирали.", "rov_msg_boneship_no_shore": "Берега не видно. Они остаются на веслах.", - "rov_msg_boneship_sunk": "Корабль идет ко дну, и $1 вместе с ним." + "rov_msg_boneship_sunk": "Корабль идет ко дну, и $1 вместе с ним.", + "rov_msg_skeleton_summon_on": "Призыв при убийстве: включён. Мёртвые восстанут ради тебя.", + "rov_msg_skeleton_summon_off": "Призыв при убийстве: выключен. Мёртвые остаются лежать.", + "rov_msg_skeleton_summon_locked": "Призыв при убийстве пробудится, когда падёт Королева." } diff --git a/JotunnModStub/Translations/Russian/status_effects.json b/JotunnModStub/Translations/Russian/status_effects.json index f1f2d58..d38df6e 100644 --- a/JotunnModStub/Translations/Russian/status_effects.json +++ b/JotunnModStub/Translations/Russian/status_effects.json @@ -58,5 +58,7 @@ "rov_se_trol_trueform_name": "Истинный облик", "rov_se_trol_trueform_tooltip": "Вы выпустили своего внутреннего тролля на свободу!", "rov_se_trol_trueformcd_name": "Перезарядка истинного облика", - "rov_se_trol_trueformcd_tooltip": "Вы истощены после пребывания в Истинном облике." + "rov_se_trol_trueformcd_tooltip": "Вы истощены после пребывания в Истинном облике.", + "rov_se_skeleton_raisedead_name": "Восстание мёртвых", + "rov_se_skeleton_raisedead_tooltip": "Каждое убийство поднимает скелета, который сражается за тебя. Нажми клавишу призыва при убийстве, чтобы выключить." } From 98b1a1b5f3318ca78289d3fd05b5a89335e5f5c9 Mon Sep 17 00:00:00 2001 From: kanym Date: Sat, 24 Oct 2026 15:38:42 +0200 Subject: [PATCH 073/176] feat(skeleton): dark aura while Summon on Kill is on, archaic toggle messages Beside the Raise the Dead icon, a faint near-black smoke now rises off the whole body while Summon on Kill is on: the Draugr's looping smoke, borrowed like the Draugh aura, emitted from a body-sized box in world space. The owner writes the switch to the ZDO, so other players see it. "Raise the Dead Icon" and "Raise the Dead Aura" under Skeleton - Visuals let each player keep either or both, for a community vote. The toggle now says "Thy dead shall rise again." / "Raising... nevermore.", in English, Italian and Russian. --- JotunnModStub/Skeleton/SkeletonConfig.cs | 8 +- JotunnModStub/Skeleton/SkeletonRace.cs | 19 ++- JotunnModStub/Skeleton/SkeletonVisuals.cs | 109 ++++++++++++++++++ .../Translations/English/messages.json | 4 +- .../Translations/Italian/messages.json | 4 +- .../Translations/Russian/messages.json | 4 +- JotunnModStub/ZdoVisualSync.cs | 3 + 7 files changed, 143 insertions(+), 8 deletions(-) diff --git a/JotunnModStub/Skeleton/SkeletonConfig.cs b/JotunnModStub/Skeleton/SkeletonConfig.cs index c5a9abf..7b4a2b9 100644 --- a/JotunnModStub/Skeleton/SkeletonConfig.cs +++ b/JotunnModStub/Skeleton/SkeletonConfig.cs @@ -46,6 +46,8 @@ namespace RacesOfValheim // ─── Visuals ─────────────────────────────────────────────────────────── public static ConfigEntry HeadFireVFXEnabled; public static ConfigEntry BodyModelEnabled; + public static ConfigEntry RaiseDeadIcon; + public static ConfigEntry RaiseDeadAura; public static void Bind(ConfigFile config) { @@ -72,7 +74,7 @@ namespace RacesOfValheim // G is the first ability key of every race that has one; the Skeleton had none. const string keybinds = "Skeleton - Keybinds"; SummonToggleKey = config.Bind(keybinds, "Toggle Summon on Kill", new KeyboardShortcut(KeyCode.G), - "Turns raising a skeleton from each kill on and off (The Queen and later). The Dead Raiser icon shows while it is on."); + "Turns raising a skeleton from each kill on and off (The Queen and later). While it is on, the Raise the Dead icon and a faint dark aura show it (see Skeleton - Visuals)."); const string resurrection = "Skeleton - Resurrection"; ResurrectionCooldown = config.Bind(resurrection, "Cooldown", 300f, @@ -83,6 +85,10 @@ namespace RacesOfValheim new ConfigDescription("Whether the burning-skull effect (worn from tier 5+) renders at all. A client-side preference: disabling it stops you from seeing it on yourself and on every other skeleton you look at, but does not change what other players see.")); BodyModelEnabled = config.Bind(visuals, "Body Model Enabled", true, new ConfigDescription("Whether Skeleton players wear the skeleton body. Turn it off if you use a player model mod (EnhancedValheimVRM and the like): Skeletons then keep the vanilla viking body, so the replacement model shows without bones clipping through it. Abilities are unchanged. Client-side, like the option above: it applies to every Skeleton you see, yourself included, and changes nothing for other players.")); + RaiseDeadIcon = config.Bind(visuals, "Raise the Dead Icon", true, + new ConfigDescription("Shows the Raise the Dead status icon while your Summon on Kill is on.")); + RaiseDeadAura = config.Bind(visuals, "Raise the Dead Aura", true, + new ConfigDescription("A faint dark smoke rises off a Skeleton whose Summon on Kill is on. Client-side: turning it off hides it on yourself and on every other Skeleton you see.")); } } } diff --git a/JotunnModStub/Skeleton/SkeletonRace.cs b/JotunnModStub/Skeleton/SkeletonRace.cs index 8a80c7e..b5fb170 100644 --- a/JotunnModStub/Skeleton/SkeletonRace.cs +++ b/JotunnModStub/Skeleton/SkeletonRace.cs @@ -106,7 +106,22 @@ namespace RacesOfValheim } } - SetRaiseDeadIcon(player, rules.SummonOnKill && SummonOnKillEnabled); + bool on = rules.SummonOnKill && SummonOnKillEnabled; + SetRaiseDeadIcon(player, on && SkeletonConfig.RaiseDeadIcon.Value); + Instance?.raisingAura.Apply(player, on && SkeletonConfig.RaiseDeadAura.Value); + SetRaisingFlag(player, on); + } + + private readonly SkeletonVisuals.RaisingAura raisingAura = new SkeletonVisuals.RaisingAura(); + + /// Owner only, and only on a change, so other clients can draw the aura. + private static void SetRaisingFlag(Player player, bool on) + { + ZNetView nview = player.GetComponent(); + if (nview == null || !nview.IsValid() || !nview.IsOwner()) return; + + ZDO zdo = nview.GetZDO(); + if (zdo.GetBool(SkeletonVisuals.RaisingZdoKey, false) != on) zdo.Set(SkeletonVisuals.RaisingZdoKey, on); } private static void SetRaiseDeadIcon(Player player, bool on) @@ -340,6 +355,8 @@ namespace RacesOfValheim headFlame.Apply(Player.m_localPlayer, false); RestoreJawBone(); SetRaiseDeadIcon(Player.m_localPlayer, false); + raisingAura.Apply(Player.m_localPlayer, false); + SetRaisingFlag(Player.m_localPlayer, false); if (Player.m_localPlayer.transform.localScale != Vector3.one) { diff --git a/JotunnModStub/Skeleton/SkeletonVisuals.cs b/JotunnModStub/Skeleton/SkeletonVisuals.cs index e91963c..aa22629 100644 --- a/JotunnModStub/Skeleton/SkeletonVisuals.cs +++ b/JotunnModStub/Skeleton/SkeletonVisuals.cs @@ -434,6 +434,115 @@ namespace RacesOfValheim aura = null; } + /// The owner's Summon on Kill switch, for every other client to read. + public const string RaisingZdoKey = "RacesOfValheim_SkeletonRaising"; + + /// + /// A faint dark smoke rising off the whole body while Summon on Kill is on: the other half + /// of the indicator, beside the Raise the Dead icon, so the community can pick either or + /// both. Cosmetic only. + /// + /// The smoke is the Draugr's own looping one, the same particle DraughVisuals.BuildAura + /// borrows, cloned through BorrowEffect and tinted near-black. It emits from a box the + /// size of the body rather than from one point, so it comes off the arms and legs too. + /// A mesh-shaped emitter would hug the body closer, but only works on a readable mesh. + /// + /// Held per player, like HeadFlame. Call Apply every frame; it builds once. + /// + public class RaisingAura + { + private static readonly Color Smoke = new Color(0.06f, 0.06f, 0.07f, 0.35f); + private static readonly Vector3 BodyBox = new Vector3(0.55f, 1.7f, 0.35f); + private const float BodyCentre = 0.95f; + + private GameObject m_instance; + + public void Apply(Player player, bool enable) + { + if (!enable || player == null) + { + if (m_instance != null && m_instance.activeSelf) m_instance.SetActive(false); + return; + } + + if (m_instance == null && !Build(player)) return; + if (!m_instance.activeSelf) m_instance.SetActive(true); + } + + private static bool warned; + + private bool Build(Player player) + { + GameObject draugr = PrefabManager.Cache.GetPrefab("Draugr"); + ParticleSystem source = null; + if (draugr != null) + { + foreach (ParticleSystem ps in draugr.GetComponentsInChildren(true)) + { + string name = ps.gameObject.name.ToLower(); + if (!ps.main.loop || name.Contains("flies") || name.Contains("drip") || name.Contains("drop") || + name.Contains("rain") || name.Contains("splash")) continue; + source = ps; + break; + } + } + + if (source == null) + { + if (!warned) + { + warned = true; + Jotunn.Logger.LogWarning("[Skeleton] No looping smoke found on 'Draugr'; the Summon on Kill aura stays off."); + } + return false; + } + + m_instance = BorrowEffect(source.gameObject, player.transform, "SkeletonRaisingAura", false, "Skeleton"); + if (m_instance == null) return false; + + m_instance.transform.localPosition = new Vector3(0f, BodyCentre, 0f); + m_instance.transform.localRotation = Quaternion.identity; + m_instance.transform.localScale = Vector3.one; + + foreach (ParticleSystem ps in m_instance.GetComponentsInChildren(true)) + { + ParticleSystem.MainModule main = ps.main; + main.startColor = new ParticleSystem.MinMaxGradient(Smoke); + // World space, so the smoke stays behind as the body moves, like a trail. + main.simulationSpace = ParticleSystemSimulationSpace.World; + main.scalingMode = ParticleSystemScalingMode.Hierarchy; + + ParticleSystem.ShapeModule shape = ps.shape; + shape.enabled = true; + shape.shapeType = ParticleSystemShapeType.Box; + shape.scale = BodyBox; + shape.position = Vector3.zero; + shape.rotation = Vector3.zero; + + // The Draugr's tint over a particle's life would put its green back; keep the + // fade (alpha) and drop the colour. + ParticleSystem.ColorOverLifetimeModule col = ps.colorOverLifetime; + if (col.enabled) + { + Gradient faded = new Gradient(); + faded.SetKeys(new[] { new GradientColorKey(Color.white, 0f), new GradientColorKey(Color.white, 1f) }, + col.color.gradient != null ? col.color.gradient.alphaKeys + : new[] { new GradientAlphaKey(1f, 0f), new GradientAlphaKey(0f, 1f) }); + col.color = new ParticleSystem.MinMaxGradient(faded); + } + } + + // The shader decides whether a dark tint can show at all: an additive one adds + // nothing for black. If the aura is invisible in game, this line says why. + Renderer smokeRenderer = m_instance.GetComponentInChildren(true); + Material smokeMaterial = smokeRenderer != null ? smokeRenderer.sharedMaterial : null; + Jotunn.Logger.LogInfo($"[Skeleton] Summon on Kill aura built from 'Draugr/{source.gameObject.name}', " + + $"material '{(smokeMaterial != null ? smokeMaterial.name : "none")}', " + + $"shader '{(smokeMaterial != null && smokeMaterial.shader != null ? smokeMaterial.shader.name : "none")}'."); + return true; + } + } + /// /// One player's burning skull. Cosmetic only - it deals nothing and blocks nothing. /// diff --git a/JotunnModStub/Translations/English/messages.json b/JotunnModStub/Translations/English/messages.json index 92fd052..1edf32c 100644 --- a/JotunnModStub/Translations/English/messages.json +++ b/JotunnModStub/Translations/English/messages.json @@ -203,7 +203,7 @@ "rov_msg_warvulture_vulture_spirals_down": "The vulture spirals down.", "rov_msg_boneship_no_shore": "No shore in reach. They stay at the oars.", "rov_msg_boneship_sunk": "The ship goes down, and $1 go with it.", - "rov_msg_skeleton_summon_on": "Summon on Kill: on. The dead will rise for you.", - "rov_msg_skeleton_summon_off": "Summon on Kill: off. The dead stay down.", + "rov_msg_skeleton_summon_on": "Thy dead shall rise again.", + "rov_msg_skeleton_summon_off": "Raising... nevermore.", "rov_msg_skeleton_summon_locked": "Summon on Kill awakens once The Queen falls." } diff --git a/JotunnModStub/Translations/Italian/messages.json b/JotunnModStub/Translations/Italian/messages.json index 1e1ee27..20caf0b 100644 --- a/JotunnModStub/Translations/Italian/messages.json +++ b/JotunnModStub/Translations/Italian/messages.json @@ -203,7 +203,7 @@ "rov_msg_warvulture_vulture_spirals_down": "L'avvoltoio scende a spirale.", "rov_msg_boneship_no_shore": "Nessuna riva a portata. Restano ai remi.", "rov_msg_boneship_sunk": "La nave affonda, e con lei $1.", - "rov_msg_skeleton_summon_on": "Evoca all'uccisione: attiva. I morti si alzeranno per te.", - "rov_msg_skeleton_summon_off": "Evoca all'uccisione: disattiva. I morti restano a terra.", + "rov_msg_skeleton_summon_on": "I tuoi morti risorgeranno ancora.", + "rov_msg_skeleton_summon_off": "Risorgere... mai più.", "rov_msg_skeleton_summon_locked": "Evoca all'uccisione si risveglia quando cade la Regina." } diff --git a/JotunnModStub/Translations/Russian/messages.json b/JotunnModStub/Translations/Russian/messages.json index 128bd9a..5b0f03e 100644 --- a/JotunnModStub/Translations/Russian/messages.json +++ b/JotunnModStub/Translations/Russian/messages.json @@ -203,7 +203,7 @@ "rov_msg_warvulture_vulture_spirals_down": "Стервятник кружит, спускаясь по спирали.", "rov_msg_boneship_no_shore": "Берега не видно. Они остаются на веслах.", "rov_msg_boneship_sunk": "Корабль идет ко дну, и $1 вместе с ним.", - "rov_msg_skeleton_summon_on": "Призыв при убийстве: включён. Мёртвые восстанут ради тебя.", - "rov_msg_skeleton_summon_off": "Призыв при убийстве: выключен. Мёртвые остаются лежать.", + "rov_msg_skeleton_summon_on": "Твои мёртвые вновь восстанут.", + "rov_msg_skeleton_summon_off": "Восстание... никогда более.", "rov_msg_skeleton_summon_locked": "Призыв при убийстве пробудится, когда падёт Королева." } diff --git a/JotunnModStub/ZdoVisualSync.cs b/JotunnModStub/ZdoVisualSync.cs index 4f1326f..241de90 100644 --- a/JotunnModStub/ZdoVisualSync.cs +++ b/JotunnModStub/ZdoVisualSync.cs @@ -41,6 +41,7 @@ namespace RacesOfValheim private GameObject m_fireAuraVFX = null; private GameObject m_draughAuraVFX = null; private readonly SkeletonVisuals.HeadFlame m_skeletonHeadFlame = new SkeletonVisuals.HeadFlame(); + private readonly SkeletonVisuals.RaisingAura m_skeletonRaisingAura = new SkeletonVisuals.RaisingAura(); private void Awake() { @@ -169,6 +170,7 @@ namespace RacesOfValheim // The burning skull, grown locally for whoever we are looking at. The tier is on the // ZDO, so this client can work out for itself whether they should be alight. m_skeletonHeadFlame.Apply(m_player, SkeletonConfig.HeadFireVFXEnabled.Value && SkeletonConfig.BodyModelEnabled.Value && SkeletonVisuals.GetModel(m_player, state) == SkeletonProgression.FireModel); + m_skeletonRaisingAura.Apply(m_player, SkeletonConfig.RaiseDeadAura.Value && nview.GetZDO().GetBool(SkeletonVisuals.RaisingZdoKey, false)); // Apply Scale Vector3 targetScale = rules.ScaleMultiplier; @@ -273,6 +275,7 @@ namespace RacesOfValheim SkeletonVisuals.EnsureFireAura(m_player, false, ref m_fireAuraVFX); DraughVisuals.EnsureAura(m_player, false, ref m_draughAuraVFX); m_skeletonHeadFlame.Apply(m_player, false); + m_skeletonRaisingAura.Apply(m_player, false); // Takes the crown off a Trenta who has died or changed race; a no-op for everyone else. TrentaVisuals.ApplyCrown(m_player); From 3591b7e375d071654a40e1de5c63572dca02e2e3 Mon Sep 17 00:00:00 2001 From: kanym Date: Sat, 24 Oct 2026 15:44:16 +0200 Subject: [PATCH 074/176] fix(skeleton): the Summon on Kill aura borrows the torch smoke The Draugr's evil_smoke is on 'Lux Lit Particles/ Bumped' and showed nothing in game once tinted dark. The torch's own Smoke, from the prefab the head flame burns from, is the grey everyone sees above a torch; darkened to (0.08, 0.08, 0.09) at 0.45 alpha. --- JotunnModStub/Skeleton/SkeletonVisuals.cs | 32 ++++++++++++----------- 1 file changed, 17 insertions(+), 15 deletions(-) diff --git a/JotunnModStub/Skeleton/SkeletonVisuals.cs b/JotunnModStub/Skeleton/SkeletonVisuals.cs index aa22629..ba7faee 100644 --- a/JotunnModStub/Skeleton/SkeletonVisuals.cs +++ b/JotunnModStub/Skeleton/SkeletonVisuals.cs @@ -442,8 +442,8 @@ namespace RacesOfValheim /// of the indicator, beside the Raise the Dead icon, so the community can pick either or /// both. Cosmetic only. /// - /// The smoke is the Draugr's own looping one, the same particle DraughVisuals.BuildAura - /// borrows, cloned through BorrowEffect and tinted near-black. It emits from a box the + /// The smoke is the torch's own (see Build for why not the Draugr's), cloned through + /// BorrowEffect and tinted near-black. It emits from a box the /// size of the body rather than from one point, so it comes off the arms and legs too. /// A mesh-shaped emitter would hug the body closer, but only works on a readable mesh. /// @@ -451,7 +451,8 @@ namespace RacesOfValheim /// public class RaisingAura { - private static readonly Color Smoke = new Color(0.06f, 0.06f, 0.07f, 0.35f); + // The torch smoke is (0.35, 0.35, 0.35, 0.21); darker and a little thicker than that. + private static readonly Color Smoke = new Color(0.08f, 0.08f, 0.09f, 0.45f); private static readonly Vector3 BodyBox = new Vector3(0.55f, 1.7f, 0.35f); private const float BodyCentre = 0.95f; @@ -473,17 +474,18 @@ namespace RacesOfValheim private bool Build(Player player) { - GameObject draugr = PrefabManager.Cache.GetPrefab("Draugr"); + // The torch's own 'Smoke', from the same prefab the head flame burns from. The + // Draugr's evil_smoke was tried first: its material is on 'Lux Lit Particles/ + // Bumped', which takes its look from the material and the scene light, so a dark + // tint on it showed nothing in game. The torch smoke is the grey everyone sees + // above a torch, so darkening it has something to darken. + GameObject torch = ResolveFlameSource(); ParticleSystem source = null; - if (draugr != null) + if (torch != null) { - foreach (ParticleSystem ps in draugr.GetComponentsInChildren(true)) + foreach (ParticleSystem ps in torch.GetComponentsInChildren(true)) { - string name = ps.gameObject.name.ToLower(); - if (!ps.main.loop || name.Contains("flies") || name.Contains("drip") || name.Contains("drop") || - name.Contains("rain") || name.Contains("splash")) continue; - source = ps; - break; + if (ps.gameObject.name.ToLower().Contains("smoke")) { source = ps; break; } } } @@ -492,7 +494,7 @@ namespace RacesOfValheim if (!warned) { warned = true; - Jotunn.Logger.LogWarning("[Skeleton] No looping smoke found on 'Draugr'; the Summon on Kill aura stays off."); + Jotunn.Logger.LogWarning("[Skeleton] No 'Smoke' particle on the torch; the Summon on Kill aura stays off."); } return false; } @@ -519,8 +521,8 @@ namespace RacesOfValheim shape.position = Vector3.zero; shape.rotation = Vector3.zero; - // The Draugr's tint over a particle's life would put its green back; keep the - // fade (alpha) and drop the colour. + // A tint over the particle's life would put the source's own colour back; keep + // the fade (alpha) and drop the colour. ParticleSystem.ColorOverLifetimeModule col = ps.colorOverLifetime; if (col.enabled) { @@ -536,7 +538,7 @@ namespace RacesOfValheim // nothing for black. If the aura is invisible in game, this line says why. Renderer smokeRenderer = m_instance.GetComponentInChildren(true); Material smokeMaterial = smokeRenderer != null ? smokeRenderer.sharedMaterial : null; - Jotunn.Logger.LogInfo($"[Skeleton] Summon on Kill aura built from 'Draugr/{source.gameObject.name}', " + + Jotunn.Logger.LogInfo($"[Skeleton] Summon on Kill aura built from '{torch.name}/{source.gameObject.name}', " + $"material '{(smokeMaterial != null ? smokeMaterial.name : "none")}', " + $"shader '{(smokeMaterial != null && smokeMaterial.shader != null ? smokeMaterial.shader.name : "none")}'."); return true; From e41f7b610e2dbe0789204620f2fa12f3bbd8ba56 Mon Sep 17 00:00:00 2001 From: kanym Date: Sat, 24 Oct 2026 15:50:05 +0200 Subject: [PATCH 075/176] revert(skeleton): drop the Summon on Kill aura, keep the icon Neither the Draugr's evil_smoke nor the torch smoke showed in game once tinted dark. The Raise the Dead icon stays, with its per-player switch. --- JotunnModStub/Skeleton/SkeletonConfig.cs | 5 +- JotunnModStub/Skeleton/SkeletonRace.cs | 16 ---- JotunnModStub/Skeleton/SkeletonVisuals.cs | 111 ---------------------- JotunnModStub/ZdoVisualSync.cs | 3 - 4 files changed, 1 insertion(+), 134 deletions(-) diff --git a/JotunnModStub/Skeleton/SkeletonConfig.cs b/JotunnModStub/Skeleton/SkeletonConfig.cs index 7b4a2b9..62c01fc 100644 --- a/JotunnModStub/Skeleton/SkeletonConfig.cs +++ b/JotunnModStub/Skeleton/SkeletonConfig.cs @@ -47,7 +47,6 @@ namespace RacesOfValheim public static ConfigEntry HeadFireVFXEnabled; public static ConfigEntry BodyModelEnabled; public static ConfigEntry RaiseDeadIcon; - public static ConfigEntry RaiseDeadAura; public static void Bind(ConfigFile config) { @@ -74,7 +73,7 @@ namespace RacesOfValheim // G is the first ability key of every race that has one; the Skeleton had none. const string keybinds = "Skeleton - Keybinds"; SummonToggleKey = config.Bind(keybinds, "Toggle Summon on Kill", new KeyboardShortcut(KeyCode.G), - "Turns raising a skeleton from each kill on and off (The Queen and later). While it is on, the Raise the Dead icon and a faint dark aura show it (see Skeleton - Visuals)."); + "Turns raising a skeleton from each kill on and off (The Queen and later). The Raise the Dead icon shows while it is on."); const string resurrection = "Skeleton - Resurrection"; ResurrectionCooldown = config.Bind(resurrection, "Cooldown", 300f, @@ -87,8 +86,6 @@ namespace RacesOfValheim new ConfigDescription("Whether Skeleton players wear the skeleton body. Turn it off if you use a player model mod (EnhancedValheimVRM and the like): Skeletons then keep the vanilla viking body, so the replacement model shows without bones clipping through it. Abilities are unchanged. Client-side, like the option above: it applies to every Skeleton you see, yourself included, and changes nothing for other players.")); RaiseDeadIcon = config.Bind(visuals, "Raise the Dead Icon", true, new ConfigDescription("Shows the Raise the Dead status icon while your Summon on Kill is on.")); - RaiseDeadAura = config.Bind(visuals, "Raise the Dead Aura", true, - new ConfigDescription("A faint dark smoke rises off a Skeleton whose Summon on Kill is on. Client-side: turning it off hides it on yourself and on every other Skeleton you see.")); } } } diff --git a/JotunnModStub/Skeleton/SkeletonRace.cs b/JotunnModStub/Skeleton/SkeletonRace.cs index b5fb170..69e8712 100644 --- a/JotunnModStub/Skeleton/SkeletonRace.cs +++ b/JotunnModStub/Skeleton/SkeletonRace.cs @@ -108,20 +108,6 @@ namespace RacesOfValheim bool on = rules.SummonOnKill && SummonOnKillEnabled; SetRaiseDeadIcon(player, on && SkeletonConfig.RaiseDeadIcon.Value); - Instance?.raisingAura.Apply(player, on && SkeletonConfig.RaiseDeadAura.Value); - SetRaisingFlag(player, on); - } - - private readonly SkeletonVisuals.RaisingAura raisingAura = new SkeletonVisuals.RaisingAura(); - - /// Owner only, and only on a change, so other clients can draw the aura. - private static void SetRaisingFlag(Player player, bool on) - { - ZNetView nview = player.GetComponent(); - if (nview == null || !nview.IsValid() || !nview.IsOwner()) return; - - ZDO zdo = nview.GetZDO(); - if (zdo.GetBool(SkeletonVisuals.RaisingZdoKey, false) != on) zdo.Set(SkeletonVisuals.RaisingZdoKey, on); } private static void SetRaiseDeadIcon(Player player, bool on) @@ -355,8 +341,6 @@ namespace RacesOfValheim headFlame.Apply(Player.m_localPlayer, false); RestoreJawBone(); SetRaiseDeadIcon(Player.m_localPlayer, false); - raisingAura.Apply(Player.m_localPlayer, false); - SetRaisingFlag(Player.m_localPlayer, false); if (Player.m_localPlayer.transform.localScale != Vector3.one) { diff --git a/JotunnModStub/Skeleton/SkeletonVisuals.cs b/JotunnModStub/Skeleton/SkeletonVisuals.cs index ba7faee..e91963c 100644 --- a/JotunnModStub/Skeleton/SkeletonVisuals.cs +++ b/JotunnModStub/Skeleton/SkeletonVisuals.cs @@ -434,117 +434,6 @@ namespace RacesOfValheim aura = null; } - /// The owner's Summon on Kill switch, for every other client to read. - public const string RaisingZdoKey = "RacesOfValheim_SkeletonRaising"; - - /// - /// A faint dark smoke rising off the whole body while Summon on Kill is on: the other half - /// of the indicator, beside the Raise the Dead icon, so the community can pick either or - /// both. Cosmetic only. - /// - /// The smoke is the torch's own (see Build for why not the Draugr's), cloned through - /// BorrowEffect and tinted near-black. It emits from a box the - /// size of the body rather than from one point, so it comes off the arms and legs too. - /// A mesh-shaped emitter would hug the body closer, but only works on a readable mesh. - /// - /// Held per player, like HeadFlame. Call Apply every frame; it builds once. - /// - public class RaisingAura - { - // The torch smoke is (0.35, 0.35, 0.35, 0.21); darker and a little thicker than that. - private static readonly Color Smoke = new Color(0.08f, 0.08f, 0.09f, 0.45f); - private static readonly Vector3 BodyBox = new Vector3(0.55f, 1.7f, 0.35f); - private const float BodyCentre = 0.95f; - - private GameObject m_instance; - - public void Apply(Player player, bool enable) - { - if (!enable || player == null) - { - if (m_instance != null && m_instance.activeSelf) m_instance.SetActive(false); - return; - } - - if (m_instance == null && !Build(player)) return; - if (!m_instance.activeSelf) m_instance.SetActive(true); - } - - private static bool warned; - - private bool Build(Player player) - { - // The torch's own 'Smoke', from the same prefab the head flame burns from. The - // Draugr's evil_smoke was tried first: its material is on 'Lux Lit Particles/ - // Bumped', which takes its look from the material and the scene light, so a dark - // tint on it showed nothing in game. The torch smoke is the grey everyone sees - // above a torch, so darkening it has something to darken. - GameObject torch = ResolveFlameSource(); - ParticleSystem source = null; - if (torch != null) - { - foreach (ParticleSystem ps in torch.GetComponentsInChildren(true)) - { - if (ps.gameObject.name.ToLower().Contains("smoke")) { source = ps; break; } - } - } - - if (source == null) - { - if (!warned) - { - warned = true; - Jotunn.Logger.LogWarning("[Skeleton] No 'Smoke' particle on the torch; the Summon on Kill aura stays off."); - } - return false; - } - - m_instance = BorrowEffect(source.gameObject, player.transform, "SkeletonRaisingAura", false, "Skeleton"); - if (m_instance == null) return false; - - m_instance.transform.localPosition = new Vector3(0f, BodyCentre, 0f); - m_instance.transform.localRotation = Quaternion.identity; - m_instance.transform.localScale = Vector3.one; - - foreach (ParticleSystem ps in m_instance.GetComponentsInChildren(true)) - { - ParticleSystem.MainModule main = ps.main; - main.startColor = new ParticleSystem.MinMaxGradient(Smoke); - // World space, so the smoke stays behind as the body moves, like a trail. - main.simulationSpace = ParticleSystemSimulationSpace.World; - main.scalingMode = ParticleSystemScalingMode.Hierarchy; - - ParticleSystem.ShapeModule shape = ps.shape; - shape.enabled = true; - shape.shapeType = ParticleSystemShapeType.Box; - shape.scale = BodyBox; - shape.position = Vector3.zero; - shape.rotation = Vector3.zero; - - // A tint over the particle's life would put the source's own colour back; keep - // the fade (alpha) and drop the colour. - ParticleSystem.ColorOverLifetimeModule col = ps.colorOverLifetime; - if (col.enabled) - { - Gradient faded = new Gradient(); - faded.SetKeys(new[] { new GradientColorKey(Color.white, 0f), new GradientColorKey(Color.white, 1f) }, - col.color.gradient != null ? col.color.gradient.alphaKeys - : new[] { new GradientAlphaKey(1f, 0f), new GradientAlphaKey(0f, 1f) }); - col.color = new ParticleSystem.MinMaxGradient(faded); - } - } - - // The shader decides whether a dark tint can show at all: an additive one adds - // nothing for black. If the aura is invisible in game, this line says why. - Renderer smokeRenderer = m_instance.GetComponentInChildren(true); - Material smokeMaterial = smokeRenderer != null ? smokeRenderer.sharedMaterial : null; - Jotunn.Logger.LogInfo($"[Skeleton] Summon on Kill aura built from '{torch.name}/{source.gameObject.name}', " + - $"material '{(smokeMaterial != null ? smokeMaterial.name : "none")}', " + - $"shader '{(smokeMaterial != null && smokeMaterial.shader != null ? smokeMaterial.shader.name : "none")}'."); - return true; - } - } - /// /// One player's burning skull. Cosmetic only - it deals nothing and blocks nothing. /// diff --git a/JotunnModStub/ZdoVisualSync.cs b/JotunnModStub/ZdoVisualSync.cs index 241de90..4f1326f 100644 --- a/JotunnModStub/ZdoVisualSync.cs +++ b/JotunnModStub/ZdoVisualSync.cs @@ -41,7 +41,6 @@ namespace RacesOfValheim private GameObject m_fireAuraVFX = null; private GameObject m_draughAuraVFX = null; private readonly SkeletonVisuals.HeadFlame m_skeletonHeadFlame = new SkeletonVisuals.HeadFlame(); - private readonly SkeletonVisuals.RaisingAura m_skeletonRaisingAura = new SkeletonVisuals.RaisingAura(); private void Awake() { @@ -170,7 +169,6 @@ namespace RacesOfValheim // The burning skull, grown locally for whoever we are looking at. The tier is on the // ZDO, so this client can work out for itself whether they should be alight. m_skeletonHeadFlame.Apply(m_player, SkeletonConfig.HeadFireVFXEnabled.Value && SkeletonConfig.BodyModelEnabled.Value && SkeletonVisuals.GetModel(m_player, state) == SkeletonProgression.FireModel); - m_skeletonRaisingAura.Apply(m_player, SkeletonConfig.RaiseDeadAura.Value && nview.GetZDO().GetBool(SkeletonVisuals.RaisingZdoKey, false)); // Apply Scale Vector3 targetScale = rules.ScaleMultiplier; @@ -275,7 +273,6 @@ namespace RacesOfValheim SkeletonVisuals.EnsureFireAura(m_player, false, ref m_fireAuraVFX); DraughVisuals.EnsureAura(m_player, false, ref m_draughAuraVFX); m_skeletonHeadFlame.Apply(m_player, false); - m_skeletonRaisingAura.Apply(m_player, false); // Takes the crown off a Trenta who has died or changed race; a no-op for everyone else. TrentaVisuals.ApplyCrown(m_player); From 18593ae1d365af7e88434032b27870b80470e994 Mon Sep 17 00:00:00 2001 From: kanym Date: Sat, 24 Oct 2026 16:36:52 +0200 Subject: [PATCH 076/176] balance(skeleton): lower max-health bonus in the early and middle game +25/+45/+65/+90/+125/+165/+215/+275 from no bosses to Fader, was +50/+80/+110/+140/+170/+200/+230/+275. A fresh Skeleton starts at 50 max health instead of 75; Fader stays at 300. Asked for by several players over three months, last by Jondar Korric. A Skeleton never eats and never spends stamina, so it ran well ahead of a fed viking. The hidden foods that carry its regeneration are picked to match the new totals, so early-tier regen drops with them. README progression updated; the compendium reads the value from code. --- JotunnModStub/Skeleton/SkeletonProgression.cs | 16 ++++++++-------- README.md | 14 +++++++------- 2 files changed, 15 insertions(+), 15 deletions(-) diff --git a/JotunnModStub/Skeleton/SkeletonProgression.cs b/JotunnModStub/Skeleton/SkeletonProgression.cs index 0045033..8d9b11f 100644 --- a/JotunnModStub/Skeleton/SkeletonProgression.cs +++ b/JotunnModStub/Skeleton/SkeletonProgression.cs @@ -7,15 +7,15 @@ namespace RacesOfValheim public static float GetMaxHealthBonus(int state) { if (state == 0) return 0f; - if (state == 1) return 50f; - if (state == 2) return 80f; - if (state == 3) return 110f; - if (state == 4) return 140f; - if (state == 5) return 170f; - if (state == 6) return 200f; - if (state == 7) return 230f; + if (state == 1) return 25f; + if (state == 2) return 45f; + if (state == 3) return 65f; + if (state == 4) return 90f; + if (state == 5) return 125f; + if (state == 6) return 165f; + if (state == 7) return 215f; if (state >= 8) return 275f; - return 50f; + return 25f; } public struct SkeletonRules diff --git a/README.md b/README.md index 9e09880..9332cc9 100644 --- a/README.md +++ b/README.md @@ -235,13 +235,13 @@ Right Mouse toggles flight. Glide towards aim, W = forward/climb, Shift+W = use
Skeleton Progression -- **Base:** +50 Max Health. Undead Diet (cannot eat normal food, no stamina bar). Lit eye sockets, in the colour of whichever skeleton your tier wears. -- **Eikthyr:** Poison Skeleton model, poison immunity, 5% lifesteal, +80 Max Health. -- **Elder:** 10% lifesteal, auto-stun first hit, +110 Max Health. -- **Bonemass:** 15% lifesteal, poison attacks, +140 Max Health. -- **Moder:** Fire Skeleton model, 20% lifesteal, fire aura, enhanced regen, +170 Max Health. -- **Yagluth:** 25% lifesteal, auto-resurrect, +200 Max Health. -- **Queen:** 30% lifesteal, summon on kill (max 3 skeletons), +230 Max Health. +- **Base:** +25 Max Health. Undead Diet (cannot eat normal food, no stamina bar). Lit eye sockets, in the colour of whichever skeleton your tier wears. +- **Eikthyr:** Poison Skeleton model, poison immunity, 5% lifesteal, +45 Max Health. +- **Elder:** 10% lifesteal, auto-stun first hit, +65 Max Health. +- **Bonemass:** 15% lifesteal, poison attacks, +90 Max Health. +- **Moder:** Fire Skeleton model, 20% lifesteal, fire aura, enhanced regen, +125 Max Health. +- **Yagluth:** 25% lifesteal, auto-resurrect, +165 Max Health. +- **Queen:** 30% lifesteal, summon on kill (max 3 skeletons), +215 Max Health. - **Fader:** 35% lifesteal, max 5 summons, +275 Max Health.
From 20dec64fa01cabecce1446156efdfe5a1db47a6e Mon Sep 17 00:00:00 2001 From: kanym Date: Sat, 24 Oct 2026 18:28:17 +0200 Subject: [PATCH 077/176] chore(release): v1.5.15 - Skeleton health rebalance, Auto-Resurrect fix, Summon on Kill toggle Skeleton max health is lower in the early and middle game, from 75 to 50 at the start and unchanged at Fader. Auto-Resurrect triggers only on a hit that would really kill, dedicated servers included. Summon on Kill toggles with G and shows a Raise the Dead icon while on. README: New in block, Queen line, changelog entry. --- JotunnModStub/Package/manifest.json | 2 +- JotunnModStub/RacesOfValheim.cs | 2 +- README.md | 11 ++++++++--- manifest.json | 2 +- 4 files changed, 11 insertions(+), 6 deletions(-) diff --git a/JotunnModStub/Package/manifest.json b/JotunnModStub/Package/manifest.json index 6c5a7ef..7418483 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.5.14", + "version_number": "1.5.15", "website_url": "", "dependencies": [ "denikson-BepInExPack_Valheim-5.4.2333", diff --git a/JotunnModStub/RacesOfValheim.cs b/JotunnModStub/RacesOfValheim.cs index 4ff8ec9..122655b 100644 --- a/JotunnModStub/RacesOfValheim.cs +++ b/JotunnModStub/RacesOfValheim.cs @@ -16,7 +16,7 @@ namespace RacesOfValheim { public const string PluginGUID = "com.nandor.racesofvalheim"; public const string PluginName = "Races Of Valheim"; - public const string PluginVersion = "1.5.14"; + public const string PluginVersion = "1.5.15"; private readonly Harmony harmony = new Harmony(PluginGUID); diff --git a/README.md b/README.md index 9332cc9..cb169ae 100644 --- a/README.md +++ b/README.md @@ -15,9 +15,9 @@ Support the mod: [Patreon — NandorTheModder](https://www.patreon.com/c/NandorT --- -## New in v1.5.14 +## New in v1.5.15 -A Fenrir's eyes now glow at night, brighter when a form is ready and yellow when the Cultist is back. Fenrir forms build adrenaline on every hit, Trenta can eat seeds with a full stomach, and the stamina bar comes back after leaving Aswid or Draugh. Full details in the [changelog](#v1514). +Skeleton round: max health is lower in the early and middle game (a fresh Skeleton starts at 50, Fader is unchanged), Auto-Resurrect fires only on a hit that would really kill you, and Summon on Kill can be switched on and off with G. Full details in the [changelog](#v1515). --- @@ -241,7 +241,7 @@ Right Mouse toggles flight. Glide towards aim, W = forward/climb, Shift+W = use - **Bonemass:** 15% lifesteal, poison attacks, +90 Max Health. - **Moder:** Fire Skeleton model, 20% lifesteal, fire aura, enhanced regen, +125 Max Health. - **Yagluth:** 25% lifesteal, auto-resurrect, +165 Max Health. -- **Queen:** 30% lifesteal, summon on kill (max 3 skeletons), +215 Max Health. +- **Queen:** 30% lifesteal, summon on kill (max 3 skeletons, toggle with G), +215 Max Health. - **Fader:** 35% lifesteal, max 5 summons, +275 Max Health. @@ -451,6 +451,11 @@ Both halves have an off switch under `Factions` in Configuration Manager: **Fact ## Changelog +### v1.5.15 +- **Balance - Skeleton max health:** lower in the early and middle game. The bonus over the base 25 is now +25 / +45 / +65 / +90 / +125 / +165 / +215 / +275, from no bosses to Fader (it was +50 / +80 / +110 / +140 / +170 / +200 / +230 / +275). A fresh Skeleton starts at 50 instead of 75; from Yagluth on the gap closes, and Fader is unchanged at 300. A Skeleton never needs food and never spends stamina, so it was well ahead of a fed viking at every tier. Thanks to Jondar Korric and everyone else who asked for this. +- **Fix - Auto-Resurrect on any hit:** a Skeleton's Auto-Resurrect now triggers only on a hit that would actually kill you. It used to compare the raw hit, before armour and blocking, with its poison and fire counted all at once, so with good armour it fired on almost any hit. On dedicated servers it could also miss a real deathblow when the server or another player controlled the attacker. Thanks to akira for the report. +- **New - Summon on Kill toggle:** turn Summon on Kill on and off with G (`Skeleton - Keybinds`), or from the gamepad radial: *"Thy dead shall rise again."* / *"Raising... nevermore."* While it's on, a "Raise the Dead" icon with the Dead Raiser's picture shows in the status bar; hide it with `Raise the Dead Icon` under `Skeleton - Visuals`. Your choice is saved with your character. Thanks to akira for the idea. + ### v1.5.14 - **New - Fenrir night eyes:** at night a Fenrir's eyes glow in the Fenring's orange, the way a wolf's eyes catch the light. Faint while no form is ready, bright when one is, and yellow when the Cultist is back from its cooldown. Other players see it too. Under `Fenrir - Appearance` each player can turn off the glow or the "Ready!" message for themselves. Thanks to lexsonn for the idea. - **Fix - Fenrir forms and adrenaline:** in Wolf, Ulv, Fenring and Cultist form, hits now build adrenaline the way a weapon does. Before, only staggering an enemy did, so Lox, Tar, Brutes and Furlings gave almost none. The Cultist's fire breath builds it too, about one hit's worth per second. Thanks to lexsonn for the report. diff --git a/manifest.json b/manifest.json index 6c5a7ef..7418483 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.5.14", + "version_number": "1.5.15", "website_url": "", "dependencies": [ "denikson-BepInExPack_Valheim-5.4.2333", From 0a843bad415f99cb306a5e9e908ade29d991a5ff Mon Sep 17 00:00:00 2001 From: kanym Date: Sat, 24 Oct 2026 23:53:53 +0200 Subject: [PATCH 078/176] fix(skeleton): the Summon on Kill "on" line is "Thy shall raise again." MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit As written by the author; Italian "Tu rialzerai ancora.", Russian "Ты вновь поднимешь.". README changelog line too. --- JotunnModStub/Translations/English/messages.json | 2 +- JotunnModStub/Translations/Italian/messages.json | 2 +- JotunnModStub/Translations/Russian/messages.json | 2 +- README.md | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/JotunnModStub/Translations/English/messages.json b/JotunnModStub/Translations/English/messages.json index 1edf32c..a764b92 100644 --- a/JotunnModStub/Translations/English/messages.json +++ b/JotunnModStub/Translations/English/messages.json @@ -203,7 +203,7 @@ "rov_msg_warvulture_vulture_spirals_down": "The vulture spirals down.", "rov_msg_boneship_no_shore": "No shore in reach. They stay at the oars.", "rov_msg_boneship_sunk": "The ship goes down, and $1 go with it.", - "rov_msg_skeleton_summon_on": "Thy dead shall rise again.", + "rov_msg_skeleton_summon_on": "Thy shall raise again.", "rov_msg_skeleton_summon_off": "Raising... nevermore.", "rov_msg_skeleton_summon_locked": "Summon on Kill awakens once The Queen falls." } diff --git a/JotunnModStub/Translations/Italian/messages.json b/JotunnModStub/Translations/Italian/messages.json index 20caf0b..2c6ed4c 100644 --- a/JotunnModStub/Translations/Italian/messages.json +++ b/JotunnModStub/Translations/Italian/messages.json @@ -203,7 +203,7 @@ "rov_msg_warvulture_vulture_spirals_down": "L'avvoltoio scende a spirale.", "rov_msg_boneship_no_shore": "Nessuna riva a portata. Restano ai remi.", "rov_msg_boneship_sunk": "La nave affonda, e con lei $1.", - "rov_msg_skeleton_summon_on": "I tuoi morti risorgeranno ancora.", + "rov_msg_skeleton_summon_on": "Tu rialzerai ancora.", "rov_msg_skeleton_summon_off": "Risorgere... mai più.", "rov_msg_skeleton_summon_locked": "Evoca all'uccisione si risveglia quando cade la Regina." } diff --git a/JotunnModStub/Translations/Russian/messages.json b/JotunnModStub/Translations/Russian/messages.json index 5b0f03e..c4f2975 100644 --- a/JotunnModStub/Translations/Russian/messages.json +++ b/JotunnModStub/Translations/Russian/messages.json @@ -203,7 +203,7 @@ "rov_msg_warvulture_vulture_spirals_down": "Стервятник кружит, спускаясь по спирали.", "rov_msg_boneship_no_shore": "Берега не видно. Они остаются на веслах.", "rov_msg_boneship_sunk": "Корабль идет ко дну, и $1 вместе с ним.", - "rov_msg_skeleton_summon_on": "Твои мёртвые вновь восстанут.", + "rov_msg_skeleton_summon_on": "Ты вновь поднимешь.", "rov_msg_skeleton_summon_off": "Восстание... никогда более.", "rov_msg_skeleton_summon_locked": "Призыв при убийстве пробудится, когда падёт Королева." } diff --git a/README.md b/README.md index cb169ae..35bd680 100644 --- a/README.md +++ b/README.md @@ -454,7 +454,7 @@ Both halves have an off switch under `Factions` in Configuration Manager: **Fact ### v1.5.15 - **Balance - Skeleton max health:** lower in the early and middle game. The bonus over the base 25 is now +25 / +45 / +65 / +90 / +125 / +165 / +215 / +275, from no bosses to Fader (it was +50 / +80 / +110 / +140 / +170 / +200 / +230 / +275). A fresh Skeleton starts at 50 instead of 75; from Yagluth on the gap closes, and Fader is unchanged at 300. A Skeleton never needs food and never spends stamina, so it was well ahead of a fed viking at every tier. Thanks to Jondar Korric and everyone else who asked for this. - **Fix - Auto-Resurrect on any hit:** a Skeleton's Auto-Resurrect now triggers only on a hit that would actually kill you. It used to compare the raw hit, before armour and blocking, with its poison and fire counted all at once, so with good armour it fired on almost any hit. On dedicated servers it could also miss a real deathblow when the server or another player controlled the attacker. Thanks to akira for the report. -- **New - Summon on Kill toggle:** turn Summon on Kill on and off with G (`Skeleton - Keybinds`), or from the gamepad radial: *"Thy dead shall rise again."* / *"Raising... nevermore."* While it's on, a "Raise the Dead" icon with the Dead Raiser's picture shows in the status bar; hide it with `Raise the Dead Icon` under `Skeleton - Visuals`. Your choice is saved with your character. Thanks to akira for the idea. +- **New - Summon on Kill toggle:** turn Summon on Kill on and off with G (`Skeleton - Keybinds`), or from the gamepad radial: *"Thy shall raise again."* / *"Raising... nevermore."* While it's on, a "Raise the Dead" icon with the Dead Raiser's picture shows in the status bar; hide it with `Raise the Dead Icon` under `Skeleton - Visuals`. Your choice is saved with your character. Thanks to akira for the idea. ### v1.5.14 - **New - Fenrir night eyes:** at night a Fenrir's eyes glow in the Fenring's orange, the way a wolf's eyes catch the light. Faint while no form is ready, bright when one is, and yellow when the Cultist is back from its cooldown. Other players see it too. Under `Fenrir - Appearance` each player can turn off the glow or the "Ready!" message for themselves. Thanks to lexsonn for the idea. From 9e9790d1e99730970e2e30f3e3b632f058f48dd4 Mon Sep 17 00:00:00 2001 From: kanym Date: Sat, 24 Oct 2026 23:55:26 +0200 Subject: [PATCH 079/176] docs(readme): the v1.5.15 entry quotes the line that shipped The new line goes out in v1.5.16 and is listed for that release. --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 35bd680..cb169ae 100644 --- a/README.md +++ b/README.md @@ -454,7 +454,7 @@ Both halves have an off switch under `Factions` in Configuration Manager: **Fact ### v1.5.15 - **Balance - Skeleton max health:** lower in the early and middle game. The bonus over the base 25 is now +25 / +45 / +65 / +90 / +125 / +165 / +215 / +275, from no bosses to Fader (it was +50 / +80 / +110 / +140 / +170 / +200 / +230 / +275). A fresh Skeleton starts at 50 instead of 75; from Yagluth on the gap closes, and Fader is unchanged at 300. A Skeleton never needs food and never spends stamina, so it was well ahead of a fed viking at every tier. Thanks to Jondar Korric and everyone else who asked for this. - **Fix - Auto-Resurrect on any hit:** a Skeleton's Auto-Resurrect now triggers only on a hit that would actually kill you. It used to compare the raw hit, before armour and blocking, with its poison and fire counted all at once, so with good armour it fired on almost any hit. On dedicated servers it could also miss a real deathblow when the server or another player controlled the attacker. Thanks to akira for the report. -- **New - Summon on Kill toggle:** turn Summon on Kill on and off with G (`Skeleton - Keybinds`), or from the gamepad radial: *"Thy shall raise again."* / *"Raising... nevermore."* While it's on, a "Raise the Dead" icon with the Dead Raiser's picture shows in the status bar; hide it with `Raise the Dead Icon` under `Skeleton - Visuals`. Your choice is saved with your character. Thanks to akira for the idea. +- **New - Summon on Kill toggle:** turn Summon on Kill on and off with G (`Skeleton - Keybinds`), or from the gamepad radial: *"Thy dead shall rise again."* / *"Raising... nevermore."* While it's on, a "Raise the Dead" icon with the Dead Raiser's picture shows in the status bar; hide it with `Raise the Dead Icon` under `Skeleton - Visuals`. Your choice is saved with your character. Thanks to akira for the idea. ### v1.5.14 - **New - Fenrir night eyes:** at night a Fenrir's eyes glow in the Fenring's orange, the way a wolf's eyes catch the light. Faint while no form is ready, bright when one is, and yellow when the Cultist is back from its cooldown. Other players see it too. Under `Fenrir - Appearance` each player can turn off the glow or the "Ready!" message for themselves. Thanks to lexsonn for the idea. From 3f8cf1ee27b0ee48badd7fdd34d6ffcea0bce9e2 Mon Sep 17 00:00:00 2001 From: Ferdinando Date: Sun, 25 Oct 2026 17:38:28 +0100 Subject: [PATCH 080/176] feat(alfar): v1.6.0 - the Alfar, an eleventh race Grey, tall and thin, with black eyes. Eitr is armour and fuel (shield, diet, soft fall, levitation), Heimkall sends a lethal blow home at one health every 20 minutes. Caster powers from Skrid to the archon Sameining, with on-screen cooldowns. Automated base around the Ljoskjarne: drones, three constructs, crystals, Ljosgard, Prismavard. Compendium page in EN/IT/RU. README: New in block, race section, progression, station line, changelog. Co-Authored-By: Claude Sonnet 5.5 --- JotunnModStub/Alfar/AlfarArchon.cs | 176 ++ JotunnModStub/Alfar/AlfarChests.cs | 134 ++ JotunnModStub/Alfar/AlfarCommands.cs | 110 + JotunnModStub/Alfar/AlfarConfig.cs | 159 ++ JotunnModStub/Alfar/AlfarConstructs.cs | 397 ++++ JotunnModStub/Alfar/AlfarDroneAI.cs | 1950 +++++++++++++++++ JotunnModStub/Alfar/AlfarDrones.cs | 365 +++ JotunnModStub/Alfar/AlfarEitr.cs | 166 ++ JotunnModStub/Alfar/AlfarHeimkall.cs | 171 ++ JotunnModStub/Alfar/AlfarLevitation.cs | 120 + JotunnModStub/Alfar/AlfarLjosgard.cs | 108 + JotunnModStub/Alfar/AlfarMark.cs | 149 ++ JotunnModStub/Alfar/AlfarMiners.cs | 104 + JotunnModStub/Alfar/AlfarNexus.cs | 576 +++++ JotunnModStub/Alfar/AlfarNexusConfig.cs | 144 ++ JotunnModStub/Alfar/AlfarNexusStore.cs | 171 ++ JotunnModStub/Alfar/AlfarPatches.cs | 149 ++ JotunnModStub/Alfar/AlfarPowerConfig.cs | 170 ++ JotunnModStub/Alfar/AlfarPowers.cs | 616 ++++++ JotunnModStub/Alfar/AlfarProbe.cs | 434 ++++ JotunnModStub/Alfar/AlfarRace.cs | 40 + JotunnModStub/Alfar/AlfarStatusEffects.cs | 169 ++ JotunnModStub/Alfar/AlfarTowers.cs | 239 ++ JotunnModStub/Alfar/AlfarVisuals.cs | 495 +++++ JotunnModStub/ConfigSync.cs | 1 + JotunnModStub/Package/manifest.json | 2 +- JotunnModStub/RaceCompendium.cs | 57 +- JotunnModStub/RaceRadial.cs | 13 + JotunnModStub/RaceScale.cs | 2 + JotunnModStub/RaceStationLock.cs | 5 + JotunnModStub/RacesOfValheim.cs | 51 +- .../Translations/English/compendium.json | 24 + JotunnModStub/Translations/English/items.json | 35 + .../Translations/English/messages.json | 30 +- JotunnModStub/Translations/English/races.json | 4 +- .../Translations/English/status_effects.json | 12 +- .../Translations/Italian/compendium.json | 24 + JotunnModStub/Translations/Italian/items.json | 35 + .../Translations/Italian/messages.json | 30 +- JotunnModStub/Translations/Italian/races.json | 4 +- .../Translations/Italian/status_effects.json | 12 +- .../Translations/Russian/compendium.json | 24 + JotunnModStub/Translations/Russian/items.json | 35 + .../Translations/Russian/messages.json | 30 +- JotunnModStub/Translations/Russian/races.json | 4 +- .../Translations/Russian/status_effects.json | 12 +- README.md | 35 +- manifest.json | 2 +- 48 files changed, 7779 insertions(+), 16 deletions(-) create mode 100644 JotunnModStub/Alfar/AlfarArchon.cs create mode 100644 JotunnModStub/Alfar/AlfarChests.cs create mode 100644 JotunnModStub/Alfar/AlfarCommands.cs create mode 100644 JotunnModStub/Alfar/AlfarConfig.cs create mode 100644 JotunnModStub/Alfar/AlfarConstructs.cs create mode 100644 JotunnModStub/Alfar/AlfarDroneAI.cs create mode 100644 JotunnModStub/Alfar/AlfarDrones.cs create mode 100644 JotunnModStub/Alfar/AlfarEitr.cs create mode 100644 JotunnModStub/Alfar/AlfarHeimkall.cs create mode 100644 JotunnModStub/Alfar/AlfarLevitation.cs create mode 100644 JotunnModStub/Alfar/AlfarLjosgard.cs create mode 100644 JotunnModStub/Alfar/AlfarMark.cs create mode 100644 JotunnModStub/Alfar/AlfarMiners.cs create mode 100644 JotunnModStub/Alfar/AlfarNexus.cs create mode 100644 JotunnModStub/Alfar/AlfarNexusConfig.cs create mode 100644 JotunnModStub/Alfar/AlfarNexusStore.cs create mode 100644 JotunnModStub/Alfar/AlfarPatches.cs create mode 100644 JotunnModStub/Alfar/AlfarPowerConfig.cs create mode 100644 JotunnModStub/Alfar/AlfarPowers.cs create mode 100644 JotunnModStub/Alfar/AlfarProbe.cs create mode 100644 JotunnModStub/Alfar/AlfarRace.cs create mode 100644 JotunnModStub/Alfar/AlfarStatusEffects.cs create mode 100644 JotunnModStub/Alfar/AlfarTowers.cs create mode 100644 JotunnModStub/Alfar/AlfarVisuals.cs diff --git a/JotunnModStub/Alfar/AlfarArchon.cs b/JotunnModStub/Alfar/AlfarArchon.cs new file mode 100644 index 0000000..0be4415 --- /dev/null +++ b/JotunnModStub/Alfar/AlfarArchon.cs @@ -0,0 +1,176 @@ +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// SAMEINING, the archon (Alfar_Progettazione.txt sec. 13.8): Fader's power, an all-or-nothing form. + /// + /// - needs 75% of the maximum eitr and a READY Heimkall, and spends ALL the eitr; + /// - lasts up to three minutes: bigger (x1.5), glowing, +20% speed; + /// - instead of armour there is a POOL of points, three per eitr spent: every blow lands on it, + /// and when it is gone the form ends early; + /// - no weapons: a psionic pulse strikes everything hostile around the body, once a second; + /// - Ljosstorm and Geisli cost nothing in the form, but wait a few seconds between uses; + /// - it ENDS (time up, pool gone) with a teleport home at one hit point, eitr at zero, and the + /// Heimkall wait starting. The form IS a Heimkall spent on purpose. + /// + /// The form is published in the ZDO so other players see the size and the glow. + /// + public static class AlfarArchon + { + public const string ZdoKey = "Alfar_Archon"; + + public static bool Active { get; private set; } + public static float Pool { get; private set; } + public static float EndsAt { get; private set; } + public static float StartedAt { get; private set; } + + private static float nextPulse; + + /// True for any player in range: the form is read off the ZDO, not local state. + public static bool IsArchon(Player player) + { + if (player == null) return false; + ZNetView nview = player.GetComponent(); + return nview != null && nview.IsValid() && nview.GetZDO().GetInt(ZdoKey, 0) == 1; + } + + public static bool IsLocalActive => Active && Player.m_localPlayer != null; + + private static void Publish(Player player, bool on) + { + ZNetView nview = player.GetComponent(); + if (nview != null && nview.IsValid()) nview.GetZDO().Set(ZdoKey, on ? 1 : 0); + } + + // ─── Entering ──────────────────────────────────────────────────────── + + public static bool TryActivate(Player player) + { + if (Active || player == null) return false; + + float max = player.GetMaxEitr(); + float eitr = player.GetEitr(); + if (max <= 0f || eitr < max * AlfarPowerConfig.ArchonThreshold.Value) + { + player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_archon_not_charged")); + return false; + } + + if (!AlfarHeimkall.IsReady(player)) + { + player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_archon_not_ready")); + return false; + } + + // Everything goes in: the strength of the form is what the Alfr had eaten. + Pool = eitr * AlfarPowerConfig.ArchonPoolPerEitr.Value; + AlfarEitr.Spend(player, eitr); + + Active = true; + StartedAt = Time.time; + EndsAt = Time.time + AlfarPowerConfig.ArchonSeconds.Value; + AlfarStatusEffects.ShowTimer("archon", AlfarPowerConfig.ArchonSeconds.Value); + nextPulse = Time.time + AlfarPowerConfig.ArchonPulseInterval.Value; + Publish(player, true); + + Jotunn.Logger.LogInfo($"[Alfar] Sameining on: pool {Pool:0} for {AlfarPowerConfig.ArchonSeconds.Value:0}s."); + player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_archon_on")); + return true; + } + + // ─── In the form ───────────────────────────────────────────────────── + + /// + /// Takes a blow into the pool. Called from the shield prefix before anything else, because in + /// the form the pool IS the defence: every type of damage, drowning and the edge of the world + /// included, since nothing else can end the form but the pool and the clock. + /// + public static void Absorb(Player player, HitData hit) + { + if (!Active || hit == null) return; + + float total = hit.m_damage.GetTotalDamage(); + hit.m_damage = default(HitData.DamageTypes); + if (total <= 0f) return; + + Pool -= total; + // The exit itself is done in Tick, outside the damage call. + } + + public static void Tick(Player player) + { + if (!Active) return; + + if (player == null || player.IsDead()) + { + // The body is gone (or the world is): nothing to teleport, only the state to drop. + Active = false; + if (player != null) Publish(player, false); + return; + } + + if (Pool <= 0f || Time.time >= EndsAt) + { + Exit(player, Pool <= 0f ? "pool gone" : "time up"); + return; + } + + if (Time.time >= nextPulse) + { + nextPulse = Time.time + AlfarPowerConfig.ArchonPulseInterval.Value; + AlfarPowers.Pulse(player, AlfarPowerConfig.ArchonPulseRadius.Value, AlfarPowerConfig.ArchonPulseDamage.Value); + } + } + + // ─── Leaving ───────────────────────────────────────────────────────── + + public static void Exit(Player player, string reason) + { + if (!Active) return; + + Active = false; + Pool = 0f; + Publish(player, false); + AlfarStatusEffects.ClearTimer("archon"); + + // Eitr to zero, then the Heimkall: the form spends the one that was ready. + AlfarEitr.Spend(player, player.GetEitr()); + AlfarHeimkall.TryTrigger(player, "Sameining " + reason, force: true); + + player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_archon_off")); + Jotunn.Logger.LogInfo($"[Alfar] Sameining off ({reason})."); + } + + /// The cooldown Ljosstorm and Geisli wait in the form, instead of costing eitr. + public static float FreePowerCooldown => AlfarPowerConfig.ArchonFreePowerCooldown.Value; + + /// + /// NO WEAPONS in the form: the psionic pulse is the attack. Humanoid.StartAttack is the one + /// door every swing, shot and draw goes through (verified, doc sec. 16B); returning false + /// with a false result is "nothing started". + /// + [HarmonyLib.HarmonyPatch(typeof(Humanoid), "StartAttack")] + public static class Alfar_Archon_NoWeapons_Patch + { + public static bool Prefix(Humanoid __instance, ref bool __result) + { + if (Active && __instance == Player.m_localPlayer) + { + __result = false; + return false; + } + return true; + } + } + + /// Clears the state without teleporting (used by the reset command). + public static void ForceClear(Player player) + { + Active = false; + Pool = 0f; + if (player != null) Publish(player, false); + AlfarStatusEffects.ClearTimer("archon"); + } + } +} diff --git a/JotunnModStub/Alfar/AlfarChests.cs b/JotunnModStub/Alfar/AlfarChests.cs new file mode 100644 index 0000000..e8fc1d9 --- /dev/null +++ b/JotunnModStub/Alfar/AlfarChests.cs @@ -0,0 +1,134 @@ +using System.Collections.Generic; +using Jotunn.Configs; +using Jotunn.Entities; +using Jotunn.Managers; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// The EIRINNSIGLI, the verdigris seal (Alfar_Progettazione.txt sec. 9.2c): a bronze nail turned at + /// the forge. Put inside a chest it tells the drones NOT to look there - the inverse of the + /// Butler's, where the seal says "this one is yours". Only the colour differs from the nail: a model + /// recolour does not touch the inventory icon (guide 5.2), so in the pack it looks like a bronze + /// nail and only the name tells it apart. + /// + public static class AlfarSigil + { + public const string PrefabName = "AlfarSigil"; + public const string DisplayName = "$rov_item_alfar_sigil_name"; + + public static void Register() + { + GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(PrefabName, "BronzeNails"); + if (prefab == null) + { + Jotunn.Logger.LogWarning("[Alfar] Could not clone BronzeNails: no verdigris seal."); + return; + } + + ItemDrop drop = prefab.GetComponent(); + if (drop == null || drop.m_itemData == null || drop.m_itemData.m_shared == null) return; + + ItemDrop.ItemData.SharedData shared = drop.m_itemData.m_shared; + shared.m_name = DisplayName; + shared.m_description = "$rov_item_alfar_sigil_desc"; + + AlfarConstructs.Tint(prefab, new Color(0.36f, 0.68f, 0.58f, 1f)); + ItemManager.Instance.AddItem(new CustomItem(prefab, fixReference: false)); + + ItemManager.Instance.AddRecipe(new CustomRecipe(new RecipeConfig + { + Item = PrefabName, + Amount = 1, + CraftingStation = CraftingStations.Forge, + MinStationLevel = 1, + Requirements = new[] { new RequirementConfig("BronzeNails", 1, 0, true) }, + })); + } + } + + /// + /// The two special chests (sec. 9.2c): built like an ordinary chest with Greydwarf eyes added to + /// the price. The ENTRY chest is where everything is thrown and where the drones sort from; the + /// WOOD chest holds the wood the drones may burn - the only wood they ever consume. + /// + public static class AlfarChests + { + public const string EntryName = "AlfarInngangskista"; + public const string WoodName = "AlfarEldividarkista"; + + public static void Register() + { + RegisterOne(EntryName, "$rov_piece_alfar_inngangskista_name", "$rov_piece_alfar_inngangskista_desc", + new Color(0.62f, 0.80f, 1f, 1f)); + RegisterOne(WoodName, "$rov_piece_alfar_eldividarkista_name", "$rov_piece_alfar_eldividarkista_desc", + new Color(0.85f, 0.62f, 0.36f, 1f)); + } + + private static void RegisterOne(string pieceName, string display, string description, Color tint) + { + GameObject source = PrefabManager.Cache.GetPrefab("piece_chest_wood"); + if (source == null) + { + Jotunn.Logger.LogWarning("[Alfar] No 'piece_chest_wood': the chest " + pieceName + " is not registered."); + return; + } + + GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(pieceName, source); + if (prefab == null) return; + + // The price of a plain chest, read from the game (guide 3.2), plus the eyes. + var requirements = new List(); + Piece vanilla = source.GetComponent(); + if (vanilla != null && vanilla.m_resources != null) + { + foreach (Piece.Requirement r in vanilla.m_resources) + { + if (r.m_resItem == null) continue; + requirements.Add(new RequirementConfig(r.m_resItem.gameObject.name, r.m_amount, 0, true)); + } + } + requirements.Add(new RequirementConfig("GreydwarfEye", AlfarNexusConfig.ChestEyes.Value, 0, true)); + + Container container = prefab.GetComponent(); + if (container != null) container.m_name = display; + + Piece piece = prefab.GetComponent(); + if (piece == null) { Jotunn.Logger.LogWarning("[Alfar] The chest has no Piece: " + pieceName); return; } + piece.m_name = display; + piece.m_description = description; + + AlfarConstructs.Tint(prefab, tint); + + PieceManager.Instance.AddPiece(new CustomPiece(prefab, fixReference: false, new PieceConfig + { + Name = display, + Description = description, + PieceTable = PieceTables.Hammer, + Category = PieceCategories.Crafting, + Icon = piece.m_icon, + Requirements = requirements.ToArray(), + })); + + // One of each inside the reach of a Ljoskjarne, and only for the Alfar, and only where a core stands. + PieceDensityLimit.Register(pieceName, AlfarNexusConfig.NexusRadius.Value, 1, "rov_msg_build_limit_alfar_chest"); + PieceDensityLimit.RegisterGate(pieceName, (player, position) => + { + if (!AlfarRace.IsLocalAlfar()) + { + if (player != null) player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_only_alfar")); + return false; + } + if (AlfarNexusBehaviour.Covering(position) == null) + { + if (player != null) player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_chest_needs_nexus")); + return false; + } + return true; + }); + + AlfarPieces.Extra.Add(pieceName); + } + } +} diff --git a/JotunnModStub/Alfar/AlfarCommands.cs b/JotunnModStub/Alfar/AlfarCommands.cs new file mode 100644 index 0000000..a0f4785 --- /dev/null +++ b/JotunnModStub/Alfar/AlfarCommands.cs @@ -0,0 +1,110 @@ +using Jotunn.Entities; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// Test helpers for the Alfar, in the F5 console. They exist so the phases of Alfar_Test.txt can + /// be walked through without waiting twenty minutes between steps. + /// + /// alfarstatus what the race is doing right now (eitr, Heimkall timer, SE, form...) + /// alfarreset clears every Alfar timer and cooldown + /// alfareitr sets the eitr pool: a number, "full", or 0 + /// alfarhp sets the current health, to try the lethal-blow case without dying + /// + public class AlfarStatusCommand : ConsoleCommand + { + public override string Name => "alfarstatus"; + public override string Help => "[DEBUG] Prints the Alfar's eitr, health, Heimkall timer and passive."; + + public override void Run(string[] args) + { + Player player = Player.m_localPlayer; + if (player == null) { Console.instance.Print("No local player."); return; } + + string race = AlfarVisuals.GetPlayerRace(player); + Print($"race={race} progression state={BossProgressionManager.GetCurrentProgressionState()}"); + Print($"health={player.GetHealth():0}/{player.GetMaxHealth():0} eitr={player.GetEitr():0.0}/{player.GetMaxEitr():0}"); + + float left = AlfarHeimkall.Remaining(player); + Print($"Heimkall: {(left <= 0f ? "READY" : (left / 60f).ToString("0.0") + " min left")} " + + $"(cooldown now {AlfarHeimkall.CooldownSeconds() / 60f:0} min)"); + + bool se = player.GetSEMan().HaveStatusEffect(SE_AlfarStats.EffectName.GetStableHashCode()); + Print($"passive status effect: {(se ? "on" : "OFF")}"); + } + + private static void Print(string text) + { + Console.instance.Print("[Alfar] " + text); + Jotunn.Logger.LogInfo("[Alfar] " + text); + } + } + + public class AlfarResetCommand : ConsoleCommand + { + public override string Name => "alfarreset"; + public override string Help => "[DEBUG] Clears the Alfar's Heimkall timer and every power cooldown."; + + public override void Run(string[] args) + { + Player player = Player.m_localPlayer; + if (player == null) return; + + AlfarHeimkall.ResetTimer(player); + AlfarHeimkall.InvulnerableUntil = 0f; + AlfarPowers.ResetCooldowns(player); + Console.instance.Print("[Alfar] Heimkall timer and power cooldowns cleared."); + } + } + + public class AlfarEitrCommand : ConsoleCommand + { + public override string Name => "alfareitr"; + public override string Help => "[DEBUG] alfareitr - sets the Alfr's current eitr."; + + public override void Run(string[] args) + { + Player player = Player.m_localPlayer; + if (player == null || args.Length == 0) { Console.instance.Print("alfareitr "); return; } + + float target; + if (args[0].ToLower() == "full") target = player.GetMaxEitr(); + else if (!float.TryParse(args[0], System.Globalization.NumberStyles.Float, + System.Globalization.CultureInfo.InvariantCulture, out target)) + { + Console.instance.Print("alfareitr "); + return; + } + + target = Mathf.Clamp(target, 0f, player.GetMaxEitr()); + float delta = target - player.GetEitr(); + if (delta > 0f) player.AddEitr(delta); + else if (delta < 0f) AlfarEitr.Spend(player, -delta); + + Console.instance.Print($"[Alfar] eitr = {player.GetEitr():0.0}/{player.GetMaxEitr():0}"); + } + } + + public class AlfarHpCommand : ConsoleCommand + { + public override string Name => "alfarhp"; + public override string Help => "[DEBUG] alfarhp - sets the current health, to test the lethal-blow case."; + + public override void Run(string[] args) + { + Player player = Player.m_localPlayer; + if (player == null || args.Length == 0) { Console.instance.Print("alfarhp "); return; } + + if (!float.TryParse(args[0], System.Globalization.NumberStyles.Float, + System.Globalization.CultureInfo.InvariantCulture, out float hp)) + { + Console.instance.Print("alfarhp "); + return; + } + + player.SetHealth(Mathf.Clamp(hp, 1f, player.GetMaxHealth())); + Console.instance.Print($"[Alfar] health = {player.GetHealth():0}/{player.GetMaxHealth():0}"); + } + } +} diff --git a/JotunnModStub/Alfar/AlfarConfig.cs b/JotunnModStub/Alfar/AlfarConfig.cs new file mode 100644 index 0000000..1769a1a --- /dev/null +++ b/JotunnModStub/Alfar/AlfarConfig.cs @@ -0,0 +1,159 @@ +using BepInEx.Configuration; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// Every number the Alfar use. Nothing numeric lives in the logic files (guide 3.4), and every + /// value here is a STARTING value: Alfar_Progettazione.txt sec. 19 says they will all be + /// corrected in play. + /// + /// Only the look is bound so far. The shield, the powers and the base add their own sections as + /// they are written. + /// + public static class AlfarConfig + { + /// + /// Written into m_customData["Race"] and the ZDO. Chosen once and never changed: renaming it + /// later leaves every saved Alfar character unrecognised and back to human (the Brandr + /// lesson, design doc sec. 2). + /// + public const string RaceId = "Alfar"; + + // ─── Look ──────────────────────────────────────────────────────────── + + /// The tint written into _SkinColor. Ash grey: low saturation, a hair cool. + public static ConfigEntry SkinColor; + + /// + /// Height against a normal Viking: +5%, design doc sec. 7.1. Applied to the Visual child's Y, + /// never the root (RaceEyeHeight explains why). + /// + public static ConfigEntry HeightScale; + + /// + /// Width and depth: "barely visibly thinner", about -8%. Together with HeightScale this is a + /// NON-UNIFORM scale, which is where held weapons and the first-person camera tend to look + /// squashed - doc sec. 7.2. If it does, raise this toward 1 before touching anything else. + /// + public static ConfigEntry WidthScale; + + /// + /// 1 is the Sverm's size, which is what the design asked to try first ("se non va li + /// allarghiamo"). Raise it to enlarge the eyes: 1.6 is roughly a grey from the films. + /// + public static ConfigEntry EyeSizeMultiplier; + + // The eye geometry is the Sverm's, unchanged (SvermVisuals): offsets are metres in the head + // bone's OWN frame, so they land on the same part of the face at any body scale. + public const float EyeSeparation = 0.032f; + public const float EyeForward = 0.081f; + public const float EyeHeight = 0.181f; + public const float EyeSize = 0.062f; + + // ─── Eitr: diet, shield, soft fall ─────────────────────────────────── + + /// + /// What each food adds to the maximum eitr besides its own: min(hp, stamina) times this. + /// 1 is the design (sec. 3): native eitr plus the lower of hp and stamina. + /// + public static ConfigEntry DietMultiplier; + + /// + /// Eitr spent per point of damage. 1:1, FIXED, for ever (sec. 4.1): progression comes from + /// the food raising the pool, not from a better rate. + /// + public static ConfigEntry ShieldRate; + + /// Lightning and spirit cost this many times the rate (sec. 5.1: the double cost). + public static ConfigEntry ConductiveMultiplier; + + /// + /// Falls cost nothing while there is any eitr (sec. 4.5: soft fall). Off, a fall is shielded + /// like any other blow. + /// + public static ConfigEntry SoftFall; + + /// + /// The fastest an Alfr falls while there is eitr, in metres per second. The vanilla Feather + /// Cape caps at 5; a little under that reads as floating. + /// + public static ConfigEntry FeatherFallSpeed; + + // ─── Heimkall: the death that costs a wait ─────────────────────────── + + /// Minutes before a second Heimkall is possible, before Yagluth (sec. 6). + public static ConfigEntry HeimkallMinutes; + + /// The same, once Yagluth is down. + public static ConfigEntry HeimkallMinutesAfterYagluth; + + /// The same, once Fader is down. + public static ConfigEntry HeimkallMinutesAfterFader; + + /// + /// Seconds of invulnerability on arrival, so a lethal blow does not simply repeat at the + /// bed. Without it a burning or drowning death would loop. + /// + public static ConfigEntry HeimkallInvulnerableSeconds; + + public static void Bind(ConfigFile config) + { + const string heimkall = "Alfar - Heimkall"; + + HeimkallMinutes = config.Bind(heimkall, "Cooldown Minutes", 20f, + new ConfigDescription("Minutes between two Heimkalls (the lethal-blow teleport to the bed). Inside this wait, a lethal blow kills normally.", + new AcceptableValueRange(0f, 120f))); + + HeimkallMinutesAfterYagluth = config.Bind(heimkall, "Cooldown Minutes After Yagluth", 15f, + new ConfigDescription("The cooldown once Yagluth is defeated.", + new AcceptableValueRange(0f, 120f))); + + HeimkallMinutesAfterFader = config.Bind(heimkall, "Cooldown Minutes After Fader", 10f, + new ConfigDescription("The cooldown once Fader is defeated.", + new AcceptableValueRange(0f, 120f))); + + HeimkallInvulnerableSeconds = config.Bind(heimkall, "Invulnerable Seconds", 5f, + new ConfigDescription("Seconds nothing can hurt the Alfr after arriving.", + new AcceptableValueRange(0f, 30f))); + + const string eitr = "Alfar - Eitr"; + + DietMultiplier = config.Bind(eitr, "Diet Multiplier", 1f, + new ConfigDescription("Each food adds its native eitr plus min(hp, stamina) times this to the maximum eitr.", + new AcceptableValueRange(0f, 3f))); + + ShieldRate = config.Bind(eitr, "Shield Rate", 1f, + new ConfigDescription("Eitr spent per point of damage absorbed (1 = 1:1).", + new AcceptableValueRange(0.1f, 5f))); + + ConductiveMultiplier = config.Bind(eitr, "Lightning And Spirit Multiplier", 2f, + new ConfigDescription("Lightning and spirit damage cost this many times the shield rate.", + new AcceptableValueRange(1f, 5f))); + + SoftFall = config.Bind(eitr, "Soft Fall", true, + new ConfigDescription("Falling does no damage, and is slowed, while the Alfr has any eitr.")); + + FeatherFallSpeed = config.Bind(eitr, "Feather Fall Speed", 4f, + new ConfigDescription("Maximum falling speed (m/s) while the Alfr has eitr. Lower floats more.", + new AcceptableValueRange(1f, 20f))); + + const string look = "Alfar - Look"; + + SkinColor = config.Bind(look, "Skin Color", new Color(0.86f, 0.88f, 0.88f, 1f), + new ConfigDescription("How light the ash-grey skin is. The skin texture itself is made grey; this only sets its brightness.")); + + HeightScale = config.Bind(look, "Height Scale", 1.05f, + new ConfigDescription("Body height against a normal Viking (1.05 = +5%).", + new AcceptableValueRange(0.8f, 1.3f))); + + WidthScale = config.Bind(look, "Width Scale", 0.92f, + new ConfigDescription("Body width and depth against a normal Viking (0.92 = 8% thinner).", + new AcceptableValueRange(0.7f, 1.2f))); + + EyeSizeMultiplier = config.Bind(look, "Eye Size Multiplier", 0.8f, + new ConfigDescription("1 = the Sverm's eye size; 0.8 is slightly smaller. Raise to enlarge the black eyes.", + new AcceptableValueRange(0.5f, 3f))); + } + } +} diff --git a/JotunnModStub/Alfar/AlfarConstructs.cs b/JotunnModStub/Alfar/AlfarConstructs.cs new file mode 100644 index 0000000..80fe2a5 --- /dev/null +++ b/JotunnModStub/Alfar/AlfarConstructs.cs @@ -0,0 +1,397 @@ +using System.Collections.Generic; +using Jotunn.Entities; +using Jotunn.Managers; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// The three constructs, the Alfar's only troops (Alfar_Progettazione.txt sec. 8.5): + /// + /// Neistvordr a Surtling: hp 60 and a shield of 60 (the vanilla Surtling has 20), fire thrower + /// Steinvordr the StoneGolem: hp 800, the tank, ONE per Nexus + /// Eldingvordr a smaller Abomination at half its hp, which fires a lightning sphere every 8 s + /// + /// Everything that makes them the Alfar's is done by what is added, not by rewriting attacks: + /// AlfarMark turns whatever they deal into lightning and keeps it off friends and buildings, + /// AlfarCreatureShield gives them a shield that returns by itself, and RaisedThrall gives them + /// the follow and stay orders every other race's troops already have. + /// + /// They are NOT repaired and do not heal: the damage to the body is permanent. RaisedThrall's + /// sentinel regeneration (SkeletonSentryBehaviour) is therefore left off, and the creature's own + /// slow vanilla regeneration is switched off too. + /// + public static class AlfarConstructs + { + public const string Neistvordr = "AlfarNeistvordr"; + public const string Steinvordr = "AlfarSteinvordr"; + public const string Eldingvordr = "AlfarEldingvordr"; + + public const string SphereProjectile = "AlfarLightningSphere"; + public const string SphereWeapon = "AlfarSphereAttack"; + + public class Kind + { + public string PrefabName; + public string Display; + public string Source; + public float Health; // 0 = keep the vanilla creature's + public float HealthFactor; // applied after Health when Health is 0 + public float Scale; // 1 = the vanilla size + } + + public static readonly Kind[] Roster = + { + new Kind { PrefabName = Neistvordr, Display = "$rov_creature_alfar_neistvordr_name", Source = "Surtling", Health = 60f, Scale = 1f }, + new Kind { PrefabName = Steinvordr, Display = "$rov_creature_alfar_steinvordr_name", Source = "StoneGolem", Health = 0f, HealthFactor = 1f, Scale = 0.6f }, + new Kind { PrefabName = Eldingvordr, Display = "$rov_creature_alfar_eldingvordr_name", Source = "Abomination", Health = 0f, HealthFactor = 0.5f, Scale = 0.4f }, + }; + + public static Kind Find(string prefabName) + { + foreach (Kind kind in Roster) if (kind.PrefabName == prefabName) return kind; + return null; + } + + // ─── Registration ──────────────────────────────────────────────────── + + public static void Register() + { + // The sphere first: the Eldingvordr's weapon needs it. + bool sphere = RegisterSphere(); + + foreach (Kind kind in Roster) + { + if (kind.PrefabName == Eldingvordr && !sphere) + { + Jotunn.Logger.LogWarning("[Alfar] No lightning sphere: the Eldingvordr keeps the Abomination's melee."); + } + RegisterOne(kind, sphere); + } + } + + private static void RegisterOne(Kind kind, bool sphere) + { + GameObject source = PrefabManager.Cache.GetPrefab(kind.Source); + if (source == null) + { + Jotunn.Logger.LogWarning($"[Alfar] No '{kind.Source}' to build {kind.Display} from."); + return; + } + + GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(kind.PrefabName, source); + if (prefab == null) return; + + Character character = prefab.GetComponent(); + if (character != null) + { + character.m_name = kind.Display; + character.m_faction = Character.Faction.Players; + if (kind.Health > 0f) character.m_health = kind.Health; + else character.m_health *= kind.HealthFactor; + + // The damage to the body is permanent: no slow regeneration either. + character.m_regenAllHPTime = 0f; + } + + if (!Mathf.Approximately(kind.Scale, 1f)) + { + prefab.transform.localScale = Vector3.one * kind.Scale; + ZNetView nview = prefab.GetComponent(); + if (nview != null) nview.m_syncInitialScale = true; + } + + BaseAI ai = prefab.GetComponent(); + if (ai != null) ai.m_randomMoveRange = AlfarNexusConfig.ConstructLeash.Value; + + MonsterAI monster = prefab.GetComponent(); + if (monster != null) + { + // The vanilla creatures attack player-built objects. Ours never touch a building. + monster.m_attackPlayerObjects = false; + monster.m_alertRange = AlfarNexusConfig.ConstructAlertRange.Value; + monster.m_maxChaseDistance = AlfarNexusConfig.ConstructAlertRange.Value; + } + + // A construct that dropped Coal, a Surtling core or a trophy would be a loot farm. + foreach (CharacterDrop drops in prefab.GetComponentsInChildren(true)) + { + if (drops != null) Object.DestroyImmediate(drops); + } + + if (kind.PrefabName == Eldingvordr && sphere) GiveSphereWeapon(prefab); + if (kind.PrefabName == Neistvordr) BlueFlames(prefab); + else Tint(prefab, new Color(0.85f, 0.52f, 0.2f, 1f)); + + AlfarMark mark = prefab.AddComponent(); + mark.Role = "construct"; + + // What a destroyed construct gives back: the METAL it was built from, and nothing else - the + // crystals and the refined eitr are spent for good (design sec. 8.5). + AlfarRefund refund = prefab.AddComponent(); + refund.Item = kind.PrefabName == Neistvordr ? "Bronze" : kind.PrefabName == Eldingvordr ? "Iron" : "BlackMetal"; + refund.Amount = kind.PrefabName == Neistvordr ? AlfarNexusConfig.NeistMetal.Value + : kind.PrefabName == Eldingvordr ? AlfarNexusConfig.EldingMetal.Value + : AlfarNexusConfig.SteinMetal.Value; + + AlfarCreatureShield shield = prefab.AddComponent(); + shield.MaxShield = character != null ? character.m_health : 0f; + shield.Shield = shield.MaxShield; + + RaisedThrall thrall = prefab.AddComponent(); + thrall.m_kind = kind.PrefabName; + thrall.m_commandingRace = AlfarConfig.RaceId; + thrall.m_maxFollowers = -1; // the cap is the Nexus's, per type, counted at the Nexus + thrall.m_witherSeconds = AlfarNexusConfig.WitherSeconds.Value; + thrall.m_homeCheckRange = AlfarNexusConfig.NexusRadius.Value; + thrall.m_refusalMessage = "$rov_msg_thrall_refusal_alfar"; + + PrefabManager.Instance.AddPrefab(prefab); + Jotunn.Logger.LogInfo($"[Alfar] Registered '{kind.PrefabName}' from '{kind.Source}'."); + } + + // ─── The lightning sphere ──────────────────────────────────────────── + + /// + /// The Eldingvordr's shot: a sphere that bursts in a small area, hurts only enemies, and never + /// touches a building (doc sec. 8.5 and 16B V12). Cloned from the Dverger ice projectile, the + /// clean base the probe found: an area burst and NO lingering effect spawned on impact (the + /// fire one drops a fire field and also spawns on buildings). + /// + private static bool RegisterSphere() + { + GameObject source = PrefabManager.Cache.GetPrefab("DvergerStaffIce_projectile"); + if (source == null) + { + Jotunn.Logger.LogWarning("[Alfar] DvergerStaffIce_projectile not found: no lightning sphere."); + return false; + } + + GameObject projectile = PrefabManager.Instance.CreateClonedPrefab(SphereProjectile, source); + if (projectile == null) return false; + + Projectile settings = projectile.GetComponent(); + if (settings == null) return false; + + settings.m_gravity = 0f; + settings.m_ttl = 4f; + settings.m_aoe = 3f; + settings.m_aoeSkipWearNTear = true; + settings.m_hitFriendly = false; + settings.m_noDamageFriendly = true; + settings.m_hitOwner = false; + settings.m_statusEffect = ""; + + Tint(projectile, new Color(0.55f, 0.85f, 1f, 1f)); + PrefabManager.Instance.AddPrefab(projectile); + + // The weapon that fires it: the Surtling's own fireball weapon, because a creature that + // shoots needs an item with a projectile attack, and that is the one that exists. + GameObject surtling = PrefabManager.Cache.GetPrefab("Surtling"); + Humanoid surtlingHumanoid = surtling != null ? surtling.GetComponent() : null; + GameObject fireball = surtlingHumanoid != null && surtlingHumanoid.m_defaultItems != null && + surtlingHumanoid.m_defaultItems.Length > 0 + ? surtlingHumanoid.m_defaultItems[0] + : null; + if (fireball == null) + { + Jotunn.Logger.LogWarning("[Alfar] The Surtling's fireball weapon was not found: no sphere weapon."); + return false; + } + + GameObject weapon = PrefabManager.Instance.CreateClonedPrefab(SphereWeapon, fireball); + if (weapon == null) return false; + + ItemDrop drop = weapon.GetComponent(); + if (drop == null || drop.m_itemData == null || drop.m_itemData.m_shared == null) return false; + + ItemDrop.ItemData.SharedData shared = drop.m_itemData.m_shared; + shared.m_name = "$rov_item_alfar_sphere_name"; + + // One shot every eight seconds (design): the AI waits this long between uses. + shared.m_aiAttackInterval = AlfarNexusConfig.SphereIntervalSeconds.Value; + shared.m_aiAttackRange = AlfarNexusConfig.SphereRange.Value; + shared.m_aiAttackRangeMin = 4f; + + HitData.DamageTypes damage = default(HitData.DamageTypes); + damage.m_lightning = AlfarNexusConfig.SphereDamage.Value; + shared.m_damages = damage; + + if (shared.m_attack != null) + { + shared.m_attack.m_attackProjectile = projectile; + // The Abomination's right hand: where the sphere leaves from. + shared.m_attack.m_attackOriginJoint = "r.hand"; + } + + ItemManager.Instance.AddItem(new CustomItem(weapon, fixReference: false)); + return true; + } + + private static void GiveSphereWeapon(GameObject prefab) + { + Humanoid humanoid = prefab.GetComponent(); + GameObject weapon = PrefabManager.Instance.GetPrefab(SphereWeapon); + if (humanoid == null || weapon == null) return; + + humanoid.m_defaultItems = new[] { weapon }; + humanoid.m_randomWeapon = new GameObject[0]; + humanoid.m_randomArmor = new GameObject[0]; + humanoid.m_randomShield = new GameObject[0]; + humanoid.m_randomSets = new Humanoid.ItemSet[0]; + } + + // ─── Colour ────────────────────────────────────────────────────────── + + /// + /// A tint on every mesh, through renderer.materials (an instanced copy) and NEVER .material or + /// sharedMaterial: the vanilla creature uses the same asset and must stay as it is (guide 3.5). + /// This is a recolour and not a retexture: a true repaint of the golem and the Abomination is + /// still to do (test file, phase 6). + /// + public static void Tint(GameObject prefab, Color color) + { + foreach (Renderer renderer in prefab.GetComponentsInChildren(true)) + { + if (renderer is ParticleSystemRenderer || renderer is TrailRenderer || renderer is LineRenderer) continue; + + Material[] materials = renderer.materials; + foreach (Material material in materials) + { + if (material == null) continue; + if (material.HasProperty("_Color")) material.color = color; + if (material.HasProperty("_EmissionColor")) + { + material.SetColor("_EmissionColor", color * 0.08f); + material.EnableKeyword("_EMISSION"); + } + } + renderer.materials = materials; + } + + foreach (Light light in prefab.GetComponentsInChildren(true)) light.color = color; + } + + /// + /// The Surtling is made of particles and lights, not textures, and the vanilla prefab ALREADY + /// carries blue variants of its flames, switched off (probe, doc 16C P2): turn those on, turn + /// the red ones off, and recolour the glow of the body and the point light. + /// + private static void BlueFlames(GameObject prefab) + { + foreach (Transform child in prefab.GetComponentsInChildren(true)) + { + if (child.name == "flames_world_BLUE") child.gameObject.SetActive(true); + else if (child.name == "flames" || child.name == "flames_world" || child.name == "flames_world_Purple") + { + child.gameObject.SetActive(false); + } + } + + Color blue = new Color(0.25f, 0.55f, 1f, 1f); + foreach (Light light in prefab.GetComponentsInChildren(true)) light.color = blue; + + foreach (Renderer renderer in prefab.GetComponentsInChildren(true)) + { + Material[] materials = renderer.materials; + foreach (Material material in materials) + { + if (material != null && material.HasProperty("_EmissionColor")) + { + // The vanilla emission is white-hot (73): keep the strength, change the hue. + material.SetColor("_EmissionColor", new Color(0.25f, 0.55f, 1f, 1f) * 30f); + } + } + renderer.materials = materials; + } + } + + // ─── Counting and spawning (called by the Nexus) ───────────────────── + + /// + /// A destroyed construct drops the metal it cost, on the ground where it fell. Only a DEATH: + /// a zone unloading destroys the object too and must not pay anyone (the same rule as the + /// Butler's payload). + /// + public class AlfarRefund : MonoBehaviour + { + public string Item = ""; + public int Amount; + } + + [HarmonyLib.HarmonyPatch(typeof(Character), "OnDeath")] + public static class Alfar_Refund_Patch + { + public static void Postfix(Character __instance) + { + AlfarRefund refund = __instance != null ? __instance.GetComponent() : null; + if (refund == null || refund.Amount <= 0 || ObjectDB.instance == null) return; + + GameObject prefab = ObjectDB.instance.GetItemPrefab(refund.Item); + ItemDrop template = prefab != null ? prefab.GetComponent() : null; + if (template == null || template.m_itemData == null) return; + + int left = refund.Amount; + int max = Mathf.Max(1, template.m_itemData.m_shared.m_maxStackSize); + Vector3 at = __instance.transform.position + Vector3.up * 0.5f; + + while (left > 0) + { + int stack = Mathf.Min(left, max); + ItemDrop.ItemData clone = template.m_itemData.Clone(); + clone.m_dropPrefab = prefab; + ItemDrop.DropItem(clone, stack, at + Random.insideUnitSphere * 0.3f, Quaternion.identity); + left -= stack; + } + refund.Amount = 0; // once only + } + } + + public static int CountAlive(Vector3 anchor, string prefabName) + { + int count = 0; + foreach (RaisedThrall thrall in RaisedThrall.BoundTo(anchor)) + { + if (thrall != null && thrall.Kind == prefabName) count++; + } + return count; + } + + public static bool Spawn(Vector3 anchor, string prefabName) + { + GameObject prefab = ZNetScene.instance != null ? ZNetScene.instance.GetPrefab(prefabName) : null; + if (prefab == null) + { + Jotunn.Logger.LogWarning($"[Alfar] No '{prefabName}' in ZNetScene: it cannot be built."); + return false; + } + + Vector3 where = SpawnSpot(anchor); + GameObject spawned = Object.Instantiate(prefab, where, Quaternion.Euler(0f, Random.Range(0, 360), 0f)); + RaisedThrall thrall = spawned != null ? spawned.GetComponent() : null; + if (thrall != null) thrall.Bind(anchor); + return spawned != null; + } + + /// A free spot on a ring around the Nexus, on the ground, or due south as a last resort. + public static Vector3 SpawnSpot(Vector3 centre) + { + const float radius = 3.5f; + 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 * 30f) * 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 * 0.3f; + } + + Vector3 fallback = centre + new Vector3(0f, 0f, -radius); + if (ZoneSystem.instance != null) fallback.y = ZoneSystem.instance.GetGroundHeight(fallback); + return fallback + Vector3.up * 0.3f; + } + } +} diff --git a/JotunnModStub/Alfar/AlfarDroneAI.cs b/JotunnModStub/Alfar/AlfarDroneAI.cs new file mode 100644 index 0000000..59d8fea --- /dev/null +++ b/JotunnModStub/Alfar/AlfarDroneAI.cs @@ -0,0 +1,1950 @@ +using System.Collections.Generic; +using System.Text; +using HarmonyLib; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// The Alfar drone's own head (Alfar_Progettazione.txt sec. 9): a FORK of the Butler's BoneServantAI, + /// kept as a separate class so nothing that ships with the Skeleton, Skadi or Sverm can be broken + /// from here. What it keeps: the movement, the payload in the ZDO, the three families of stations, + /// the burn protection and the one-stage rule. What it changes: ONE drone does both trades; chests + /// are read the other way round (the sigil marks the ones NOT to touch); stations are fed only from + /// the entry chest, wood only from the wood chest; the product goes back to the entry chest and is + /// SORTED from there into the chest that already holds the same thing; and three jobs are new - + /// repair, farming (with the replant rule) and sorting. + /// + /// The Bone Servant's own head, as it was written: everything it does is here; vanilla's MonsterAI + /// never runs on it. + /// + /// HOW IT MOVES, which was the one open question in the design and is answered here rather than in + /// the doc. Three candidates were on the table: a ghost follow-target, pinning m_patrolPoint the way + /// RaisedThrall does, and calling BaseAI.MoveTo directly. The IL settled it: + /// + /// - BaseAI has NO Update and NO FixedUpdate. UpdateAI(dt) is driven centrally by + /// MonoUpdaters.FixedUpdate over BaseAI.Instances, and that list is maintained by OnEnable / + /// OnDisable. So "disable the AI and drive MoveTo yourself" kills the only thing that would + /// call anything: a disabled BaseAI is not ticked at all. That candidate is dead. + /// - BaseAI.UpdateAI itself does almost nothing - IsOwner, UpdateTakeoffLanding, + /// UpdateRegeneration - so skipping it costs a flying check we do not need and a regeneration + /// we already have from SkeletonSentryBehaviour. + /// + /// So: a PREFIX on MonsterAI.UpdateAI that hands the tick to this class and returns false. The + /// servant keeps its place in the central tick, keeps vanilla pathing through BaseAI.MoveTo, and + /// vanilla's own AI - targeting, fleeing, wandering, attacking - never executes a single line. That + /// is also why the servant cannot fight: not because its weapon was taken (it was), but because the + /// code that would swing it is never reached. + /// + /// MoveTo(dt, point, dist, run) is private, hence the cached MethodInfo. It returns TRUE on arrival + /// (read in the IL: DistanceXZ under the threshold calls StopMoving and returns 1), which is the + /// whole arrival test - no distance maths of our own. + /// + /// THE PAYLOAD IS VIRTUAL. The servant has no inventory. Every station's input RPC takes a STRING, + /// so what it carries is a list of prefab names and counts in its own ZDO, which survives saving, + /// zone reload and - the case that matters - a change of owner mid-job in multiplayer. The one + /// thing this costs is that the goods do not exist as objects while in transit, so they have to be + /// put back into the world by hand if the servant dies holding them. That is , + /// and it is the reason nothing here can quietly delete a player's ore. + /// + public class AlfarDroneAI : MonoBehaviour + { + // ─── ZDO keys ──────────────────────────────────────────────────────── + public const string KeyAnchor = "RoV_alfarAnchor"; + public const string KeyOrphanAt = "RoV_alfarOrphanAt"; + public const string KeyLoad = "RoV_alfarLoad"; + public const string KeySource = "RoV_alfarSource"; + public const string KeyTarget = "RoV_alfarTarget"; + public const string KeyStatus = "RoV_alfarStatus"; + public const string KeyDest = "RoV_alfarDest"; + + /// Every drone alive in the loaded zones: the repairs look at each other through it. + public static readonly List All = new List(); + + /// Written into a STATION's ZDO: the chest whose material is in it right now, so the + /// product goes home to where the raw came from even after a reload, and even if a different + /// client collects it. + public const string KeyFedBy = "RoV_alfarFedBy"; + + // ─── numbers that are not worth a config entry ─────────────────────── + private const float PlanInterval = 1.5f; + + /// + /// How close is close enough. Measured to the piece's ORIGIN, which on a furnace or a kiln sits + /// inside a metre or so of solid collider - so anything tight enough to look like hugging the + /// thing is a distance the servant can never actually reach, and it would time out and put a + /// perfectly good station in the penalty box. Two and a half metres is roughly where a player + /// stands to use one. + /// + private const float ArriveDistance = 2.5f; + + private const float CollectRadius = 3.5f; + private const float JobTimeout = 25f; + private const float PenaltySeconds = 180f; + + /// Set aside briefly when a job was reached but achieved nothing. Without this, a job + /// that arrives and finds nothing to do is re-planned identically on the next tick and the + /// servant stands there deciding the same thing forever. + private const float ShortPenaltySeconds = 20f; + private const float FleeSeconds = 6f; + private const float WitherSeconds = 30f; + private const float HomeCheckRange = 25f; + + /// A cooking slot inside this many seconds of burning outranks everything else. Twelve + /// seconds is a walk of about twenty metres with room to spare, which is the whole radius. + private const float SpoilPanicSeconds = 12f; + + /// How long a station may sit unserved before its wait starts outweighing distance. + /// This is what stops a furnace at the edge of the circle from starving while the servant + /// shuttles between two closer ones. + private const float WaitToMetres = 0.25f; + + private const int PayloadCap = 120; + + private static readonly System.Reflection.MethodInfo MoveToMethod = + AccessTools.Method(typeof(BaseAI), "MoveTo", + new[] { typeof(float), typeof(Vector3), typeof(float), typeof(bool) }); + + private static readonly System.Reflection.FieldInfo AllPiecesField = + AccessTools.Field(typeof(Piece), "s_allPieces"); + + private static readonly System.Reflection.MethodInfo ContainerSaveMethod = + AccessTools.Method(typeof(Container), "Save"); + + private static int s_itemMask = -1; + + /// Which stations this one serves. Set on the prefab at registration, so it travels + /// with every instance the table raises. + public ButlerFamily m_family = ButlerFamily.Forge; + + /// + /// Whether this one stands and fights instead of walking home when trouble comes. Off for the + /// Bone Servants, which are pacifists by decision; on for the Sverm's Seeker Workers, which + /// keep the forge AND defend the nest. See . + /// + public bool m_fightsBack = false; + + /// + /// How close to the anchor counts as home, and how far past the configured radius it works. + /// 2.5 and 0 for a table. A Sverm nest is metres of collider that grows with its stage, so + /// SvermWorkerBehaviour sets both to the nest's measured edge - otherwise an idle worker would + /// spend its life walking into the trunk, and the work circle would be mostly nest. + /// + public float m_homeDistance = 2.5f; + public float m_radiusBonus = 0f; + + /// For a servant that fights back: how close an enemy has to be to stop the work, how + /// often that is asked, and how long the fight holds after the last sign of one. + private const float FightRange = 12f; + private const float FightScanInterval = 1f; + private const float FightLinger = 5f; + + private float m_nextFightScan; + private float m_fightUntil; + + private ZNetView m_nview; + private Character m_character; + private MonsterAI m_ai; + + private readonly object[] m_moveArgs = new object[4]; + private readonly List m_payload = new List(); + private readonly Dictionary m_penalties = new Dictionary(); + private readonly Dictionary m_idleSince = new Dictionary(); + + private readonly List m_stations = new List(); + private readonly List m_chests = new List(); // the storage chests + private Container m_entry; // the entry chest + private Container m_wood; // the wood-to-burn chest + private readonly List m_damaged = new List(); + + // Farming: where the last harvest was, and what to put back there. + private Vector3? m_farmSpot; + private Quaternion m_farmRot; + private PlantInfo m_farmInfo; + private float m_farmReadyAt; + + // Sorting: what was chosen at the entry chest and where it is going. + private string m_sortItem; + private ZDOID m_sortDest; + private float m_scannedAt = -99f; + + private Job m_job; + private float m_nextPlan; + private float m_jobDeadline; + private float m_fleeUntil; + private string m_status = ""; + + private class Load + { + public string Name; + public int Count; + } + + private class Job + { + public string Kind; // load | fuel | collect | deposit | drop + public ZDOID Target; + public Vector3 Point; + public bool Hurry; + public string Label; + public ZDOID Claim; // the one target other drones must leave alone + } + + // ================================================================ life + + private void Awake() + { + m_nview = GetComponent(); + m_character = GetComponent(); + m_ai = GetComponent(); + + All.Add(this); + ReadPayload(); + } + + private void OnDestroy() + { + All.Remove(this); + + // Only a DEATH scatters the load. A zone unloading destroys this object too, and there the + // payload must stay in the ZDO where it will be read again on the way back in - dropping it + // would mint a copy every time the player walked away. + if (m_character != null && m_character.IsDead()) DropPayload(); + } + + /// Called by the table the moment it raises one. + public void Bind(Vector3 anchor) + { + if (m_nview == null || !m_nview.IsValid()) return; + + m_nview.GetZDO().Set(KeyAnchor, anchor); + + if (m_ai != null) m_ai.MakeTame(); + if (m_character != null) m_character.SetTamed(true); + } + + public Vector3? Anchor + { + get + { + if (m_nview == null || !m_nview.IsValid()) return null; + + Vector3 anchor = m_nview.GetZDO().GetVec3(KeyAnchor, Vector3.zero); + return anchor == Vector3.zero ? (Vector3?)null : anchor; + } + } + + public bool IsBoundTo(Vector3 anchor) + { + Vector3? own = Anchor; + return own != null && Vector3.SqrMagnitude(own.Value - anchor) < 0.25f; + } + + /// The one line the table's hover shows. Read from the ZDO so a client that does not + /// own the servant still sees what it is doing. + public string Status + { + get + { + if (m_nview == null || !m_nview.IsValid()) return m_status; + return m_nview.GetZDO().GetString(KeyStatus, m_status); + } + } + + private void SetStatus(string text) + { + if (text == m_status) return; + + m_status = text; + if (m_nview != null && m_nview.IsValid() && m_nview.IsOwner()) + { + m_nview.GetZDO().Set(KeyStatus, text); + } + } + + /// Hit by something: stop working and walk home. It never fights back - there is + /// nothing in this class that could. A servant that fights back ignores this: vanilla already + /// holds the attacker as its target (MonsterAI.OnDamaged calls SetTarget, read off the IL), and + /// gives it the tick on the next frame. + public void NoteDamage() + { + if (m_fightsBack) return; + + m_fleeUntil = Time.time + FleeSeconds; + m_job = null; + } + + /// + /// True while vanilla's MonsterAI should have the tick instead of the work - only ever for a + /// servant that fights back, and only on the client that runs it. + /// + /// VANILLA DOES THE FIGHTING, this only decides when. Two things start a fight: a target the + /// MonsterAI already holds - which covers being hit, see NoteDamage - and an enemy inside + /// FightRange, found with BaseAI.FindClosestEnemy. That one is a static sweep of distance and + /// IsEnemy with no line of sight (IL), which is why the range is short. Either holds the fight + /// for FightLinger seconds, so the worker does not flicker between swinging and walking to the + /// chest on alternate ticks. + /// + /// The job is dropped, not the payload: whatever it was carrying stays in the ZDO, and the + /// first plan after the fight carries it on to where it was going. + /// + public bool HandsToVanilla() + { + if (!m_fightsBack || m_ai == null || m_character == null || m_character.IsDead()) return false; + if (m_nview == null || !m_nview.IsValid() || !m_nview.IsOwner()) return false; + + Character target = m_ai.GetTargetCreature(); + if (target != null && !target.IsDead()) + { + m_fightUntil = Time.time + FightLinger; + } + else if (Time.time >= m_nextFightScan) + { + m_nextFightScan = Time.time + FightScanInterval; + if (BaseAI.FindClosestEnemy(m_character, transform.position, FightRange) != null) + { + m_fightUntil = Time.time + FightLinger; + } + } + + if (Time.time >= m_fightUntil) return false; + + m_job = null; + m_nextPlan = 0f; // the fight moved it; plan afresh the moment it hands back + SetStatus("Fighting."); + return true; + } + + // ================================================================ the tick + + /// Everything. Returns what MonsterAI.UpdateAI would have returned. + public bool Tick(float dt) + { + if (m_nview == null || !m_nview.IsValid() || !m_nview.IsOwner()) return false; + if (m_character == null || m_character.IsDead()) return false; + + if (TickWither()) return true; + + if (Time.time < m_fleeUntil) + { + SetStatus("Driven off."); + GoHome(dt); + return true; + } + + if (Time.time >= m_nextPlan) + { + m_nextPlan = Time.time + PlanInterval; + Plan(); + } + + Execute(dt); + return true; + } + + /// + /// The table is gone: start the clock, and stop when it runs out. Same shape as RaisedThrall's, + /// and deliberately only asked near home - further out the table's zone is simply not loaded, so + /// "nothing there" would be a lie. + /// + private bool TickWither() + { + Vector3? anchor = Anchor; + if (anchor == null || ZNet.instance == null) return false; + + long stamp = m_nview.GetZDO().GetLong(KeyOrphanAt, 0L); + + if (stamp == 0L) + { + if (Vector3.SqrMagnitude(transform.position - anchor.Value) > + HomeCheckRange * HomeCheckRange) return false; + if (RaisedThrall.StationStandsAt(anchor.Value)) return false; + + m_nview.GetZDO().Set(KeyOrphanAt, ZNet.instance.GetTime().Ticks); + return false; + } + + if (RaisedThrall.StationStandsAt(anchor.Value)) + { + m_nview.GetZDO().Set(KeyOrphanAt, 0L); + return false; + } + + double elapsed = (ZNet.instance.GetTime() - new System.DateTime(stamp)).TotalSeconds; + if (elapsed < WitherSeconds) return false; + + HitData hit = new HitData(); + hit.m_damage.m_damage = 1E+10f; + hit.m_hitType = HitData.HitType.Undefined; + m_character.ApplyDamage(hit, true, false); + return true; + } + + // ================================================================ planning + + private void Plan() + { + Vector3? anchor = Anchor; + if (anchor == null) { m_job = null; return; } + + Scan(anchor.Value); + ExpirePenalties(); + + // A harvest is in progress: wait for the drops to land, then gather them and replant. + if (m_farmSpot != null) + { + m_job = Time.time < m_farmReadyAt + ? new Job { Kind = "wait", Point = transform.position, Label = "Waiting" } + : new Job { Kind = "farm_finish", Point = m_farmSpot.Value, Label = "Gathering" }; + return; + } + + if (m_payload.Count > 0) { m_job = PlanDelivery(anchor.Value); return; } + + // The forge has no clock: a smelter holds its ore indefinitely and puts its own output on + // the floor, so PlanRescue would ask a question whose answer is always no. The smith is a + // four-state machine and the cook is a five-state one, and that is the whole of the + // simplification the split bought. + // REFUEL BEFORE LOAD, and that order is the whole of the blast furnace fix. FreeSlots goes + // back above zero the instant a furnace eats one ore, so while there is scrap left in any + // chest PlanLoad always has an answer and PlanFuel, sitting behind it, never got a turn - + // the furnace was topped up forever and burned down to nothing. Fuel cannot starve loading + // in return, because FuelWanted is zero for a station with no work: an empty furnace asks + // for no coal, gets filled, and only then becomes worth stoking. + // One drone does both trades, so the burn protection is always on. Stations first, then the + // base: repairs, the fields, and last the tidying of the entry chest. + Job job = PlanRescue(); + job = job ?? PlanCollect() ?? PlanFuel() ?? PlanLoad(); + job = job ?? PlanRepair(anchor.Value) ?? PlanFarm(anchor.Value) ?? PlanSort(); + + if (job != null && (m_job == null || m_job.Kind != job.Kind || m_job.Target != job.Target)) + { + m_jobDeadline = Time.time + JobTimeout; + } + if (m_job != null && !ReferenceEquals(m_job, job)) Release(m_job.Claim); + if (job != null) Claim(job.Claim); + m_job = job; + } + + /// + /// Everything within the radius, once every planning tick. Piece.s_allPieces is the cheap way in + /// - it is the list the game already keeps of every built piece - so there is no OverlapSphere + /// and no guessing at layer masks for the part that runs constantly. + /// + private void Scan(Vector3 anchor) + { + if (Time.time - m_scannedAt < PlanInterval * 0.5f) return; + m_scannedAt = Time.time; + + m_stations.Clear(); + m_chests.Clear(); + m_damaged.Clear(); + m_entry = null; + m_wood = null; + + List pieces = AllPiecesField != null ? AllPiecesField.GetValue(null) as List : null; + if (pieces == null) return; + + float radius = AlfarNexusConfig.NexusRadius.Value + m_radiusBonus; + float radiusSq = radius * radius; + + for (int i = 0; i < pieces.Count; i++) + { + Piece piece = pieces[i]; + if (piece == null) continue; + if (Vector3.SqrMagnitude(piece.transform.position - anchor) > radiusSq) continue; + + // A station of the other trade is not this servant's business, but it is still not a + // chest - hence the continue either way. + // Both trades: the drone serves the smelters AND the kitchens. + ButlerStation station = ButlerStation.From(piece.gameObject); + if (station != null) + { + m_stations.Add(station); + continue; + } + + // Every chest in reach is the drone's, EXCEPT one holding the sigil. The two special + // chests are told apart by prefab name. + Container container = piece.GetComponent(); + if (container != null && !IsMarkedOff(container)) + { + string chestName = Utils.GetPrefabName(piece.gameObject); + if (chestName == AlfarChests.EntryName) m_entry = container; + else if (chestName == AlfarChests.WoodName) m_wood = container; + else m_chests.Add(container); + } + + // Anything damaged is for the drones to mend, towers and chests and walls alike. + WearNTear wear = piece.GetComponent(); + if (wear != null && wear.GetHealthPercentage() < 0.999f) m_damaged.Add(wear); + } + } + + /// + /// The sigil is INVERTED from the Butler's: it marks the chests the drones must NOT look at. A + /// chest in use by a player is left alone too. The sigil itself is never counted as material and + /// never carried away - see TakeFrom. + /// + private static bool IsMarkedOff(Container container) + { + if (container == null || container.IsInUse()) return true; + + Inventory inventory = container.GetInventory(); + if (inventory == null) return true; + + string sigil = SigilSharedName(); + return !string.IsNullOrEmpty(sigil) && inventory.CountItems(sigil) > 0; + } + + private static string s_sigilShared; + private static string s_sigilFor; + + /// Inventory.CountItems matches on the SHARED name ($item_...), not on the prefab name + /// the stations use, so the configured prefab is resolved once into the other kind of name. + private static string SigilSharedName() + { + string wanted = AlfarSigil.PrefabName; + if (s_sigilFor == wanted) return s_sigilShared; + + s_sigilFor = wanted; + s_sigilShared = null; + + GameObject prefab = ObjectDB.instance != null ? ObjectDB.instance.GetItemPrefab(wanted) : null; + ItemDrop drop = prefab != null ? prefab.GetComponent() : null; + if (drop != null && drop.m_itemData != null && drop.m_itemData.m_shared != null) + { + s_sigilShared = drop.m_itemData.m_shared.m_name; + } + else + { + Jotunn.Logger.LogWarning($"[AlfarDrone] No item '{wanted}' to use as the sigil; " + + "no chest can be marked until that name is right."); + } + + return s_sigilShared; + } + + // ---------------------------------------------------------------- the five states + + /// 1. SAVE. A slot about to burn beats everything, and it is the only job it runs to. + private Job PlanRescue() + { + ButlerStation best = null; + float soonest = SpoilPanicSeconds; + + foreach (ButlerStation station in m_stations) + { + if (!station.Alive || IsPenalised(station.Id) || ClaimedByOther(station.Id)) continue; + if (!station.HasOutput) continue; // nothing pullable yet, panic changes nothing + + float left = station.SecondsToSpoil; + if (left >= soonest) continue; + + soonest = left; + best = station; + } + + if (best == null) return null; + + return new Job + { + Kind = "collect", + Target = best.Id, + Claim = best.Id, + Point = best.Position, + Hurry = true, + Label = "Saving the food", + }; + } + + /// 2. COLLECT. Anything finished, and anything already lying under a station. + private Job PlanCollect() + { + ButlerStation best = null; + float bestScore = float.MaxValue; + + foreach (ButlerStation station in m_stations) + { + if (!station.Alive || IsPenalised(station.Id) || ClaimedByOther(station.Id)) continue; + if (!station.HasOutput && !HasDropsNear(station.Position)) continue; + + float score = Vector3.Distance(transform.position, station.Position); + if (score >= bestScore) continue; + + bestScore = score; + best = station; + } + + if (best == null) return null; + + return new Job + { + Kind = "collect", + Target = best.Id, + Claim = best.Id, + Point = best.Position, + Label = "Collecting", + }; + } + + /// + /// 4. LOAD. Urgency, then distance - and the urgency of a station with nothing wrong with it is + /// how long it has been waiting. A metre of walking is worth four seconds of a station standing + /// idle, so the far furnace wins eventually instead of never. + /// + private Job PlanLoad() + { + ButlerStation best = null; + string bestItem = null; + Container bestChest = null; + float bestScore = float.MaxValue; + + foreach (ButlerStation station in m_stations) + { + if (!station.Alive || IsPenalised(station.Id) || ClaimedByOther(station.Id)) continue; + if (!station.Operable || station.FreeSlots <= 0) continue; + + Container chest; + string item = FindMaterialFor(station, out chest); + if (item == null) { m_idleSince.Remove(station.Id); continue; } + + float waited = NoteIdle(station.Id); + float score = Vector3.Distance(transform.position, chest.transform.position) + + Vector3.Distance(chest.transform.position, station.Position) - + waited * WaitToMetres; + + if (score >= bestScore) continue; + + bestScore = score; + best = station; + bestItem = item; + bestChest = chest; + } + + if (best == null) return null; + + // The chest first - the station is where the payload goes afterwards, and PlanDelivery + // works that out from the target written on the load. + return new Job + { + Kind = "load", + Target = ZdoOf(bestChest), + Claim = best.Id, + Point = bestChest.transform.position, + Label = "Fetching " + bestItem, + }; + } + + /// + /// 3. REFUEL. Only stations that actually have something to work on. + /// + /// Scored by the walk, the same way PlanLoad is, and for a reason that only appeared once this + /// moved up the list: taking the first station in scan order was harmless while refuelling was + /// the job of last resort, but ahead of loading it lets one furnace at the edge of the circle + /// hold the servant while a cold one two metres away waits. + /// + private Job PlanFuel() + { + Container bestChest = null; + string bestFuel = null; + float bestScore = float.MaxValue; + + foreach (ButlerStation station in m_stations) + { + if (!station.Alive || IsPenalised(station.Id) || ClaimedByOther(station.Id)) continue; + if (!station.Operable) continue; + + int wanted = station.FuelWanted; + if (wanted <= 0) continue; + + string fuel = station.FuelPrefab; + if (string.IsNullOrEmpty(fuel)) continue; + + Container chest = FindChestWith(fuel); + if (chest == null) continue; + + float score = Vector3.Distance(transform.position, chest.transform.position) + + Vector3.Distance(chest.transform.position, station.Position); + if (score >= bestScore) continue; + + bestScore = score; + bestChest = chest; + bestFuel = fuel; + } + + if (bestChest == null) return null; + + return new Job + { + Kind = "fuel", + Target = ZdoOf(bestChest), + Point = bestChest.transform.position, + Label = "Fetching " + bestFuel, + }; + } + + /// Where the load in hand is going: on to its station, or back into a chest. + private Job PlanDelivery(Vector3 anchor) + { + // A sorting trip has a destination chosen at the entry chest: take it there. + ZDOID dest = m_nview.GetZDO().GetZDOID(KeyDest); + if (dest != ZDOID.None) + { + Container destination = ContainerById(dest); + if (destination != null && !IsMarkedOff(destination) && !IsPenalised(dest) && HasRoomFor(destination)) + { + return new Job + { + Kind = "deposit", + Target = dest, + Point = destination.transform.position, + Label = "Sorting " + Describe(), + }; + } + m_nview.GetZDO().Set(KeyDest, ZDOID.None); + } + + ZDOID target = m_nview.GetZDO().GetZDOID(KeyTarget); + if (target != ZDOID.None) + { + // NO FreeSlots CHECK HERE, and that was the first bug found in play: fuel does not go + // into a slot. A furnace filled to m_maxOre with copper has FreeSlots 0 and still wants + // coal, so gating the delivery on free slots sent the servant back to the chest with + // the coal it had just fetched - and then PlanFuel sent it out for the same coal again, + // forever. AcceptsAnything already asks the right question of both doors. + ButlerStation station = StationById(target); + if (station != null && station.Alive && station.Operable && AcceptsAnything(station)) + { + return new Job + { + Kind = "deposit_station", + Target = target, + Point = station.Position, + Label = "Loading " + Describe(), + }; + } + + // The station is gone, full or cold. The goods are ours to put back, not to hold. + m_nview.GetZDO().Set(KeyTarget, ZDOID.None); + } + + Container chest = ChestForProduct(); + if (chest != null) + { + return new Job + { + Kind = "deposit", + Target = ZdoOf(chest), + Point = chest.transform.position, + Label = "Storing " + Describe(), + }; + } + + // Every sealed chest is full - but a chest is not the only place a thing can go. A station + // that BURNS what is in hand is a destination too, and for the smith it is usually the + // right one: the charcoal kiln releases its whole batch in one go (verified in the IL - + // UpdateSmelter only calls SpawnProcessed once the ore queue empties), which is exactly the + // delivery a nearly full chest cannot absorb, and the coal it makes is what the furnace + // beside it is waiting for. Offering the load to a consumer before giving up is what turns + // "nowhere to put 20x Coal" into a full blast furnace. + // + // It comes AFTER the chest and not before, so a product still goes home to the chest that + // paid for it whenever there is room; this is the step before the floor, not instead of + // storing. + ButlerStation consumer = StationWanting(); + if (consumer != null) + { + return new Job + { + Kind = "deposit_station", + Target = consumer.Id, + Point = consumer.Position, + Label = "Loading " + Describe(), + }; + } + + // Nothing will take it. Beside the table it goes: a stalled chain is worse than a tidy + // floor, and nothing may vanish (sec. 7.3). + return new Job + { + Kind = "drop", + Target = ZDOID.None, + Point = anchor, + Label = "Nowhere to put " + Describe(), + }; + } + + /// The nearest station that will take something out of the payload, as material or as + /// fuel. No FreeSlots check, for the reason spelled out above the KeyTarget branch: fuel does + /// not go into a slot, and AcceptsAnything already asks the right question of both doors. + private ButlerStation StationWanting() + { + ButlerStation best = null; + float bestDistance = float.MaxValue; + + foreach (ButlerStation station in m_stations) + { + if (!station.Alive || IsPenalised(station.Id) || ClaimedByOther(station.Id)) continue; + if (!station.Operable || !AcceptsAnything(station)) continue; + + float distance = Vector3.Distance(transform.position, station.Position); + if (distance >= bestDistance) continue; + + bestDistance = distance; + best = station; + } + + return best; + } + + // ================================================================ execution + + private void Execute(float dt) + { + if (m_job == null) + { + SetStatus(m_stations.Count == 0 ? "Nothing to serve." : "Nothing to do."); + GoHome(dt); + return; + } + + SetStatus(m_job.Label); + + if (!MoveToPoint(dt, m_job.Point, ArriveDistance, m_job.Hurry)) + { + // Doors do not open for pathfinding. A target it cannot reach goes into the penalty box + // and the servant gets on with something it can do. + if (Time.time > m_jobDeadline) + { + Penalise(m_job.Target); + Jotunn.Logger.LogInfo($"[AlfarDrone] Could not reach {m_job.Kind} target; " + + "setting it aside for a few minutes."); + m_job = null; + m_nextPlan = 0f; + } + return; + } + + bool achieved; + switch (m_job.Kind) + { + case "load": achieved = DoLoad(); break; + case "fuel": achieved = DoFuel(); break; + case "collect": achieved = DoCollect(); break; + case "deposit_station": achieved = DoDepositStation(); break; + case "deposit": achieved = DoDeposit(); break; + case "drop": DropPayload(); achieved = true; break; + case "wait": achieved = true; break; + case "repair": achieved = DoRepair(); break; + case "farm": achieved = DoFarm(); break; + case "farm_finish": achieved = DoFarmFinish(); break; + case "sortfetch": achieved = DoSortFetch(); break; + default: achieved = true; break; + } + + // Arrived and nothing happened: the world moved while it walked. Set that target aside for + // twenty seconds so the next plan picks something else instead of re-deciding the same + // errand on every tick. + if (!achieved) PenaliseShort(m_job.Target); + + m_job = null; + m_nextPlan = 0f; // arriving changes the world; re-plan on the next tick rather than in 1.5 s + } + + /// At the chest: take what the chosen station will eat, and remember where it came from. + private bool DoLoad() + { + Container chest = ContainerById(m_job.Target); + if (chest == null) return false; + + // The station is chosen again here rather than carried on the job, because the walk took + // time and the world may have moved on. + ButlerStation station = null; + string item = null; + + foreach (ButlerStation candidate in m_stations) + { + if (!candidate.Alive || !candidate.Operable || candidate.FreeSlots <= 0) continue; + if (IsPenalised(candidate.Id)) continue; + + string found = FirstAccepted(candidate, chest); + if (found == null) continue; + + station = candidate; + item = found; + break; + } + + if (station == null || item == null) return false; + + int taken = TakeFrom(chest, item, station.FreeSlots); + if (taken <= 0) return false; + + AddToPayload(item, taken); + m_nview.GetZDO().Set(KeySource, ZdoOf(chest)); + m_nview.GetZDO().Set(KeyTarget, station.Id); + WritePayload(); + return true; + } + + /// At the chest, for fuel. Same shape as DoLoad, and kept separate because fuel goes in + /// through a different door and is never the thing being processed. + private bool DoFuel() + { + Container chest = ContainerById(m_job.Target); + if (chest == null) return false; + + foreach (ButlerStation station in m_stations) + { + if (!station.Alive || !station.Operable || IsPenalised(station.Id)) continue; + + int wanted = station.FuelWanted; + string fuel = station.FuelPrefab; + if (wanted <= 0 || string.IsNullOrEmpty(fuel)) continue; + + int taken = TakeFrom(chest, fuel, wanted); + if (taken <= 0) continue; + + AddToPayload(fuel, taken); + m_nview.GetZDO().Set(KeySource, ZdoOf(chest)); + m_nview.GetZDO().Set(KeyTarget, station.Id); + WritePayload(); + return true; + } + + return false; + } + + /// + /// At a station with something finished. Pull first, sweep second - and the sweep is the only + /// place the servant ever picks anything up off the ground, which is what keeps it from tidying + /// away things the player left lying about on purpose. + /// + /// THE ORDER IS THE POINT, and it used to be the other way round. Sweeping first meant every + /// visit collected what the LAST visit had thrown on the floor and then threw a fresh one down; + /// since Plan() hands the servant to PlanDelivery the moment it is carrying anything, it walked + /// off to the chest the instant the sweep landed and abandoned the item it had just pulled. + /// While a hearth kept working there was therefore always exactly one cooked meat lying on the + /// ground - the "loses one per batch, whether that is two or five" the testers reported. + /// + /// The loop is the other half of it. RPC_RemoveDoneItem empties ONE slot per call, so a hearth + /// with five done slots needs five calls; one per visit turned one batch into five round trips + /// to the chest. It runs against OutputPulls rather than against HasOutput alone because the + /// fermenter's Ready survives its own tap for the length of the animation. + /// + private bool DoCollect() + { + ButlerStation station = StationById(m_job.Target); + if (station == null || !station.Alive) return false; + + bool pulled = false; + for (int i = 0; i < station.OutputPulls && station.HasOutput; i++) + { + station.PullOutput(transform.position); + pulled = true; + } + + int before = PayloadCount(); + SweepDrops(station.Position); + bool swept = PayloadCount() > before; + + if (swept) + { + // The product belongs to whoever fed the station. If nothing was written there - the + // player loaded it by hand - it goes to the nearest sealed chest instead, which is the + // "yes, it collects your work too" decision paying its own way. + ZDOID fedBy = station.Nview.GetZDO().GetZDOID(KeyFedBy); + m_nview.GetZDO().Set(KeySource, fedBy); + m_nview.GetZDO().Set(KeyTarget, ZDOID.None); + WritePayload(); + } + + return swept || pulled; + } + + /// At the station, with raw material in hand. + private bool DoDepositStation() + { + ButlerStation station = StationById(m_job.Target); + if (station == null || !station.Alive || !station.Operable) return false; + + bool loadedAny = false; + + for (int i = m_payload.Count - 1; i >= 0; i--) + { + Load load = m_payload[i]; + + while (load.Count > 0 && station.FreeSlots > 0 && station.Accepts(load.Name)) + { + station.Add(load.Name); + load.Count--; + loadedAny = true; + } + + // Fuel goes in through its own door, and only for as long as it is wanted. + if (load.Count > 0 && load.Name == station.FuelPrefab) + { + int wanted = station.FuelWanted; + while (load.Count > 0 && wanted > 0) + { + station.AddFuel(); + load.Count--; + wanted--; + loadedAny = true; + } + } + + if (load.Count <= 0) m_payload.RemoveAt(i); + } + + if (loadedAny) + { + // Whoever fed it, gets it back. + ZDOID source = m_nview.GetZDO().GetZDOID(KeySource); + if (source != ZDOID.None && station.Nview.IsValid()) + { + if (!station.Nview.IsOwner()) station.Nview.ClaimOwnership(); + station.Nview.GetZDO().Set(KeyFedBy, source); + } + } + + if (m_payload.Count == 0) m_nview.GetZDO().Set(KeyTarget, ZDOID.None); + WritePayload(); + return loadedAny; + } + + /// At a chest, with the finished goods. + private bool DoDeposit() + { + Container chest = ContainerById(m_job.Target); + if (chest == null) return false; + + ZNetView nview = chest.GetComponent(); + if (nview == null || !nview.IsValid()) return false; + if (!nview.IsOwner()) nview.ClaimOwnership(); + + Inventory inventory = chest.GetInventory(); + if (inventory == null) return false; + + bool wrote = false; + + for (int i = m_payload.Count - 1; i >= 0; i--) + { + Load load = m_payload[i]; + + GameObject prefab = ObjectDB.instance != null + ? ObjectDB.instance.GetItemPrefab(load.Name) + : null; + if (prefab == null) continue; + + // One at a time: it stacks correctly, it stops exactly when the chest is full, and the + // counts are small enough that being tidy costs nothing. + while (load.Count > 0 && inventory.CanAddItem(prefab, 1) && inventory.AddItem(prefab, 1)) + { + load.Count--; + wrote = true; + } + + if (load.Count <= 0) m_payload.RemoveAt(i); + } + + if (wrote && ContainerSaveMethod != null) ContainerSaveMethod.Invoke(chest, null); + WritePayload(); + + // Still holding something: that chest is full, so do not choose it again on the next pass. + if (m_payload.Count > 0) Penalise(m_job.Target); + else m_nview.GetZDO().Set(KeyDest, ZDOID.None); + return wrote; + } + + // ================================================================ claims + + // Two drones must not take the same station or chest in the same moment. The Butler forbids a + // second table nearby; with N drones to a Nexus that is impossible, so the choice is made + // visible between them: a target is CLAIMED by the drone that picked it for a short while. This + // is the local-client form of the dispatcher the design asks for; two clients owning two + // drones still cannot see each other's claims (doc 17.14). + private static readonly Dictionary> s_claims = + new Dictionary>(); + private const float ClaimSeconds = 30f; + + private bool ClaimedByOther(ZDOID id) + { + if (id == ZDOID.None) return false; + KeyValuePair claim; + if (!s_claims.TryGetValue(id, out claim)) return false; + + if (claim.Key == null || Time.time >= claim.Value) { s_claims.Remove(id); return false; } + return claim.Key != this; + } + + private void Claim(ZDOID id) + { + if (id != ZDOID.None) s_claims[id] = new KeyValuePair(this, Time.time + ClaimSeconds); + } + + private void Release(ZDOID id) + { + KeyValuePair claim; + if (id != ZDOID.None && s_claims.TryGetValue(id, out claim) && claim.Key == this) s_claims.Remove(id); + } + + // ================================================================ repair + + /// + /// Anything damaged in the base, and any other drone that is hurt. Free, like the hammer. NOT the + /// constructs: their damage is permanent by design (they are Characters and not pieces, and + /// they are not drones, so they never come up here). + /// + private Job PlanRepair(Vector3 anchor) + { + WearNTear bestPiece = null; + AlfarDroneAI bestDrone = null; + float bestDistance = float.MaxValue; + + foreach (WearNTear wear in m_damaged) + { + if (wear == null) continue; + ZDOID id = ZdoOf(wear); + if (IsPenalised(id) || ClaimedByOther(id)) continue; + + float distance = Vector3.Distance(transform.position, wear.transform.position); + if (distance >= bestDistance) continue; + bestDistance = distance; + bestPiece = wear; + } + + foreach (AlfarDroneAI other in All) + { + if (other == null || other == this || other.m_character == null || other.m_character.IsDead()) continue; + if (other.m_character.GetHealth() >= other.m_character.GetMaxHealth() - 0.5f) continue; + if (Vector3.Distance(other.transform.position, anchor) > AlfarNexusConfig.NexusRadius.Value) continue; + + ZDOID id = ZdoOf(other); + if (IsPenalised(id) || ClaimedByOther(id)) continue; + + float distance = Vector3.Distance(transform.position, other.transform.position); + if (distance >= bestDistance) continue; + bestDistance = distance; + bestDrone = other; + bestPiece = null; + } + + if (bestPiece != null) + { + ZDOID id = ZdoOf(bestPiece); + return new Job { Kind = "repair", Target = id, Claim = id, Point = bestPiece.transform.position, Label = "Repairing" }; + } + if (bestDrone != null) + { + ZDOID id = ZdoOf(bestDrone); + return new Job { Kind = "repair", Target = id, Claim = id, Point = bestDrone.transform.position, Label = "Mending a drone" }; + } + return null; + } + + private bool DoRepair() + { + if (ZNetScene.instance == null) return false; + + GameObject go = ZNetScene.instance.FindInstance(m_job.Target); + if (go == null) return false; + + WearNTear wear = go.GetComponent(); + if (wear != null) return wear.Repair(); + + Character character = go.GetComponent(); + if (character != null && !character.IsDead() && go.GetComponent() != null) + { + character.Heal(character.GetMaxHealth(), true); + return true; + } + return false; + } + + // ================================================================ farming + + private class PlantInfo + { + public GameObject Sapling; // the piece that grows the plant + public string Item; // the item that piece costs, and so the item to put back + } + + // pickable prefab name -> the sapling that grows it and the item that sapling costs + private static readonly Dictionary s_plants = new Dictionary(); + private static bool s_plantsBuilt; + private static float s_pickScanAt = -99f; + private static readonly List s_pickables = new List(); + private static readonly System.Reflection.FieldInfo PickedField = AccessTools.Field(typeof(Pickable), "m_picked"); + + /// + /// Built from the game, not from a list: every Plant in ZNetScene names the pickable it grows + /// into and costs one of an item through its Piece. The drone ONLY works plants it can put back + /// (rule R2): it never harvests something it could not replant. + /// + private static void BuildPlants() + { + if (s_plantsBuilt || ZNetScene.instance == null) return; + s_plantsBuilt = true; + + foreach (GameObject prefab in ZNetScene.instance.m_prefabs) + { + if (prefab == null) continue; + + Plant plant = prefab.GetComponent(); + Piece piece = prefab.GetComponent(); + if (plant == null || piece == null || plant.m_grownPrefabs == null) continue; + if (piece.m_resources == null || piece.m_resources.Length == 0 || piece.m_resources[0].m_resItem == null) continue; + + string item = piece.m_resources[0].m_resItem.gameObject.name; + foreach (GameObject grown in plant.m_grownPrefabs) + { + if (grown != null && !s_plants.ContainsKey(grown.name)) + { + s_plants[grown.name] = new PlantInfo { Sapling = prefab, Item = item }; + } + } + } + Jotunn.Logger.LogInfo($"[AlfarDrone] {s_plants.Count} replantable crops known."); + } + + private static void RefreshPickables() + { + if (Time.time - s_pickScanAt < 4f) return; + s_pickScanAt = Time.time; + + s_pickables.Clear(); + s_pickables.AddRange(Object.FindObjectsByType(FindObjectsSortMode.None)); + } + + private static bool IsPicked(Pickable pickable) + { + return PickedField != null && (bool)PickedField.GetValue(pickable); + } + + /// Does picking it give back the item the sapling costs? + private static bool Yields(Pickable pickable, string item) + { + if (pickable.m_itemPrefab != null && pickable.m_itemPrefab.name == item) return true; + + if (pickable.m_extraDrops != null && pickable.m_extraDrops.m_drops != null) + { + foreach (DropTable.DropData drop in pickable.m_extraDrops.m_drops) + { + if (drop.m_item != null && drop.m_item.name == item) return true; + } + } + return false; + } + + private static string[] s_wild; + private static bool IsWildTarget(string prefabName) + { + if (s_wild == null) s_wild = AlfarNexusConfig.WildPickables.Value.Split(new[] { ',' }, System.StringSplitOptions.RemoveEmptyEntries); + foreach (string part in s_wild) + { + if (prefabName.IndexOf(part.Trim(), System.StringComparison.OrdinalIgnoreCase) >= 0) return true; + } + return false; + } + + /// + /// FARMING, with the iron rule (doc 9.4): a cultivated plant is harvested only if the drone can + /// replant one of what it gives; the replant is made RIGHT AWAY, in the SAME place, out of what + /// was just picked, and the rest is stored. Wild mushrooms, berry bushes and flowers on the list + /// are picked and NOT replanted (they grow back by themselves, and trees are never touched). + /// + private Job PlanFarm(Vector3 anchor) + { + BuildPlants(); + RefreshPickables(); + + float radius = AlfarNexusConfig.NexusRadius.Value; + Pickable best = null; + PlantInfo bestInfo = null; + float bestDistance = float.MaxValue; + + foreach (Pickable pickable in s_pickables) + { + if (pickable == null || !pickable.gameObject.activeInHierarchy) continue; + if (Vector3.Distance(pickable.transform.position, anchor) > radius) continue; + if (IsPicked(pickable)) continue; + + ZDOID id = ZdoOf(pickable); + if (id == ZDOID.None || IsPenalised(id) || ClaimedByOther(id)) continue; + + string name = Utils.GetPrefabName(pickable.gameObject); + PlantInfo info = null; + + if (pickable.m_respawnTimeMinutes > 0f) + { + if (!IsWildTarget(name)) continue; // wild and regrowing: only the listed ones + } + else + { + if (!s_plants.TryGetValue(name, out info) || !Yields(pickable, info.Item)) continue; + } + + float distance = Vector3.Distance(transform.position, pickable.transform.position); + if (distance >= bestDistance) continue; + + bestDistance = distance; + best = pickable; + bestInfo = info; + } + + if (best == null) return null; + + m_farmInfo = bestInfo; + ZDOID target = ZdoOf(best); + return new Job { Kind = "farm", Target = target, Claim = target, Point = best.transform.position, Label = "Harvesting" }; + } + + private bool DoFarm() + { + if (ZNetScene.instance == null) return false; + + GameObject go = ZNetScene.instance.FindInstance(m_job.Target); + Pickable pickable = go != null ? go.GetComponent() : null; + if (pickable == null || IsPicked(pickable)) return false; + + Humanoid hands = m_character as Humanoid; + if (hands == null) return false; + + Vector3 spot = pickable.transform.position; + Quaternion rot = pickable.transform.rotation; + + if (!pickable.Interact(hands, false, false)) return false; + + m_farmSpot = spot; + m_farmRot = rot; + m_farmReadyAt = Time.time + 0.8f; // the drops need a moment to land + return true; + } + + private bool DoFarmFinish() + { + Vector3? spot = m_farmSpot; + PlantInfo info = m_farmInfo; + m_farmSpot = null; + m_farmInfo = null; + if (spot == null) return false; + + SweepDrops(spot.Value); + + if (info != null) + { + // R6: the replant comes OUT OF what was just picked, never out of anyone's stock. + bool have = false; + foreach (Load load in m_payload) + { + if (load.Name == info.Item && load.Count > 0) { load.Count--; have = true; break; } + } + m_payload.RemoveAll(l => l.Count <= 0); + WritePayload(); + + if (have && info.Sapling != null) + { + Object.Instantiate(info.Sapling, spot.Value, m_farmRot); + } + else + { + Jotunn.Logger.LogWarning($"[AlfarDrone] Harvested a crop but found no '{info.Item}' to put back."); + } + } + + m_nview.GetZDO().Set(KeySource, ZDOID.None); + m_nview.GetZDO().Set(KeyTarget, ZDOID.None); + return true; + } + + // ================================================================ sorting + + private bool AnyStationAccepts(string prefabName) + { + foreach (ButlerStation station in m_stations) + { + if (!station.Alive || !station.Operable) continue; + if (station.Accepts(prefabName) || prefabName == station.FuelPrefab) return true; + } + return false; + } + + /// The storage chest that already holds this item and has room; else the first EMPTY one. + private Container DestinationFor(string prefabName) + { + GameObject prefab = ObjectDB.instance != null ? ObjectDB.instance.GetItemPrefab(prefabName) : null; + if (prefab == null) return null; + + Container firstEmpty = null; + foreach (Container chest in m_chests) + { + if (chest == null || chest.IsInUse()) continue; + + ZDOID id = ZdoOf(chest); + if (IsPenalised(id) || ClaimedByOther(id)) continue; + + Inventory inventory = chest.GetInventory(); + if (inventory == null || !inventory.CanAddItem(prefab, 1)) continue; + + if (inventory.GetAllItems().Count == 0) + { + if (firstEmpty == null) firstEmpty = chest; + continue; + } + + foreach (ItemDrop.ItemData item in inventory.GetAllItems()) + { + if (item != null && item.m_dropPrefab != null && item.m_dropPrefab.name == prefabName) return chest; + } + } + return firstEmpty; + } + + /// + /// Tidying the entry chest, last of all. What a station will take is the WORK QUEUE and stays; the + /// rest (and any wood, which is stock unless it is in the wood chest) goes to the chest that + /// already holds the same thing, or to an empty one. With nowhere to go it stays where it is. + /// + private Job PlanSort() + { + if (m_entry == null || m_entry.IsInUse()) return null; + + ZDOID entryId = ZdoOf(m_entry); + if (IsPenalised(entryId)) return null; + + Inventory inventory = m_entry.GetInventory(); + if (inventory == null) return null; + + string sigil = AlfarSigil.PrefabName; + foreach (ItemDrop.ItemData item in inventory.GetAllItems()) + { + if (item == null || item.m_dropPrefab == null) continue; + + string name = item.m_dropPrefab.name; + if (name == sigil) continue; + if (!IsWood(name) && AnyStationAccepts(name)) continue; + + Container destination = DestinationFor(name); + if (destination == null) continue; + + m_sortItem = name; + m_sortDest = ZdoOf(destination); + return new Job + { + Kind = "sortfetch", + Target = entryId, + Claim = m_sortDest, + Point = m_entry.transform.position, + Label = "Sorting " + name, + }; + } + return null; + } + + private bool DoSortFetch() + { + if (m_sortItem == null || m_sortDest == ZDOID.None) return false; + + Container entry = ContainerById(m_job.Target); + if (entry == null) return false; + + int taken = TakeFrom(entry, m_sortItem, 40); + if (taken <= 0) return false; + + AddToPayload(m_sortItem, taken); + m_nview.GetZDO().Set(KeyDest, m_sortDest); + m_nview.GetZDO().Set(KeyTarget, ZDOID.None); + WritePayload(); + return true; + } + + // ================================================================ moving + + /// Vanilla pathing, through the private MoveTo. True the moment it has arrived. + private bool MoveToPoint(float dt, Vector3 point, float distance, bool run) + { + if (m_ai == null || MoveToMethod == null) return true; // cannot walk: act in place + + m_moveArgs[0] = dt; + m_moveArgs[1] = point; + m_moveArgs[2] = distance; + m_moveArgs[3] = run; + + return (bool)MoveToMethod.Invoke(m_ai, m_moveArgs); + } + + private void GoHome(float dt) + { + Vector3? anchor = Anchor; + if (anchor == null) + { + if (m_ai != null) m_ai.StopMoving(); + return; + } + + MoveToPoint(dt, anchor.Value, m_homeDistance, false); + } + + // ================================================================ the ground + + private static int ItemMask() + { + if (s_itemMask >= 0) return s_itemMask; + + int mask = LayerMask.GetMask("item"); + s_itemMask = mask != 0 ? mask : ~0; + return s_itemMask; + } + + private bool HasDropsNear(Vector3 point) + { + Collider[] hits = Physics.OverlapSphere(point, CollectRadius, ItemMask()); + foreach (Collider hit in hits) + { + if (hit == null) continue; + ItemDrop drop = hit.GetComponentInParent(); + if (drop != null && drop.m_itemData != null) return true; + } + return false; + } + + /// + /// Picks up everything lying around a station. The drop is destroyed and its contents become + /// entries in the virtual payload, which is the same road the smelter's bars, the oven's bread + /// and the fermenter's bottles all arrive by - one pickup routine for three families. + /// + private void SweepDrops(Vector3 point) + { + Collider[] hits = Physics.OverlapSphere(point, CollectRadius, ItemMask()); + + foreach (Collider hit in hits) + { + if (hit == null) continue; + if (PayloadCount() >= PayloadCap) return; + + ItemDrop drop = hit.GetComponentInParent(); + if (drop == null || drop.m_itemData == null) continue; + + ZNetView nview = drop.GetComponent(); + if (nview == null || !nview.IsValid()) continue; + if (!nview.IsOwner()) nview.ClaimOwnership(); + + string name = drop.m_itemData.m_dropPrefab != null + ? drop.m_itemData.m_dropPrefab.name + : Utils.GetPrefabName(drop.gameObject); + if (string.IsNullOrEmpty(name)) continue; + + AddToPayload(name, Mathf.Max(1, drop.m_itemData.m_stack)); + if (ZNetScene.instance != null) ZNetScene.instance.Destroy(drop.gameObject); + } + } + + /// + /// Puts the virtual load back into the world as real objects. Called when the servant dies and + /// when there is nowhere left to put anything - the two ends of the same promise, which is that + /// nothing the player owns is ever deleted by this feature. + /// + public void DropPayload() + { + if (m_payload.Count == 0) return; + if (ObjectDB.instance == null) { m_payload.Clear(); return; } + + Vector3 at = transform.position + Vector3.up * 0.4f; + + foreach (Load load in m_payload) + { + GameObject prefab = ObjectDB.instance.GetItemPrefab(load.Name); + ItemDrop template = prefab != null ? prefab.GetComponent() : null; + if (template == null || template.m_itemData == null) continue; + + int left = load.Count; + int max = Mathf.Max(1, template.m_itemData.m_shared.m_maxStackSize); + + while (left > 0) + { + int stack = Mathf.Min(left, max); + + // ItemDrop.DropItem instantiates item.m_dropPrefab - a clone off a raw ObjectDB + // prefab does not carry that (see AswidBloodPotions.MakeFood for the same fix). + // Without this, dropping a payload throws instantiating null and never clears + // it, so the same broken load is retried - and crashes - on every AI tick after. + ItemDrop.ItemData clone = template.m_itemData.Clone(); + clone.m_dropPrefab = prefab; + + ItemDrop.DropItem(clone, stack, + at + Random.insideUnitSphere * 0.3f, Quaternion.identity); + left -= stack; + } + } + + m_payload.Clear(); + WritePayload(); + } + + // ================================================================ chests + + /// + /// Takes up to of a prefab out of a chest. The sigil is skipped by name, + /// which is the one thing in here that must never be got wrong: carrying it off would unmark the + /// chest halfway through a job. + /// + private int TakeFrom(Container chest, string prefabName, int want) + { + if (chest == null || want <= 0) return 0; + if (prefabName == AlfarSigil.PrefabName) return 0; + + ZNetView nview = chest.GetComponent(); + if (nview == null || !nview.IsValid()) return 0; + if (!nview.IsOwner()) nview.ClaimOwnership(); + + Inventory inventory = chest.GetInventory(); + if (inventory == null) return 0; + + List matches = new List(); + foreach (ItemDrop.ItemData item in inventory.GetAllItems()) + { + if (item == null || item.m_dropPrefab == null) continue; + if (item.m_dropPrefab.name != prefabName) continue; + matches.Add(item); + } + + int taken = 0; + foreach (ItemDrop.ItemData item in matches) + { + if (taken >= want) break; + + int amount = Mathf.Min(item.m_stack, want - taken); + if (amount <= 0) continue; + + inventory.RemoveItem(item, amount); + taken += amount; + } + + if (taken > 0 && ContainerSaveMethod != null) ContainerSaveMethod.Invoke(chest, null); + return taken; + } + + // The wood that may be burnt. Only the wood chest's wood is ever consumed: the same wood in the + // entry chest is stock to be sorted, never fuel or charcoal. + private static readonly HashSet s_woodFamily = new HashSet + { + "Wood", "FineWood", "RoundLog", "ElderBark", "YggdrasilWood", "Blackwood", + }; + + private static bool IsWood(string prefabName) => s_woodFamily.Contains(prefabName); + + /// + /// The first thing a station will take, and the chest it is in: raw material from the ENTRY chest + /// (never its wood), and wood only from the WOOD chest. + /// + private string FindMaterialFor(ButlerStation station, out Container chest) + { + foreach (Container candidate in new[] { m_entry, m_wood }) + { + if (candidate == null || candidate.IsInUse()) continue; + + string item = FirstAccepted(station, candidate); + if (item == null) continue; + + chest = candidate; + return item; + } + + chest = null; + return null; + } + + private string FirstAccepted(ButlerStation station, Container chest) + { + Inventory inventory = chest != null ? chest.GetInventory() : null; + if (inventory == null) return null; + + bool woodChest = chest == m_wood; + string sigil = AlfarSigil.PrefabName; + string fuel = station.FuelPrefab; + + foreach (ItemDrop.ItemData item in inventory.GetAllItems()) + { + if (item == null || item.m_dropPrefab == null) continue; + + string name = item.m_dropPrefab.name; + if (name == sigil) continue; + if (name == fuel) continue; // fuel has its own errand + if (IsWood(name) != woodChest) continue; // wood from the wood chest, the rest from the entry + if (!station.Accepts(name)) continue; + + return name; + } + + return null; + } + + /// Fuel: wood-type fuel from the wood chest, anything else (coal) from the entry chest. + private Container FindChestWith(string prefabName) + { + Container chest = IsWood(prefabName) ? m_wood : m_entry; + if (chest == null || chest.IsInUse()) return null; + + Inventory inventory = chest.GetInventory(); + if (inventory == null) return null; + + foreach (ItemDrop.ItemData item in inventory.GetAllItems()) + { + if (item != null && item.m_dropPrefab != null && item.m_dropPrefab.name == prefabName) return chest; + } + return null; + } + + /// + /// Where the finished goods go: back to the ENTRY chest, which is both the inbox and the outbox; + /// they are sorted from there. If it is full, the nearest storage chest with room. + /// + private Container ChestForProduct() + { + if (m_entry != null && !m_entry.IsInUse() && !IsPenalised(ZdoOf(m_entry)) && HasRoomFor(m_entry)) return m_entry; + + Container best = null; + float bestDistance = float.MaxValue; + + foreach (Container chest in m_chests) + { + if (chest == null || chest.IsInUse()) continue; + if (IsPenalised(ZdoOf(chest))) continue; + if (!HasRoomFor(chest)) continue; + + float distance = Vector3.Distance(transform.position, chest.transform.position); + if (distance >= bestDistance) continue; + + bestDistance = distance; + best = chest; + } + + return best; + } + + private bool HasRoomFor(Container chest) + { + Inventory inventory = chest != null ? chest.GetInventory() : null; + if (inventory == null || ObjectDB.instance == null) return false; + + foreach (Load load in m_payload) + { + GameObject prefab = ObjectDB.instance.GetItemPrefab(load.Name); + if (prefab != null && inventory.CanAddItem(prefab, 1)) return true; + } + + return false; + } + + // ================================================================ payload + + private bool AcceptsAnything(ButlerStation station) + { + foreach (Load load in m_payload) + { + if (station.Accepts(load.Name)) return true; + if (load.Name == station.FuelPrefab && station.FuelWanted > 0) return true; + } + return false; + } + + private void AddToPayload(string name, int count) + { + if (string.IsNullOrEmpty(name) || count <= 0) return; + + foreach (Load load in m_payload) + { + if (load.Name != name) continue; + load.Count += count; + WritePayload(); + return; + } + + m_payload.Add(new Load { Name = name, Count = count }); + WritePayload(); + } + + private int PayloadCount() + { + int total = 0; + foreach (Load load in m_payload) total += load.Count; + return total; + } + + private string Describe() + { + if (m_payload.Count == 0) return "nothing"; + if (m_payload.Count == 1) return m_payload[0].Count + "x " + m_payload[0].Name; + + return PayloadCount() + " items"; + } + + /// "Copper:8;Coal:12". Small, readable in a ZDO dump, and enough to survive a handover + /// mid-job - which is the whole reason the payload lives in the ZDO instead of in this class. + private void WritePayload() + { + if (m_nview == null || !m_nview.IsValid()) return; + + StringBuilder builder = new StringBuilder(); + foreach (Load load in m_payload) + { + if (load.Count <= 0) continue; + if (builder.Length > 0) builder.Append(';'); + builder.Append(load.Name).Append(':').Append(load.Count); + } + + m_nview.GetZDO().Set(KeyLoad, builder.ToString()); + } + + private void ReadPayload() + { + m_payload.Clear(); + if (m_nview == null || !m_nview.IsValid()) return; + + string raw = m_nview.GetZDO().GetString(KeyLoad, ""); + if (string.IsNullOrEmpty(raw)) return; + + foreach (string entry in raw.Split(';')) + { + if (string.IsNullOrEmpty(entry)) continue; + + int split = entry.LastIndexOf(':'); + if (split <= 0) continue; + + int count; + if (!int.TryParse(entry.Substring(split + 1), out count) || count <= 0) continue; + + m_payload.Add(new Load { Name = entry.Substring(0, split), Count = count }); + } + } + + // ================================================================ small change + + private static ZDOID ZdoOf(Component component) + { + ZNetView nview = component != null ? component.GetComponent() : null; + return nview != null && nview.IsValid() ? nview.GetZDO().m_uid : ZDOID.None; + } + + private Container ContainerById(ZDOID id) + { + if (id == ZDOID.None || ZNetScene.instance == null) return null; + + GameObject go = ZNetScene.instance.FindInstance(id); + return go != null ? go.GetComponent() : null; + } + + private ButlerStation StationById(ZDOID id) + { + foreach (ButlerStation station in m_stations) + { + if (station.Id == id) return station; + } + + if (id == ZDOID.None || ZNetScene.instance == null) return null; + + GameObject go = ZNetScene.instance.FindInstance(id); + return go != null ? ButlerStation.From(go) : null; + } + + private void Penalise(ZDOID id) + { + if (id == ZDOID.None) return; + m_penalties[id] = Time.time + PenaltySeconds; + } + + /// Never shortens a penalty already running: a target set aside for three minutes + /// because it could not be reached must not be let back in after twenty seconds. + private void PenaliseShort(ZDOID id) + { + if (id == ZDOID.None) return; + + float until; + float wanted = Time.time + ShortPenaltySeconds; + if (m_penalties.TryGetValue(id, out until) && until > wanted) return; + + m_penalties[id] = wanted; + } + + private bool IsPenalised(ZDOID id) + { + float until; + return m_penalties.TryGetValue(id, out until) && Time.time < until; + } + + private void ExpirePenalties() + { + if (m_penalties.Count == 0) return; + + List done = null; + foreach (KeyValuePair entry in m_penalties) + { + if (Time.time < entry.Value) continue; + if (done == null) done = new List(); + done.Add(entry.Key); + } + + if (done == null) return; + foreach (ZDOID id in done) m_penalties.Remove(id); + } + + /// Seconds this station has been waiting with work available. + private float NoteIdle(ZDOID id) + { + float since; + if (!m_idleSince.TryGetValue(id, out since)) + { + m_idleSince[id] = Time.time; + return 0f; + } + + return Time.time - since; + } + } + + /// + /// The whole of the servant's mind, in one prefix. + /// + /// Returning false skips MonsterAI.UpdateAI entirely - targeting, alerting, fleeing, wandering and + /// attacking with it - so the servant is peaceful by construction rather than by having its weapon + /// confiscated. __result is legitimate here and not the old PlacePiece trap: that one threw because + /// the patched method was VOID. This one returns bool, which is exactly what a prefix may write. + /// + /// Bound positionally (__0) so a parameter rename in a future patch cannot stop the mod from + /// applying its patches at startup. + /// + [HarmonyPatch(typeof(MonsterAI), "UpdateAI")] + public static class AlfarDroneUpdateAIPatch + { + public static bool Prefix(MonsterAI __instance, float __0, ref bool __result) + { + if (__instance == null) return true; + + AlfarDroneAI servant = __instance.GetComponent(); + if (servant == null) return true; + + // The one way back into vanilla: a servant that fights back hands over the whole tick for + // as long as there is a fight. Always false for the Bone Servants themselves. + if (servant.HandsToVanilla()) return true; + + __result = servant.Tick(__0); + return false; + } + } + + /// Hit and it walks home. The same postfix shape the sentry's regeneration uses, on the + /// same method, which is a shape known to work in this project. + [HarmonyPatch(typeof(Character), "Damage")] + public static class AlfarDroneDamagePatch + { + public static void Postfix(Character __instance) + { + if (__instance == null) return; + + AlfarDroneAI servant = __instance.GetComponent(); + if (servant != null) servant.NoteDamage(); + } + } +} diff --git a/JotunnModStub/Alfar/AlfarDrones.cs b/JotunnModStub/Alfar/AlfarDrones.cs new file mode 100644 index 0000000..7cef524 --- /dev/null +++ b/JotunnModStub/Alfar/AlfarDrones.cs @@ -0,0 +1,365 @@ +using System.Collections.Generic; +using HarmonyLib; +using Jotunn.Entities; +using Jotunn.Managers; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// The LJOSVAETTIR, the Alfar's drones (Alfar_Progettazione.txt sec. 9): a Deathsquito without legs, + /// stinger or buzz, bronze, with blue light. One kind of drone does every job (the work itself is + /// AlfarDroneWork); the only thing apart is the GRAFVAETTIR, the same creature thrown like a + /// grenade to dig the precious ores around a point for two minutes and then vanish. + /// + /// What a drone is by itself: 25 hp and a shield of 25, tamed, tied to its Ljoskjarne, and able to + /// defend itself with a lightning zap of 1 damage every two seconds. It never attacks anything + /// outside the Nexus's radius and never goes after anything: it is a worker, not a soldier. + /// + /// The Deathsquito is ONE skinned mesh with one material (probe, doc 16C P1): the legs are bones, so + /// they are hidden by scaling the bones to zero, and the blue is an emission on a bronze body, not + /// separate eyes and wings - a true repaint is still to do. + /// + public static class AlfarDrones + { + public const string DroneName = "AlfarDrone"; + public const string MinerName = "AlfarGrafvaettir"; + public const string ZapWeapon = "AlfarDroneZap"; + + private static readonly Color Bronze = new Color(1f, 0.62f, 0.25f, 1f); + private static readonly Color ElectricBlue = new Color(0.25f, 0.65f, 1f, 1f); + + public static void Register() + { + GameObject source = PrefabManager.Cache.GetPrefab("Deathsquito"); + if (source == null) + { + Jotunn.Logger.LogWarning("[Alfar] No 'Deathsquito' to build the drones from."); + return; + } + + bool zap = RegisterZap(source); + RegisterOne(source, DroneName, "$rov_creature_alfar_drone_name", zap, miner: false); + RegisterOne(source, MinerName, "$rov_creature_alfar_grafvaettir_name", zap, miner: true); + } + + /// The Deathsquito's sting turned into a zap: 1 lightning, every two seconds. + private static bool RegisterZap(GameObject deathsquito) + { + Humanoid humanoid = deathsquito.GetComponent(); + GameObject sting = humanoid != null && humanoid.m_defaultItems != null && humanoid.m_defaultItems.Length > 0 + ? humanoid.m_defaultItems[0] + : null; + if (sting == null) return false; + + GameObject weapon = PrefabManager.Instance.CreateClonedPrefab(ZapWeapon, sting); + if (weapon == null) return false; + + ItemDrop drop = weapon.GetComponent(); + if (drop == null || drop.m_itemData == null || drop.m_itemData.m_shared == null) return false; + + ItemDrop.ItemData.SharedData shared = drop.m_itemData.m_shared; + shared.m_name = "$rov_item_alfar_zap_name"; + + HitData.DamageTypes damage = default(HitData.DamageTypes); + damage.m_lightning = AlfarNexusConfig.DroneZapDamage.Value; + shared.m_damages = damage; + shared.m_aiAttackInterval = AlfarNexusConfig.DroneZapInterval.Value; + + ItemManager.Instance.AddItem(new CustomItem(weapon, fixReference: false)); + return true; + } + + private static void RegisterOne(GameObject source, string prefabName, string display, bool zap, bool miner) + { + GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(prefabName, source); + if (prefab == null) return; + + Character character = prefab.GetComponent(); + if (character != null) + { + character.m_name = display; + character.m_faction = Character.Faction.Players; + character.m_health = AlfarNexusConfig.DroneHealth.Value; + } + + Humanoid humanoid = prefab.GetComponent(); + if (humanoid != null) + { + GameObject weapon = zap ? PrefabManager.Instance.GetPrefab(ZapWeapon) : null; + // A miner does not fight at all; the worker only defends itself. + humanoid.m_defaultItems = !miner && weapon != null ? new[] { weapon } : new GameObject[0]; + humanoid.m_randomWeapon = new GameObject[0]; + humanoid.m_randomArmor = new GameObject[0]; + humanoid.m_randomShield = new GameObject[0]; + humanoid.m_randomSets = new Humanoid.ItemSet[0]; + } + + MonsterAI monster = prefab.GetComponent(); + if (monster != null) + { + monster.m_attackPlayerObjects = false; + monster.m_alertRange = AlfarNexusConfig.NexusRadius.Value; + monster.m_maxChaseDistance = AlfarNexusConfig.NexusRadius.Value; + } + + BaseAI ai = prefab.GetComponent(); + if (ai != null) ai.m_randomMoveRange = 5f; + + foreach (CharacterDrop drops in prefab.GetComponentsInChildren(true)) + { + if (drops != null) Object.DestroyImmediate(drops); + } + + // The buzz: the continuous sound child, and the flying loop effect. + foreach (Transform child in prefab.GetComponentsInChildren(true)) + { + if (child != null && child.name == "SFX") Object.DestroyImmediate(child.gameObject); + } + if (character != null) character.m_flyingContinuousEffect = new EffectList { m_effectPrefabs = new EffectList.EffectData[0] }; + + HideLegs(prefab); + Look(prefab); + prefab.AddComponent(); + + AlfarMark mark = prefab.AddComponent(); + mark.Role = miner ? "miner" : "drone"; + + AlfarCreatureShield shield = prefab.AddComponent(); + shield.MaxShield = AlfarNexusConfig.DroneHealth.Value; + shield.Shield = shield.MaxShield; + + if (miner) + { + // The mining drone has no anchor and no leash: it lives two minutes and vanishes. + prefab.AddComponent(); + } + else + { + // The worker is NOT a RaisedThrall: that brings the follow command on E, and a drone + // that can be walked out of the base stops working (the Butler's reasoning, Butler 9). + // AlfarDroneAI keeps its own anchor to the Nexus and its own wither. + AlfarDroneAI work = prefab.AddComponent(); + work.m_fightsBack = true; // it defends itself with the zap + work.m_homeDistance = 4f; + } + + PrefabManager.Instance.AddPrefab(prefab); + Jotunn.Logger.LogInfo($"[Alfar] Registered '{prefabName}'."); + } + + /// + /// No legs: the mesh is one skinned body, so the leg bones are scaled to zero and take their + /// part of the mesh with them. The stinger has no bone of its own and is left (doc 16C P1). + /// + private static void HideLegs(GameObject prefab) + { + foreach (Transform bone in prefab.GetComponentsInChildren(true)) + { + string n = bone.name; + if (n == "L.leg1" || n == "R.leg1") bone.localScale = Vector3.zero; + } + } + + private static void Look(GameObject prefab) + { + foreach (Renderer renderer in prefab.GetComponentsInChildren(true)) + { + Material[] materials = renderer.materials; + foreach (Material material in materials) + { + if (material == null) continue; + if (material.HasProperty("_Color")) material.color = Bronze; + if (material.HasProperty("_EmissionColor")) + { + material.SetColor("_EmissionColor", ElectricBlue * 0.15f); + material.EnableKeyword("_EMISSION"); + } + } + renderer.materials = materials; + } + foreach (Light light in prefab.GetComponentsInChildren(true)) light.color = ElectricBlue; + } + + /// + /// The same look, applied to the LIVE body at spawn and re-applied after the animator every + /// frame for the bones: edits made on the registered clone may not reach the instance, and the + /// animator can write the leg scale back. + /// + public class AlfarDroneLook : MonoBehaviour + { + private Transform[] legs; + + private void Awake() + { + var list = new System.Collections.Generic.List(); + foreach (Transform bone in GetComponentsInChildren(true)) + { + if (bone.name == "L.leg1" || bone.name == "R.leg1") list.Add(bone); + } + legs = list.ToArray(); + Look(gameObject); + } + + private void LateUpdate() + { + foreach (Transform leg in legs) if (leg != null) leg.localScale = Vector3.zero; + } + } + + // ─── Counting and spawning ─────────────────────────────────────────── + + public static int CountAlive(Vector3 anchor) + { + int count = 0; + foreach (AlfarDroneAI drone in AlfarDroneAI.All) + { + if (drone != null && drone.IsBoundTo(anchor)) count++; + } + return count; + } + + public static bool Spawn(Vector3 anchor) + { + GameObject prefab = ZNetScene.instance != null ? ZNetScene.instance.GetPrefab(DroneName) : null; + if (prefab == null) + { + Jotunn.Logger.LogWarning($"[Alfar] No '{DroneName}' in ZNetScene: no drone can be made."); + return false; + } + + Vector3 where = AlfarConstructs.SpawnSpot(anchor) + Vector3.up * 1.5f; + GameObject spawned = Object.Instantiate(prefab, where, Quaternion.identity); + AlfarDroneAI work = spawned != null ? spawned.GetComponent() : null; + if (work != null) work.Bind(anchor); + return spawned != null; + } + } + + /// + /// A MINING DRONE: thrown to a point, it digs the precious ores around that point for a fixed time + /// and then vanishes (design sec. 9.3). It takes over its own AI tick like the Butler's servants do + /// (a prefix on MonsterAI.UpdateAI), flies to the nearest deposit on the list and strikes it with + /// pickaxe damage at a tool tier high enough for any of them. The ore falls where it stands. + /// + /// Whatever it breaks is on the list in AlfarMiner.Deposits; a name list in the config so a + /// wrong or missing name is a config edit, not a rebuild. + /// + public class AlfarMiner : MonoBehaviour + { + public Vector3 Centre; + public float Radius = 12f; + public float LiveSeconds = 120f; + + private float born; + private float nextStrike; + private Component target; + + private static readonly System.Reflection.MethodInfo MoveToMethod = + AccessTools.Method(typeof(BaseAI), "MoveTo", new[] { typeof(float), typeof(Vector3), typeof(float), typeof(bool) }); + + private void Start() + { + born = Time.time; + } + + public bool Tick(MonsterAI ai, float dt) + { + if (Time.time - born >= LiveSeconds) + { + ZNetView nview = GetComponent(); + if (nview != null && nview.IsValid() && nview.IsOwner()) ZNetScene.instance.Destroy(gameObject); + return true; + } + + if (target == null || !target.gameObject.activeInHierarchy) target = FindDeposit(); + if (target == null) { ai.StopMoving(); return true; } + + Vector3 point = target.transform.position; + float distance = Vector3.Distance(transform.position, point); + + if (distance > 3.5f) + { + if (MoveToMethod != null) MoveToMethod.Invoke(ai, new object[] { dt, point + Vector3.up * 1.5f, 2f, true }); + return true; + } + + ai.StopMoving(); + if (Time.time < nextStrike) return true; + nextStrike = Time.time + 1f; + Strike(target); + return true; + } + + private static string[] names; + private static string[] Deposits => names ?? (names = AlfarNexusConfig.MinerDeposits.Value.Split( + new[] { ',' }, System.StringSplitOptions.RemoveEmptyEntries)); + + private bool IsPrecious(string prefabName) + { + foreach (string wanted in Deposits) + { + if (prefabName.IndexOf(wanted.Trim(), System.StringComparison.OrdinalIgnoreCase) >= 0) return true; + } + return false; + } + + private Component FindDeposit() + { + Component best = null; + float bestDistance = float.MaxValue; + foreach (Collider collider in Physics.OverlapSphere(Centre, Radius, ~0, QueryTriggerInteraction.Ignore)) + { + Component deposit = collider.GetComponentInParent(); + if (deposit == null) deposit = collider.GetComponentInParent(); + if (deposit == null) deposit = collider.GetComponentInParent(); + if (deposit == null) continue; + + string prefabName = Utils.GetPrefabName(deposit.gameObject); + if (!IsPrecious(prefabName)) continue; + + float distance = Vector3.Distance(transform.position, deposit.transform.position); + if (distance < bestDistance) { best = deposit; bestDistance = distance; } + } + return best; + } + + private void Strike(Component deposit) + { + IDestructible destructible = deposit as IDestructible; + if (destructible == null) return; + + HitData hit = new HitData(); + hit.m_damage.m_pickaxe = AlfarNexusConfig.MinerDamage.Value; + hit.m_toolTier = 100; + hit.m_dodgeable = false; + hit.m_blockable = false; + hit.m_point = deposit.transform.position; + hit.m_dir = (deposit.transform.position - transform.position).normalized; + + // MineRock5 picks the piece of the rock to hurt from the collider that was hit. + Collider collider = deposit.GetComponentInChildren(); + if (collider != null) + { + hit.m_hitCollider = collider; + hit.m_point = collider.bounds.center; + } + + destructible.Damage(hit); + } + + [HarmonyPatch(typeof(MonsterAI), "UpdateAI")] + public static class Alfar_Miner_UpdateAI_Patch + { + public static bool Prefix(MonsterAI __instance, float __0, ref bool __result) + { + if (__instance == null) return true; + AlfarMiner miner = __instance.GetComponent(); + if (miner == null) return true; + + __result = miner.Tick(__instance, __0); + return false; + } + } + } +} diff --git a/JotunnModStub/Alfar/AlfarEitr.cs b/JotunnModStub/Alfar/AlfarEitr.cs new file mode 100644 index 0000000..5d79655 --- /dev/null +++ b/JotunnModStub/Alfar/AlfarEitr.cs @@ -0,0 +1,166 @@ +using System.Reflection; +using HarmonyLib; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// The Alfar's one resource (Alfar_Progettazione.txt sec. 3, 4 and 5.1): food becomes eitr, and + /// eitr is the shield. + /// + /// Every signature and call order here was read from assembly_valheim.dll (doc sec. 16B V1-V4), + /// not remembered: + /// - Character.ApplyDamage is the single final stage for direct hits, burning and poison + /// ticks AND falls, so one prefix on it covers all three; + /// - Player.RPC_UseEitr spends eitr and arms the vanilla regeneration delay, which is the + /// only brake the shield has - writing m_eitr by hand would skip the delay; + /// - Player.GetTotalFoodValue is what UpdateFood hands to SetMaxEitr. + /// + public static class AlfarEitr + { + private static readonly MethodInfo UseEitrRpc = + AccessTools.Method(typeof(Player), "RPC_UseEitr", new[] { typeof(long), typeof(float) }); + + /// + /// Spends eitr WITHOUT Game.m_eitrRate scaling, so the rate is exactly the configured one. + /// UseEitr would multiply by the world modifier first; the RPC does not, and it is what + /// arms the regeneration delay (V3). + /// + public static void Spend(Player player, float amount) + { + if (player == null || amount <= 0f) return; + + if (UseEitrRpc == null) + { + Jotunn.Logger.LogWarning("[Alfar] Player.RPC_UseEitr not found: the shield cannot spend eitr."); + return; + } + UseEitrRpc.Invoke(player, new object[] { 0L, amount }); + } + + // ─── Diet ──────────────────────────────────────────────────────────── + + /// + /// Each food adds min(hp, stamina) to the maximum eitr, on top of the eitr it already has. + /// Clarified by the user: the minimum is between hp and stamina ONLY, so a plain cooked + /// meat (40 / 30 / 0) is worth +30 eitr and a balanced food is better than a lopsided one. + /// + /// Locally only: GetTotalFoodValue is the owner's own bookkeeping. Positional parameters + /// (guide 5.16): __0 hp, __1 stamina, __2 eitr. + /// + [HarmonyPatch(typeof(Player), "GetTotalFoodValue")] + public static class Alfar_FoodValue_Patch + { + public static void Postfix(Player __instance, ref float __2) + { + if (__instance == null || !AlfarVisuals.IsAlfarPlayer(__instance)) return; + + float bonus = 0f; + foreach (Player.Food food in __instance.GetFoods()) + { + bonus += Mathf.Min(food.m_health, food.m_stamina); + } + + __2 += bonus * AlfarConfig.DietMultiplier.Value; + } + } + + // ─── Shield and soft fall ──────────────────────────────────────────── + + /// + /// Blows land on the eitr first, 1 for 1. + /// + /// - No cooldown: the shield absorbs for as long as one point of eitr remains. + /// - Lightning and spirit cost double (the cost, not the damage: DamageModifier.Weak is a + /// flat +50% and cannot be made to double anything). + /// - A blow bigger than the pool is shared out: the eitr takes the share it can, the body + /// takes the rest. + /// - Drowning and the edge of the world skip the shield altogether; falls are free while + /// there is eitr and shielded like anything else once there is none left. + /// + /// The prefix edits the HitData and lets ApplyDamage run: with nothing left in it, + /// ApplyDamage returns at once ("took no damage"). Positional parameters, and the argument + /// types are in the attribute so the patch binds to the real overload (guide 5.16). + /// + [HarmonyPatch(typeof(Character), "ApplyDamage", + new[] { typeof(HitData), typeof(bool), typeof(bool), typeof(HitData.DamageModifier) })] + public static class Alfar_ApplyDamage_Patch + { + public static void Prefix(Character __instance, HitData __0) + { + Player player = __instance as Player; + if (player == null || __0 == null) return; + if (!AlfarVisuals.IsAlfarPlayer(player)) return; + + // The shield belongs to whoever owns the body: ApplyDamage runs on the owner, and a + // remote copy must not spend eitr it does not hold. + ZNetView nview = player.GetComponent(); + if (nview == null || !nview.IsValid() || !nview.IsOwner()) return; + + // The same early exits ApplyDamage has: nothing to absorb, nothing to spend. + if (player.IsDead() || player.IsTeleporting() || player.InCutscene() || player.InGodMode()) return; + + // Just arrived by Heimkall: nothing hurts for a few seconds, or a burning death would + // simply repeat at the bed. + if (Time.time < AlfarHeimkall.InvulnerableUntil) + { + __0.m_damage = default(HitData.DamageTypes); + return; + } + + // In the archon form the pool IS the defence: it takes every blow, drowning and the + // edge of the world included, and the eitr is already spent (AlfarArchon). + if (AlfarArchon.Active) + { + AlfarArchon.Absorb(player, __0); + return; + } + + HitData.HitType type = __0.m_hitType; + if (type == HitData.HitType.Drowning || type == HitData.HitType.EdgeOfWorld) return; + + float available = player.GetEitr(); + + if (type == HitData.HitType.Fall && AlfarConfig.SoftFall.Value) + { + // Soft fall: free while there is eitr, a normal fall once there is none. + if (available > 0f) __0.m_damage = default(HitData.DamageTypes); + return; + } + + float cost = Cost(__0.m_damage); + if (cost <= 0f || available <= 0f) return; + + if (available >= cost) + { + Spend(player, cost); + __0.m_damage = default(HitData.DamageTypes); + return; + } + + // Shared out: the eitr absorbs the fraction it can pay for, the body takes the rest. + float covered = available / cost; + HitData.DamageTypes remaining = __0.m_damage; + remaining.Modify(1f - covered); + __0.m_damage = remaining; + Spend(player, available); + } + + /// + /// The eitr a blow costs. Every damage type that wounds a person counts; chop and + /// pickaxe are tool damage (trees, rocks) and do not. Lightning and spirit are doubled. + /// + private static float Cost(HitData.DamageTypes damage) + { + float rate = AlfarConfig.ShieldRate.Value; + float conductive = AlfarConfig.ConductiveMultiplier.Value; + + float ordinary = damage.m_damage + damage.m_blunt + damage.m_slash + damage.m_pierce + + damage.m_fire + damage.m_frost + damage.m_poison; + float double_ = damage.m_lightning + damage.m_spirit; + + return (ordinary + double_ * conductive) * rate; + } + } + } +} diff --git a/JotunnModStub/Alfar/AlfarHeimkall.cs b/JotunnModStub/Alfar/AlfarHeimkall.cs new file mode 100644 index 0000000..49a7dc4 --- /dev/null +++ b/JotunnModStub/Alfar/AlfarHeimkall.cs @@ -0,0 +1,171 @@ +using System.Globalization; +using HarmonyLib; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// HEIMKALL: a lethal blow does not kill an Alfr, it sends them to their bed with one hit point + /// (Alfar_Progettazione.txt sec. 6). Then a wait: 20 minutes, 15 after Yagluth, 10 after Fader. + /// Inside the wait a lethal blow kills like it does anyone. + /// + /// HOW IT AVOIDS DEATH (read from the IL, doc sec. 16B V5): + /// Character.ApplyDamage ends with the health at zero, and the death itself is not decided + /// there but in Character.CheckDeath, which Character.CustomFixedUpdate calls on its next step. + /// So a POSTFIX on ApplyDamage that puts one hit point back, the same frame, means the check + /// finds a living body and there is no death routine, no tomb, no skill loss, no message. + /// + /// The timer lives in m_customData as a world-time stamp, so it survives a logout. + /// + public static class AlfarHeimkall + { + private const string TimerKey = "Alfar_HeimkallAt"; + + /// Time.time until which nothing may hurt the local Alfr (the arrival grace). + public static float InvulnerableUntil; + + // ─── The timer ─────────────────────────────────────────────────────── + + /// The cooldown for the current boss progress, in seconds. + public static float CooldownSeconds() + { + int state = BossProgressionManager.GetCurrentProgressionState(); + float minutes = state >= 8 ? AlfarConfig.HeimkallMinutesAfterFader.Value + : state >= 6 ? AlfarConfig.HeimkallMinutesAfterYagluth.Value + : AlfarConfig.HeimkallMinutes.Value; + return minutes * 60f; + } + + /// Seconds left before the next Heimkall; 0 when it is ready. + public static float Remaining(Player player) + { + if (player == null || player.m_customData == null || ZNet.instance == null) return 0f; + if (!player.m_customData.TryGetValue(TimerKey, out string stamp)) return 0f; + if (!double.TryParse(stamp, NumberStyles.Float, CultureInfo.InvariantCulture, out double at)) return 0f; + + double elapsed = ZNet.instance.GetTimeSeconds() - at; + + // A stamp from a different world (its clock is another clock) reads as the future, or as + // a wait longer than any cooldown. Either way the timer is not this world's: ready. + float cooldown = CooldownSeconds(); + if (elapsed < 0d || elapsed > 1e9) return 0f; + + return Mathf.Max(0f, cooldown - (float)elapsed); + } + + public static bool IsReady(Player player) => Remaining(player) <= 0f; + + public static void StartTimer(Player player) + { + if (player == null || ZNet.instance == null) return; + player.m_customData[TimerKey] = + ZNet.instance.GetTimeSeconds().ToString("R", CultureInfo.InvariantCulture); + } + + public static void ResetTimer(Player player) + { + if (player != null && player.m_customData != null) player.m_customData.Remove(TimerKey); + AlfarStatusEffects.ClearTimer("heimkall"); + } + + private static float nextIconSync; + + /// + /// Keeps the on-screen Heimkall countdown honest: status effects are not saved, so after a + /// reload the wait is put back on screen with what is really left of it, and removed when over. + /// + public static void SyncIcon(Player player) + { + if (Time.time < nextIconSync) return; + nextIconSync = Time.time + 2f; + + float left = Remaining(player); + bool shown = AlfarStatusEffects.HasTimer("heimkall"); + if (left > 0f && !shown) AlfarStatusEffects.ShowTimer("heimkall", left); + else if (left <= 0f && shown) AlfarStatusEffects.ClearTimer("heimkall"); + } + + // ─── The call home ─────────────────────────────────────────────────── + + /// + /// Teleports to the bed (or the world spawn when there is none) at one hit point, clears what + /// was killing the body, and starts the wait. Returns false when it is not ready. + /// + public static bool TryTrigger(Player player, string reason, bool force = false) + { + // force: the archon form ends with a Heimkall that it already paid for at the start. + if (player == null || (!force && !IsReady(player))) return false; + + bool bed; + Vector3 destination = FindDestination(out bed); + + // distantTeleport tells Valheim to stream the destination zone in first. Anything past a + // couple of zone-widths needs it. + bool distant = Vector3.Distance(player.transform.position, destination) > 100f; + bool teleported = player.TeleportTo(destination, player.transform.rotation, distant); + + // Whether or not the teleport was accepted (it refuses for two seconds after another + // one), the body must not die this frame. + player.SetHealth(1f); + + // What was killing the body goes with it: burning, poison, the cold, being wet. Cleared + // before the passive is put back, since RemoveAll takes that too. + player.GetSEMan().RemoveAllStatusEffects(true); + AlfarStatusEffects.Ensure(player); + + InvulnerableUntil = Time.time + AlfarConfig.HeimkallInvulnerableSeconds.Value; + StartTimer(player); + AlfarStatusEffects.ShowTimer("heimkall", CooldownSeconds()); + + Jotunn.Logger.LogInfo($"[Alfar] Heimkall ({reason}): teleported={teleported} to {destination}; " + + $"next in {CooldownSeconds() / 60f:0} min."); + player.Message(MessageHud.MessageType.Center, ModText.Get(bed ? "rov_msg_alfar_heimkall" : "rov_msg_alfar_heimkall_nobed")); + return true; + } + + /// + /// The bed the player set, else the world's original spawn. A bed point already has its height; + /// the world spawn is stored with a placeholder height (50), so its ground is worked out from the + /// world generator, which answers even when the zone there is not loaded yet - the first version + /// stood the Alfr at 50.5 m in the air or inside a hill. A bed counts only after the player has + /// SET it (sleeping in it, or interacting with it); an unused bed is not a spawn point. + /// + private static Vector3 FindDestination(out bool bed) + { + PlayerProfile profile = Game.instance != null ? Game.instance.GetPlayerProfile() : null; + + bed = profile != null && profile.HaveCustomSpawnPoint(); + if (bed) return profile.GetCustomSpawnPoint() + Vector3.up * 0.5f; + + Vector3 point = PlayerProfile.m_originalSpawnPoint; + if (WorldGenerator.instance != null) + { + float ground = WorldGenerator.instance.GetHeight(point.x, point.z); + point.y = Mathf.Max(ground, 30f) + 1f; // 30 is the sea level: never under the water + } + return point; + } + + // ─── The patch ─────────────────────────────────────────────────────── + + /// + /// After the blow has landed: if it left the body at zero, call it home instead. The shield + /// prefix has already taken what it could, so this only fires for the blow the eitr could + /// not cover (or a fall at eitr zero, a drowning, the edge of the world). + /// + [HarmonyPatch(typeof(Character), "ApplyDamage", + new[] { typeof(HitData), typeof(bool), typeof(bool), typeof(HitData.DamageModifier) })] + public static class Alfar_Heimkall_Patch + { + public static void Postfix(Character __instance) + { + Player player = __instance as Player; + if (player == null || player != Player.m_localPlayer) return; + if (!AlfarVisuals.IsAlfarPlayer(player)) return; + if (player.IsDead() || player.GetHealth() > 0f) return; + + TryTrigger(player, "lethal blow"); + } + } + } +} diff --git a/JotunnModStub/Alfar/AlfarLevitation.cs b/JotunnModStub/Alfar/AlfarLevitation.cs new file mode 100644 index 0000000..77f6b9d --- /dev/null +++ b/JotunnModStub/Alfar/AlfarLevitation.cs @@ -0,0 +1,120 @@ +using HarmonyLib; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// LEVITATION (Alfar_Progettazione.txt sec. 4.6): in the air, hold the jump key and the Alfr rises + /// slowly, burning eitr slowly. Let go and the soft fall takes over. + /// + /// There is no hover in vanilla. This pushes the rigidbody's vertical speed up toward a small + /// target while the key is held, and nothing else: no horizontal speed is added, so it is a way + /// over a ledge or out of a pit and not flight (the pool of an early Alfr lasts about half a + /// minute of it). + /// + /// It runs on the owner's FixedUpdate, where the rigidbody is read, and the position syncs like + /// any other movement. The eitr is spent in small batches, not every physics step: each spend arms + /// the regeneration delay and goes through an RPC call. + /// + public static class AlfarLevitation + { + // A short moment in the air before it starts, so a normal jump (a tap) is just a jump. + private const float AirDelay = 0.2f; + private const float SpendInterval = 0.25f; + + private static float airTime; + private static float owed; + private static float nextSpend; + + public static bool Rising { get; private set; } + + [HarmonyPatch(typeof(Player), "FixedUpdate")] + public static class Alfar_Levitation_Patch + { + public static void Postfix(Player __instance) + { + if (__instance == null || __instance != Player.m_localPlayer) return; + if (!AlfarVisuals.IsAlfarPlayer(__instance) || __instance.IsDead()) { Reset(); return; } + + // THE ARCHON FLIES for as long as the form lasts: it hovers where it is, climbs while + // jump is held and sinks while crouch is held. The eitr is already gone, so nothing is + // spent. Horizontal movement stays the normal controls. + if (AlfarArchon.Active) + { + Rigidbody flyer = Traverse.Create(__instance).Field("m_body").GetValue(); + if (flyer != null) + { + float speed = AlfarPowerConfig.LevitationRise.Value * 2f; + float target = 0f; + if (Time.time - AlfarArchon.StartedAt < 0.6f) target = 4f; // lift off + else if (RaceInput.Allowed && JumpHeld()) target = speed; + else if (RaceInput.Allowed && ZInput.GetButton("Crouch")) target = -speed; + + Vector3 velocity = flyer.linearVelocity; + velocity.y = Mathf.Lerp(velocity.y, target, 0.25f); + flyer.linearVelocity = velocity; + } + Traverse.Create(__instance).Field("m_maxAirAltitude").SetValue(__instance.transform.position.y); + Rising = true; + return; + } + + bool wants = RaceInput.Allowed && JumpHeld(); + bool airborne = !__instance.IsOnGround() && !__instance.IsSwimming() && !__instance.IsAttached() && + !__instance.IsFlying(); + + airTime = airborne ? airTime + Time.fixedDeltaTime : 0f; + + float cost = AlfarPowerConfig.LevitationCostPerSecond.Value; + bool canPay = AlfarArchon.Active || __instance.GetEitr() > 0f; + + if (!wants || !airborne || airTime < AirDelay || !canPay) + { + Rising = false; + FlushSpend(__instance); + return; + } + + Rising = true; + + Rigidbody body = Traverse.Create(__instance).Field("m_body").GetValue(); + if (body != null) + { + Vector3 velocity = body.linearVelocity; + velocity.y = Mathf.Lerp(velocity.y, AlfarPowerConfig.LevitationRise.Value, 0.25f); + body.linearVelocity = velocity; + } + + // Rising resets the fall: the point of the soft fall is that the way down starts at + // the top, and a long climb must not count as a long drop at eitr zero. + Traverse.Create(__instance).Field("m_maxAirAltitude").SetValue(__instance.transform.position.y); + + // In the archon form the eitr is already gone and the pool pays for nothing here. + if (!AlfarArchon.Active) owed += cost * Time.fixedDeltaTime; + if (Time.time >= nextSpend) FlushSpend(__instance); + } + } + + private static bool JumpHeld() + { + // ZInput's "Jump" covers the space bar and the pad's jump button alike, and respects the + // controls the player picked in the settings. + return ZInput.GetButton("Jump"); + } + + private static void FlushSpend(Player player) + { + nextSpend = Time.time + SpendInterval; + if (owed <= 0f) return; + AlfarEitr.Spend(player, owed); + owed = 0f; + } + + private static void Reset() + { + airTime = 0f; + owed = 0f; + Rising = false; + } + } +} diff --git a/JotunnModStub/Alfar/AlfarLjosgard.cs b/JotunnModStub/Alfar/AlfarLjosgard.cs new file mode 100644 index 0000000..e70c5cb --- /dev/null +++ b/JotunnModStub/Alfar/AlfarLjosgard.cs @@ -0,0 +1,108 @@ +using System.Collections.Generic; +using Jotunn.Configs; +using Jotunn.Entities; +using Jotunn.Managers; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// The LJOSGARD, the garden of light (Alfar_Progettazione.txt sec. 8.6 and 12): the module of the + /// Nexus that mixes the two mushrooms of the Mistlands into SAP, very slowly. + /// + /// It is a clone of the stone furnace with its recipe turned: MAGECAP is the "ore" and JOTUN PUFFS + /// the "fuel", one of each per sap, so mixing the two is exactly what a smelter already does with + /// its two inputs. Being a Smelter it needs no new code to be served: the drones feed it (a + /// Smelter-family station) and carry the sap away, and the refinery (vanilla, sap as fuel and soft + /// tissue as ore) is served by them too. Output falls where a furnace's does. + /// + public static class AlfarLjosgard + { + public const string PieceName = "AlfarLjosgard"; + public const string PieceDisplay = "$rov_piece_alfar_ljosgard_name"; + + public static void Register() + { + GameObject source = PrefabManager.Cache.GetPrefab("smelter"); + ItemDrop magecap = PrefabManager.Cache.GetPrefab("MushroomMagecap"); + ItemDrop puffs = PrefabManager.Cache.GetPrefab("MushroomJotunPuffs"); + ItemDrop sap = PrefabManager.Cache.GetPrefab("Sap"); + + if (source == null || magecap == null || puffs == null || sap == null) + { + Jotunn.Logger.LogWarning("[Alfar] The Ljosgard needs the 'smelter' piece and the Magecap, Jotun Puffs and Sap items: not registered."); + return; + } + + GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(PieceName, source); + if (prefab == null) return; + + // The furnace's heat and its fire: the Ljosgard is cool to the touch (guide 5.1). + AswidBloodRefinery.StripOffensive(prefab, "Ljosgard"); + + Smelter smelter = prefab.GetComponent(); + if (smelter == null) + { + Jotunn.Logger.LogWarning("[Alfar] The cloned smelter has no Smelter component: no Ljosgard."); + return; + } + + smelter.m_name = PieceDisplay; + smelter.m_conversion = new List + { + new Smelter.ItemConversion { m_from = magecap, m_to = sap }, + }; + smelter.m_fuelItem = puffs; + smelter.m_fuelPerProduct = 1; + smelter.m_maxOre = AlfarNexusConfig.GardCapacity.Value; + smelter.m_maxFuel = AlfarNexusConfig.GardCapacity.Value; + smelter.m_secPerProduct = AlfarNexusConfig.GardSecondsPerSap.Value; + smelter.m_requiresRoof = false; + smelter.m_spawnStack = false; + smelter.m_windmill = null; + + AlfarConstructs.Tint(prefab, new Color(0.55f, 0.85f, 0.7f, 1f)); + + Piece piece = prefab.GetComponent(); + if (piece == null) { Jotunn.Logger.LogWarning("[Alfar] The cloned smelter has no Piece."); return; } + + piece.m_craftingStation = null; + piece.m_name = PieceDisplay; + piece.m_description = "$rov_piece_alfar_ljosgard_desc"; + + PieceManager.Instance.AddPiece(new CustomPiece(prefab, fixReference: false, new PieceConfig + { + Name = PieceDisplay, + Description = "$rov_piece_alfar_ljosgard_desc", + PieceTable = PieceTables.Hammer, + Category = PieceCategories.Crafting, + Icon = piece.m_icon, + Requirements = new[] + { + new RequirementConfig("Bronze", AlfarNexusConfig.GardBronze.Value, 0, true), + new RequirementConfig("MushroomJotunPuffs", AlfarNexusConfig.GardMushrooms.Value, 0, true), + new RequirementConfig("MushroomMagecap", AlfarNexusConfig.GardMushrooms.Value, 0, true), + }, + })); + + // One per Ljoskjarne, inside its reach, and only for the Alfar. + PieceDensityLimit.Register(PieceName, AlfarNexusConfig.NexusRadius.Value, 1, "rov_msg_build_limit_alfar_ljosgard"); + PieceDensityLimit.RegisterGate(PieceName, (player, position) => + { + if (!AlfarRace.IsLocalAlfar()) + { + if (player != null) player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_only_alfar")); + return false; + } + if (AlfarNexusBehaviour.Covering(position) == null) + { + if (player != null) player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_gard_needs_nexus")); + return false; + } + return true; + }); + + AlfarPieces.Extra.Add(PieceName); + } + } +} diff --git a/JotunnModStub/Alfar/AlfarMark.cs b/JotunnModStub/Alfar/AlfarMark.cs new file mode 100644 index 0000000..2bfc3ae --- /dev/null +++ b/JotunnModStub/Alfar/AlfarMark.cs @@ -0,0 +1,149 @@ +using System.Collections.Generic; +using System.Reflection; +using HarmonyLib; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// Marks a creature or a piece as one of the Alfar's own: a construct, a drone or a tower. + /// + /// What the mark does is decided in ONE place, the patches below, instead of editing every attack + /// of every cloned creature (Alfar_Progettazione.txt sec. 8.5 and 16C P4): + /// - everything the marked thing deals becomes LIGHTNING, with the same total; chop and pickaxe + /// are tool damage and are dropped; + /// - it never hurts an ally; + /// - it never hurts a building, a tree or a rock. + /// Intercepting the hit covers melee, projectiles and area attacks alike, whatever the vanilla + /// creature does with its weapons. + /// + public class AlfarMark : MonoBehaviour + { + /// "drone", "construct" or "tower": only for logs and the status command. + public string Role = ""; + + /// The attacker's mark, or null when the hit is not from one of ours. + public static AlfarMark Of(HitData hit) + { + if (hit == null) return null; + Character attacker = hit.GetAttacker(); + return attacker != null ? attacker.GetComponent() : null; + } + + /// All the damage that can wound a person, moved into lightning. Chop and pickaxe go. + public static void ConvertToLightning(HitData hit) + { + HitData.DamageTypes d = hit.m_damage; + float total = d.m_damage + d.m_blunt + d.m_slash + d.m_pierce + d.m_fire + d.m_frost + + d.m_poison + d.m_spirit + d.m_lightning; + + HitData.DamageTypes converted = default(HitData.DamageTypes); + converted.m_lightning = total; + hit.m_damage = converted; + } + } + + /// The blows of an Alfar creature: lightning only, and never on a friend. + [HarmonyPatch(typeof(Character), "Damage")] + public static class AlfarMark_CharacterDamage_Patch + { + public static bool Prefix(Character __instance, HitData __0) + { + AlfarMark mark = AlfarMark.Of(__0); + if (mark == null) return true; + + Character attacker = __0.GetAttacker(); + if (__instance == attacker) return false; + + // Nobody on our side is ever hurt by us: players, their tames, the other constructs. + if (!BaseAI.IsEnemy(attacker, __instance)) return false; + + AlfarMark.ConvertToLightning(__0); + return true; + } + } + + /// + /// Buildings, trees and rocks take nothing from the Alfar's creatures: the golem that razed its + /// owner's base would be a bug. One prefix on every kind of thing that can be struck. + /// + [HarmonyPatch] + public static class AlfarMark_StructureDamage_Patch + { + public static IEnumerable TargetMethods() + { + System.Type[] types = + { + typeof(WearNTear), typeof(Destructible), typeof(MineRock5), typeof(MineRock), + typeof(TreeBase), typeof(TreeLog), + }; + + foreach (System.Type type in types) + { + MethodBase method = AccessTools.Method(type, "Damage", new[] { typeof(HitData) }); + if (method != null) yield return method; + else Jotunn.Logger.LogWarning($"[Alfar] {type.Name}.Damage(HitData) not found: that structure is not protected from the Alfar's creatures."); + } + } + + public static bool Prefix(HitData __0) + { + return AlfarMark.Of(__0) == null; + } + } + + /// + /// A shield equal to the creature's health that comes back by itself: 1% of it per second once it + /// has gone five seconds without being hit (design sec. 8.5 and 9.6). Health does NOT come back: + /// the damage to the body is permanent, which is why a construct is rebuilt and not repaired. + /// + /// Its own absorption and not SE_Shield: the blow arrives at ApplyDamage, and what is left after + /// the shield is what reaches the health (the same stage the Alfr's own eitr shield uses). + /// + public class AlfarCreatureShield : MonoBehaviour + { + public float MaxShield; + public float Shield; + public float RegenPerSecondFraction = 0.01f; + public float QuietSeconds = 5f; + + private float lastHit = -999f; + + private void Awake() + { + if (Shield <= 0f) Shield = MaxShield; + } + + private void Update() + { + if (Shield >= MaxShield || Time.time - lastHit < QuietSeconds) return; + Shield = Mathf.Min(MaxShield, Shield + MaxShield * RegenPerSecondFraction * Time.deltaTime); + } + + public void Absorb(HitData hit) + { + float total = hit.m_damage.GetTotalDamage(); + if (total <= 0f) return; + + lastHit = Time.time; + float absorbed = Mathf.Min(Shield, total); + Shield -= absorbed; + + HitData.DamageTypes rest = hit.m_damage; + rest.Modify((total - absorbed) / total); + hit.m_damage = rest; + } + + [HarmonyPatch(typeof(Character), "ApplyDamage", + new[] { typeof(HitData), typeof(bool), typeof(bool), typeof(HitData.DamageModifier) })] + public static class Alfar_CreatureShield_Patch + { + public static void Prefix(Character __instance, HitData __0) + { + if (__0 == null || __instance is Player) return; + AlfarCreatureShield shield = __instance.GetComponent(); + if (shield != null) shield.Absorb(__0); + } + } + } +} diff --git a/JotunnModStub/Alfar/AlfarMiners.cs b/JotunnModStub/Alfar/AlfarMiners.cs new file mode 100644 index 0000000..59b3b22 --- /dev/null +++ b/JotunnModStub/Alfar/AlfarMiners.cs @@ -0,0 +1,104 @@ +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// GRAFVAETTIR, the mining grenade (Alfar_Progettazione.txt sec. 9.3): unlocked at Eikthyr, thrown + /// like a grenade at a point; five drones dig the precious ores around it for two minutes and + /// vanish. The ore falls where it stands, and nothing else limits it but its cost (eitr, a little + /// stone and flint) and a five minute wait. + /// + /// The thrown part is only the spawn; the digging is AlfarMiner on the drones themselves. + /// + public static class AlfarMiners + { + private static float readyAt; + + public static void Tick(Player player) + { + // Nothing to tick per frame: the miners run themselves. Kept so the power loop treats + // every power the same way. + } + + public static void Throw(Player player) + { + if (Time.time < readyAt) return; + + Transform aim = GameCamera.instance != null ? GameCamera.instance.transform : player.transform; + Vector3 origin = aim.position; + Vector3 direction = aim.forward; + float range = AlfarPowerConfig.GrafRange.Value; + + Vector3 point = origin + direction * range; + foreach (RaycastHit hit in Physics.RaycastAll(origin, direction, range, ~0, QueryTriggerInteraction.Ignore)) + { + if (hit.collider.GetComponentInParent() == player) continue; + if (Vector3.Distance(origin, hit.point) < Vector3.Distance(origin, point)) point = hit.point; + } + + // The price: a little eitr, a little stone, a little flint. + string stone = SharedName("Stone"); + string flint = SharedName("Flint"); + int needStone = AlfarPowerConfig.GrafStone.Value; + int needFlint = AlfarPowerConfig.GrafFlint.Value; + float eitr = AlfarPowerConfig.GrafEitr.Value; + + Inventory inventory = player.GetInventory(); + if (inventory.CountItems(stone, -1, false) < needStone || inventory.CountItems(flint, -1, false) < needFlint) + { + player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_graf_materials", needStone, needFlint)); + return; + } + if (player.GetEitr() < eitr) + { + player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_no_eitr")); + return; + } + + GameObject prefab = ZNetScene.instance != null ? ZNetScene.instance.GetPrefab(AlfarDrones.MinerName) : null; + if (prefab == null) + { + Jotunn.Logger.LogWarning($"[Alfar] No '{AlfarDrones.MinerName}' in ZNetScene: the mining drones cannot be thrown."); + return; + } + + inventory.RemoveItem(stone, needStone, -1, false); + inventory.RemoveItem(flint, needFlint, -1, false); + AlfarEitr.Spend(player, eitr); + readyAt = Time.time + AlfarPowerConfig.GrafCooldown.Value; + AlfarStatusEffects.ShowTimer("graf", AlfarPowerConfig.GrafCooldown.Value); + + int count = AlfarPowerConfig.GrafCount.Value; + for (int i = 0; i < count; i++) + { + Vector2 offset = Random.insideUnitCircle * 1.5f; + Vector3 where = point + new Vector3(offset.x, 1.5f + i * 0.2f, offset.y); + GameObject spawned = Object.Instantiate(prefab, where, Quaternion.identity); + + AlfarMiner miner = spawned.GetComponent(); + if (miner != null) + { + miner.Centre = point; + miner.Radius = AlfarPowerConfig.GrafRadius.Value; + miner.LiveSeconds = AlfarPowerConfig.GrafSeconds.Value; + } + + // Tame at once so nothing flees them and they flee nothing; no anchor, no leash. + MonsterAI ai = spawned.GetComponent(); + Character character = spawned.GetComponent(); + if (ai != null) ai.MakeTame(); + if (character != null) character.SetTamed(true); + } + + AlfarFx.Spawn("fx_JotunWitch_LightningBolt_Explosion", point); + Jotunn.Logger.LogInfo($"[Alfar] Grafvaettir thrown: {count} at {point}."); + } + + private static string SharedName(string prefabName) + { + GameObject prefab = ObjectDB.instance != null ? ObjectDB.instance.GetItemPrefab(prefabName) : null; + ItemDrop drop = prefab != null ? prefab.GetComponent() : null; + return drop != null ? drop.m_itemData.m_shared.m_name : prefabName; + } + } +} diff --git a/JotunnModStub/Alfar/AlfarNexus.cs b/JotunnModStub/Alfar/AlfarNexus.cs new file mode 100644 index 0000000..8ba5ac9 --- /dev/null +++ b/JotunnModStub/Alfar/AlfarNexus.cs @@ -0,0 +1,576 @@ +using System.Collections.Generic; +using System.Text; +using HarmonyLib; +using Jotunn.Configs; +using Jotunn.Entities; +using Jotunn.Managers; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// The LJOSKJARNE, the Alfar's Nexus (Alfar_Progettazione.txt sec. 8): the one piece the whole + /// base hangs from. It makes the drones and the constructs, it keeps the crystals, and the towers + /// and the drones only work inside its radius. One per 1.6 km2 like the other races' stations. + /// + /// ONE INTERACTION POINT (guide 4.7): E opens the vanilla merchant window with a row per product + /// (AlfarNexusStore), the way the Trol's war totem and the Dvergar's contract bank do. The first + /// version stepped through the products with Shift+E, which gave trouble in other races' tests, and + /// the player asked for the store. The prices are not coins: they come out of the pack, and the + /// row's tooltip lists them with how many exist and how many are allowed. + /// + /// Everything is paid from the player's inventory. The crystals the Nexus makes (after the + /// Kristallvigsla) pile up inside it, a beehive's way - slowly, to a cap, and it stops when full + /// until somebody collects - and "collect" moves them to the pack. + /// + public static class AlfarNexus + { + public const string PieceName = "AlfarNexus"; + public const string PieceDisplay = "$rov_piece_alfar_nexus_name"; + + public static void Register() + { + GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(PieceName, "piece_cartographytable"); + if (prefab == null) + { + Jotunn.Logger.LogWarning("[Alfar] Could not clone piece_cartographytable; the Ljoskjarne is not registered."); + return; + } + + // The MapTable trap (Butler 4.1): MapTable is Interactable AND Hoverable and takes the E + // key before our Switch sees it. Everything goes except what makes it a building. + foreach (MonoBehaviour behaviour in prefab.GetComponentsInChildren(true)) + { + if (behaviour == null) continue; + if (behaviour is Piece || behaviour is ZNetView || behaviour is WearNTear) continue; + Object.DestroyImmediate(behaviour); + } + + AlfarConstructs.Tint(prefab, new Color(0.62f, 0.8f, 1f, 1f)); + + AlfarNexusBehaviour nexus = prefab.AddComponent(); + nexus.m_switch = prefab.AddComponent(); + nexus.m_switch.m_name = PieceDisplay; + + // A Trader with an empty catalogue: StoreGui needs one to open at all, and the rows are drawn + // by AlfarNexusStore. Disabled and with every list filled, for the reasons the Trol's totem + // spells out (Trader.Update and Start assume an animator and a look-at rig that a nucleus + // does not have, and an unfilled list sends Trader.Interact into a null Say). + Trader trader = prefab.GetComponent() ?? prefab.AddComponent(); + trader.m_name = PieceDisplay; + trader.enabled = false; + trader.m_items = new List(); + trader.m_useItems = new List(); + trader.m_randomTalk = new List(); + trader.m_randomGreets = new List(); + trader.m_randomGoodbye = new List(); + trader.m_randomStartTrade = new List(); + trader.m_randomBuy = new List(); + trader.m_randomSell = new List(); + trader.m_randomGiveItemNo = new List(); + trader.m_randomUseItemAlreadyRecieved = new List(); + trader.m_randomTalkConditionals = new List(); + + Sprite icon = BorrowIcon("Eitr") ?? BorrowIcon("SurtlingCore"); + + Piece piece = prefab.GetComponent() ?? prefab.AddComponent(); + piece.m_craftingStation = null; + piece.m_resources = new Piece.Requirement[0]; + piece.m_name = PieceDisplay; + piece.m_canBeRemoved = true; + piece.m_groundPiece = false; + piece.m_groundOnly = false; + piece.m_icon = icon; + + Piece template = PrefabManager.Cache.GetPrefab("piece_workbench"); + if (template != null && template.m_placeEffect != null) piece.m_placeEffect = template.m_placeEffect; + + PieceManager.Instance.AddPiece(new CustomPiece(prefab, fixReference: false, new PieceConfig + { + Name = PieceDisplay, + Description = "$rov_piece_alfar_nexus_desc", + PieceTable = PieceTables.Hammer, + Category = PieceCategories.Crafting, + Icon = icon, + Requirements = new[] + { + new RequirementConfig("Bronze", AlfarNexusConfig.NexusBronze.Value, 0, true), + new RequirementConfig("Stone", AlfarNexusConfig.NexusStone.Value, 0, true), + }, + })); + + PieceDensityLimit.Register(PieceName, PieceDensityLimit.RadiusForArea(AlfarNexusConfig.NexusDensityKm2.Value), + 1, "rov_msg_build_limit_alfar_nexus"); + PieceDensityLimit.RegisterGate(PieceName, (player, position) => + { + if (AlfarRace.IsLocalAlfar()) return true; + if (player != null) player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_only_alfar")); + return false; + }); + } + + public static Sprite BorrowIcon(string prefabName) + { + ItemDrop drop = PrefabManager.Cache.GetPrefab(prefabName); + Sprite[] icons = drop != null && drop.m_itemData != null && drop.m_itemData.m_shared != null + ? drop.m_itemData.m_shared.m_icons + : null; + return icons != null && icons.Length > 0 ? icons[0] : null; + } + + /// Teaches the player the Alfar's pieces: a piece registered after the learning pass does not reach its table alone (guide 4.4). + public static void EnsureKnown(Player player) + { + if (player == null || !AlfarVisuals.IsAlfarPlayer(player)) return; + + Traverse traverse = Traverse.Create(player); + foreach (string name in AlfarPieces.AllNames()) + { + GameObject prefab = PrefabManager.Instance.GetPrefab(name); + Piece piece = prefab != null ? prefab.GetComponent() : null; + if (piece != null) traverse.Method("AddKnownPiece", piece).GetValue(); + } + traverse.Method("UpdateAvailablePiecesList").GetValue(); + } + } + + /// The names of every piece the Alfar can build, in one place for the lock and for learning. + public static class AlfarPieces + { + public static readonly List Extra = new List(); + + public static IEnumerable AllNames() + { + yield return AlfarNexus.PieceName; + foreach (string name in Extra) yield return name; + } + } + + [HarmonyPatch(typeof(Player), "OnSpawned")] + public static class AlfarKnownPatch + { + public static void Postfix(Player __instance) + { + if (__instance != Player.m_localPlayer) return; + AlfarNexus.EnsureKnown(__instance); + } + } + + public class AlfarNexusBehaviour : MonoBehaviour + { + public Switch m_switch; + + public static readonly List All = new List(); + + private const string KeySelected = "RoV_alfarSel"; + private const string KeyUpgrade = "RoV_alfarUp"; + private const string KeyCrystals = "RoV_alfarCr"; + private const string KeyCrystalAt = "RoV_alfarCrAt"; + + public enum Product { Drone = 0, Neistvordr = 1, Eldingvordr = 2, Steinvordr = 3, Upgrade = 4, Collect = 5 } + private static readonly int ProductCount = System.Enum.GetValues(typeof(Product)).Length; + + private ZNetView m_nview; + + private void Awake() + { + m_nview = GetComponent(); + All.Add(this); + RaisedThrall.RegisterStation(transform); + + if (m_switch != null) + { + m_switch.m_onUse = OnUse; + m_switch.m_onHover = Hover; + } + } + + private void OnDestroy() + { + All.Remove(this); + RaisedThrall.UnregisterStation(transform); + } + + /// The nearest Ljoskjarne whose radius covers the point, or null. + public static AlfarNexusBehaviour Covering(Vector3 point) + { + AlfarNexusBehaviour best = null; + float bestDistance = float.MaxValue; + foreach (AlfarNexusBehaviour nexus in All) + { + if (nexus == null) continue; + float distance = Vector3.Distance(nexus.transform.position, point); + if (distance <= AlfarNexusConfig.NexusRadius.Value && distance < bestDistance) + { + best = nexus; + bestDistance = distance; + } + } + return best; + } + + // ─── State ─────────────────────────────────────────────────────────── + + private bool Upgraded => m_nview != null && m_nview.IsValid() && m_nview.GetZDO().GetInt(KeyUpgrade, 0) == 1; + public int Crystals => m_nview != null && m_nview.IsValid() ? m_nview.GetZDO().GetInt(KeyCrystals, 0) : 0; + + private Product Selected + { + get + { + int value = m_nview != null && m_nview.IsValid() ? m_nview.GetZDO().GetInt(KeySelected, 0) : 0; + return (Product)Mathf.Clamp(value, 0, ProductCount - 1); + } + } + + private bool Available(Product product) + { + bool constructsOpen = Upgraded && BossProgressionManager.GetCurrentProgressionState() >= AlfarNexusConfig.ConstructState; + switch (product) + { + case Product.Drone: return true; + case Product.Neistvordr: + case Product.Eldingvordr: + case Product.Steinvordr: return constructsOpen; + case Product.Upgrade: return !Upgraded; + case Product.Collect: return Upgraded; + } + return false; + } + + // ─── Crystals: a beehive's way ─────────────────────────────────────── + + /// + /// One crystal per Time Factor beehive-intervals of WORLD time, up to the cap, and nothing while + /// full: the clock restarts when somebody collects, like the honey. Only the owner counts. + /// The beehive's own interval is read, not copied (guide 3.2) - and only the INTERVAL, not its + /// daylight rule: the Alfar have no light mechanic (doc sec. 8.6). + /// + private void Update() + { + if (m_nview == null || !m_nview.IsValid() || !m_nview.IsOwner() || !Upgraded || ZNet.instance == null) return; + + ZDO zdo = m_nview.GetZDO(); + int cap = AlfarNexusConfig.CrystalCap.Value; + int stored = zdo.GetInt(KeyCrystals, 0); + double now = ZNet.instance.GetTimeSeconds(); + + if (stored >= cap) { zdo.Set(KeyCrystalAt, now.ToString("R", System.Globalization.CultureInfo.InvariantCulture)); return; } + + string stamp = zdo.GetString(KeyCrystalAt, ""); + if (!double.TryParse(stamp, System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out double at)) + { + zdo.Set(KeyCrystalAt, now.ToString("R", System.Globalization.CultureInfo.InvariantCulture)); + return; + } + + float interval = CrystalInterval(); + int made = Mathf.FloorToInt((float)((now - at) / interval)); + if (made <= 0) return; + + stored = Mathf.Min(cap, stored + made); + zdo.Set(KeyCrystals, stored); + zdo.Set(KeyCrystalAt, (at + made * interval).ToString("R", System.Globalization.CultureInfo.InvariantCulture)); + } + + /// Seconds per crystal: Time Factor times a vanilla beehive's seconds per honey. + public static float CrystalInterval() + { + Beehive hive = TrentaConfig.FindVanillaBeehive(); + float honey = hive != null && hive.m_secPerUnit > 0f ? hive.m_secPerUnit : 1200f; + return honey * AlfarNexusConfig.CrystalTimeFactor.Value; + } + + // ─── Costs ─────────────────────────────────────────────────────────── + + private struct Cost + { + public string Item; + public int Amount; + public Cost(string item, int amount) { Item = item; Amount = amount; } + } + + private static List CostOf(Product product) + { + switch (product) + { + case Product.Drone: + return new List { new Cost("Bronze", AlfarNexusConfig.DroneBronze.Value) }; + case Product.Neistvordr: + return new List + { + new Cost("Bronze", AlfarNexusConfig.NeistMetal.Value), + new Cost("Crystal", AlfarNexusConfig.NeistCrystal.Value), + new Cost("Eitr", AlfarNexusConfig.NeistEitr.Value), + }; + case Product.Eldingvordr: + return new List + { + new Cost("Iron", AlfarNexusConfig.EldingMetal.Value), + new Cost("Crystal", AlfarNexusConfig.EldingCrystal.Value), + new Cost("Eitr", AlfarNexusConfig.EldingEitr.Value), + }; + case Product.Steinvordr: + return new List + { + new Cost("BlackMetal", AlfarNexusConfig.SteinMetal.Value), + new Cost("Crystal", AlfarNexusConfig.SteinCrystal.Value), + new Cost("Eitr", AlfarNexusConfig.SteinEitr.Value), + }; + case Product.Upgrade: + return new List { new Cost("Crystal", AlfarNexusConfig.UpgradeCrystals.Value) }; + } + return new List(); + } + + private static string SharedName(string prefabName) + { + GameObject prefab = ObjectDB.instance != null ? ObjectDB.instance.GetItemPrefab(prefabName) : null; + ItemDrop drop = prefab != null ? prefab.GetComponent() : null; + return drop != null ? drop.m_itemData.m_shared.m_name : prefabName; + } + + private static bool CanPay(Player player, List costs) + { + foreach (Cost cost in costs) + { + if (cost.Amount <= 0) continue; + if (player.GetInventory().CountItems(SharedName(cost.Item), -1, false) < cost.Amount) return false; + } + return true; + } + + private static void Pay(Player player, List costs) + { + foreach (Cost cost in costs) + { + if (cost.Amount > 0) player.GetInventory().RemoveItem(SharedName(cost.Item), cost.Amount, -1, false); + } + } + + private static string CostText(List costs) + { + var parts = new List(); + foreach (Cost cost in costs) + { + if (cost.Amount > 0) parts.Add($"{cost.Amount} {Localization.instance.Localize(SharedName(cost.Item))}"); + } + return parts.Count == 0 ? "-" : string.Join(", ", parts); + } + + // ─── Counts and caps ───────────────────────────────────────────────── + + private int AliveOf(Product product) + { + Vector3 anchor = transform.position; + switch (product) + { + case Product.Drone: return AlfarDrones.CountAlive(anchor); + case Product.Neistvordr: return AlfarConstructs.CountAlive(anchor, AlfarConstructs.Neistvordr); + case Product.Eldingvordr: return AlfarConstructs.CountAlive(anchor, AlfarConstructs.Eldingvordr); + case Product.Steinvordr: return AlfarConstructs.CountAlive(anchor, AlfarConstructs.Steinvordr); + } + return 0; + } + + private static int CapOf(Product product) + { + switch (product) + { + case Product.Drone: return AlfarNexusConfig.DroneCap.Value; + case Product.Neistvordr: return AlfarNexusConfig.NeistCap.Value; + case Product.Eldingvordr: return AlfarNexusConfig.EldingCap.Value; + case Product.Steinvordr: return AlfarNexusConfig.SteinCap.Value; + } + return int.MaxValue; + } + + private static string NameOf(Product product) => ModText.Get("rov_alfar_product_" + product.ToString().ToLowerInvariant()); + + // ─── Interaction ───────────────────────────────────────────────────── + + private string Hover() + { + var sb = new StringBuilder(); + sb.AppendLine(Localization.instance.Localize(AlfarNexus.PieceDisplay)); + sb.AppendLine($"[$KEY_Use] {ModText.Get("rov_alfar_nexus_open")}"); + + if (Upgraded) sb.AppendLine(ModText.Get("rov_alfar_nexus_crystals", Crystals, AlfarNexusConfig.CrystalCap.Value)); + else sb.AppendLine(ModText.Get("rov_alfar_nexus_no_upgrade")); + + return Localization.instance.Localize(sb.ToString()); + } + + private bool OnUse(Switch sw, Humanoid user, ItemDrop.ItemData item) + { + Player player = user as Player; + if (player == null || m_nview == null || !m_nview.IsValid()) return false; + + if (!AlfarVisuals.IsAlfarPlayer(player)) + { + player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_only_alfar")); + return item != null; + } + + // Holding something is not a way to use the nucleus: it only opens the store. + if (item != null) + { + player.Message(MessageHud.MessageType.Center, "$msg_wontwork"); + return true; + } + + Trader trader = GetComponent(); + if (trader == null || StoreGui.instance == null) + { + player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_nexus_no_store")); + return false; + } + + // The store reads the nucleus back out of StoreGui's own m_trader when it repaints. + StoreGui.instance.Show(trader); + return true; + } + + // ─── What the store window uses ────────────────────────────────────── + + /// The products on offer right now, in the order the rows are drawn. + public List OnOffer() + { + var list = new List(); + foreach (Product product in System.Enum.GetValues(typeof(Product))) + { + if (Available(product)) list.Add(product); + } + return list; + } + + /// Builds a product from the row the player clicked. Every check Build makes still applies. + public void BuildFromStore(Product product) + { + Player player = Player.m_localPlayer; + if (player == null || m_nview == null || !m_nview.IsValid() || !Available(product)) return; + + m_nview.ClaimOwnership(); + Build(player, product); + } + + /// The short number on a row: the metal (or the crystals of the upgrade) it costs. + public static string PriceShort(Product product) + { + foreach (Cost cost in CostOf(product)) + { + if (cost.Amount > 0) return cost.Amount.ToString(); + } + return "-"; + } + + /// The full terms for the row's tooltip: the price, how many exist, how many are allowed. + public string Terms(Product product) + { + var sb = new StringBuilder(); + sb.AppendLine(CostText(CostOf(product))); + + int cap = CapOf(product); + if (cap != int.MaxValue) sb.AppendLine(ModText.Get("rov_alfar_store_count", AliveOf(product), cap)); + if (product == Product.Collect) sb.AppendLine(ModText.Get("rov_alfar_nexus_crystals", Crystals, AlfarNexusConfig.CrystalCap.Value)); + + sb.Append(ModText.Get("rov_alfar_store_terms")); + return sb.ToString(); + } + + public static string ProductName(Product product) => NameOf(product); + + private void Build(Player player, Product product) + { + List costs = CostOf(product); + + if (product == Product.Collect) + { + Collect(player); + return; + } + + if (AliveOf(product) >= CapOf(product)) + { + player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_nexus_cap")); + return; + } + + if (!CanPay(player, costs)) + { + player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_nexus_cannot_pay", CostText(costs))); + return; + } + + bool done; + switch (product) + { + case Product.Drone: done = AlfarDrones.Spawn(transform.position); break; + case Product.Neistvordr: done = AlfarConstructs.Spawn(transform.position, AlfarConstructs.Neistvordr); break; + case Product.Eldingvordr: done = AlfarConstructs.Spawn(transform.position, AlfarConstructs.Eldingvordr); break; + case Product.Steinvordr: done = AlfarConstructs.Spawn(transform.position, AlfarConstructs.Steinvordr); break; + case Product.Upgrade: done = true; break; + default: done = false; break; + } + if (!done) return; + + Pay(player, costs); + + if (product == Product.Upgrade) + { + ZDO zdo = m_nview.GetZDO(); + zdo.Set(KeyUpgrade, 1); + zdo.Set(KeyCrystalAt, ZNet.instance.GetTimeSeconds().ToString("R", System.Globalization.CultureInfo.InvariantCulture)); + player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_nexus_upgraded")); + } + else + { + player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_nexus_built", NameOf(product))); + } + } + + private void Collect(Player player) + { + int stored = Crystals; + if (stored <= 0) + { + player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_nexus_no_crystals")); + return; + } + + GameObject prefab = ObjectDB.instance != null ? ObjectDB.instance.GetItemPrefab("Crystal") : null; + if (prefab == null) return; + + // Whatever fits goes in the pack; the rest stays in the Nexus. + int taken = 0; + for (int i = 0; i < stored; i++) + { + if (!player.GetInventory().CanAddItem(prefab, 1)) break; + if (!player.GetInventory().AddItem(prefab, 1)) break; + taken++; + } + + if (taken > 0) + { + ZDO zdo = m_nview.GetZDO(); + zdo.Set(KeyCrystals, stored - taken); + // Collecting restarts the clock, like emptying a hive. + zdo.Set(KeyCrystalAt, ZNet.instance.GetTimeSeconds().ToString("R", System.Globalization.CultureInfo.InvariantCulture)); + } + player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_nexus_collected", taken)); + } + + /// Crystals a drone may carry away from the Nexus, and the call that does it (used by the drone's work). + public int TakeCrystals(int wanted) + { + if (m_nview == null || !m_nview.IsValid() || !m_nview.IsOwner()) return 0; + int stored = Crystals; + int taken = Mathf.Min(stored, wanted); + if (taken <= 0) return 0; + ZDO zdo = m_nview.GetZDO(); + zdo.Set(KeyCrystals, stored - taken); + zdo.Set(KeyCrystalAt, ZNet.instance.GetTimeSeconds().ToString("R", System.Globalization.CultureInfo.InvariantCulture)); + return taken; + } + } +} diff --git a/JotunnModStub/Alfar/AlfarNexusConfig.cs b/JotunnModStub/Alfar/AlfarNexusConfig.cs new file mode 100644 index 0000000..59c4020 --- /dev/null +++ b/JotunnModStub/Alfar/AlfarNexusConfig.cs @@ -0,0 +1,144 @@ +using BepInEx.Configuration; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// The numbers of the Alfar's base: the Nexus, its drones, the constructs, the towers and the + /// crystals (Alfar_Progettazione.txt sec. 8, 9 and 19). All starting values, all to be corrected + /// in play, none in the logic files. + /// + public static class AlfarNexusConfig + { + // The progression state the constructs open at (BossProgressionManager: 6 = Yagluth down). + public const int ConstructState = 6; + + // ─── The Nexus ─────────────────────────────────────────────────────── + public static ConfigEntry NexusRadius; + public static ConfigEntry NexusDensityKm2; + public static ConfigEntry NexusBronze; + public static ConfigEntry NexusStone; + + // ─── Drones ────────────────────────────────────────────────────────── + public static ConfigEntry DroneBronze; + public static ConfigEntry DroneCap; + public static ConfigEntry DroneHealth; + public static ConfigEntry DroneZapDamage; + public static ConfigEntry DroneZapInterval; + + // ─── Mining drones ─────────────────────────────────────────────────── + public static ConfigEntry MinerDeposits; + public static ConfigEntry MinerDamage; + public static ConfigEntry WildPickables; + + // ─── Constructs ────────────────────────────────────────────────────── + public static ConfigEntry NeistMetal; + public static ConfigEntry NeistCrystal; + public static ConfigEntry NeistEitr; + public static ConfigEntry NeistCap; + + public static ConfigEntry EldingMetal; + public static ConfigEntry EldingCrystal; + public static ConfigEntry EldingEitr; + public static ConfigEntry EldingCap; + + public static ConfigEntry SteinMetal; + public static ConfigEntry SteinCrystal; + public static ConfigEntry SteinEitr; + public static ConfigEntry SteinCap; + + public static ConfigEntry ConstructLeash; + public static ConfigEntry ConstructAlertRange; + public static ConfigEntry WitherSeconds; + + public static ConfigEntry SphereDamage; + public static ConfigEntry SphereIntervalSeconds; + public static ConfigEntry SphereRange; + + // ─── Crystals ──────────────────────────────────────────────────────── + public static ConfigEntry UpgradeCrystals; + public static ConfigEntry CrystalCap; + public static ConfigEntry CrystalTimeFactor; + + // ─── Towers ────────────────────────────────────────────────────────── + public static ConfigEntry TowerBronze; + public static ConfigEntry TowerCrystal; + public static ConfigEntry TowerHealthFactor; + public static ConfigEntry TowerDamage; + public static ConfigEntry TowerScale; + + // ─── Ljosgard (sap) and chests ─────────────────────────────────────── + public static ConfigEntry GardBronze; + public static ConfigEntry GardMushrooms; + public static ConfigEntry GardSecondsPerSap; + public static ConfigEntry GardCapacity; + public static ConfigEntry ChestEyes; + + public static void Bind(ConfigFile config) + { + const string nexus = "Alfar - Nexus"; + NexusRadius = config.Bind(nexus, "Radius", 40f, new ConfigDescription("Metres around a Ljoskjarne where its drones work and its towers run.", new AcceptableValueRange(10f, 150f))); + NexusDensityKm2 = config.Bind(nexus, "Density Km2", 1.6f, new ConfigDescription("At most one Ljoskjarne per this many square kilometres.", new AcceptableValueRange(0.1f, 20f))); + NexusBronze = config.Bind(nexus, "Bronze Cost", 40, new ConfigDescription("Bronze to build a Ljoskjarne.", new AcceptableValueRange(0, 500))); + NexusStone = config.Bind(nexus, "Stone Cost", 30, new ConfigDescription("Stone to build a Ljoskjarne.", new AcceptableValueRange(0, 500))); + + const string drone = "Alfar - Drones"; + DroneBronze = config.Bind(drone, "Bronze Cost", 8, new ConfigDescription("Bronze for each Ljosvaettir.", new AcceptableValueRange(0, 200))); + DroneCap = config.Bind(drone, "Cap Per Nexus", 6, new ConfigDescription("Most drones one Ljoskjarne keeps.", new AcceptableValueRange(0, 50))); + DroneHealth = config.Bind(drone, "Health", 25f, new ConfigDescription("A drone's health and shield (a Deathsquito has 10).", new AcceptableValueRange(1f, 1000f))); + DroneZapDamage = config.Bind(drone, "Zap Damage", 1f, new ConfigDescription("Lightning damage of a drone's defensive zap.", new AcceptableValueRange(0f, 100f))); + DroneZapInterval = config.Bind(drone, "Zap Interval", 2f, new ConfigDescription("Seconds between a drone's zaps.", new AcceptableValueRange(0.2f, 30f))); + + MinerDeposits = config.Bind(drone, "Mining Targets", "MineRock_Copper,MineRock_Tin,MineRock_Iron,silvervein,rock3_silver,giant_brain", + new ConfigDescription("Comma separated parts of prefab names the mining drones dig (case does not matter). Soft tissue comes from giant_brain.")); + MinerDamage = config.Bind(drone, "Mining Damage", 40f, new ConfigDescription("Pickaxe damage each mining drone does per second to a deposit.", new AcceptableValueRange(1f, 1000f))); + + WildPickables = config.Bind(drone, "Wild Plants Harvested", "Pickable_Mushroom,Pickable_Dandelion,Pickable_Thistle,RaspberryBush,BlueberryBush,CloudberryBush", + new ConfigDescription("Comma separated parts of prefab names of WILD plants the drones pick without replanting (mushrooms, berry bushes, flowers). Trees are never touched. Cultivated crops are always replanted.")); + + const string construct = "Alfar - Constructs"; + NeistMetal = config.Bind(construct, "Neistvordr Bronze", 20, new ConfigDescription("Bronze for a Neistvordr.", new AcceptableValueRange(0, 500))); + NeistCrystal = config.Bind(construct, "Neistvordr Crystal", 3, new ConfigDescription("Crystals for a Neistvordr.", new AcceptableValueRange(0, 50))); + NeistEitr = config.Bind(construct, "Neistvordr Refined Eitr", 3, new ConfigDescription("Refined eitr for a Neistvordr.", new AcceptableValueRange(0, 50))); + NeistCap = config.Bind(construct, "Neistvordr Cap", 4, new ConfigDescription("Most Neistvordr one Ljoskjarne keeps.", new AcceptableValueRange(0, 50))); + + EldingMetal = config.Bind(construct, "Eldingvordr Iron", 20, new ConfigDescription("Iron for an Eldingvordr.", new AcceptableValueRange(0, 500))); + EldingCrystal = config.Bind(construct, "Eldingvordr Crystal", 5, new ConfigDescription("Crystals for an Eldingvordr.", new AcceptableValueRange(0, 50))); + EldingEitr = config.Bind(construct, "Eldingvordr Refined Eitr", 4, new ConfigDescription("Refined eitr for an Eldingvordr.", new AcceptableValueRange(0, 50))); + EldingCap = config.Bind(construct, "Eldingvordr Cap", 4, new ConfigDescription("Most Eldingvordr one Ljoskjarne keeps.", new AcceptableValueRange(0, 50))); + + SteinMetal = config.Bind(construct, "Steinvordr Black Metal", 20, new ConfigDescription("Black metal for a Steinvordr.", new AcceptableValueRange(0, 500))); + SteinCrystal = config.Bind(construct, "Steinvordr Crystal", 8, new ConfigDescription("Crystals for a Steinvordr.", new AcceptableValueRange(0, 50))); + SteinEitr = config.Bind(construct, "Steinvordr Refined Eitr", 6, new ConfigDescription("Refined eitr for a Steinvordr.", new AcceptableValueRange(0, 50))); + SteinCap = config.Bind(construct, "Steinvordr Cap", 1, new ConfigDescription("Most Steinvordr one Ljoskjarne keeps.", new AcceptableValueRange(0, 50))); + + ConstructLeash = config.Bind(construct, "Leash Range", 12f, new ConfigDescription("How far a construct wanders from its Ljoskjarne when not following.", new AcceptableValueRange(2f, 80f))); + ConstructAlertRange = config.Bind(construct, "Alert Range", 25f, new ConfigDescription("How far a construct notices and chases enemies.", new AcceptableValueRange(5f, 100f))); + WitherSeconds = config.Bind(construct, "Wither Seconds", 60f, new ConfigDescription("How long creatures last after their Ljoskjarne falls.", new AcceptableValueRange(0f, 600f))); + + SphereDamage = config.Bind(construct, "Sphere Damage", 80f, new ConfigDescription("Lightning damage of the Eldingvordr's sphere.", new AcceptableValueRange(1f, 1000f))); + SphereIntervalSeconds = config.Bind(construct, "Sphere Interval", 8f, new ConfigDescription("Seconds between the Eldingvordr's shots.", new AcceptableValueRange(0.5f, 60f))); + SphereRange = config.Bind(construct, "Sphere Range", 30f, new ConfigDescription("How far the Eldingvordr shoots.", new AcceptableValueRange(5f, 80f))); + + const string crystal = "Alfar - Crystals"; + UpgradeCrystals = config.Bind(crystal, "Upgrade Cost", 20, new ConfigDescription("Crystals the player must find for the Kristallvigsla.", new AcceptableValueRange(0, 200))); + CrystalCap = config.Bind(crystal, "Stored Cap", 20, new ConfigDescription("Most crystals the Ljoskjarne holds before it stops making them.", new AcceptableValueRange(1, 200))); + CrystalTimeFactor = config.Bind(crystal, "Time Factor", 2f, new ConfigDescription("A crystal takes this many times a vanilla beehive's time for one honey.", new AcceptableValueRange(0.1f, 20f))); + + const string tower = "Alfar - Towers"; + TowerBronze = config.Bind(tower, "Bronze Cost", 25, new ConfigDescription("Bronze for a Prismavard.", new AcceptableValueRange(0, 500))); + TowerCrystal = config.Bind(tower, "Crystal Cost", 2, new ConfigDescription("Crystals for a Prismavard.", new AcceptableValueRange(0, 50))); + TowerHealthFactor = config.Bind(tower, "Health Factor", 0.5f, new ConfigDescription("A Prismavard's health against the charred ballista's 400.", new AcceptableValueRange(0.05f, 3f))); + TowerDamage = config.Bind(tower, "Bolt Damage", 40f, new ConfigDescription("Lightning damage of a Prismavard's bolt.", new AcceptableValueRange(1f, 1000f))); + TowerScale = config.Bind(tower, "Scale", 0.6f, new ConfigDescription("Size of a Prismavard against the charred ballista.", new AcceptableValueRange(0.2f, 2f))); + + const string gard = "Alfar - Ljosgard"; + GardBronze = config.Bind(gard, "Bronze Cost", 40, new ConfigDescription("Bronze for a Ljosgard.", new AcceptableValueRange(0, 500))); + GardMushrooms = config.Bind(gard, "Mushrooms Cost", 10, new ConfigDescription("Jotun Puffs AND Magecap, this many of each, to build a Ljosgard.", new AcceptableValueRange(0, 100))); + GardSecondsPerSap = config.Bind(gard, "Seconds Per Sap", 600f, new ConfigDescription("Seconds to turn one Jotun Puffs and one Magecap into a Sap.", new AcceptableValueRange(10f, 7200f))); + GardCapacity = config.Bind(gard, "Sap Capacity", 10, new ConfigDescription("Sap the Ljosgard holds before it stops.", new AcceptableValueRange(1, 200))); + + ChestEyes = config.Bind(gard, "Chest Greydwarf Eyes", 3, new ConfigDescription("Greydwarf eyes in the price of the entry chest and the wood chest.", new AcceptableValueRange(0, 50))); + } + } +} diff --git a/JotunnModStub/Alfar/AlfarNexusStore.cs b/JotunnModStub/Alfar/AlfarNexusStore.cs new file mode 100644 index 0000000..4b17cc1 --- /dev/null +++ b/JotunnModStub/Alfar/AlfarNexusStore.cs @@ -0,0 +1,171 @@ +using System.Collections.Generic; +using HarmonyLib; +using TMPro; +using UnityEngine; +using UnityEngine.UI; + +namespace RacesOfValheim +{ + /// + /// The Ljoskjarne's window: the merchant's own store with a column of products in it - the drone, + /// the three constructs, the crystal upgrade, and the crystals to collect. + /// + /// It is the Trol war totem's window (TrolTotemStore) cloned for another trader, and for the same + /// reasons: same three patch points (Awake to build, FillList to repaint, Hide to clear), same trick + /// of instantiating StoreGui.m_listElement for the rows. The empty-catalogue guard that keeps vanilla + /// FillList from throwing is already on every trader with no wares (StoreGuiEmptyCatalogueGuardPatch), + /// so this one needs none of its own. + /// + /// What is different from the totem: a row's price is a number out of the pack and not coins, so the + /// short figure on the row is the metal or the crystals, and the tooltip carries the whole price. + /// + public static class AlfarNexusStore + { + private static RectTransform _list; + private static readonly List _rows = new List(); + + public static AlfarNexusBehaviour ActiveNexus(StoreGui gui) + { + Trader trader = FactionMerchantRuntime.GetActiveTrader(gui); + return trader != null ? trader.GetComponent() : null; + } + + // ─── build ─────────────────────────────────────────────────────────── + + public static void Create(StoreGui gui) + { + if (gui == null || gui.m_listRoot == null || _list != null) return; + + GameObject clone = Object.Instantiate(gui.m_listRoot.gameObject, gui.m_listRoot.parent); + clone.name = "AlfarProductList"; + _list = clone.GetComponent(); + _list.anchoredPosition = gui.m_listRoot.anchoredPosition; + + // The clone carries whatever rows the vanilla list held at Awake: it starts empty. + foreach (Transform child in _list) Object.Destroy(child.gameObject); + _list.gameObject.SetActive(false); + } + + public static void Clear() + { + foreach (GameObject row in _rows) if (row != null) Object.Destroy(row); + _rows.Clear(); + if (_list != null) _list.gameObject.SetActive(false); + } + + // ─── fill ──────────────────────────────────────────────────────────── + + public static void Refresh(StoreGui gui) + { + Clear(); + + AlfarNexusBehaviour nexus = ActiveNexus(gui); + if (nexus == null) return; // an ordinary merchant: not ours + + if (_list == null) + { + Jotunn.Logger.LogWarning("[Alfar] The Ljoskjarne's column was never built (did the patch on StoreGui.Awake fail?)."); + return; + } + + _list.gameObject.SetActive(true); + + int row = 0; + foreach (AlfarNexusBehaviour.Product product in nexus.OnOffer()) + { + BuildRow(gui, nexus, product, row++); + } + + float baseSize = Traverse.Create(gui).Field("m_itemlistBaseSize").GetValue(); + _list.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, Mathf.Max(baseSize, row * gui.m_itemSpacing)); + } + + private static string IconOf(AlfarNexusBehaviour.Product product) + { + switch (product) + { + case AlfarNexusBehaviour.Product.Drone: return "TrophyDeathsquito"; + case AlfarNexusBehaviour.Product.Neistvordr: return "TrophySurtling"; + case AlfarNexusBehaviour.Product.Eldingvordr: return "TrophyAbomination"; + case AlfarNexusBehaviour.Product.Steinvordr: return "TrophySGolem"; + default: return "Crystal"; + } + } + + private static void BuildRow(StoreGui gui, AlfarNexusBehaviour nexus, AlfarNexusBehaviour.Product product, int rowIndex) + { + GameObject element = Object.Instantiate(gui.m_listElement, _list); + element.SetActive(true); + + RectTransform rt = (RectTransform)element.transform; + float offset = (_list.rect.width - rt.rect.width) / 2f; + rt.anchoredPosition = new Vector2(offset, rowIndex * -gui.m_itemSpacing - offset); + + Sprite icon = Icon(IconOf(product)); + Image iconImage = element.transform.Find("icon").GetComponent(); + if (icon != null) iconImage.sprite = icon; + + string name = AlfarNexusBehaviour.ProductName(product); + element.transform.Find("name").GetComponent().text = Localization.instance.Localize(name); + + TMP_Text price = FindDescendant(element.transform, "price"); + if (price != null) price.text = AlfarNexusBehaviour.PriceShort(product); + + // The coin that sits beside the number on a vanilla row is the wrong picture here. + foreach (Image image in element.GetComponentsInChildren(true)) + { + if (image != null && image.gameObject.name.ToLowerInvariant().Contains("coin")) image.gameObject.SetActive(false); + } + + UITooltip tooltip = element.GetComponent(); + if (tooltip != null) tooltip.Set(Localization.instance.Localize(name), nexus.Terms(product), gui.m_tooltipAnchor, default(Vector2)); + + AlfarNexusBehaviour.Product chosen = product; + element.GetComponent