RacesOfValheim/JotunnModStub/Sverm/SvermHiveGoods.cs
2026-10-06 11:36:18 +02:00

495 lines
20 KiB
C#

using System;
using System.Collections.Generic;
using HarmonyLib;
using TMPro;
using UnityEngine;
using UnityEngine.UI;
namespace RacesOfValheim
{
/// <summary>
/// What the Hive Market sells, and the column it is sold from.
///
/// THE VANILLA BUY LIST CANNOT CARRY THIS. StoreGui's own column is a list of
/// Trader.TradeItem, every one of which is an ItemDrop that lands in your inventory when you pay
/// coin for it. The hive sells no items: it sells a stage of growth, which is a number on its
/// own ZDO. So the goods hang in a column of our own, cloned from the store's list element -
/// exactly what TrolTotemStore does for its warbands, down to sitting at m_listRoot's own
/// position and switching itself off when the window belongs to somebody else.
///
/// That position matters and it is the correction of a failed attempt: the first version of the
/// hive's panel put its column at m_listRoot's position PLUS 260 px, which is outside the panel
/// that clips it. It drew perfectly and nobody could see or click a single row of it.
///
/// PRICES ARE THE DOCUMENT'S, unchanged: 1000, 1500, 2000, each one the full tank of the stage
/// it buys you out of, so growing always empties the hive.
/// </summary>
public static class SvermHiveGoods
{
/// <summary>One thing the market sells.</summary>
public class Good
{
public string Id;
public string Name;
public float Price;
public string Icon;
public string Description;
/// <summary>Why this cannot be bought right now, or null when it can.</summary>
public Func<SvermHiveBehaviour, string> Refusal;
/// <summary>Hands over the goods. Only ever called after the price has been taken.</summary>
public Action<SvermHiveBehaviour> Deliver;
/// <summary>
/// How long before another of these, in seconds. A function and not a number because the
/// upgrades wait a GAME DAY, and how long a game day is belongs to the world rather than
/// to this table.
/// </summary>
public Func<float> Cooldown;
}
/// <summary>
/// The shelf: three stages, two stars, four troops.
///
/// NO VENOM COIL. Section 13's serpent turret was built and then taken out again at the
/// player's call - it is not on this shelf, there is no prefab for it, and it is not a thing
/// waiting to be finished. If it ever comes back it comes back as a new decision.
///
/// Stages first, because they are what unlocks the rest of the list.
/// </summary>
public static readonly List<Good> Shelf = BuildShelf();
private static List<Good> BuildShelf()
{
List<Good> shelf = new List<Good>
{
StageUpgrade(2, "TrophySeeker"),
StageUpgrade(3, "TrophySeekerBrute"),
StageUpgrade(4, "TrophySeekerQueen"),
Star(1, ModText.Get("rov_sverm_good_glands_name"), 800f, "TrophySeeker",
ModText.Get("rov_sverm_good_glands_desc")),
Star(2, ModText.Get("rov_sverm_good_hyperplasia_name"), 1600f, "TrophySeekerQueen",
ModText.Get("rov_sverm_good_hyperplasia_desc")),
};
foreach (SvermBrood.Kind kind in SvermBrood.Roster) shelf.Add(Troop(kind));
shelf.Add(BlisterTick());
return shelf;
}
/// <summary>
/// The bomb tick, which is the only thing on this shelf you buy ONCE and keep having.
/// Section 12: fifty biomass and an egg buy a slot, the slot is permanent, and whatever
/// stands in it comes back for free half a minute after it bursts.
/// </summary>
private static Good BlisterTick()
{
return new Good
{
Id = "blistertick",
Name = Localization.instance.Localize(SvermBlisterTick.DisplayName),
Price = SvermConfig.TickPrice,
Icon = "TrophyTick",
Description = ModText.Get("rov_sverm_good_tick_desc"),
Refusal = hive =>
{
int slots = SvermBlisterTick.SlotsOf(hive.transform);
if (slots >= SvermBlisterTick.SlotCap(hive.transform))
{
return ModText.Get("rov_sverm_refusal_keeps", slots);
}
if (SvermBroodEggs.Count(hive.transform) < 1) return ModText.Get("rov_sverm_refusal_no_egg");
return null;
},
Deliver = hive =>
{
if (!SvermBroodEggs.Take(hive.transform, 1))
{
SvermBiomass.Refund(hive.transform, SvermConfig.TickPrice);
return;
}
if (SvermBlisterTick.SlotsOf(hive.transform) >= SvermBlisterTick.SlotCap(hive.transform))
{
SvermBiomass.Refund(hive.transform, SvermConfig.TickPrice);
return;
}
SvermBlisterTick.BuySlot(hive.transform);
SvermBlisterTick.Hatch(hive);
},
// The tick has no queue of its own: the wait is the thirty seconds it takes to come
// back, and that is enforced at the nest rather than at the counter.
Cooldown = () => 0f,
};
}
/// <summary>
/// One step up the four stages. The price is the tank it empties, from section 10.1.
/// </summary>
private static Good StageUpgrade(int target, string icon)
{
int from = target - 1;
return new Good
{
Id = "stage" + target,
Name = Localization.instance.Localize(SvermHiveStage.NameOf(target)),
Price = SvermHiveStage.PriceToLeave(from),
Icon = icon,
Description = ModText.Get("rov_sverm_good_stage_desc", SvermHiveStage.NameOf(target),
SvermHiveStage.Capacity(target).ToString("0"), SvermHiveStage.Capacity(from).ToString("0")),
Refusal = hive =>
{
int stage = SvermHiveStage.Of(hive.transform);
if (stage > from) return ModText.Get("rov_sverm_refusal_grown_past");
if (stage < from) return ModText.Get("rov_sverm_refusal_stage_first", SvermHiveStage.NameOf(from));
return null;
},
Deliver = hive => SvermHiveStage.Advance(hive.transform),
Cooldown = () => DayLength() * SvermConfig.UpgradeCooldownDays,
};
}
/// <summary>
/// One of the two permanent star upgrades. They are a ladder: the glands before the
/// hyperplasia.
///
/// THE LADDER IS AN INVENTION. The document prices them separately and says nothing about
/// needing one for the other - but without it the cheap path to two stars is to skip the
/// eight hundred entirely, which makes the first upgrade a thing only a mistake buys.
/// </summary>
private static Good Star(int stars, string name, float price, string icon, string description)
{
return new Good
{
Id = "stars" + stars,
Name = name,
Price = price,
Icon = icon,
Description = description,
Refusal = hive =>
{
int have = SvermBroodStars.Of(hive.transform);
if (have >= stars) return ModText.Get("rov_sverm_refusal_already_breeds");
if (have < stars - 1) return ModText.Get("rov_sverm_refusal_one_star");
return null;
},
Deliver = hive => SvermBroodStars.Set(hive.transform, stars),
Cooldown = () => DayLength() * SvermConfig.UpgradeCooldownDays,
};
}
/// <summary>
/// One rung of the roster on sale. Costs biomass AND a brood egg, which is section 10.2's
/// two resources in parallel: the egg is the slot and grows back, the biomass is the price
/// and does not.
/// </summary>
private static Good Troop(SvermBrood.Kind kind)
{
return new Good
{
Id = "troop_" + kind.Id,
Name = Localization.instance.Localize(kind.Display),
Price = kind.Price,
Icon = kind.Icon,
Description = ModText.Get("rov_sverm_good_troop_desc", kind.Display, kind.Cap),
Refusal = hive =>
{
int stage = SvermHiveStage.Of(hive.transform);
if (stage < kind.Stage)
{
return ModText.Get("rov_sverm_refusal_stage_first", SvermHiveStage.NameOf(kind.Stage));
}
int alive = SvermBrood.CountAlive(hive, kind);
if (alive >= kind.Cap) return ModText.Get("rov_sverm_refusal_keeping", alive);
if (SvermBroodEggs.Count(hive.transform) < 1) return ModText.Get("rov_sverm_refusal_no_egg");
return null;
},
Deliver = hive =>
{
// The egg is taken here rather than in Buy, because it is this good's price and
// not every good's: an upgrade costs biomass and nothing else.
//
// And if the egg is gone between the refusal check and this line - which only two
// players at one nest can manage - the biomass goes back. A purchase that took
// the price and handed over nothing is the one outcome worth writing code for.
if (!SvermBroodEggs.Take(hive.transform, 1))
{
SvermBiomass.Refund(hive.transform, kind.Price);
return;
}
if (!SvermBrood.Hatch(hive, kind))
{
SvermBiomass.Refund(hive.transform, kind.Price);
}
},
Cooldown = () => kind.Cooldown,
};
}
// ─── Buying ──────────────────────────────────────────────────────────
/// <summary>
/// Why this good is greyed out, or null when it can be bought.
///
/// The order of the questions is the order the player would ask them: can I have it at all,
/// is it too soon, can I afford it.
/// </summary>
public static string RefusalFor(Good good, SvermHiveBehaviour hive)
{
if (good == null || hive == null) return ModText.Get("rov_sverm_refusal_no_hive");
string ownRefusal = good.Refusal != null ? good.Refusal(hive) : null;
if (ownRefusal != null) return ownRefusal;
long waitingSeconds = CooldownLeft(hive.transform, good);
if (waitingSeconds > 0L)
{
return waitingSeconds >= 60L
? ModText.Get("rov_sverm_refusal_working_m", waitingSeconds / 60)
: ModText.Get("rov_sverm_refusal_working_s", waitingSeconds);
}
if (SvermBiomass.Bank(hive.transform) < good.Price) return ModText.Get("rov_msg_sverm_not_enough_biomass_bank");
return null;
}
public static bool Buy(Good good, SvermHiveBehaviour hive, Player player)
{
string refusal = RefusalFor(good, hive);
if (refusal != null)
{
player?.Message(MessageHud.MessageType.Center, refusal);
return false;
}
// Paid first and delivered second, and never the other way round: Spend is the only
// thing here that can fail on a race with another client, and a hive that hands over a
// stage it was not paid for cannot be undone.
if (!SvermBiomass.Spend(hive.transform, good.Price))
{
player?.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_sverm_not_enough_biomass_bank"));
return false;
}
good.Deliver?.Invoke(hive);
StampCooldown(hive.transform, good.Id);
player?.Message(MessageHud.MessageType.Center, good.Name);
return true;
}
// ─── The day between purchases ───────────────────────────────────────
/// <summary>
/// How long this good still has to wait, on the world clock.
///
/// Section 20.4 asks for two different clocks and this is both of them: a GAME DAY between
/// upgrades, and a wait of its own for every troop - ten minutes for a Gjall, the rest
/// scaled by price. On the three stage upgrades nobody will ever see it, since each of them
/// can only be bought once; on the troops it is the pacing.
/// </summary>
private static long CooldownLeft(Transform nest, Good good)
{
ZNetView nview = nest != null ? nest.GetComponent<ZNetView>() : null;
if (nview == null || !nview.IsValid()) return 0L;
long stamped = nview.GetZDO().GetLong(CooldownKey(good.Id), 0L);
if (stamped <= 0L) return 0L;
float wait = good.Cooldown != null ? good.Cooldown() : 0f;
if (wait <= 0f) return 0L;
long ready = stamped + (long)wait;
long now = WorldSecond();
return now >= ready ? 0L : ready - now;
}
private static void StampCooldown(Transform nest, string id)
{
ZNetView nview = nest != null ? nest.GetComponent<ZNetView>() : null;
if (nview == null || !nview.IsValid()) return;
if (!nview.IsOwner()) nview.ClaimOwnership();
nview.GetZDO().Set(CooldownKey(id), WorldSecond());
}
private static string CooldownKey(string id) => "RacesOfValheim_SvermBought_" + id;
/// <summary>A day of game time in seconds. The world's own setting, not a hardcoded 1800.</summary>
private static float DayLength()
{
return EnvMan.instance != null ? EnvMan.instance.m_dayLengthSec : 1800f;
}
private static long WorldSecond()
{
return ZNet.instance != null ? (long)ZNet.instance.GetTimeSeconds() : 0L;
}
}
// ─── The column ──────────────────────────────────────────────────────────
[HarmonyPatch(typeof(StoreGui), "Awake")]
public static class SvermHiveGoodsSetupPatch
{
public static void Postfix(StoreGui __instance) => SvermHiveGoodsPanel.Create(__instance);
}
[HarmonyPatch(typeof(StoreGui), "FillList")]
public static class SvermHiveGoodsFillPatch
{
public static void Postfix(StoreGui __instance) => SvermHiveGoodsPanel.Refresh(__instance);
}
[HarmonyPatch(typeof(StoreGui), "Hide")]
public static class SvermHiveGoodsHidePatch
{
public static void Postfix() => SvermHiveGoodsPanel.Clear();
}
/// <summary>
/// The market's shelf on screen. Built the way TrolTotemStore builds the war totem's, which is
/// the one column in this mod that is known to draw where a player can see it.
/// </summary>
public static class SvermHiveGoodsPanel
{
private static RectTransform _root;
private static readonly List<GameObject> _rows = new List<GameObject>();
public static void Create(StoreGui gui)
{
if (gui == null || gui.m_listRoot == null)
{
Jotunn.Logger.LogWarning("[Sverm] StoreGui has no m_listRoot; the market's shelf cannot be built.");
return;
}
if (_root != null) return;
GameObject clone = UnityEngine.Object.Instantiate(gui.m_listRoot.gameObject, gui.m_listRoot.parent);
clone.name = "SvermHiveGoodsList";
_root = clone.GetComponent<RectTransform>();
// The vanilla list's OWN position. An offset from it - 260 px was the first guess - puts
// the column outside the panel that clips it, where it draws perfectly and invisibly.
_root.anchoredPosition = gui.m_listRoot.anchoredPosition;
foreach (Transform child in _root) UnityEngine.Object.Destroy(child.gameObject);
_root.gameObject.SetActive(false);
}
public static void Clear()
{
foreach (GameObject row in _rows) if (row != null) UnityEngine.Object.Destroy(row);
_rows.Clear();
if (_root != null) _root.gameObject.SetActive(false);
}
public static void Refresh(StoreGui gui)
{
Clear();
SvermHiveBehaviour hive = SvermHiveStore.ActiveHive(gui);
if (hive == null) return; // an ordinary merchant, or the war totem. Not ours.
if (_root == null)
{
Jotunn.Logger.LogWarning("[Sverm] The market's shelf was never built (did the patch on " +
"StoreGui.Awake fail?), so nothing can be drawn into it.");
return;
}
_root.gameObject.SetActive(true);
int row = 0;
foreach (SvermHiveGoods.Good good in SvermHiveGoods.Shelf)
{
BuildRow(gui, hive, good, row++);
}
float baseSize = Traverse.Create(gui).Field("m_itemlistBaseSize").GetValue<float>();
_root.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, Mathf.Max(baseSize, row * gui.m_itemSpacing));
}
private static void BuildRow(StoreGui gui, SvermHiveBehaviour hive, SvermHiveGoods.Good good, int rowIndex)
{
GameObject element = UnityEngine.Object.Instantiate(gui.m_listElement, _root);
element.SetActive(true);
RectTransform rt = (RectTransform)element.transform;
float offset = (_root.rect.width - rt.rect.width) / 2f;
rt.anchoredPosition = new Vector2(offset, rowIndex * -gui.m_itemSpacing - offset);
string refusal = SvermHiveGoods.RefusalFor(good, hive);
bool available = refusal == null;
Sprite icon = SvermHive.BorrowIcon(good.Icon) ?? SvermHive.BorrowIcon("Honey");
Image iconImage = element.transform.Find("icon").GetComponent<Image>();
if (icon != null) iconImage.sprite = icon;
iconImage.color = available ? Color.white : Color.grey;
TMP_Text nameLabel = element.transform.Find("name").GetComponent<TMP_Text>();
nameLabel.text = good.Name;
nameLabel.color = available ? Color.white : Color.grey;
TMP_Text price = FindDescendant<TMP_Text>(element.transform, "price");
if (price != null)
{
price.text = good.Price.ToString("0");
price.color = available ? Color.white : Color.grey;
}
UITooltip tooltip = element.GetComponent<UITooltip>();
if (tooltip != null)
{
string body = available ? good.Description : refusal + "\n\n" + good.Description;
tooltip.Set(good.Name, body, gui.m_tooltipAnchor, default(Vector2));
}
Button button = element.GetComponent<Button>();
button.interactable = available;
button.onClick.AddListener(() =>
{
SvermHiveGoods.Buy(good, hive, Player.m_localPlayer);
Traverse.Create(gui).Method("FillList").GetValue(); // repaints the shelf
});
_rows.Add(element);
}
private static T FindDescendant<T>(Transform root, string childName) where T : Component
{
foreach (T candidate in root.GetComponentsInChildren<T>(true))
{
if (candidate.gameObject.name == childName) return candidate;
}
return null;
}
}
}