warvulture

This commit is contained in:
Ferdinando 2026-08-13 19:13:24 +02:00
commit d79f78e9f0
10 changed files with 901 additions and 90 deletions

View file

@ -15,7 +15,7 @@ namespace RacesOfValheim
{
public const string PluginGUID = "com.nandor.racesofvalheim";
public const string PluginName = "Races Of Valheim";
public const string PluginVersion = "1.4.0";
public const string PluginVersion = "1.4.2";
private readonly Harmony harmony = new Harmony(PluginGUID);
@ -40,6 +40,9 @@ namespace RacesOfValheim
// Not a race: a summoned mount two races share, so it binds after the races rather
// than inside the alphabetical run above.
WarVultureConfig.Bind(Config);
// Not a race either: a tool any race can craft, so it sits beside the vulture rather
// than inside the alphabetical run above.
TrolsHammerConfig.Bind(Config);
harmony.PatchAll();
gameObject.AddComponent<FenrirRace>();
gameObject.AddComponent<SkadiRace>();
@ -126,6 +129,7 @@ namespace RacesOfValheim
TrentaRace.Instance.CreateModAssets();
SvermRace.Instance.CreateModAssets();
WarVultureItem.Register();
TrolsHammerItem.Register();
}
// --- RACE SELECTION UI ---
public void ShowRaceSelectionMenu()

View file

@ -163,35 +163,23 @@ namespace RacesOfValheim
private static void Clone(GameObject source, Transform parentBone, string namePrefix)
{
GameObject copy = Object.Instantiate(source, parentBone);
copy.name = namePrefix + source.name;
// Through BorrowEffect, which builds the copy inside an inactive holder and strips it
// there. This used to instantiate straight onto the bone and clean up afterwards, and
// "afterwards" is a frame too late: a borrowed node gets its Awake the moment it lands
// on a live player. That is what left burnt-in torches in people's worlds when the head
// flame did the same thing - see the note on FlameSourcePrefabs. Nothing on a creature
// is known to be as expensive as an ItemDrop, but the eye glow reads whatever the
// creature happens to carry, which is exactly the kind of place that surprise comes
// from.
GameObject copy = SkeletonVisuals.BorrowEffect(source, parentBone, namePrefix + source.name,
true, "Skeleton");
if (copy == null) return;
// The pose it was authored at on the creature. Instantiate keeps the world transform,
// which for a prefab means nothing useful.
copy.transform.localPosition = source.transform.localPosition;
copy.transform.localRotation = source.transform.localRotation;
copy.transform.localScale = source.transform.localScale;
// Allowlist, not a blocklist - the same rule the head flame is built under. Whatever
// else rode along (an AnimEvent, a collider, a script that expects a Character above
// it) goes, whatever type it turns out to be; what is left is a light and the things
// that draw it.
foreach (Component comp in copy.GetComponentsInChildren<Component>(true))
{
if (comp is Transform || comp is Light || comp is ParticleSystem ||
comp is ParticleSystemRenderer || comp is MeshRenderer || comp is MeshFilter)
{
continue;
}
Object.Destroy(comp);
}
// A creature can leave its own effects switched off for a script to turn on later, and
// that script is exactly what was just destroyed.
copy.SetActive(true);
foreach (Light light in copy.GetComponentsInChildren<Light>(true)) light.enabled = true;
foreach (Renderer renderer in copy.GetComponentsInChildren<Renderer>(true)) renderer.enabled = true;
}
/// <summary>

View file

