From 6d9f07217e371d243e2a29bb79e3b3503627d496 Mon Sep 17 00:00:00 2001 From: kanym Date: Sun, 18 Oct 2026 13:33:21 +0200 Subject: [PATCH 1/2] 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 2/2] 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); } }