RacesOfValheim/JotunnModStub/Sverm/SvermBeehive.cs
Ferdinando 7ac7f99287 feat(sverm): enforce the beehive cap, and put the aura and the nest limits in config
"Beehives per Aura" was bound into the config and then read by nobody.
SvermConfigManagement.Beehives had no callers and neither did the
constant behind it, so the entry described a limit that did not exist and
a player could raise thirty hives in one aura and get thirty workers.

SweepAura is two passes now, with the cap between them. The first applies
to hives already taken and counts them - that maintenance is not
skippable, it is what survives a zone reload - and only then are new
candidates considered. One pass would have let the order the physics
query happens to return decide whether a hive counted against the cap or
was measured by it. The minute keeps running on a hive that does not fit
today, so when a taken hive is destroyed the one that has waited longest
is claimed on the next sweep instead of starting over; lowering the cap
never hands a hive back.

Three limits are now the player's: Aura Radius, Nests per Radius and Nest
Spacing Radius. PieceDensityLimit.Register takes a snapshot of its
numbers, so the Hive Market and the Brood Mound both watch their entries
and re-register when one moves - Register replaces an entry rather than
stacking a second limit on the same piece.

All three are clamped, and the reason is not tidiness: Register REFUSES a
radius of zero or a maximum below one, and a refused limit is no limit at
all. A player typing 0 into "Nests per Radius" to mean "no nests" would
have been handed unlimited nests.

Every player-facing string that stated the old numbers now reads the live
ones - the two build refusals, the orphaned market's message and hover,
and the two Compendium lines. The nest's hover shows the cap next to the
count, so moving the knob has visible effect.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-29 08:45:28 +02:00

227 lines
10 KiB
C#

