RacesOfValheim/JotunnModStub/Trol/TrolFoodManager.cs
2026-08-24 19:17:47 +02:00

203 lines
9.2 KiB
C#

using System.Collections.Generic;
using System.Globalization;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The Trol's 4th and 5th stomach. The runtime side is two dictionaries; the persistent side
/// is four keys in Player.m_customData, which is the only per-character store Valheim writes
/// to disk (Player.Save/Player.Load pack it into the profile).
///
/// Two rules hold this file together, and both exist because breaking them ate people's food:
///
/// 1. Never write to m_customData from a path that cannot prove what it is looking at.
/// Removing a key here is not "failing to load" - it is a deletion from the save file.
/// 2. The two slots are independent. Slot 5 is not a continuation of slot 4 and must never
/// be gated behind slot 4 having something in it.
/// </summary>
public static class TrolFoodManager
{
// Runtime dictionaries holding the 4th and 5th food slot per player
public static Dictionary<Player, Player.Food> ExtraFoods = new Dictionary<Player, Player.Food>();
public static Dictionary<Player, Player.Food> ExtraFoods5 = new Dictionary<Player, Player.Food>();
private const string Slot4Prefab = "TrolFood_Prefab";
private const string Slot4Time = "TrolFood_Time";
private const string Slot5Prefab = "TrolFood5_Prefab";
private const string Slot5Time = "TrolFood5_Time";
// Called when the player spawns, to restore both extra stomachs from custom data.
public static void LoadFood(Player player)
{
if (player == null) return;
// GetPlayerRace returns null when the race cannot be read at all - ZDO empty AND no
// m_customData entry - and that is the case this method used to get catastrophically
// wrong. It asked TrolRace.IsTrol(), which answered a flat "no" during the spawn frame
// (see IsTrol's comment for why), and then called ClearFood on that "no", deleting all
// four keys. Every reload dropped the Trol's 4th and 5th stomach on the floor.
//
// Now only a race we actually READ, and that is not ours, may touch the save file.
// "I cannot tell yet" drops the runtime entries and leaves the disk alone.
string race = FactionHostilityPatch.GetPlayerRace(player);
if (race != "Trol")
{
ExtraFoods.Remove(player);
ExtraFoods5.Remove(player);
if (race != null) ClearFood(player);
return;
}
LoadSlot(player, ExtraFoods, Slot4Prefab, Slot4Time);
LoadSlot(player, ExtraFoods5, Slot5Prefab, Slot5Time);
}
/// <summary>
/// Restores one slot. Called once per slot rather than once for both: slot 5 used to sit
/// inside slot 4's early return, so a Trol carrying food in the 5th stomach and nothing in
/// the 4th lost the 5th on every load, independently of everything else wrong here.
/// </summary>
private static void LoadSlot(Player player, Dictionary<Player, Player.Food> dict, string prefabKey, string timeKey)
{
dict.Remove(player);
if (!player.m_customData.TryGetValue(prefabKey, out string prefabName)) return;
if (ObjectDB.instance == null) return;
GameObject prefab = ObjectDB.instance.GetItemPrefab(prefabName);
if (prefab == null) return;
ItemDrop itemDrop = prefab.GetComponent<ItemDrop>();
if (itemDrop == null) return;
float time = 0f;
if (player.m_customData.TryGetValue(timeKey, out string timeStr))
{
float.TryParse(timeStr, NumberStyles.Float, CultureInfo.InvariantCulture, out time);
}
ItemDrop.ItemData.SharedData shared = itemDrop.m_itemData.m_shared;
// A meal that finished digesting is not restored, and its keys go with it - otherwise
// a stale pair could sit in the save forever, since UpdateFood only prunes what it can
// already see in the dictionaries.
if (shared.m_foodBurnTime > 0f && time >= shared.m_foodBurnTime)
{
player.m_customData.Remove(prefabKey);
player.m_customData.Remove(timeKey);
return;
}
Player.Food food = new Player.Food();
food.m_item = itemDrop.m_itemData.Clone();
food.m_item.m_stack = 1;
food.m_time = time;
// Restore the values the stomach actually had, not a fresh meal's. Same lerp
// Trol_PlayerUpdateFood_Patch runs every frame; without it a reload handed back full
// nourishment until the next tick corrected it.
float factor = shared.m_foodBurnTime > 0f ? Mathf.Clamp01(time / shared.m_foodBurnTime) : 0f;
food.m_health = Mathf.Lerp(shared.m_food, shared.m_food * 0.2f, factor);
food.m_stamina = Mathf.Lerp(shared.m_foodStamina, shared.m_foodStamina * 0.2f, factor);
food.m_eitr = Mathf.Lerp(shared.m_foodEitr, shared.m_foodEitr * 0.2f, factor);
dict[player] = food;
}
// Saves the current runtime state of both extra stomachs. Authoritative: it is called from
// SetExtraFood/SetExtraFood5, where the dictionaries are known to be current, and it
// removes the keys of an empty slot on purpose. Do NOT call it from anywhere that could
// run before LoadFood has populated the dictionaries - use SaveFoodTimes there.
public static void SaveFood(Player player)
{
if (player == null) return;
if (ExtraFoods.TryGetValue(player, out Player.Food food) && food != null && food.m_item != null)
{
player.m_customData[Slot4Prefab] = food.m_item.m_dropPrefab.name;
player.m_customData[Slot4Time] = food.m_time.ToString(CultureInfo.InvariantCulture);
}
else
{
player.m_customData.Remove(Slot4Prefab);
player.m_customData.Remove(Slot4Time);
}
if (ExtraFoods5.TryGetValue(player, out Player.Food food5) && food5 != null && food5.m_item != null)
{
player.m_customData[Slot5Prefab] = food5.m_item.m_dropPrefab.name;
player.m_customData[Slot5Time] = food5.m_time.ToString(CultureInfo.InvariantCulture);
}
else
{
player.m_customData.Remove(Slot5Prefab);
player.m_customData.Remove(Slot5Time);
}
}
/// <summary>
/// Writes how far each stomach has digested, and nothing else. Called from a Player.Save
/// prefix, because the time was previously only ever written at the moment of eating -
/// always as 0 - so both extra stomachs came back from a reload at full duration while the
/// three vanilla slots kept their remaining time.
///
/// This updates existing entries and never removes a key. Player.Save can run at any
/// moment, including before OnSpawned has restored the dictionaries, and a save hook able
/// to empty the save file is the exact bug this file is recovering from.
/// </summary>
public static void SaveFoodTimes(Player player)
{
if (player == null) return;
WriteTime(player, ExtraFoods, Slot4Time);
WriteTime(player, ExtraFoods5, Slot5Time);
}
private static void WriteTime(Player player, Dictionary<Player, Player.Food> dict, string timeKey)
{
if (dict.TryGetValue(player, out Player.Food food) && food != null && food.m_item != null)
{
player.m_customData[timeKey] = food.m_time.ToString(CultureInfo.InvariantCulture);
}
}
public static void SetExtraFood(Player player, ItemDrop.ItemData item)
{
Player.Food food = new Player.Food();
food.m_item = item.Clone();
food.m_item.m_stack = 1; // Only eat 1
food.m_time = 0f;
food.m_health = item.m_shared.m_food;
food.m_stamina = item.m_shared.m_foodStamina;
food.m_eitr = item.m_shared.m_foodEitr;
ExtraFoods[player] = food;
SaveFood(player);
}
public static void SetExtraFood5(Player player, ItemDrop.ItemData item)
{
Player.Food food = new Player.Food();
food.m_item = item.Clone();
food.m_item.m_stack = 1;
food.m_time = 0f;
food.m_health = item.m_shared.m_food;
food.m_stamina = item.m_shared.m_foodStamina;
food.m_eitr = item.m_shared.m_foodEitr;
ExtraFoods5[player] = food;
SaveFood(player);
}
public static void ClearFood(Player player)
{
if (player == null) return;
ExtraFoods.Remove(player);
ExtraFoods5.Remove(player);
player.m_customData.Remove(Slot4Prefab);
player.m_customData.Remove(Slot4Time);
player.m_customData.Remove(Slot5Prefab);
player.m_customData.Remove(Slot5Time);
}
}
}