@ -1,3 +1,4 @@
using System.Collections.Generic;
using Jotunn.Managers;
using UnityEngine;
@ -96,13 +97,78 @@ namespace RacesOfValheim
return BossProgressionManager.GetCurrentProgressionState();
}
// Fire sources in preference order. The torch is an item every world has; the ground
// torch and the fire pit are the building pieces to fall back on.
/// <summary>
/// Fire sources in preference order. BUILDING PIECES ONLY, and that is the bug fix.
///
/// This list used to start with "Torch", which is the ITEM prefab, and an item in Valheim
/// is a live world object: ItemDrop, a Rigidbody and a ZNetView, all of them on the same
/// node the fire particles are on. That the borrow was reaching that node and not a bare
/// flame was already known here - the strip below used to name "the stick mesh, ItemDrop,
/// durability", and the Rigidbody it had to destroy was the one that made an early version
/// of the clone visibly fall away from the skull.
///
/// What was missed is that the copy was made into a holder that was ALREADY SWITCHED ON,
/// so all of it woke up for a frame before the strip could take any of it off - and a woken
/// ZNetView is not a cosmetic mistake. ZNetView.Awake with no init ZDO calls
/// ZDOMan.CreateNewZDO at the object's position, marks it persistent, stamps it with the
/// prefab hash and registers it with the scene; ZNetView.OnDestroy does none of that in
/// reverse - it only releases asset references. So every rebuild of the flame left the
/// world holding a persistent "there is a Torch here" record that nothing was drawing,
/// saved with everything else, and the next time that zone was built from the save every
/// client spawned the torch. That is the whole of the report: a torch dropped on logging
/// in and out, and a portal handing it to everyone.
///
/// A ground torch is a building piece. It has the same fire (both carry fx_Torch_Basic) and
/// no item behaviour at all, so there is nothing on it to bring across by accident. The
/// inactive holder in Build and the two filters below are the lines of defence behind that,
/// for whatever a future source turns out to carry.
/// </summary>
private static readonly string[] FlameSourcePrefabs =
{
"Torch", "piece_groundtorch_wood", "piece_groundtorch", "fire_pit"
"piece_groundtorch_wood", "piece_groundtorch", "fire_pit"
};
/// <summary>
/// Particle systems that are not fire. Matched on the object name, which is how these are
/// named in the prefabs that carry them - an item's pickup glitter above all, which is a
/// ParticleSystem like any other and was worn on the skull along with the flame.
/// </summary>
private static readonly string[] NotFire =
{
"sparkle", "sparcle", "glitter", "pickup", "shine", "twinkle"
};
private static bool IsFire(GameObject candidate)
{
string name = candidate.name.ToLower();
foreach (string word in NotFire)
{
if (name.Contains(word)) return false;
}
return true;
}
// Said once per particle name per session, with everything the borrowed node carries that
// is not a particle. The point is that the next time something rides along, the log names
// it - this bug cost a bug report because nothing ever said "that flame is an item".
private static readonly HashSet<string> loggedParticles = new HashSet<string>();
private static void LogClonedOnce(GameObject source)
{
if (!loggedParticles.Add(source.name)) return;
List<string> passengers = new List<string>();
foreach (Component comp in source.GetComponentsInChildren<Component>(true))
{
if (comp == null || IsPureVfx(comp, true)) continue;
passengers.Add(comp.GetType().Name);
}
Jotunn.Logger.LogInfo(
$"[Skeleton] Head flame: cloned '{source.name}'" +
(passengers.Count == 0 ? "." : ", stripped " + string.Join(", ", passengers.ToArray()) + "."));
}
private static GameObject cachedFlameSource;
private static bool flameSourceResolved;
@ -119,7 +185,13 @@ namespace RacesOfValheim
{
GameObject prefab = PrefabManager.Cache.GetPrefab<GameObject>(name);
if (prefab == null) continue;
if (prefab.GetComponentsInChildren<ParticleSystem>(true).Length == 0) continue;
bool hasFire = false;
foreach (ParticleSystem ps in prefab.GetComponentsInChildren<ParticleSystem>(true))
{
if (IsFire(ps.gameObject)) { hasFire = true; break; }
}
if (!hasFire) continue;
Jotunn.Logger.LogInfo($"[Skeleton] Head flame source resolved to '{name}'.");
cachedFlameSource = prefab;
@ -132,6 +204,108 @@ namespace RacesOfValheim
return null;
}
/// <summary>
/// Strips a borrowed subtree down to what a pure VFX needs, and nothing else.
///
/// Allowlist, not a blocklist: keep the particle systems, their renderers and the lights
/// (and the loose meshes, for the eye glow), destroy every other component whatever it
/// turns out to be. A blocklist of "known bad" types (MonoBehaviour, Collider) missed
/// Rigidbody - not a MonoBehaviour in Unity - and a fire node carrying one meant physics
/// kept acting on the clone independently of the holder being repositioned every frame.
///
/// DestroyImmediate rather than Destroy, because the caller is about to switch the holder
/// on and Destroy does not take effect until the end of the frame - by which time every
/// script it was supposed to remove would have had its Awake.
///
/// Repeated passes, because Unity refuses to destroy a component another one still
/// requires ("Can't remove Humanoid because CharacterDrop depends on it"): the dependent
/// goes on one pass and the component it held down goes on the next. Behaviours first
/// within each pass, for the same reason.
/// </summary>
public static void StripToVfx(GameObject root, bool keepMeshes, string label)
{
if (root == null) return;
for (int pass = 0; pass < 4; pass++)
{
bool anyLeft = false;
foreach (MonoBehaviour behaviour in root.GetComponentsInChildren<MonoBehaviour>(true))
{
if (behaviour == null) continue;
Object.DestroyImmediate(behaviour);
}
foreach (Component comp in root.GetComponentsInChildren<Component>(true))
{
if (comp == null || IsPureVfx(comp, keepMeshes)) continue;
Object.DestroyImmediate(comp);
anyLeft = true;
}
if (!anyLeft) return;
}
// Four passes and something is still holding on. Say what it is: a survivor here is the
// exact shape of bug this whole class exists to prevent, and it is about to be woken.
foreach (Component comp in root.GetComponentsInChildren<Component>(true))
{
if (comp == null || IsPureVfx(comp, keepMeshes)) continue;
Jotunn.Logger.LogWarning(
$"[{label}] '{comp.GetType().Name}' on '{comp.gameObject.name}' could not be stripped " +
"off the borrowed effect; it will run on the player.");
}
}
private static bool IsPureVfx(Component comp, bool keepMeshes)
{
if (comp is Transform || comp is ParticleSystem || comp is ParticleSystemRenderer || comp is Light)
{
return true;
}
return keepMeshes && (comp is MeshRenderer || comp is MeshFilter);
}
/// <summary>
/// Clones one node of a vanilla prefab as pure VFX and hangs it under <paramref name="parent"/>.
///
/// The temporary holder is created INACTIVE and the copy is made inside it. That single
/// line is the point of this method: Unity does not run Awake on an object that is not
/// active in its hierarchy, so ItemDrop, ZNetView, Rigidbody and every script on the
/// borrowed node are destroyed before any of them ever exists as far as the game is
/// concerned. Stripping AFTER the copy is already live - which is what the head flame and
/// the eye glow both used to do - is a frame too late, and one frame is all a ZNetView
/// needs to write a persistent object into the save. Same lesson, same fix, as ModelBorrow.
///
/// The copy is handed back parented to <paramref name="parent"/> and switched on, with its
/// pose left to the caller.
/// </summary>
public static GameObject BorrowEffect(GameObject source, Transform parent, string cloneName,
bool keepMeshes, string label)
{
if (source == null || parent == null) return null;
GameObject holder = new GameObject("BorrowedEffectHolder");
holder.SetActive(false); // BEFORE the Instantiate below.
GameObject copy = Object.Instantiate(source, holder.transform);
copy.name = cloneName;
StripToVfx(copy, keepMeshes, label);
copy.transform.SetParent(parent, false);
Object.DestroyImmediate(holder);
// A prefab can leave its own effects switched off for a script to turn on later, and
// that script is exactly what was just destroyed.
copy.SetActive(true);
foreach (Light light in copy.GetComponentsInChildren<Light>(true)) light.enabled = true;
foreach (Renderer renderer in copy.GetComponentsInChildren<Renderer>(true)) renderer.enabled = true;
return copy;
}
/// <summary>
/// One player's burning skull. Cosmetic only - it deals nothing and blocks nothing.
///
@ -191,13 +365,22 @@ namespace RacesOfValheim
// Real fire is cloned rather than built by hand. The first attempt at this made a
// particle system from scratch on the smoke material, and a hand-rolled gradient
// over a smoke sprite reads as a wisp, not a burning skull.
//
// Every clone goes through BorrowEffect, which builds it inactive and strips it
// before it can wake. Nothing from the source prefab - a script, a Rigidbody, a
// ZNetView - ever gets a frame of life on the player.
foreach (ParticleSystem ps in source.GetComponentsInChildren<ParticleSystem>(true))
{
GameObject copy = Object.Instantiate(ps.gameObject, m_instance.transform);
copy.name = ps.gameObject.name;
if (!IsFire(ps.gameObject)) continue;
GameObject copy = BorrowEffect(ps.gameObject, m_instance.transform,
ps.gameObject.name, false, "Skeleton");
if (copy == null) continue;
LogClonedOnce(ps.gameObject);
copy.transform.localPosition = Vector3.zero;
copy.transform.localRotation = Quaternion.identity;
copy.SetActive(true);
// So the holder's scale actually enlarges the fire rather than just spreading
// out where the particles spawn.
@ -213,22 +396,6 @@ namespace RacesOfValheim
light.intensity *= 0.6f;
}
// Allowlist, not a blocklist: keep only what a pure VFX actually needs (the
// particle systems, their renderers, and the light tweaked above) and destroy
// every other component, whatever it turns out to be. A blocklist of "known bad"
// types (MonoBehaviour, Collider) missed Rigidbody - not a MonoBehaviour in Unity,
// so the old loop never touched it - and a torch's fire-particle node carrying one
// meant physics kept acting on the clone independently of m_instance being
// repositioned onto the head every frame: it visibly fell away while the empty
// parent stayed correctly tracked above it. Anything that made the source a torch
// rather than a bare flame - the stick mesh, ItemDrop, durability, all of it -
// goes the same way.
foreach (Component comp in m_instance.GetComponentsInChildren<Component>(true))
{
if (comp is Transform || comp is ParticleSystem || comp is ParticleSystemRenderer || comp is Light) continue;
Object.Destroy(comp);
}
return true;
}
}

