RacesOfValheim/JotunnModStub/PieceDensityLimit.cs
Ferdinando b1f5da2249 feat: shared foundations for stations and servants
RaisedThrall is the common servant base (leash, wither timer,
follow command, anchor), used by Draugh, Skeleton and Trol.
ModelBorrow lends a vanilla prefab's look without its behaviour.
PieceDensityLimit caps how many of a piece fit in an area.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-07 17:02:34 +02:00

147 lines
6.9 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;
return PieceDensityLimit.Allow(__instance, Utils.GetPrefabName(__0.gameObject), __1);
}
}
}