warvulture

This commit is contained in:
Ferdinando 2026-08-11 16:30:20 +02:00
commit 1d66b00374
29 changed files with 7236 additions and 4 deletions

View file

@ -0,0 +1,518 @@
using System.Collections.Generic;
using HarmonyLib;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The two mouths of the nest, and the window behind one of them.
///
/// FIRST PASS, AND WHY IT WAS THROWN AWAY. Feeding used to be a button in a second column of
/// the vanilla store, cloned the way FactionMerchantSellPanel clones one. In game the window
/// came up EMPTY and the button did nothing you could click - the column is drawn outside the
/// panel that clips it, and that panel's own sell button sells for coins, which a hive does not
/// have. Both problems disappear if the feeding never goes through a UI at all.
///
/// So the nest wears two hives instead. The one at its foot is the STOMACH: press E and it
/// takes a whole stack out of your inventory. The one up top is the MARKET: press E and the
/// vanilla store opens, which is where the upgrades of 20.4 will hang when they are written.
/// The store's own sell button is switched off while a hive's window is open.
///
/// Feeding reads the INVENTORY and never the hand, which was the point of section 20.1: food is
/// a consumable, it never reaches the weapon slot, and "press E holding meat" only ever fed the
/// player.
/// </summary>
public static class SvermHiveStore
{
/// <summary>
/// Opens the store standing at <paramref name="host"/>, spending the tank of
/// <paramref name="hive"/>.
///
/// THE TRADER LIVES ON THE BENCH AND NOT ON THE NEST, and that is not tidiness either.
/// StoreGui.Update measures the player against the TRADER's transform and closes the window
/// past m_hideDistance - so a trader left on the nest would slam the window shut the moment
/// you used a bench standing anywhere but on top of it. The bench carries the trader; the
/// nest it points at carries the biomass.
///
/// It goes on a CHILD of the bench for a second reason: Trader is an Interactable and so is
/// the bench, and vanilla Player.Interact resolves its target with
/// GetComponentInParent&lt;Interactable&gt;, which returns whichever implementation happens to
/// sit first in the component list. The Factions module lost a day to exactly that ambiguity
/// (see FactionMerchantInteractPatch). A child with no collider is never the hovered object,
/// so it never enters the race.
/// </summary>
public static bool Open(GameObject host, SvermHiveBehaviour hive, Player player)
{
if (host == null || hive == null || player == null || StoreGui.instance == null) return false;
Trader trader = Mount(host, hive);
if (trader == null) return false;
StoreGui.instance.Show(trader);
return true;
}
private static Trader Mount(GameObject host, SvermHiveBehaviour hive)
{
SvermHiveShop shop = host.GetComponentInChildren<SvermHiveShop>(true);
if (shop != null)
{
// Re-bound on every visit: the nest a bench answers to is whichever one is nearest
// TODAY, and nests can be torn down and raised again around a bench that never moved.
shop.Hive = hive;
return shop.GetComponent<Trader>();
}
GameObject holder = new GameObject("SvermHiveMerchant");
holder.transform.SetParent(host.transform, false);
shop = holder.AddComponent<SvermHiveShop>();
shop.Hive = hive;
Trader trader = holder.AddComponent<Trader>();
trader.m_name = SvermHive.DisplayName;
// DISABLED ON PURPOSE, and this is the load-bearing line of the file. Trader was written
// for Haldor, who is a creature with an animator: Trader.Update() calls
// m_animator.SetBool("Stand", false) with no null check whenever no player is nearby, and
// Trader.Start() calls InvokeRepeating("RandomTalk", m_randomTalkInterval, ...) with an
// interval of zero on a component nobody authored in the editor. On a building both of
// those throw. A disabled component runs neither - and StoreGui needs neither, because
// Show() only reads fields off the Trader and asks it for its item list.
trader.enabled = false;
// Filled rather than assumed: these are serialized fields, and what a runtime
// AddComponent leaves in them is the constructor's business, not the editor's.
trader.m_items = new List<Trader.TradeItem>();
trader.m_useItems = new List<Trader.TraderUseItem>();
trader.m_randomTalk = new List<string>();
trader.m_randomGreets = new List<string>();
trader.m_randomGoodbye = new List<string>();
trader.m_randomStartTrade = new List<string>();
trader.m_randomBuy = new List<string>();
trader.m_randomSell = new List<string>();
return trader;
}
/// <summary>The nest behind the store window, or null if the window is not a hive's.</summary>
public static SvermHiveBehaviour ActiveHive(StoreGui gui)
{
Trader trader = FactionMerchantRuntime.GetActiveTrader(gui);
if (trader == null) return null;
SvermHiveShop shop = ((Component)trader).GetComponent<SvermHiveShop>();
return shop != null ? shop.Hive : null;
}
// ─── Feeding ─────────────────────────────────────────────────────────
/// <summary>
/// One press, one stack.
///
/// A stack and not the whole pack: the player can see what left, one press at a time, and a
/// misplaced E costs a stack of wood rather than the larder. The first thing in the
/// inventory the hive will eat is the thing it takes, so the order on screen is the order it
/// goes in.
///
/// Returns true if it did anything at all - the messages are the honest part, since a nest
/// that quietly does nothing is what sent the last pass back.
/// </summary>
public static bool FeedOneStack(SvermHiveBehaviour hive, Player player)
{
if (hive == null || player == null) return false;
Inventory inventory = player.GetInventory();
if (inventory == null) return false;
float room = SvermBiomass.Space(hive.transform);
if (room <= 0f)
{
player.Message(MessageHud.MessageType.Center, "The hive is full. Give it time to digest.");
return true;
}
foreach (ItemDrop.ItemData item in new List<ItemDrop.ItemData>(inventory.GetAllItems()))
{
if (item == null || item.m_stack <= 0) continue;
float perUnit = SvermBiomass.ValueOf(item);
if (perUnit <= 0f) continue;
// Not "does the stack fit" but "how much of it does": one royal jelly's worth of room
// should still take one royal jelly.
int units = Mathf.Min(item.m_stack, Mathf.FloorToInt(room / perUnit));
if (units <= 0) continue;
string name = Localization.instance.Localize(item.m_shared.m_name);
float fed = SvermBiomass.Swallow(hive.transform, units * perUnit);
inventory.RemoveItem(item, units);
player.Message(MessageHud.MessageType.TopLeft,
$"{name} x{units} -> +{fed:0} biomass, digesting");
return true;
}
player.Message(MessageHud.MessageType.Center,
"Nothing here it will eat. Food, wood and resin - honey and royal jelly are medicine.");
return true;
}
}
/// <summary>
/// Marker on the child that carries the nest's Trader. Everything else reads it to answer "is
/// the open store window a hive's, and if so, whose".
/// </summary>
public class SvermHiveShop : MonoBehaviour
{
public SvermHiveBehaviour Hive;
}
// ─── The two mouths ──────────────────────────────────────────────────────
/// <summary>
/// Shared half of the two hives bolted to the nest: find the nest, refuse anyone who is not a
/// Sverm, and show the tank.
///
/// EACH MOUTH NEEDS ITS OWN COLLIDER, and that is not decoration. Player.FindHoverObject asks
/// hit.collider.GetComponent&lt;Hoverable&gt; - GetComponent on the collider's own GameObject, not
/// GetComponentInParent - and stops at the first collider the ray meets. So what the player is
/// pointing at is decided entirely by which collider is in front, and a mouth with no collider
/// of its own can never be pointed at. SvermHive.MountMouth gives each one a sphere wide enough
/// to stand clear of the trunk.
/// </summary>
public abstract class SvermHiveMouth : MonoBehaviour, Hoverable, Interactable
{
protected SvermHiveBehaviour Hive => GetComponentInParent<SvermHiveBehaviour>();
protected abstract string Title { get; }
protected abstract string Prompt { get; }
protected abstract bool Use(SvermHiveBehaviour hive, Player player);
public bool Interact(Humanoid user, bool hold, bool alt)
{
if (hold) return false;
Player player = user as Player;
if (player == null || player != Player.m_localPlayer) return false;
SvermHiveBehaviour hive = Hive;
if (hive == null) return false;
if (!SvermVisuals.IsSvermPlayer(player))
{
player.Message(MessageHud.MessageType.Center, "The hive does not know you.");
return true;
}
return Use(hive, player);
}
public bool UseItem(Humanoid user, ItemDrop.ItemData item) => false;
public string GetHoverName() => Title;
public string GetHoverText()
{
SvermHiveBehaviour hive = Hive;
if (hive == null) return Title;
return $"{Title}\n" +
SvermHiveReadout.Tank(hive.transform) +
$"[<color=yellow><b>$KEY_Use</b></color>] {Prompt}";
}
}
/// <summary>The hive at the foot of the nest. Press E, a stack goes in.</summary>
public class SvermHiveStomach : SvermHiveMouth
{
protected override string Title => "Hive Stomach";
protected override string Prompt => "Feed it a stack";
protected override bool Use(SvermHiveBehaviour hive, Player player)
{
return SvermHiveStore.FeedOneStack(hive, player);
}
}
// ─── The market, a building of its own ───────────────────────────────────
/// <summary>
/// The Hive Market: a bench you raise inside a nest's ten metres, and the only door to the shop.
///
/// IT WAS A SECOND MOUTH ON THE NEST and it never worked. On the trunk's measured crown it stood
/// eight metres above the player; moved to a reachable height, the .cfg still held the old zero
/// from the launch before, so it sat inside the stomach's sphere and the ray found the stomach
/// every time. The lesson is not the numbers - it is that a mouth on a shared body is always a
/// race between colliders, and this mod already has two stores that avoided that race by being
/// their own building: DvergarBanco and TrolTotem.
///
/// It owns no biomass. It finds the nest it stands in and spends THAT tank, so the serbatoio
/// stays one number in one place no matter how many benches end up around it.
/// </summary>
public static class SvermHiveMarketPiece
{
public const string PieceName = "SvermHiveMarket";
public const string DisplayName = "Hive Market";
/// <summary>Scenery only, and checked rather than trusted - see SvermHive.MouthCandidates.</summary>
private static readonly string[] SourceCandidates =
{
"CreepProp_egg_hanging01",
"CreepProp_egg_hanging02",
"Creeppillar_half_shorttendrils",
"CreepProp_hanging01",
};
public static void Register()
{
// A REAL PIECE as the body and a BORROWED MODEL as the look, which is TrolTotem's recipe
// line for line - the one store-building in this mod that is known to work in game.
// Cloning scenery instead would have meant taking whatever pivot its author used: a
// hanging egg sac hangs, and a hanging thing used as a ground piece floats or sinks.
// ModelBorrow measures the mesh and stands it on the piece's own origin, so "on the
// ground" needs no guess.
GameObject prefab = Jotunn.Managers.PrefabManager.Instance.CreateClonedPrefab(PieceName, "piece_workbench");
if (prefab == null)
{
Jotunn.Logger.LogWarning("[Sverm] Could not clone piece_workbench; the market is not registered.");
return;
}
// Down to a placeable shell: no station, no crafting, no furniture.
foreach (MonoBehaviour behaviour in prefab.GetComponentsInChildren<MonoBehaviour>(true))
{
if (behaviour == null) continue;
if (behaviour is Piece || behaviour is ZNetView || behaviour is WearNTear) continue;
Object.DestroyImmediate(behaviour);
}
foreach (Renderer renderer in prefab.GetComponentsInChildren<Renderer>(true))
{
if (renderer != null) renderer.enabled = false; // the bench's own mesh, hidden
}
AswidBloodRefinery.StripOffensive(prefab, PieceName);
string sourceName = null;
foreach (string candidate in SourceCandidates)
{
GameObject source = Jotunn.Managers.PrefabManager.Cache.GetPrefab<GameObject>(candidate);
if (source == null) continue;
if (!SvermHive.IsSafeScenery(source, candidate)) continue;
sourceName = candidate;
break;
}
if (sourceName == null)
{
Jotunn.Logger.LogWarning("[Sverm] No safe scenery to dress the market with (" +
string.Join(", ", SourceCandidates) + "); it is registered " +
"anyway and will be an invisible counter rather than none.");
}
else
{
ModelBorrow.Attach(prefab.transform, "MarketModel", sourceName,
Vector3.zero, Quaternion.identity, SvermConfigManagement.MarketSize, "Sverm");
}
Piece piece = prefab.GetComponent<Piece>() ?? prefab.AddComponent<Piece>();
piece.m_craftingStation = null;
piece.m_resources = new Piece.Requirement[0];
piece.m_name = DisplayName;
piece.m_description = "Where the colony trades. It spends the tank of the nest it stands in.";
piece.m_groundPiece = true;
piece.m_groundOnly = true;
piece.m_canBeRemoved = true;
if (prefab.GetComponent<WearNTear>() == null)
{
WearNTear wear = prefab.AddComponent<WearNTear>();
wear.m_health = 500f;
wear.m_noRoofWear = true;
wear.m_noSupportWear = true;
wear.m_destroyedEffect = new EffectList();
wear.m_hitEffect = new EffectList();
}
if (prefab.GetComponent<ZNetView>() == null) prefab.AddComponent<ZNetView>();
prefab.AddComponent<SvermHiveMarket>();
Jotunn.Managers.PieceManager.Instance.AddPiece(new Jotunn.Entities.CustomPiece(prefab, fixReference: false,
new Jotunn.Configs.PieceConfig
{
Name = DisplayName,
Description = piece.m_description,
PieceTable = Jotunn.Configs.PieceTables.Hammer,
Category = "Crafting",
Icon = SvermHive.BorrowIcon("TrophySeeker") ?? SvermHive.BorrowIcon("TrophySeekerBrute") ??
SvermHive.BorrowIcon("Honey"),
// Cheap on purpose, and these two numbers are INVENTED - the design document
// never had this building in it. The market is not a gate on anything: the nest
// is the achievement, this is the counter you trade over.
Requirements = new[]
{
new Jotunn.Configs.RequirementConfig { Item = "Wood", Amount = 10, Recover = true },
new Jotunn.Configs.RequirementConfig { Item = "Resin", Amount = 5, Recover = true },
},
}));
// One counter to a nest. The radius is the nest's own aura, so "another market too close"
// and "inside this nest's ten metres" are the same circle measured from opposite ends.
PieceDensityLimit.Register(PieceName, SvermConfig.HiveAuraRadius, 1,
"This hive already has a market.");
PieceDensityLimit.RegisterGate(PieceName, (player, position) =>
{
if (player == null) return false;
if (!SvermVisuals.IsSvermPlayer(player))
{
player.Message(MessageHud.MessageType.Center, "Only the Sverm can raise a market.");
return false;
}
if (SvermHive.NearestNest(position, SvermConfig.HiveAuraRadius) == null)
{
player.Message(MessageHud.MessageType.Center,
"A market has to stand within ten metres of a hive.");
return false;
}
return true;
});
Jotunn.Logger.LogInfo($"[Sverm] Registered '{PieceName}' from '{sourceName}'.");
}
}
/// <summary>The bench itself. Press E, the store opens on the nest it stands in.</summary>
public class SvermHiveMarket : MonoBehaviour, Hoverable, Interactable
{
private SvermHiveBehaviour Nest => SvermHive.NearestNest(transform.position, SvermConfig.HiveAuraRadius);
public bool Interact(Humanoid user, bool hold, bool alt)
{
if (hold) return false;
Player player = user as Player;
if (player == null || player != Player.m_localPlayer) return false;
if (!SvermVisuals.IsSvermPlayer(player))
{
player.Message(MessageHud.MessageType.Center, "The hive does not know you.");
return true;
}
// Asked again at every press rather than remembered: the nest this counter answered to
// last week may have been torn down since, and a market quietly spending a tank that no
// longer exists is worse than one that says so.
SvermHiveBehaviour nest = Nest;
if (nest == null)
{
player.Message(MessageHud.MessageType.Center, "No hive within ten metres. This counter is dead.");
return true;
}
return SvermHiveStore.Open(gameObject, nest, player);
}
public bool UseItem(Humanoid user, ItemDrop.ItemData item) => false;
public string GetHoverName() => SvermHiveMarketPiece.DisplayName;
public string GetHoverText()
{
SvermHiveBehaviour nest = Nest;
if (nest == null) return $"{SvermHiveMarketPiece.DisplayName}\nNo hive within ten metres.";
return $"{SvermHiveMarketPiece.DisplayName}\n" +
SvermHiveReadout.Tank(nest.transform) +
"[<color=yellow><b>$KEY_Use</b></color>] Trade with the hive";
}
}
/// <summary>The tank, worded once, for every mouth and for the trunk between them.</summary>
public static class SvermHiveReadout
{
public static string Tank(Transform nest)
{
return $"Biomass {SvermBiomass.Bank(nest):0} / {SvermBiomass.Capacity(nest):0}\n" +
$"Digesting {SvermBiomass.Digesting(nest):0}\n" +
$"Brood eggs {SvermBroodEggs.Count(nest)} / {SvermBroodEggs.Cap(nest)}\n";
}
}
// ─── The store window, made fit for a hive ───────────────────────────────
/// <summary>
/// Two edits to the vanilla window while a hive owns it, and no new UI whatsoever.
///
/// THE SELL BUTTON IS SWITCHED OFF, at the player's call and for a good reason of its own: it
/// sells the first valuable thing in the pack for COINS, which is nonsense against a hive that
/// has no coins and never wanted the amber. Switched off rather than destroyed - StoreGui is one
/// object shared with Haldor, the faction merchants and the war totem, so it has to come back
/// the moment the window belongs to somebody else.
///
/// WHERE THE COINS GO, the hive's own three numbers go instead. StoreGui.Update writes the coin
/// count into that label every frame, so this writes over it afterwards.
/// </summary>
[HarmonyPatch(typeof(StoreGui), "Update")]
public static class SvermHiveStoreWindowPatch
{
public static void Postfix(StoreGui __instance)
{
SvermHiveBehaviour hive = SvermHiveStore.ActiveHive(__instance);
if (__instance.m_sellButton != null)
{
GameObject button = __instance.m_sellButton.gameObject;
bool wanted = hive == null;
if (button.activeSelf != wanted) button.SetActive(wanted);
}
if (hive == null || __instance.m_coinText == null) return;
float bank = SvermBiomass.Bank(hive.transform);
float digesting = SvermBiomass.Digesting(hive.transform);
float capacity = SvermBiomass.Capacity(hive.transform);
__instance.m_coinText.text = digesting > 0f
? $"{bank:0} / {capacity:0} (+{digesting:0})"
: $"{bank:0} / {capacity:0}";
}
}
/// <summary>The same refusal at the other end, for a gamepad that reaches the sell action anyway.</summary>
[HarmonyPatch(typeof(StoreGui), "SellItem")]
public static class SvermHiveStoreSellItemPatch
{
public static bool Prefix(StoreGui __instance)
{
return SvermHiveStore.ActiveHive(__instance) == null;
}
}
/// <summary>
/// Belt as well as braces on the disabled Trader in SvermHiveStore.Mount: if anything ever
/// enables that component - a mod, a future edit here - Trader.Update() would start
/// dereferencing an animator the nest does not have, every frame. One component lookup removes
/// the whole class of failure.
/// </summary>
[HarmonyPatch(typeof(Trader), "Update")]
public static class SvermHiveStoreTraderUpdatePatch
{
public static bool Prefix(Trader __instance)
{
return ((Component)__instance).GetComponent<SvermHiveShop>() == null;
}
}
// The empty-catalogue crash that used to kill the whole window is NOT guarded here: the war
// totem hit it first and StoreGuiEmptyCatalogueGuardPatch in Trol/TrolTotemStore.cs already
// covers every trader in the game, this one included. It is the reason the hive's window opens
// at all with nothing in its buy list, and a second prefix doing the same job would only make
// the log lie about who is holding the door.
}