View file

@ -316,7 +316,16 @@ namespace RacesOfValheim
Character character = GetComponent<Character>();
if (character == null || character.IsDead())
{
Destroy(gameObject);
// ZNetScene.Destroy, NEVER Object.Destroy, and this line was the teleport crash.
//
// An escort is a real networked creature, and ZNetView.OnDestroy - read out of the
// assembly, not assumed - only releases asset references: it does not take the
// object out of ZNetScene.m_instances. A plain Object.Destroy therefore left the
// scene holding a dead ZNetView, and the next time the world unloaded around the
// player, which is exactly what a teleport is, ZNetScene.RemoveObjects walked that
// entry and threw. See ZNetSceneOrphanPatch.cs for the whole chain.
if (ZNetScene.instance != null) ZNetScene.instance.Destroy(gameObject);
else Destroy(gameObject);
return;
}

View file

@ -0,0 +1,50 @@
using BepInEx.Configuration;
namespace RacesOfValheim
{
/// <summary>
/// The two numbers behind Trol's Hammer, bound as BepInEx ConfigEntry so they can be dragged in
/// Configuration Manager rather than recompiled - the same shape as WarVultureConfig.
///
/// Note what the switch does NOT do: turning the hammer off never un-scales anything already
/// standing. A piece carries its own size on its ZDO, and that is read back on load whatever
/// the config says, so a house built at 1.2 stays a house and not a pile of clipping walls.
/// The switch only decides whether NEW placements are enlarged.
/// </summary>
public static class TrolsHammerConfig
{
public static ConfigEntry<bool> Enabled;
public static ConfigEntry<float> ScaleFactor;
public static void Bind(ConfigFile config)
{
// No apostrophe, and not a typo: BepInEx rejects ' in a section name outright, and this
// Bind runs from the plugin's Awake - so "Trol's Hammer" did not merely fail to appear
// in Configuration Manager, it threw and took the whole mod's startup with it.
const string section = "Trols Hammer";
Enabled = config.Bind(section, "Enabled", true,
new ConfigDescription("Whether pieces placed with Trol's Hammer come out enlarged. " +
"Switching this off leaves every piece already built at the size " +
"it was built at; only new placements are affected."));
ScaleFactor = config.Bind(section, "Scale factor", 1.2f,
new ConfigDescription("How much bigger than the vanilla piece. 1.2 is the +20% the " +
"hammer exists for. Cost and drop never change - this is size " +
"only.", new AcceptableValueRange<float>(1f, 3f)));
}
/// <summary>
/// The multiplier a new placement should use, or 1 when the hammer is switched off. Clamped
/// against a zero or negative value typed straight into the .cfg file, which the
/// Configuration Manager slider cannot produce but a text editor can - and a piece scaled to
/// zero is a piece that cannot be seen, hit or removed.
/// </summary>
public static float ActiveFactor()
{
if (Enabled == null || ScaleFactor == null) return 1f;
if (!Enabled.Value) return 1f;
return ScaleFactor.Value > 0.01f ? ScaleFactor.Value : 1f;
}
}
}

