RacesOfValheim/JotunnModStub/Sverm/SvermFood.cs
2026-08-11 16:30:20 +02:00

273 lines
14 KiB
C#

using System.Collections.Generic;
using HarmonyLib;
using Jotunn.Entities;
using Jotunn.Managers;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// Insect Metabolism: raw meat is nearly as good as cooked, seeds are food, and honey and royal
/// jelly are worth twice what anyone else gets out of them.
///
/// THE ONE RULE THAT SHAPES THIS FILE: never write to a vanilla item's m_shared. That object is
/// shared by every instance of the item in the game, for every player and every race - setting
/// RoyalJelly.m_food would make royal jelly edible for a Skeleton too, permanently, and a
/// Sverm's 70% raw meat would be everyone's 70% raw meat.
///
/// So each edible gets a HIDDEN CLONE carrying the Sverm's numbers. When a Sverm right-clicks
/// the real item, the clone is what gets eaten and one of the real item is removed. The player
/// never sees the clone and the vanilla item is never touched. This is DraughFoodPatches'
/// EdibleUncooked_ trick, and it is here for the same reason it is there.
/// </summary>
public static class SvermFood
{
private const string ClonePrefix = "SvermMeal_";
/// <summary>Every real prefab we intercept, mapped to the clone that carries our numbers.</summary>
private static readonly Dictionary<string, string> meals = new Dictionary<string, string>();
/// <summary>Seeds are gated behind The Elder, everything else is live from tier 1.</summary>
private static readonly HashSet<string> gatedSeeds = new HashSet<string>();
private static bool registered;
// ─── The tables ──────────────────────────────────────────────────────
/// <summary>
/// Seeds by biome, and the numbers are deliberately modest.
///
/// This is grinding, not cooking: raw bulk with no buff attached. The buff on a seed is
/// Trenta's whole feature (TrentaConfig.AwakenedSeedFood), and two races eating the same
/// ingredient for the same reward would cost one of them its identity.
///
/// AncientSeed is deliberately absent. It is the offering that summons The Elder, not a
/// seed, and eating one would be an expensive accident.
/// </summary>
private struct SeedFood
{
public string Prefab;
public float Health, Stamina, Eitr, Duration, Regen;
public SeedFood(string prefab, float health, float stamina, float eitr, float duration, float regen)
{
Prefab = prefab; Health = health; Stamina = stamina; Eitr = eitr; Duration = duration; Regen = regen;
}
}
private static readonly SeedFood[] Seeds =
{
// Meadows - the weakest thing that still counts as a meal
new SeedFood("CarrotSeeds", 8f, 12f, 0f, 900f, 1f),
new SeedFood("TurnipSeeds", 8f, 12f, 0f, 900f, 1f),
new SeedFood("BeechSeeds", 8f, 10f, 0f, 900f, 1f),
new SeedFood("BirchSeeds", 8f, 10f, 0f, 900f, 1f),
// Black Forest - nuts and cones, denser
new SeedFood("Acorn", 12f, 16f, 0f, 1000f, 1f),
new SeedFood("FirCone", 12f, 16f, 0f, 1000f, 1f),
new SeedFood("PineCone", 12f, 16f, 0f, 1000f, 1f),
// Plains
new SeedFood("OnionSeeds", 16f, 20f, 0f, 1200f, 1f),
// Mistlands - the only seeds with eitr in them, which is what makes going that far pay
new SeedFood("VineberrySeeds",20f, 24f, 8f, 1200f, 2f),
new SeedFood("VineGreenSeeds",20f, 24f, 8f, 1200f, 2f),
};
// ─── Registration ────────────────────────────────────────────────────
/// <summary>
/// Builds every clone. Driven from SvermRace.CreateModAssets, which runs on
/// PrefabManager.OnVanillaPrefabsAvailable - the one moment Jotunn accepts new items.
/// </summary>
public static void Register()
{
if (registered) return;
registered = true;
// RAW MEAT. The raw-to-cooked table is Draugh's, borrowed on purpose rather than
// copied: which raw item becomes which cooked one is a fact about Valheim, not an
// opinion of either race, and a second copy would only drift out of step with the
// first the next time the game adds a meat.
foreach (KeyValuePair<string, string> pair in DraughFoodPatches.rawToCookedMapping)
{
ItemDrop.ItemData.SharedData cooked = SharedOf(pair.Value);
if (cooked == null) continue;
BuildMeal(pair.Key,
cooked.m_food * SvermConfig.RawMeatFraction,
cooked.m_foodStamina * SvermConfig.RawMeatFraction,
cooked.m_foodEitr * SvermConfig.RawMeatFraction,
cooked.m_foodBurnTime,
cooked.m_foodRegen,
"raw meat");
}
// SEEDS. Gated behind The Elder in the UseItem hook, not here: the clone can exist all
// along, it simply is not reachable before tier 3.
foreach (SeedFood seed in Seeds)
{
if (BuildMeal(seed.Prefab, seed.Health, seed.Stamina, seed.Eitr, seed.Duration, seed.Regen, "seed"))
{
gatedSeeds.Add(seed.Prefab);
}
}
// HONEY, doubled. Read at runtime and multiplied rather than transcribed, so a patch
// that rebalances honey rebalances the Sverm with it.
ItemDrop.ItemData.SharedData honey = SharedOf("Honey");
if (honey != null)
{
BuildMeal("Honey",
honey.m_food * SvermConfig.HoneyMultiplier,
honey.m_foodStamina * SvermConfig.HoneyMultiplier,
honey.m_foodEitr * SvermConfig.HoneyMultiplier,
honey.m_foodBurnTime * SvermConfig.HoneyMultiplier,
honey.m_foodRegen,
"honey");
}
// ROYAL JELLY. Not a food in vanilla at all - it is crafting material - so there is
// nothing to double and the numbers are the ones the design settled on. They are
// already the doubled figures; they are not multiplied again.
BuildMeal(SvermConfig.RoyalJellyPrefab,
SvermConfig.RoyalJellyHealth,
SvermConfig.RoyalJellyStamina,
SvermConfig.RoyalJellyEitr,
SvermConfig.RoyalJellyDuration,
SvermConfig.RoyalJellyRegen,
"royal jelly");
Jotunn.Logger.LogInfo($"[Sverm] Insect Metabolism: {meals.Count} edibles registered.");
}
private static ItemDrop.ItemData.SharedData SharedOf(string prefabName)
{
ItemDrop drop = PrefabManager.Cache.GetPrefab<ItemDrop>(prefabName);
return drop != null && drop.m_itemData != null ? drop.m_itemData.m_shared : null;
}
/// <summary>
/// One hidden clone of one real item, carrying the Sverm's numbers.
///
/// The clone is made a Consumable whatever the original was - a seed is Material in vanilla
/// and would otherwise be refused by EatFood before it got to look at the numbers.
/// </summary>
private static bool BuildMeal(string sourcePrefab, float health, float stamina, float eitr,
float duration, float regen, string label)
{
GameObject source = PrefabManager.Cache.GetPrefab<GameObject>(sourcePrefab);
if (source == null)
{
Jotunn.Logger.LogWarning($"[Sverm] No '{sourcePrefab}' to build a {label} from; skipped.");
return false;
}
string cloneName = ClonePrefix + sourcePrefab;
GameObject clone = PrefabManager.Instance.CreateClonedPrefab(cloneName, source);
if (clone == null) return false;
ItemDrop drop = clone.GetComponent<ItemDrop>();
if (drop == null || drop.m_itemData == null || drop.m_itemData.m_shared == null) return false;
ItemDrop.ItemData.SharedData shared = drop.m_itemData.m_shared;
shared.m_itemType = ItemDrop.ItemData.ItemType.Consumable;
shared.m_food = health;
shared.m_foodStamina = stamina;
shared.m_foodEitr = eitr;
shared.m_foodBurnTime = duration;
shared.m_foodRegen = regen;
// The name is what Player.Food compares on when it decides whether you are eating the
// same thing twice, so it must stay the ORIGINAL's name - otherwise raw meat and its
// clone would occupy two food slots at once.
// m_maxStackSize left alone; nothing ever holds one of these.
ItemManager.Instance.AddItem(new CustomItem(clone, fixReference: false));
meals[sourcePrefab] = cloneName;
return true;
}
// ─── Eating ──────────────────────────────────────────────────────────
/// <summary>Which clone answers for this item, or null when we do not cover it.</summary>
private static string MealFor(ItemDrop.ItemData item, int state)
{
if (item == null || item.m_shared == null) return null;
string prefabName = item.m_dropPrefab != null ? item.m_dropPrefab.name : null;
if (string.IsNullOrEmpty(prefabName)) return null;
if (gatedSeeds.Contains(prefabName) && state < SvermConfig.SeedsEdibleState) return null;
return meals.TryGetValue(prefabName, out string clone) ? clone : null;
}
public static bool IsGatedSeed(string prefabName) => gatedSeeds.Contains(prefabName);
/// <summary>
/// Swaps the real item for its clone at the moment of eating.
///
/// A prefix on UseItem rather than on EatFood, and that is what lets seeds and royal jelly
/// work at all: they are Material in vanilla, so by the time EatFood is reached the game
/// has already decided they are not food. UseItem runs before that judgement.
/// </summary>
[HarmonyPatch(typeof(Humanoid), "UseItem")]
public static class Sverm_UseItem_Patch
{
public static bool Prefix(Humanoid __instance, Inventory inventory, ItemDrop.ItemData item)
{
Player player = __instance as Player;
if (player == null || player != Player.m_localPlayer) return true;
if (!SvermVisuals.IsSvermPlayer(player)) return true;
if (item == null || item.m_shared == null) return true;
// MEDICINE BEFORE FOOD, and called from here rather than from a prefix of its own:
// honey and royal jelly are both a meal and the colony's medicine, and which one a
// press means is decided by whether the player is looking at one of our insects.
// Two prefixes both wanting to answer that first would be a coin toss.
if (SvermMedicine.TryAdminister(player, item)) return false;
// The one thing a Sverm may not eat. Blocked here rather than left to fail
// silently, so the refusal says why.
if (item.m_dropPrefab != null && item.m_dropPrefab.name.StartsWith("SvermMeal_") == false
&& IsAswidBlood(item))
{
player.Message(MessageHud.MessageType.Center, "Alchemical blood is not food.");
return false;
}
string cloneName = MealFor(item, BossProgressionManager.GetCurrentProgressionState());
if (cloneName == null) return true;
GameObject clonePrefab = ObjectDB.instance != null ? ObjectDB.instance.GetItemPrefab(cloneName) : null;
ItemDrop cloneDrop = clonePrefab != null ? clonePrefab.GetComponent<ItemDrop>() : null;
if (cloneDrop == null) return true; // registration failed; let vanilla decide
if (!player.EatFood(cloneDrop.m_itemData)) return false; // full, or too soon - vanilla already said so
if (inventory != null) inventory.RemoveItem(item, 1);
EffectList consume = Traverse.Create(player).Field<EffectList>("m_consumeItemEffects").Value;
if (consume != null) consume.Create(player.transform.position, Quaternion.identity, player.transform, 1f, -1);
ZSyncAnimation anim = Traverse.Create(player).Field<ZSyncAnimation>("m_zanim").Value;
if (anim != null) anim.SetTrigger("eat");
return false; // handled
}
/// <summary>
/// The Aswid's alchemical blood, recognised without a hard dependency on that race's
/// tables: everything it makes carries its own prefix.
/// </summary>
private static bool IsAswidBlood(ItemDrop.ItemData item)
{
string name = item.m_dropPrefab != null ? item.m_dropPrefab.name : "";
return name.StartsWith("Aswid") || name == "BloodEssence" || name.Contains("BloodPotion");
}
}
}
}