RacesOfValheim/JotunnModStub/PieceDensityLimit.cs
Ferdinando 5c5b8c34d2 feat(races): Skadi hollow chain, plus the pending Dvergar and Fenrir ones
Three per-race item chains had accumulated uncommitted. They land
together because FactionMerchantCatalog.cs carries hunks from all
three and cannot be split without interactive staging.

Skadi (new this session):
- SkadiNokkel - "Skadis Nokkel", a StaffSkeleton clone recoloured to
  ice, stripped of its eitr and health costs and of the skeleton
  summon, opening an ice-blue portal to a troll cave the player
  claims as their own. Crafted at the forge after Moder from a
  1500-coin Greater Frost Heart, a DragonTear and a TrophySkeleton.
- SkadiFrostHeart - the bought leg of that recipe, sold by the
  Cultist bench.
- SkadiHollow / SkadiHollowPortal - claims one existing TrollCave02
  in the Black Forest, half a world radius out and south of the
  equator, and opens a linked local portal pair to it.
- RaceCaveBuilding - Skadi and Trol may build inside any troll cave.

Two facts worth keeping, both paid for the hard way:
- a troll cave counts as a DUNGEON, so the flag that refuses a piece
  there is the per-piece Piece.m_allowedInDungeons, not the
  per-location Location.m_noBuild. Player.m_placementStatus names the
  exact refusal reason and is now logged.
- Object.DestroyImmediate is forbidden inside an animation event
  callback, and a staff cast runs in one - it fails silently there.

Also carried in, from earlier sessions and unverified in game:
- Dvergar contract bank and barrel (DvergarBanco*, DvergarBotte*)
- Fenrir Ulvsblod trough (FenrirMangiatoia*)
- the Wolf -> Ulv merchant bench move, so tameable wolves stop
  answering the E key with a shop window

Status: compiles clean with no new warnings. The Skadi chain has NOT
been confirmed working in game - the most recent fix to the troll
cave detection is still untested.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-08 14:58:43 +02:00

168 lines
8 KiB
C#