View file

@ -0,0 +1,97 @@
using Jotunn.Configs;
using Jotunn.Entities;
using Jotunn.Managers;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// Trol's Hammer: the builder's hammer, one size up.
///
/// It is a straight clone of the vanilla Hammer and it deliberately keeps the ONE field that
/// makes it a hammer at all - m_buildPieces, the PieceTable. Sharing the vanilla table rather
/// than cloning it is the whole trick behind "exactly the same things to build": every piece
/// vanilla puts in the hammer's menu is there, at the same cost and with the same drop, and so
/// is every piece another mod adds to that table later. A cloned table would have been a
/// snapshot of the build menu taken at startup and would have quietly gone stale.
///
/// Nothing about the piece prefabs is touched, so the size does not live on the item: it lives
/// on the placement, and TrolsHammerPatches is where that happens.
///
/// The recipe (1 core wood, 2 fine wood) is on a workbench rather than free-hand like the
/// vanilla hammer, because both materials already require one to exist.
/// </summary>
public static class TrolsHammerItem
{
public const string PrefabName = "TrolsHammer";
public const string DisplayName = "Trol's Hammer";
private const string SourcePrefab = "Hammer";
private const string Label = "TrolsHammer";
/// <summary>Core wood. The item id is RoundLog - a display name that does not predict the id.</summary>
private const string CoreWood = "RoundLog";
private const string FineWood = "FineWood";
public static void Register()
{
GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(PrefabName, SourcePrefab);
if (prefab == null)
{
Jotunn.Logger.LogWarning($"[{Label}] Could not clone {SourcePrefab}; {DisplayName} not registered.");
return;
}
ItemDrop drop = prefab.GetComponent<ItemDrop>();
if (drop == null || drop.m_itemData == null || drop.m_itemData.m_shared == null)
{
Jotunn.Logger.LogWarning($"[{Label}] {SourcePrefab} clone has no usable ItemDrop; {DisplayName} not registered.");
return;
}
ItemDrop.ItemData.SharedData shared = drop.m_itemData.m_shared;
shared.m_name = DisplayName;
shared.m_description = "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.";
if (shared.m_buildPieces == null)
{
// Not fatal, but worth saying out loud: without a piece table the item is a stick.
Jotunn.Logger.LogWarning($"[{Label}] The {SourcePrefab} clone carries no build piece table; " +
$"{DisplayName} will open an empty build menu.");
}
ItemManager.Instance.AddItem(new CustomItem(prefab, fixReference: false));
ItemManager.Instance.AddRecipe(new CustomRecipe(new RecipeConfig
{
Item = PrefabName,
Amount = 1,
CraftingStation = CraftingStations.Workbench,
MinStationLevel = 1,
Requirements = new[]
{
new RequirementConfig(CoreWood, 1, 0, true),
new RequirementConfig(FineWood, 2, 0, true),
},
}));
Jotunn.Logger.LogInfo($"[{Label}] {DisplayName} registered on the vanilla hammer's piece table.");
}
/// <summary>
/// Whether an item in hand is this hammer.
///
/// m_dropPrefab is the reliable identity - it is the prefab the ItemData came from - but it
/// is null on an ItemData built before ObjectDB finished, so the display name is kept as a
/// second reading rather than as the only one.
/// </summary>
public static bool IsTrolsHammer(ItemDrop.ItemData item)
{
if (item == null) return false;
if (item.m_dropPrefab != null) return item.m_dropPrefab.name == PrefabName;
return item.m_shared != null && item.m_shared.m_name == DisplayName;
}
}
}

