RacesOfValheim/JotunnModStub/PieceDensityLimit.cs
2026-09-10 18:05:24 +02:00

202 lines
9.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>
/// Extra placement rules, one per piece, for the chains whose cap cannot be expressed as
/// "how many of THIS piece stand nearby".
///
/// The Skadi's golem is the case that forced this: the piece it builds removes itself a frame
/// later and leaves a creature behind, so counting the piece counts nothing, and one of its two
/// caps is per-stonecutter rather than per-area. A gate is handed the same player and the same
/// placement point the simple limit gets, says yes or no, and is responsible for its own
/// refusal message - which is the whole extension: the counting is the chain's business, being
/// the ONE Player.PlacePiece prefix in the mod is still this class's.
/// </summary>
private static readonly Dictionary<string, System.Func<Player, Vector3, bool>> Gates =
new Dictionary<string, System.Func<Player, Vector3, bool>>();
/// <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>
/// Adds a rule of the chain's own to a piece. Same call-once-from-Register() contract as
/// <see cref="Register"/>, and a second call replaces the first rather than stacking.
/// </summary>
public static void RegisterGate(string piecePrefabName, System.Func<Player, Vector3, bool> gate)
{
if (string.IsNullOrEmpty(piecePrefabName) || gate == null)
{
Jotunn.Logger.LogWarning($"[Density] Refusing a nonsense gate for '{piecePrefabName}'.");
return;
}
Gates[piecePrefabName] = gate;
Jotunn.Logger.LogInfo($"[Density] {piecePrefabName}: a rule of its own runs at placement.");
}
/// <summary>
/// Every ZDO in the world carrying that prefab. False when the world cannot be asked right
/// now, which callers must read as "no information" rather than as "none".
///
/// ZDOs and not loaded GameObjects, for the reason at the top of this file, and public
/// because the Skadi's golem counts by an anchor written INTO each ZDO rather than by
/// distance - so it needs the ZDOs themselves and not a tally of them.
/// </summary>
public static bool Gather(string prefabName, List<ZDO> into)
{
if (ZDOMan.instance == null || into == null) return false;
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(prefabName, into, ref index)) break;
}
return true;
}
/// <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)
{
List<ZDO> zdos = new List<ZDO>();
if (!Gather(piecePrefabName, zdos)) return -1;
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)
{
// The chain's own rule first: it is the more specific of the two, so it should be the one
// that gets to explain itself when both would refuse.
if (Gates.TryGetValue(piecePrefabName, out System.Func<Player, Vector3, bool> gate) &&
!gate(player, position))
{
return false;
}
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>
// Valheim 1.0 appended a 'bool cheated' parameter to this overload. The type array has to
// match it exactly or the patch silently fails to bind and PatchAll throws.
[HarmonyPatch(typeof(Player), "PlacePiece",
new[] { typeof(Piece), typeof(Vector3), typeof(Quaternion), typeof(bool), 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);
}
}
}