warvulture

This commit is contained in:
Ferdinando 2026-08-24 19:17:47 +02:00
commit ee5a2e2e7b
12 changed files with 314 additions and 76 deletions

View file

@ -1,100 +1,163 @@
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 dictionary holding the 4th food slot per player
// 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>();
// Called when player spawns to load the 4th and 5th food from custom data
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;
// If they are no longer a Trol, clear it out
if (!TrolRace.IsTrol())
// 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")
{
ClearFood(player);
ExtraFoods.Remove(player);
ExtraFoods5.Remove(player);
if (race != null) ClearFood(player);
return;
}
if (!player.m_customData.ContainsKey("TrolFood_Prefab")) 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;
string prefabName = player.m_customData["TrolFood_Prefab"];
GameObject prefab = ObjectDB.instance.GetItemPrefab(prefabName);
if (prefab == null) return;
ItemDrop itemDrop = prefab.GetComponent<ItemDrop>();
if (itemDrop == null) return;
// Build food object
Player.Food food = new Player.Food();
food.m_item = itemDrop.m_itemData.Clone(); // Clone to be safe
// Try parse remaining time
if (player.m_customData.TryGetValue("TrolFood_Time", out string timeStr) && float.TryParse(timeStr, System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out float time))
float time = 0f;
if (player.m_customData.TryGetValue(timeKey, out string timeStr))
{
food.m_time = time;
float.TryParse(timeStr, NumberStyles.Float, CultureInfo.InvariantCulture, out time);
}
food.m_health = itemDrop.m_itemData.m_shared.m_food;
food.m_stamina = itemDrop.m_itemData.m_shared.m_foodStamina;
food.m_eitr = itemDrop.m_itemData.m_shared.m_foodEitr;
ExtraFoods[player] = food;
if (player.m_customData.ContainsKey("TrolFood5_Prefab"))
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)
{
string prefabName5 = player.m_customData["TrolFood5_Prefab"];
GameObject prefab5 = ObjectDB.instance.GetItemPrefab(prefabName5);
if (prefab5 != null)
{
ItemDrop itemDrop5 = prefab5.GetComponent<ItemDrop>();
if (itemDrop5 != null)
{
Player.Food food5 = new Player.Food();
food5.m_item = itemDrop5.m_itemData.Clone();
if (player.m_customData.TryGetValue("TrolFood5_Time", out string timeStr5) && float.TryParse(timeStr5, System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out float time5))
{
food5.m_time = time5;
}
food5.m_health = itemDrop5.m_itemData.m_shared.m_food;
food5.m_stamina = itemDrop5.m_itemData.m_shared.m_foodStamina;
food5.m_eitr = itemDrop5.m_itemData.m_shared.m_foodEitr;
ExtraFoods5[player] = food5;
}
}
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;
}
// Called to save the current runtime 4th food to custom data for persistence
// 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["TrolFood_Prefab"] = food.m_item.m_dropPrefab.name;
player.m_customData["TrolFood_Time"] = food.m_time.ToString(System.Globalization.CultureInfo.InvariantCulture);
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("TrolFood_Prefab");
player.m_customData.Remove("TrolFood_Time");
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["TrolFood5_Prefab"] = food5.m_item.m_dropPrefab.name;
player.m_customData["TrolFood5_Time"] = food5.m_time.ToString(System.Globalization.CultureInfo.InvariantCulture);
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("TrolFood5_Prefab");
player.m_customData.Remove("TrolFood5_Time");
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);
}
}
@ -131,10 +194,10 @@ namespace RacesOfValheim
if (player == null) return;
ExtraFoods.Remove(player);
ExtraFoods5.Remove(player);
player.m_customData.Remove("TrolFood_Prefab");
player.m_customData.Remove("TrolFood_Time");
player.m_customData.Remove("TrolFood5_Prefab");
player.m_customData.Remove("TrolFood5_Time");
player.m_customData.Remove(Slot4Prefab);
player.m_customData.Remove(Slot4Time);
player.m_customData.Remove(Slot5Prefab);
player.m_customData.Remove(Slot5Time);
}
}
}

View file

@ -252,4 +252,22 @@ namespace RacesOfValheim
return true;
}
}
// m_customData only reaches the disk through Player.Save, and TrolFood_Time / TrolFood5_Time
// were only ever written at the moment of eating - always as 0. Both extra stomachs therefore
// came back from every reload with a full burn time ahead of them, digesting from scratch,
// while the three vanilla slots kept whatever they had left. Refreshing the two timestamps
// just before the package is packed puts all five on the same footing.
//
// A prefix, so the two keys are already in m_customData when Save packs it. SaveFoodTimes only
// updates keys that already exist and never removes one - see its comment for why that
// distinction matters here.
[HarmonyPatch(typeof(Player), nameof(Player.Save))]
public static class Trol_PlayerSave_Patch
{
public static void Prefix(Player __instance)
{
TrolFoodManager.SaveFoodTimes(__instance);
}
}
}

View file

@ -24,12 +24,26 @@ namespace RacesOfValheim
}
}
// The ZDO copy is authoritative once it has been written - but it is written by a
// Player.OnSpawned postfix in ZdoVisualSync that Harmony registers AFTER this race's own
// OnSpawned postfix (type 363 against type 319 in the built assembly), and the player's
// ZDO is a brand new empty one every session. So on every single load there is a window
// where m_customData is the only place the race exists, and returning out of the ZDO
// branch unconditionally made that window answer "not a Trol" - which is what had
// TrolFoodManager.LoadFood wiping the 4th and 5th stomach out of the save file on reload.
//
// Same fix, same reason, as FactionHostilityPatch.GetPlayerRace: only trust the ZDO
// string when it is non-empty. An explicit "Human" written by resetrace IS non-empty and
// still wins over a stale m_customData, which is the behaviour that fix was added for.
public static bool IsTrol()
{
if (Player.m_localPlayer == null) return false;
ZNetView nview = Player.m_localPlayer.GetComponent<ZNetView>();
if (nview != null && nview.IsValid())
return nview.GetZDO().GetString("RacesOfValheim_Race", "") == "Trol";
{
string zdoRace = nview.GetZDO().GetString("RacesOfValheim_Race", "");
if (!string.IsNullOrEmpty(zdoRace)) return zdoRace == "Trol";
}
return Player.m_localPlayer.m_customData.TryGetValue("Race", out string r) && r == "Trol";
}