View file

@ -0,0 +1,217 @@
using HarmonyLib;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// Where the +20% actually happens.
///
/// Three things had to be true for this to be a feature rather than a trick, and each one is a
/// separate patch below:
///
/// 1. the SIZE MUST SURVIVE. Valheim does not replicate localScale - a piece is rebuilt from
/// its ZDO every time the zone loads, at whatever size its prefab has. So the multiplier is
/// written onto the piece's own ZDO at placement and read back in ZNetView.Awake, which is
/// the earliest moment a ZDO is guaranteed to exist (confirmed from the assembly:
/// WearNTear.Awake returns early if GetZDO() is null, so it already assumes this order).
/// That one hook covers all three cases at once - the builder's client, every other
/// player's client, and the same world reopened next week;
///
/// 2. the PREVIEW MUST NOT LIE. The ghost is what the game tests for clipping, overlap and
/// snapping, so an unscaled ghost would let a player place a piece that immediately
/// overlapped its neighbour. SetupPlacementGhost ends by copying the prefab's localScale
/// onto the ghost, so a postfix - and only a postfix - can multiply it;
///
/// 3. the PIECE ITSELF MUST NOT BE TOUCHED. Nothing here writes to a piece prefab. Cost,
/// drop, health, comfort and build menu are vanilla's, untouched, which is exactly why the
/// same walls can still be built at normal size with the ordinary hammer.
///
/// Placement is caught with a flag around Player.PlacePiece rather than by patching the piece:
/// PlacePiece is void and instantiates the PREFAB (not the ghost) inside itself, so there is no
/// return value to read and no way to reach the new object afterwards. The instantiate runs
/// synchronously, which means every Awake it triggers happens inside that window.
/// </summary>
public static class TrolsHammerScaling
{
/// <summary>
/// The ZDO key the size is written to. Hashed once: this is read in ZNetView.Awake, which
/// runs for every networked object in the world, so it is not a place to be hashing strings.
/// </summary>
public static readonly int ScaleKey = "RoV_TrolHammerScale".GetStableHashCode();
/// <summary>
/// True only for the few milliseconds Player.PlacePiece spends instantiating a piece the
/// player asked for with Trol's Hammer in hand. Static because the only caller is the local
/// player and the window never nests.
/// </summary>
public static bool Placing;
public static float PlacingFactor = 1f;
public static void Apply(Transform t, float factor)
{
if (t == null || factor <= 0f || Mathf.Approximately(factor, 1f)) return;
// A multiply and not an assignment: a handful of vanilla pieces do not sit at scale 1,
// and the brief is "20% bigger than it was", not "20% bigger than one metre".
Vector3 s = t.localScale;
t.localScale = new Vector3(s.x * factor, s.y * factor, s.z * factor);
}
}
/// <summary>
/// The preview, at the size it will actually be built.
///
/// A postfix because vanilla's last act in this method is to copy the source prefab's
/// localScale onto the ghost - a prefix would be overwritten a few instructions later.
///
/// The hand is read through the public RightItem property and NOT through GetCurrentWeapon,
/// which is the obvious-looking call and the wrong one: it only returns the right hand when
/// ItemData.IsWeapon() is true, and that method does not count ItemType.Tool. A hammer would
/// have come back as the player's fists.
/// </summary>
public static class TrolsHammerGhost
{
private static GameObject m_tracked;
private static Vector3 m_baseScale = Vector3.one;
private static float m_applied = 1f;
/// <summary>
/// Remembers the size vanilla just gave the ghost, before anything of ours touches it. This
/// is the only moment that number is knowable: a few frames later the ghost's localScale is
/// whatever WE last wrote, and using it as a base would compound on every pass.
/// </summary>
public static void Adopt(GameObject ghost)
{
m_tracked = ghost;
m_baseScale = ghost != null ? ghost.transform.localScale : Vector3.one;
m_applied = 1f;
}
/// <summary>
/// Puts the ghost at the size the hand in the player's right hand would build it.
///
/// Called every frame because the ghost is NOT rebuilt when the player swaps tools:
/// SetupPlacementGhost only runs on Awake, on a piece-selection change and on a build menu
/// refresh (confirmed by walking its callers in the assembly). Swapping from one hammer to
/// the other with the same wall selected keeps the same ghost object alive, so a size
/// applied once at setup would go on lying about a piece that is now built at normal size.
///
/// Cheap enough to be unconditional: it exits on a float comparison in every frame but the
/// one where the answer actually changed.
/// </summary>
public static void Sync(Player player, GameObject ghost)
{
if (player == null || ghost == null)
{
m_tracked = null;
return;
}
if (ghost != m_tracked) Adopt(ghost);
float desired = TrolsHammerItem.IsTrolsHammer(player.RightItem)
? TrolsHammerConfig.ActiveFactor()
: 1f;
if (Mathf.Approximately(desired, m_applied)) return;
ghost.transform.localScale = m_baseScale * desired;
m_applied = desired;
}
}
[HarmonyPatch(typeof(Player), "SetupPlacementGhost")]
public static class TrolsHammerGhostSetupPatch
{
private static void Postfix(Player __instance, GameObject ___m_placementGhost)
{
TrolsHammerGhost.Adopt(___m_placementGhost);
TrolsHammerGhost.Sync(__instance, ___m_placementGhost);
}
}
/// <summary>
/// The correction pass. This also runs once inside TryPlacePiece, immediately before the piece
/// is placed, which is what guarantees the thing tested for clipping is the size that lands.
/// </summary>
[HarmonyPatch(typeof(Player), "UpdatePlacementGhost")]
public static class TrolsHammerGhostUpdatePatch
{
private static void Postfix(Player __instance, GameObject ___m_placementGhost)
{
TrolsHammerGhost.Sync(__instance, ___m_placementGhost);
}
}
/// <summary>
/// The window. PlacePiece is void, so there is nothing to postfix onto - the flag is the whole
/// mechanism, and ZNetView.Awake is what reads it.
///
/// A Finalizer rather than a Postfix closes the window, so the flag is cleared even if vanilla
/// throws halfway through placing. A flag left stuck on would enlarge the next unrelated
/// networked object to spawn anywhere in the world.
/// </summary>
[HarmonyPatch(typeof(Player), "PlacePiece")]
public static class TrolsHammerPlacePatch
{
private static void Prefix(Player __instance)
{
if (__instance == null || __instance != Player.m_localPlayer) return;
if (!TrolsHammerItem.IsTrolsHammer(__instance.RightItem)) return;
float factor = TrolsHammerConfig.ActiveFactor();
if (Mathf.Approximately(factor, 1f)) return;
TrolsHammerScaling.Placing = true;
TrolsHammerScaling.PlacingFactor = factor;
}
private static void Finalizer()
{
TrolsHammerScaling.Placing = false;
}
}
/// <summary>
/// The one hook that both stamps the size and restores it.
///
/// It runs for EVERY networked object in the world, so the ordinary path is deliberately as
/// cheap as one dictionary lookup on a pre-hashed key: no GetComponent, no string work, no
/// allocation. The GetComponent&lt;Piece&gt; guard is paid only inside the placement window, and
/// it is there so an effect prefab that happens to carry a ZNetView cannot be mistaken for the
/// wall being built.
///
/// The restore branch ignores the config on purpose - see TrolsHammerConfig.
/// </summary>
[HarmonyPatch(typeof(ZNetView), "Awake")]
public static class TrolsHammerZNetViewPatch
{
private static void Postfix(ZNetView __instance)
{
if (__instance == null || !__instance.IsValid()) return;
ZDO zdo = __instance.GetZDO();
if (zdo == null) return;
if (TrolsHammerScaling.Placing && __instance.GetComponent<Piece>() != null)
{
float factor = TrolsHammerScaling.PlacingFactor;
// Written before it is applied, and only by the owner - which the placing client
// always is, since this ZDO was created a few instructions ago by this very Awake.
if (zdo.IsOwner()) zdo.Set(TrolsHammerScaling.ScaleKey, factor);
TrolsHammerScaling.Apply(__instance.transform, factor);
// The window is closed here as well as in the Finalizer: one placement is one
// piece, and leaving it open for the rest of PlacePiece would hand the same size to
// anything else that woke up inside it.
TrolsHammerScaling.Placing = false;
return;
}
float saved = zdo.GetFloat(TrolsHammerScaling.ScaleKey, 0f);
if (saved > 0f) TrolsHammerScaling.Apply(__instance.transform, saved);
}
}
}