using System.Collections.Generic;
using HarmonyLib;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// "How many of these may stand in one region." One place, one patch, one line per station.
///
/// Every station in the per-race item-progression system that produces something continuously has
/// to be capped, or five copies are five times the effect - a field of groves is a carpet of bees,
/// five body piles are fifty draugr. Each chain used to be expected to write its own placement
/// check; this exists so the five races still to come add a limit with one call instead of
/// re-deriving ZDO counting, and so there is exactly one Player.PlacePiece prefix rather than one
/// per race.
///
/// Counting is done over ZDOs and not over loaded GameObjects, and that distinction is the whole
/// point: Valheim keeps only a handful of zones alive around the player, a few hundred metres at
/// most, so counting objects would let anyone dodge the cap by walking away and building again.
///
/// HONEST LIMIT: a client only holds the ZDOs the server has sent it. In singleplayer and on the
/// host the count is exact; on a remote client it can undercount, so a cap can be exceeded by
/// someone building far from every other copy. It still closes the case that matters - fifty of
/// them around one base - and no client-side hook can do better without a server-authoritative
/// check.
/// </summary>
public static class PieceDensityLimit
{
private class Limit
{
public float Radius;
public int Max;
public string Message;
}
private static readonly Dictionary<string, Limit> Limits = new Dictionary<string, Limit>();
/// <summary>
/// The radius of a circle with the given area, so a limit can be written the way it is
/// actually discussed - "five per 1.6 square kilometres" - instead of as a magic distance.
/// </summary>
public static float RadiusForArea(float squareKilometres)
{
return Mathf.Sqrt(squareKilometres * 1000000f / Mathf.PI);
}
/// <summary>
/// Caps a piece. Call once from the chain's Register(); calling twice just replaces the entry,
/// so a Register() that runs more than once cannot stack limits.
/// </summary>
public static void Register(string piecePrefabName, float radius, int max, string refusalMessage)
{
if (string.IsNullOrEmpty(piecePrefabName) || max < 1 || radius <= 0f)
{
Jotunn.Logger.LogWarning($"[Density] Refusing a nonsense limit for '{piecePrefabName}' " +
$"(radius {radius}, max {max}); it will not be capped.");
return;
}
Limits[piecePrefabName] = new Limit { Radius = radius, Max = max, Message = refusalMessage };
Jotunn.Logger.LogInfo($"[Density] {piecePrefabName}: at most {max} within {radius:0} m.");
}
/// <summary>
/// How many of that piece already stand within the radius of a point, or -1 if the world
/// cannot be asked right now - in which case callers must let the placement through rather
/// than refuse on no information.
/// </summary>
public static int Count(string piecePrefabName, Vector3 position, float radius)
{
if (ZDOMan.instance == null) return -1;
List<ZDO> zdos = new List<ZDO>();
int index = 0;
// The iterative sweep hands back a chunk per call and reports true when it is done. The
// guard is so a pathological world cannot spin here forever.
for (int guard = 0; guard < 1000; guard++)
{
if (ZDOMan.instance.GetAllZDOsWithPrefabIterative(piecePrefabName, zdos, ref index)) break;
}
float rangeSq = radius * radius;
int count = 0;
foreach (ZDO zdo in zdos)
{
if (zdo == null) continue;
if (Vector3.SqrMagnitude(zdo.GetPosition() - position) <= rangeSq) count++;
}
return count;
}
/// <summary>
/// True if one more may be placed there. Unknown pieces are always allowed - a station with no
/// registered limit is not this class's business.
/// </summary>
public static bool Allow(Player player, string piecePrefabName, Vector3 position)
{
if (!Limits.TryGetValue(piecePrefabName, out Limit limit)) return true;
int nearby = Count(piecePrefabName, position, limit.Radius);
if (nearby < 0 || nearby < limit.Max) return true;
if (player != null)
{
player.Message(MessageHud.MessageType.Center, string.Format(limit.Message, nearby, limit.Max));
}
return false;
}
}
/// <summary>
/// The single enforcement point, at the moment of building - which is the only moment a refusal is
/// both cheap and understandable. Refusing later, or building and then quietly deleting what it
/// produced, would spend the player's gate item before telling them no.
/// </summary>
/// <summary>
/// The single enforcement point.
///
/// The signature is spelled out because it is NOT the one every Valheim modding example uses. The
/// familiar `bool PlacePiece(Piece)` does not exist in this build; the real one is
///
/// void PlacePiece(Piece piece, Vector3 pos, Quaternion rot, bool doAttack)
///
/// read off the HarmonyX error this patch produced on the first launch. Two things follow, and the
/// first one cost a whole startup:
/// - it returns VOID, so there is no __result to write. Asking for one throws "Cannot get result
/// from void method" at patch time, and that exception propagates out of Harmony.PatchAll() -
/// which means one bad signature here stops the rest of the mod's patches from being applied
/// at all. A prefix returning false is the whole mechanism: the original simply does not run,
/// nothing is placed, and no resources are spent.
/// - the placement position is an ARGUMENT, not the piece's transform. At prefix time the Piece
/// is the build ghost, so `pos` is the authority on where this thing is actually going.
/// Parameters are bound positionally (__0, __1) so a rename cannot break startup either.
/// </summary>
[HarmonyPatch(typeof(Player), "PlacePiece",
new[] { typeof(Piece), typeof(Vector3), typeof(Quaternion), typeof(bool) })]
public static class PieceDensityLimitPatch
{
public static bool Prefix(Player __instance, Piece __0, Vector3 __1)
{
if (__instance != Player.m_localPlayer || __0 == null) return true;
if (!HollowAllowsPiece(__instance, __0)) return false;
return PieceDensityLimit.Allow(__instance, Utils.GetPrefabName(__0.gameObject), __1);
}
/// <summary>
/// "You may build in your hollow, but nothing takes root there." Rides along on this prefix
/// rather than adding a second one, which is the whole reason this class exists.
///
/// Worth knowing that the refusal is about the MESSAGE, not about making the impossible
/// impossible: a Plant needs cultivated ground and a matching biome (Plant.m_needCultivated-
/// Ground, Plant.m_biome), and five kilometres above the sea there is no terrain to cultivate
/// and no biome to match, so a seed would have failed anyway - with a vanilla error that says
/// nothing useful about why.
/// </summary>
private static bool HollowAllowsPiece(Player player, Piece piece)
{
if (!SkadiHollow.IsInside(player)) return true;
if (piece.GetComponentInChildren<Plant>(true) == null) return true;
player.Message(MessageHud.MessageType.Center, "Nothing takes root here.");
return false;
}
}
}