524 lines
24 KiB
C#
524 lines
24 KiB
C#
using System;
|
|
using System.Reflection;
|
|
using HarmonyLib;
|
|
using UnityEngine;
|
|
|
|
namespace RacesOfValheim
|
|
{
|
|
/// <summary>
|
|
/// Which servant a station belongs to.
|
|
///
|
|
/// The split is not cosmetic, it is the answer to the one complaint the first working version drew:
|
|
/// with a kitchen at one edge of the circle and three furnaces at the other, a single servant spends
|
|
/// its life walking and the margin that keeps food off the fire gets eaten by travel. Two servants
|
|
/// with two tables in the same yard walk half as far each.
|
|
///
|
|
/// It also cuts the AI in half along a seam that was already there. FORGE cannot spoil - a smelter
|
|
/// holds its ore forever and drops its own output - so the forge servant has no clock, never runs,
|
|
/// and never pre-empts itself. All of that machinery lives on in the KITCHEN, which is the only
|
|
/// place it was ever needed.
|
|
/// </summary>
|
|
public enum ButlerFamily
|
|
{
|
|
/// <summary>Smelter: furnace, blast furnace, charcoal kiln, windmill, spinning wheel, eitr
|
|
/// refinery. Nothing here has a deadline.</summary>
|
|
Forge,
|
|
|
|
/// <summary>CookingStation and Fermenter: hearths, ovens and mead. The only family with a
|
|
/// clock.</summary>
|
|
Kitchen,
|
|
}
|
|
|
|
/// <summary>
|
|
/// One working station, seen through the handful of questions the servant ever asks it.
|
|
///
|
|
/// THREE FAMILIES, and they are not variations on a theme - they behave OPPOSITELY on output, which
|
|
/// is the single fact the whole feature is built around (Butler_BoneServant.txt sec. 5, all of it
|
|
/// read off assembly_valheim.dll with Cecil rather than guessed):
|
|
///
|
|
/// Smelter furnace, blast furnace, charcoal kiln, windmill, spinning wheel, eitr
|
|
/// refinery. Its output FALLS ON THE GROUND BY ITSELF - UpdateSmelter runs
|
|
/// RemoveOneOre -> QueueProcessed -> SpawnProcessed with nobody asking. Nothing
|
|
/// to pull; the servant just picks the bars up.
|
|
/// CookingStation hearth, iron cooking station, stone oven. Output STAYS IN THE SLOT and keeps
|
|
/// cooking: Done at m_cookTime, Burnt at exactly twice it (verified: the IL
|
|
/// literally loads m_cookTime, pushes 2 and multiplies). This is the family that
|
|
/// can lose you food, and the only one with a clock.
|
|
/// Fermenter mead. Output stays in until the tap is opened, and never spoils.
|
|
///
|
|
/// NOTHING HERE KNOWS WHAT A MATERIAL IS. Every family exposes IsItemAllowed(string) and
|
|
/// GetItemConversion(string), matching on the PREFAB name (m_from.gameObject.name - verified), so
|
|
/// the servant asks the station "do you take this?" instead of carrying a list of ores and crops.
|
|
/// That is what makes it serve this mod's own stations, other races' stations, and other mods'
|
|
/// stations without a line of code per station.
|
|
///
|
|
/// WHY SO MUCH REFLECTION. Every one of those question methods is PRIVATE in this build -
|
|
/// GetQueueSize, IsItemAllowed, GetSlot, GetFuel, HaveDoneItem, IsFireLit, GetStatus, the lot - and
|
|
/// both Status enums are private nested types, so they cannot even be named in source. The
|
|
/// alternative was reimplementing each station's rules by reading its public m_conversion list,
|
|
/// which would be a second copy of vanilla's logic drifting out of step at the next patch. Calling
|
|
/// the real method through a cached MethodInfo is the smaller lie. The enum values are hard-coded
|
|
/// as ints, and they are not guesses: Cecil reports NotDone=0, Done=1, Burnt=2 and Empty=0,
|
|
/// Fermenting=1, Exposed=2, Ready=3.
|
|
///
|
|
/// Every write goes through InvokeRPC with the name the station REGISTERED, which carries the
|
|
/// "RPC_" prefix in this build - "RPC_AddOre", not "AddOre". A wrong name here is a silent no-op,
|
|
/// which is exactly the class of bug that takes an evening to find, so the four names below were
|
|
/// read out of each Awake() rather than remembered.
|
|
///
|
|
/// A wrong ARGUMENT LIST is not silent: Valheim 1.0 added a trailing "bool cheated" to every
|
|
/// add-item RPC (and the Fermenter's now takes the prefab's stable hash, not its name), and the
|
|
/// old calls threw EndOfStreamException on the receiving end, every tick. The servant's goods
|
|
/// are real, so cheated is always false.
|
|
/// </summary>
|
|
public abstract class ButlerStation
|
|
{
|
|
public Component Behaviour;
|
|
public ZNetView Nview;
|
|
public Transform Transform;
|
|
|
|
public Vector3 Position { get { return Transform.position; } }
|
|
|
|
public ZDOID Id
|
|
{
|
|
get { return Nview != null && Nview.IsValid() ? Nview.GetZDO().m_uid : ZDOID.None; }
|
|
}
|
|
|
|
public bool Alive { get { return Behaviour != null && Nview != null && Nview.IsValid(); } }
|
|
|
|
/// <summary>Wraps whichever of the three this object is, or null if it is not a station.</summary>
|
|
public static ButlerStation From(GameObject go)
|
|
{
|
|
if (go == null) return null;
|
|
|
|
ZNetView nview = go.GetComponent<ZNetView>();
|
|
if (nview == null || !nview.IsValid()) return null;
|
|
|
|
Smelter smelter = go.GetComponent<Smelter>();
|
|
if (smelter != null) return Fill(new SmelterStation { m_smelter = smelter }, smelter, nview);
|
|
|
|
CookingStation cooking = go.GetComponent<CookingStation>();
|
|
if (cooking != null) return Fill(new CookingStationStation { m_cooking = cooking }, cooking, nview);
|
|
|
|
Fermenter fermenter = go.GetComponent<Fermenter>();
|
|
if (fermenter != null) return Fill(new FermenterStation { m_fermenter = fermenter }, fermenter, nview);
|
|
|
|
return null;
|
|
}
|
|
|
|
private static ButlerStation Fill(ButlerStation station, Component behaviour, ZNetView nview)
|
|
{
|
|
station.Behaviour = behaviour;
|
|
station.Nview = nview;
|
|
station.Transform = behaviour.transform;
|
|
return station;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Taking ownership before writing is the multiplayer rule of this feature (sec. 10), and it
|
|
/// buys a second thing that matters here: once we own the ZDO the RPC runs locally and
|
|
/// immediately, so GetQueueSize and GetFuel answer truthfully on the very next line instead of
|
|
/// a network round trip later.
|
|
/// </summary>
|
|
protected void Claim()
|
|
{
|
|
if (Nview != null && Nview.IsValid() && !Nview.IsOwner()) Nview.ClaimOwnership();
|
|
}
|
|
|
|
// ---------------------------------------------------------------- what the servant asks
|
|
|
|
/// <summary>Which of the two servants this one belongs to.</summary>
|
|
public abstract ButlerFamily Family { get; }
|
|
|
|
/// <summary>Can it work at all right now - fire lit, roof up? An inoperable station is skipped
|
|
/// in silence, which is a decision and not an oversight (sec. 7.7).</summary>
|
|
public abstract bool Operable { get; }
|
|
|
|
/// <summary>How many more items it can take. Zero means full.</summary>
|
|
public abstract int FreeSlots { get; }
|
|
|
|
public abstract bool Accepts(string prefabName);
|
|
|
|
/// <summary>Puts one unit in. Called FreeSlots times at most, never more.</summary>
|
|
public abstract void Add(string prefabName);
|
|
|
|
/// <summary>True while it has something to work on - so an empty furnace is never stoked.</summary>
|
|
public abstract bool HasWork { get; }
|
|
|
|
public abstract string FuelPrefab { get; }
|
|
|
|
/// <summary>Units of fuel it wants right now, already filtered by the configured threshold.</summary>
|
|
public abstract int FuelWanted { get; }
|
|
|
|
public abstract void AddFuel();
|
|
|
|
/// <summary>Something finished and needs a hand to get out. Always false for the Smelter, which
|
|
/// throws its own output on the floor.</summary>
|
|
public abstract bool HasOutput { get; }
|
|
|
|
/// <summary>Gets the finished goods onto the ground at <paramref name="at"/>, where the one
|
|
/// pickup routine will find them.</summary>
|
|
public abstract void PullOutput(Vector3 at);
|
|
|
|
/// <summary>
|
|
/// How many times PullOutput is worth calling in a single visit, which is not the same question
|
|
/// as how much is finished.
|
|
///
|
|
/// One, everywhere except the hearth. The Fermenter is the reason this is not simply "keep
|
|
/// pulling while HasOutput": tapping does not clear Ready straight away - DelayedTap waits
|
|
/// m_tapDelay for the animation - so a loop on HasOutput would pull the same tap over and over
|
|
/// in one frame.
|
|
/// </summary>
|
|
public virtual int OutputPulls { get { return 1; } }
|
|
|
|
/// <summary>Seconds until something in here is ruined. float.MaxValue for the two families that
|
|
/// cannot spoil, which is what keeps the urgency comparison honest without special cases.</summary>
|
|
public virtual float SecondsToSpoil { get { return float.MaxValue; } }
|
|
|
|
// ================================================================ the private doors
|
|
|
|
/// <summary>
|
|
/// Every private member of the three station classes this feature touches, resolved once.
|
|
///
|
|
/// Anything that fails to resolve stays null and its caller falls back to the safe answer -
|
|
/// "cannot tell, do not act" - so a future patch that renames one method costs that one
|
|
/// capability and a line in the log, not a servant that stands still or, worse, one that keeps
|
|
/// pouring ore into a station it can no longer read.
|
|
/// </summary>
|
|
private static class Vanilla
|
|
{
|
|
public static readonly MethodInfo SmelterQueueSize = AccessTools.Method(typeof(Smelter), "GetQueueSize");
|
|
public static readonly MethodInfo SmelterAllowed =
|
|
AccessTools.Method(typeof(Smelter), "IsItemAllowed", new[] { typeof(string) });
|
|
public static readonly MethodInfo SmelterFuel = AccessTools.Method(typeof(Smelter), "GetFuel");
|
|
public static readonly FieldInfo SmelterHaveRoof = AccessTools.Field(typeof(Smelter), "m_haveRoof");
|
|
|
|
public static readonly MethodInfo CookGetSlot = AccessTools.Method(typeof(CookingStation), "GetSlot");
|
|
public static readonly MethodInfo CookEmpty = AccessTools.Method(typeof(CookingStation), "IsEmpty");
|
|
public static readonly MethodInfo CookHaveDone = AccessTools.Method(typeof(CookingStation), "HaveDoneItem");
|
|
public static readonly MethodInfo CookAllowed =
|
|
AccessTools.Method(typeof(CookingStation), "IsItemAllowed", new[] { typeof(string) });
|
|
public static readonly MethodInfo CookConversion =
|
|
AccessTools.Method(typeof(CookingStation), "GetItemConversion", new[] { typeof(string) });
|
|
public static readonly MethodInfo CookFuel = AccessTools.Method(typeof(CookingStation), "GetFuel");
|
|
public static readonly MethodInfo CookFireLit = AccessTools.Method(typeof(CookingStation), "IsFireLit");
|
|
|
|
public static readonly MethodInfo FermenterStatus = AccessTools.Method(typeof(Fermenter), "GetStatus");
|
|
// 1.0 dropped the string overload: the Fermenter matches on GetStableHashCode of the name.
|
|
public static readonly MethodInfo FermenterAllowed =
|
|
AccessTools.Method(typeof(Fermenter), "IsItemAllowed", new[] { typeof(int) });
|
|
|
|
// CookingStation.Status and Fermenter.Status are private nested enums: they cannot be named
|
|
// in source, so they travel as ints. Values read from the assembly, not assumed.
|
|
public const int CookNotDone = 0;
|
|
public const int CookDone = 1;
|
|
public const int CookBurnt = 2;
|
|
|
|
public const int FermentEmpty = 0;
|
|
public const int FermentExposed = 2;
|
|
public const int FermentReady = 3;
|
|
|
|
public static bool Call(MethodInfo method, object target, bool fallback)
|
|
{
|
|
if (method == null) return fallback;
|
|
return (bool)method.Invoke(target, null);
|
|
}
|
|
|
|
public static int CallInt(MethodInfo method, object target, int fallback)
|
|
{
|
|
if (method == null) return fallback;
|
|
return Convert.ToInt32(method.Invoke(target, null));
|
|
}
|
|
|
|
public static float CallFloat(MethodInfo method, object target, float fallback)
|
|
{
|
|
if (method == null) return fallback;
|
|
return Convert.ToSingle(method.Invoke(target, null));
|
|
}
|
|
|
|
public static bool Allowed(MethodInfo method, object target, string prefabName)
|
|
{
|
|
if (method == null || string.IsNullOrEmpty(prefabName)) return false;
|
|
return (bool)method.Invoke(target, new object[] { prefabName });
|
|
}
|
|
}
|
|
|
|
// ================================================================ Smelter
|
|
|
|
private class SmelterStation : ButlerStation
|
|
{
|
|
public Smelter m_smelter;
|
|
|
|
public override ButlerFamily Family { get { return ButlerFamily.Forge; } }
|
|
|
|
public override bool Operable
|
|
{
|
|
get
|
|
{
|
|
if (!m_smelter.m_requiresRoof) return true;
|
|
if (Vanilla.SmelterHaveRoof == null) return true; // cannot tell: let it try
|
|
return (bool)Vanilla.SmelterHaveRoof.GetValue(m_smelter);
|
|
}
|
|
}
|
|
|
|
private int Queued { get { return Vanilla.CallInt(Vanilla.SmelterQueueSize, m_smelter, int.MaxValue); } }
|
|
|
|
public override int FreeSlots
|
|
{
|
|
get { return Mathf.Max(0, m_smelter.m_maxOre - Queued); }
|
|
}
|
|
|
|
public override bool Accepts(string prefabName)
|
|
{
|
|
return Vanilla.Allowed(Vanilla.SmelterAllowed, m_smelter, prefabName);
|
|
}
|
|
|
|
public override void Add(string prefabName)
|
|
{
|
|
Claim();
|
|
Nview.InvokeRPC("RPC_AddOre", prefabName, false);
|
|
}
|
|
|
|
public override bool HasWork { get { return Queued > 0; } }
|
|
|
|
public override string FuelPrefab
|
|
{
|
|
get { return m_smelter.m_fuelItem != null ? m_smelter.m_fuelItem.gameObject.name : null; }
|
|
}
|
|
|
|
public override int FuelWanted
|
|
{
|
|
get
|
|
{
|
|
if (m_smelter.m_fuelItem == null || m_smelter.m_maxFuel <= 0) return 0;
|
|
if (!HasWork) return 0;
|
|
|
|
float fuel = Vanilla.CallFloat(Vanilla.SmelterFuel, m_smelter, float.MaxValue);
|
|
if (fuel >= m_smelter.m_maxFuel * ButlerConfig.FuelThreshold.Value) return 0;
|
|
|
|
return Mathf.Max(0, Mathf.FloorToInt(m_smelter.m_maxFuel - fuel));
|
|
}
|
|
}
|
|
|
|
public override void AddFuel()
|
|
{
|
|
Claim();
|
|
Nview.InvokeRPC("RPC_AddFuel");
|
|
}
|
|
|
|
// The whole point of this family: nothing to collect, it drops its own.
|
|
public override bool HasOutput { get { return false; } }
|
|
public override void PullOutput(Vector3 at) { }
|
|
}
|
|
|
|
// ================================================================ CookingStation
|
|
|
|
private class CookingStationStation : ButlerStation
|
|
{
|
|
public CookingStation m_cooking;
|
|
|
|
public override ButlerFamily Family { get { return ButlerFamily.Kitchen; } }
|
|
|
|
private int SlotCount
|
|
{
|
|
get { return m_cooking.m_slots != null ? m_cooking.m_slots.Length : 0; }
|
|
}
|
|
|
|
/// <summary>GetSlot hands back four values through out parameters, one of which is a
|
|
/// private enum. Through reflection that means an args array and an int. The fourth, a
|
|
/// bool "cheated", arrived with 1.0; it is ignored, but the array must have room for it.</summary>
|
|
private bool ReadSlot(int index, out string name, out float cooked, out int status)
|
|
{
|
|
name = null;
|
|
cooked = 0f;
|
|
status = Vanilla.CookNotDone;
|
|
|
|
if (Vanilla.CookGetSlot == null) return false;
|
|
|
|
object[] args = new object[] { index, null, null, null, null };
|
|
Vanilla.CookGetSlot.Invoke(m_cooking, args);
|
|
|
|
name = args[1] as string;
|
|
cooked = Convert.ToSingle(args[2]);
|
|
status = Convert.ToInt32(args[3]);
|
|
return true;
|
|
}
|
|
|
|
public override bool Operable
|
|
{
|
|
get { return !m_cooking.m_requireFire || Vanilla.Call(Vanilla.CookFireLit, m_cooking, false); }
|
|
}
|
|
|
|
public override int FreeSlots
|
|
{
|
|
get
|
|
{
|
|
int free = 0;
|
|
for (int i = 0; i < SlotCount; i++)
|
|
{
|
|
string name;
|
|
float cooked;
|
|
int status;
|
|
if (!ReadSlot(i, out name, out cooked, out status)) return 0;
|
|
if (string.IsNullOrEmpty(name)) free++;
|
|
}
|
|
return free;
|
|
}
|
|
}
|
|
|
|
public override bool Accepts(string prefabName)
|
|
{
|
|
return Vanilla.Allowed(Vanilla.CookAllowed, m_cooking, prefabName);
|
|
}
|
|
|
|
public override void Add(string prefabName)
|
|
{
|
|
Claim();
|
|
Nview.InvokeRPC("RPC_AddItem", prefabName, false);
|
|
}
|
|
|
|
public override bool HasWork { get { return !Vanilla.Call(Vanilla.CookEmpty, m_cooking, true); } }
|
|
|
|
public override string FuelPrefab
|
|
{
|
|
get
|
|
{
|
|
return m_cooking.m_useFuel && m_cooking.m_fuelItem != null
|
|
? m_cooking.m_fuelItem.gameObject.name
|
|
: null;
|
|
}
|
|
}
|
|
|
|
public override int FuelWanted
|
|
{
|
|
get
|
|
{
|
|
if (!m_cooking.m_useFuel || m_cooking.m_fuelItem == null || m_cooking.m_maxFuel <= 0) return 0;
|
|
if (!HasWork) return 0;
|
|
|
|
float fuel = Vanilla.CallFloat(Vanilla.CookFuel, m_cooking, float.MaxValue);
|
|
if (fuel >= m_cooking.m_maxFuel * ButlerConfig.FuelThreshold.Value) return 0;
|
|
|
|
return Mathf.Max(0, Mathf.FloorToInt(m_cooking.m_maxFuel - fuel));
|
|
}
|
|
}
|
|
|
|
public override void AddFuel()
|
|
{
|
|
Claim();
|
|
Nview.InvokeRPC("RPC_AddFuel");
|
|
}
|
|
|
|
public override bool HasOutput { get { return Vanilla.Call(Vanilla.CookHaveDone, m_cooking, false); } }
|
|
|
|
/// <summary>
|
|
/// ONE CALL, ONE SLOT - and the 1 is the count, not the slot.
|
|
///
|
|
/// Read again off the IL after the cook was reported losing a meat per batch, because the
|
|
/// first reading of it was wrong in a way that mattered. RPC_RemoveDoneItem walks the slots,
|
|
/// finds the FIRST one that is Done, spawns its item <c>amount</c> times, clears that slot,
|
|
/// sends RPC_SetSlotVisual and RETURNS. It does not go on to the other slots. So the
|
|
/// argument is a multiplier - anything above 1 prints money - and a hearth with five cooked
|
|
/// slots needs five calls, which is what OutputPulls below is for.
|
|
/// </summary>
|
|
public override void PullOutput(Vector3 at)
|
|
{
|
|
Claim();
|
|
Nview.InvokeRPC("RPC_RemoveDoneItem", at, 1);
|
|
}
|
|
|
|
/// <summary>One call per slot, so a full hearth is emptied in one visit instead of one item
|
|
/// per errand. The loop that uses this stops on HasOutput anyway; this is only its bound.</summary>
|
|
public override int OutputPulls { get { return Mathf.Max(1, SlotCount); } }
|
|
|
|
/// <summary>
|
|
/// The clock this whole feature exists for. Done at m_cookTime, Burnt at 2x - so what is
|
|
/// left is 2*cookTime - cookedTime, and a slot already Done is the urgent one because its
|
|
/// remaining half is all that stands between dinner and charcoal.
|
|
///
|
|
/// GetItemConversion is asked with whatever name the slot currently holds, which is the raw
|
|
/// item before Done and the COOKED one after: CookingStation.GetItemConversion matches on
|
|
/// both m_from and m_to (verified), so the cook time is readable in either phase.
|
|
/// </summary>
|
|
public override float SecondsToSpoil
|
|
{
|
|
get
|
|
{
|
|
if (Vanilla.CookConversion == null) return float.MaxValue;
|
|
|
|
float soonest = float.MaxValue;
|
|
|
|
for (int i = 0; i < SlotCount; i++)
|
|
{
|
|
string name;
|
|
float cooked;
|
|
int status;
|
|
if (!ReadSlot(i, out name, out cooked, out status)) break;
|
|
|
|
if (string.IsNullOrEmpty(name)) continue;
|
|
if (status == Vanilla.CookBurnt) continue; // already lost, no hurry
|
|
|
|
CookingStation.ItemConversion conversion =
|
|
Vanilla.CookConversion.Invoke(m_cooking, new object[] { name })
|
|
as CookingStation.ItemConversion;
|
|
if (conversion == null) continue;
|
|
|
|
float left = conversion.m_cookTime * 2f - cooked;
|
|
if (left < soonest) soonest = left;
|
|
}
|
|
|
|
return soonest;
|
|
}
|
|
}
|
|
}
|
|
|
|
// ================================================================ Fermenter
|
|
|
|
private class FermenterStation : ButlerStation
|
|
{
|
|
public Fermenter m_fermenter;
|
|
|
|
/// <summary>Mead goes with the food. It has no deadline of its own, so it costs the cook
|
|
/// nothing beyond one more thing to fill and one more tap to open.</summary>
|
|
public override ButlerFamily Family { get { return ButlerFamily.Kitchen; } }
|
|
|
|
private int Status
|
|
{
|
|
get { return Vanilla.CallInt(Vanilla.FermenterStatus, m_fermenter, Vanilla.FermentExposed); }
|
|
}
|
|
|
|
public override bool Operable { get { return Status != Vanilla.FermentExposed; } }
|
|
|
|
public override int FreeSlots { get { return Status == Vanilla.FermentEmpty ? 1 : 0; } }
|
|
|
|
public override bool Accepts(string prefabName)
|
|
{
|
|
if (Vanilla.FermenterAllowed == null || string.IsNullOrEmpty(prefabName)) return false;
|
|
return (bool)Vanilla.FermenterAllowed.Invoke(m_fermenter, new object[] { prefabName.GetStableHashCode() });
|
|
}
|
|
|
|
public override void Add(string prefabName)
|
|
{
|
|
Claim();
|
|
Nview.InvokeRPC("RPC_AddItem", prefabName.GetStableHashCode(), false);
|
|
}
|
|
|
|
public override bool HasWork { get { return Status != Vanilla.FermentEmpty; } }
|
|
|
|
public override string FuelPrefab { get { return null; } }
|
|
public override int FuelWanted { get { return 0; } }
|
|
public override void AddFuel() { }
|
|
|
|
public override bool HasOutput { get { return Status == Vanilla.FermentReady; } }
|
|
|
|
/// <summary>Opens the tap. The bottles are not out yet when this returns - DelayedTap waits
|
|
/// m_tapDelay for the animation - so the servant collects them on a later pass, which the
|
|
/// pickup sweep handles without knowing anything about fermenting.</summary>
|
|
public override void PullOutput(Vector3 at)
|
|
{
|
|
Claim();
|
|
Nview.InvokeRPC("RPC_Tap");
|
|
}
|
|
}
|
|
}
|
|
}
|