using System.Collections.Generic;
using Jotunn.Managers;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The takeover of the ordinary beehives standing inside a nest's aura.
///
/// A minute inside the aura and a hive stops being the player's and becomes the colony's: an
/// egg pushes out through the roof, and from then on it fills twice as fast and holds three
/// times as much. After Yagluth what comes out is royal jelly instead of honey.
///
/// NOTHING IS CLONED AND NOTHING IS REPLACED. The vanilla Beehive component is retuned in
/// place on that one instance, and the state lives on that instance's ZDO - so an infected
/// hive stays infected across a reload, other players see the same thing, and a hive outside
/// any aura is never touched. The egg is a borrowed model parented to the hive, exactly the
/// way the crest is worn on a bone.
///
/// Retuning a COMPONENT is safe where retuning m_shared would not be: m_secPerUnit lives on
/// the instance, not on shared item data, so one hive changing does not change every hive in
/// the world.
/// </summary>
public static class SvermBeehive
{
/// <summary>Written on the hive's own ZDO, so the takeover survives a reload.</summary>
private const string InfectedKey = "RacesOfValheim_SvermInfected";
/// <summary>When this hive first came under an aura, so the minute can be counted.</summary>
private const string ClaimedAtKey = "RacesOfValheim_SvermClaimedAt";
private const string EggName = "SvermHiveEgg";
/// <summary>Values captured before we touched them, so a hive can be handed back intact.</summary>
private static readonly Dictionary<Beehive, float> originalSecPerUnit = new Dictionary<Beehive, float>();
// ─── The sweep ───────────────────────────────────────────────────────
/// <summary>
/// Called by the nest, on a timer. Claims what is in range and ripens what has waited.
///
/// TWO PASSES, AND THE CAP SITS BETWEEN THEM. "Beehives per Aura" was bound into the config
/// and then read by nobody: the number sat in the file describing a limit that did not
/// exist, and a player could raise thirty hives in one aura and get thirty workers. The
/// maintenance of hives already taken has to happen either way - Apply is what survives a
/// zone reload, so skipping it would quietly hand hives back at vanilla speed - which is
/// exactly why the count has to be finished before the first new one is considered. One
/// pass would let the order the physics query happens to return decide whether a hive
/// counts against the cap or is measured by it.
///
/// LOWERING THE CAP NEVER UNTAKES ANYTHING. An infected hive is an egg the player has been
/// looking at and a worker that already exists; the cap governs what happens next, not what
/// has happened. Over the cap simply means nothing new is claimed until one goes.
/// </summary>
public static void SweepAura(Vector3 nest)
{
List<Beehive> hives = Find(nest);
int taken = 0;
foreach (Beehive hive in hives)
{
ZNetView nview = hive.GetComponent<ZNetView>();
if (nview == null || !nview.IsValid()) continue;
if (!nview.GetZDO().GetBool(InfectedKey, false)) continue;
Apply(hive, nview);
taken++;
}
int cap = SvermConfigManagement.Beehives;
foreach (Beehive hive in hives)
{
ZNetView nview = hive.GetComponent<ZNetView>();
if (nview == null || !nview.IsValid()) continue;
if (nview.GetZDO().GetBool(InfectedKey, false)) continue;
// First sighting starts the clock. Stored as world time rather than counted in a
// field, because a nest that unloads and comes back must not restart the minute.
double claimedAt = nview.GetZDO().GetFloat(ClaimedAtKey, 0f);
if (claimedAt <= 0.0)
{
nview.GetZDO().Set(ClaimedAtKey, (float)ZNet.instance.GetTimeSeconds());
continue;
}
if (ZNet.instance.GetTimeSeconds() - claimedAt < SvermConfig.BeehiveInfectionSeconds) continue;
// Ripe, and the colony may still be full. The cap is tested HERE and not at the top
// of the loop so the minute keeps running on a hive that does not fit today: when a
// taken hive is destroyed, the one that has been waiting longest is claimed on the
// very next sweep instead of starting its minute over.
if (taken >= cap) continue;
nview.GetZDO().Set(InfectedKey, true);
Apply(hive, nview);
taken++;
Jotunn.Logger.LogInfo($"[Sverm] A beehive has been taken over by the colony ({taken} of {cap}).");
}
}
/// <summary>
/// Retunes one infected hive and makes sure it is wearing its egg.
///
/// Re-applied on every sweep rather than once at infection: Valheim rebuilds these
/// components when the zone reloads, and a hive that came back at vanilla speed would
/// quietly undo the whole feature with nothing in the log to say so.
/// </summary>
private static void Apply(Beehive hive, ZNetView nview)
{
if (!originalSecPerUnit.ContainsKey(hive)) originalSecPerUnit[hive] = hive.m_secPerUnit;
float wanted = originalSecPerUnit[hive] / SvermConfig.BeehiveSpeedMultiplier;
if (!Mathf.Approximately(hive.m_secPerUnit, wanted)) hive.m_secPerUnit = wanted;
int wantedMax = Mathf.RoundToInt(SvermConfig.BeehiveBaseMaxHoney * SvermConfig.BeehiveCapacityMultiplier);
if (hive.m_maxHoney != wantedMax) hive.m_maxHoney = wantedMax;
// After Yagluth the colony stops making honey and starts making royal jelly. Read from
// ObjectDB rather than held as a reference, because the item has to exist first.
string wantedItem = BossProgressionManager.GetCurrentProgressionState() >= SvermConfig.RoyalJellyHiveState
? SvermConfig.RoyalJellyPrefab
: "Honey";
if (hive.m_honeyItem == null || hive.m_honeyItem.gameObject.name != wantedItem)
{
ItemDrop replacement = PrefabManager.Cache.GetPrefab<ItemDrop>(wantedItem);
if (replacement != null) hive.m_honeyItem = replacement;
}
EnsureEgg(hive.transform);
}
/// <summary>
/// The egg on the roof: a permanent mark, and the only way to tell an infected hive from an
/// ordinary one at a glance.
///
/// Borrowed through ModelBorrow, so it arrives stripped of its ItemDrop and its networking
/// and cannot be picked up, walked into, or dropped on the floor.
/// </summary>
private static void EnsureEgg(Transform hive)
{
if (hive.Find(EggName) != null) return;
ModelBorrow.Attach(
hive,
EggName,
SvermConfig.HiveEggPrefab,
Vector3.up * SvermConfigManagement.EggHeight,
Quaternion.identity,
SvermConfigManagement.EggSize,
"Sverm");
}
// ─── Lookups ─────────────────────────────────────────────────────────
/// <summary>Every beehive standing inside a nest's aura.</summary>
public static List<Beehive> Find(Vector3 nest)
{
List<Beehive> found = new List<Beehive>();
foreach (Collider collider in Physics.OverlapSphere(nest, SvermConfigManagement.AuraRadius))
{
if (collider == null) continue;
Beehive hive = collider.GetComponentInParent<Beehive>();
if (hive != null && !found.Contains(hive)) found.Add(hive);
}
return found;
}
public static int CountInAura(Vector3 nest) => Find(nest).Count;
public static int CountInfectedInAura(Vector3 nest)
{
int count = 0;
foreach (Beehive hive in Find(nest))
{
if (IsInfected(hive)) count++;
}
return count;
}
/// <summary>
/// Puts the colony's marks on every taken hive in range: flies always, green gas only when
/// the hive is FULL and has nothing left to do but wait for someone to empty it.
///
/// Called by the nest on every client, not from the owner's sweep - particles are local, and
/// a hive that only smoked on the host's screen would be half a feature.
/// </summary>
public static void DressInfected(Vector3 nest)
{
float scale = SvermConfigManagement.BeehiveVfxScale;
foreach (Beehive hive in Find(nest))
{
if (!IsInfected(hive)) continue;
SvermHiveVfx.EnsureFlies(hive.transform, scale);
SvermHiveVfx.SetGas(hive.transform, IsFull(hive), scale);
}
}
/// <summary>
/// Whether the hive has no room left for honey.
///
/// GetHoneyLevel is private in the assembly this project compiles against - like
/// Container.Save and Inventory.FindEmptySlot - so it is read through Traverse rather than
/// called, and rather than second-guessed by reading the ZDO key by hand.
/// </summary>
private static bool IsFull(Beehive hive)
{
if (hive == null) return false;
int level = HarmonyLib.Traverse.Create(hive).Method("GetHoneyLevel").GetValue<int>();
return level >= hive.m_maxHoney;
}
public static bool IsInfected(Beehive hive)
{
ZNetView nview = hive != null ? hive.GetComponent<ZNetView>() : null;
return nview != null && nview.IsValid() && nview.GetZDO().GetBool(InfectedKey, false);
}
}
}