View file

@ -0,0 +1,174 @@
using System;
using System.Collections.Generic;
using System.Reflection;
using HarmonyLib;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The "teleport bug", and why it is a crash about teleporting at all.
///
/// WHAT THE REPORT LOOKS LIKE. Two NullReferenceExceptions out of ZNetScene.Update, the first
/// of them through UnityEngine.Component.get_gameObject:
///
/// ZNetScene.RemoveObjects -> ZNetScene.CreateDestroyObjects -> ZNetScene.Update
///
/// WHAT IT ACTUALLY IS. ZNetScene keeps a table of every networked object it has built,
/// m_instances, mapping ZDO to ZNetView, and RemoveObjects is the pass that unloads whatever is
/// no longer near the player. Read out of the assembly rather than assumed, it does exactly
/// this:
///
/// foreach (ZNetView value in m_instances.Values)
/// if (value.GetZDO().TempRemoveEarmark != b) m_tempRemoved.Add(value); // (1)
/// ...
/// UnityEngine.Object.Destroy(zNetView.gameObject); // (2)
///
/// Neither line can survive an entry whose object is already gone: (1) throws a plain NRE if the
/// ZDO has been reset out from under it, and (2) throws through get_gameObject - Unity's "this
/// object was destroyed and you are still using it" - if the ZNetView itself is dead. That is
/// the exact pair of stack traces in the report.
///
/// AND THE ENTRY IS NEVER CLEANED UP BY UNITY, which is the part worth writing down, because it
/// is the trap every despawn in this mod has to avoid. ZNetView.OnDestroy, in full:
///
/// private void OnDestroy() { _ = (bool)ZNetScene.instance; if (m_heldReferences != null) ... }
///
/// It releases asset references and NOTHING else - it does not take itself out of m_instances.
/// So any object that is destroyed the Unity way instead of the ZNetScene way (Object.Destroy on
/// a networked creature or piece, a ZNetView stripped off a clone that had already woken, an
/// ancestor destroyed with a networked child underneath it) leaves a dead entry in the table,
/// and it sits there harmlessly until something walks the whole table.
///
/// WHICH IS WHY IT IS ALWAYS A TELEPORT. Standing still, the dead entry is earmarked as "near"
/// every frame and line (2) is never reached for it. A teleport moves the reference position a
/// world away, so on that frame everything that was around the player becomes removable, the
/// dead entry is finally reached, and RemoveObjects throws. The throw aborts
/// CreateDestroyObjects, which aborts ZNetScene.Update - and because the offending entry is
/// removed on the line AFTER the one that threw, it is still there next frame. From that moment
/// the scene manager is dead for the rest of the session: nothing new loads, nothing unloads,
/// the player stands in an empty world.
///
/// WHAT THIS PATCH DOES. It is a finalizer, so it costs nothing on the millions of calls that
/// work. When RemoveObjects does throw, it sweeps m_instances for entries whose ZNetView is dead
/// or whose ZDO has been reset, takes them out, and swallows the exception so the next frame
/// runs clean. Vanilla's own rule is used for the ZDO behind each one - a temporary ZDO this
/// client owns is destroyed with its object, a persistent one is world data and is left exactly
/// where it is, because "the view is broken" is not evidence that the player's building should
/// be deleted.
///
/// If the sweep finds nothing, the exception is handed back untouched: this patch is for one
/// specific failure and must not hide anybody else's.
///
/// AND IT NAMES THE CULPRIT. Every purge logs the PREFAB NAME behind each dead entry, which is
/// the one thing the stack trace cannot tell us. Whatever is producing these - this mod, another
/// mod, or a plain vanilla race condition - the next log from a crashed teleport says so by
/// name, and the fix can then go where it belongs: at the despawn that used Object.Destroy
/// instead of ZNetScene.Destroy.
/// </summary>
[HarmonyPatch(typeof(ZNetScene), "RemoveObjects")]
public static class ZNetScene_RemoveObjects_OrphanPatch
{
private static readonly FieldInfo InstancesField = AccessTools.Field(typeof(ZNetScene), "m_instances");
// Reused rather than allocated per sweep: a sweep runs from inside a failing frame, and the
// one thing that must not happen there is extra pressure on the frame that is already sick.
private static readonly List<ZDO> Broken = new List<ZDO>();
private static readonly Dictionary<string, int> CountByPrefab = new Dictionary<string, int>();
private static int totalPurged;
public static Exception Finalizer(Exception __exception, ZNetScene __instance)
{
if (__exception == null) return null;
int purged = Purge(__instance);
// Nothing broken in the table means this throw was not ours to catch.
return purged > 0 ? null : __exception;
}
private static int Purge(ZNetScene scene)
{
if (scene == null || InstancesField == null) return 0;
Dictionary<ZDO, ZNetView> instances = InstancesField.GetValue(scene) as Dictionary<ZDO, ZNetView>;
if (instances == null) return 0;
Broken.Clear();
CountByPrefab.Clear();
foreach (KeyValuePair<ZDO, ZNetView> instance in instances)
{
// Unity's own == is what makes the first half of this work: a component whose
// GameObject has been destroyed is still a live managed object, and only this
// comparison knows it is dead. The second half is the reset-ZDO case from line (1).
if (instance.Value != null && instance.Value.GetZDO() != null) continue;
Broken.Add(instance.Key);
}
if (Broken.Count == 0) return 0;
int purged = Broken.Count;
int persistentLeftAlone = 0;
foreach (ZDO zdo in Broken)
{
string prefab = PrefabNameOf(zdo);
int seen;
CountByPrefab.TryGetValue(prefab, out seen);
CountByPrefab[prefab] = seen + 1;
instances.Remove(zdo);
if (!zdo.Persistent && zdo.IsOwner() && ZDOMan.instance != null)
{
ZDOMan.instance.DestroyZDO(zdo);
}
else if (zdo.Persistent)
{
persistentLeftAlone++;
}
}
totalPurged += purged;
List<string> named = new List<string>(CountByPrefab.Count);
foreach (KeyValuePair<string, int> entry in CountByPrefab)
{
named.Add(entry.Value == 1 ? entry.Key : entry.Key + " x" + entry.Value);
}
Jotunn.Logger.LogWarning(
$"[RacesOfValheim] ZNetScene.RemoveObjects threw on {purged} dead scene " +
(purged == 1 ? "entry" : "entries") +
$" - the teleport crash. Purged: {string.Join(", ", named)}. " +
(persistentLeftAlone > 0
? $"{persistentLeftAlone} of them had a persistent ZDO, which is world data and was left alone. "
: "") +
$"The world keeps loading. ({totalPurged} purged this session.) " +
"Whoever destroyed those objects used Object.Destroy where ZNetScene.Destroy was needed.");
Broken.Clear();
CountByPrefab.Clear();
return purged;
}
/// <summary>
/// The name behind a dead entry, which is the whole diagnostic value of this patch. A hash
/// with no prefab behind it is still worth printing - it means the object came from a mod
/// that is no longer loaded, which is an answer too.
/// </summary>
private static string PrefabNameOf(ZDO zdo)
{
if (zdo == null) return "no ZDO";
int hash = zdo.GetPrefab();
GameObject prefab = hash != 0 && ZNetScene.instance != null ? ZNetScene.instance.GetPrefab(hash) : null;
return prefab != null ? prefab.name : $"unknown prefab (hash {hash})";
}
}
}