Grey, tall and thin, with black eyes. Eitr is armour and fuel (shield, diet, soft fall, levitation), Heimkall sends a lethal blow home at one health every 20 minutes. Caster powers from Skrid to the archon Sameining, with on-screen cooldowns. Automated base around the Ljoskjarne: drones, three constructs, crystals, Ljosgard, Prismavard. Compendium page in EN/IT/RU. README: New in block, race section, progression, station line, changelog. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
1950 lines
80 KiB
C#
1950 lines
80 KiB
C#
using System.Collections.Generic;
|
|
using System.Text;
|
|
using HarmonyLib;
|
|
using UnityEngine;
|
|
|
|
namespace RacesOfValheim
|
|
{
|
|
/// <summary>
|
|
/// The Alfar drone's own head (Alfar_Progettazione.txt sec. 9): a FORK of the Butler's BoneServantAI,
|
|
/// kept as a separate class so nothing that ships with the Skeleton, Skadi or Sverm can be broken
|
|
/// from here. What it keeps: the movement, the payload in the ZDO, the three families of stations,
|
|
/// the burn protection and the one-stage rule. What it changes: ONE drone does both trades; chests
|
|
/// are read the other way round (the sigil marks the ones NOT to touch); stations are fed only from
|
|
/// the entry chest, wood only from the wood chest; the product goes back to the entry chest and is
|
|
/// SORTED from there into the chest that already holds the same thing; and three jobs are new -
|
|
/// repair, farming (with the replant rule) and sorting.
|
|
///
|
|
/// The Bone Servant's own head, as it was written: everything it does is here; vanilla's MonsterAI
|
|
/// never runs on it.
|
|
///
|
|
/// HOW IT MOVES, which was the one open question in the design and is answered here rather than in
|
|
/// the doc. Three candidates were on the table: a ghost follow-target, pinning m_patrolPoint the way
|
|
/// RaisedThrall does, and calling BaseAI.MoveTo directly. The IL settled it:
|
|
///
|
|
/// - BaseAI has NO Update and NO FixedUpdate. UpdateAI(dt) is driven centrally by
|
|
/// MonoUpdaters.FixedUpdate over BaseAI.Instances, and that list is maintained by OnEnable /
|
|
/// OnDisable. So "disable the AI and drive MoveTo yourself" kills the only thing that would
|
|
/// call anything: a disabled BaseAI is not ticked at all. That candidate is dead.
|
|
/// - BaseAI.UpdateAI itself does almost nothing - IsOwner, UpdateTakeoffLanding,
|
|
/// UpdateRegeneration - so skipping it costs a flying check we do not need and a regeneration
|
|
/// we already have from SkeletonSentryBehaviour.
|
|
///
|
|
/// So: a PREFIX on MonsterAI.UpdateAI that hands the tick to this class and returns false. The
|
|
/// servant keeps its place in the central tick, keeps vanilla pathing through BaseAI.MoveTo, and
|
|
/// vanilla's own AI - targeting, fleeing, wandering, attacking - never executes a single line. That
|
|
/// is also why the servant cannot fight: not because its weapon was taken (it was), but because the
|
|
/// code that would swing it is never reached.
|
|
///
|
|
/// MoveTo(dt, point, dist, run) is private, hence the cached MethodInfo. It returns TRUE on arrival
|
|
/// (read in the IL: DistanceXZ under the threshold calls StopMoving and returns 1), which is the
|
|
/// whole arrival test - no distance maths of our own.
|
|
///
|
|
/// THE PAYLOAD IS VIRTUAL. The servant has no inventory. Every station's input RPC takes a STRING,
|
|
/// so what it carries is a list of prefab names and counts in its own ZDO, which survives saving,
|
|
/// zone reload and - the case that matters - a change of owner mid-job in multiplayer. The one
|
|
/// thing this costs is that the goods do not exist as objects while in transit, so they have to be
|
|
/// put back into the world by hand if the servant dies holding them. That is <see cref="DropPayload"/>,
|
|
/// and it is the reason nothing here can quietly delete a player's ore.
|
|
/// </summary>
|
|
public class AlfarDroneAI : MonoBehaviour
|
|
{
|
|
// ─── ZDO keys ────────────────────────────────────────────────────────
|
|
public const string KeyAnchor = "RoV_alfarAnchor";
|
|
public const string KeyOrphanAt = "RoV_alfarOrphanAt";
|
|
public const string KeyLoad = "RoV_alfarLoad";
|
|
public const string KeySource = "RoV_alfarSource";
|
|
public const string KeyTarget = "RoV_alfarTarget";
|
|
public const string KeyStatus = "RoV_alfarStatus";
|
|
public const string KeyDest = "RoV_alfarDest";
|
|
|
|
/// <summary>Every drone alive in the loaded zones: the repairs look at each other through it.</summary>
|
|
public static readonly List<AlfarDroneAI> All = new List<AlfarDroneAI>();
|
|
|
|
/// <summary>Written into a STATION's ZDO: the chest whose material is in it right now, so the
|
|
/// product goes home to where the raw came from even after a reload, and even if a different
|
|
/// client collects it.</summary>
|
|
public const string KeyFedBy = "RoV_alfarFedBy";
|
|
|
|
// ─── numbers that are not worth a config entry ───────────────────────
|
|
private const float PlanInterval = 1.5f;
|
|
|
|
/// <summary>
|
|
/// How close is close enough. Measured to the piece's ORIGIN, which on a furnace or a kiln sits
|
|
/// inside a metre or so of solid collider - so anything tight enough to look like hugging the
|
|
/// thing is a distance the servant can never actually reach, and it would time out and put a
|
|
/// perfectly good station in the penalty box. Two and a half metres is roughly where a player
|
|
/// stands to use one.
|
|
/// </summary>
|
|
private const float ArriveDistance = 2.5f;
|
|
|
|
private const float CollectRadius = 3.5f;
|
|
private const float JobTimeout = 25f;
|
|
private const float PenaltySeconds = 180f;
|
|
|
|
/// <summary>Set aside briefly when a job was reached but achieved nothing. Without this, a job
|
|
/// that arrives and finds nothing to do is re-planned identically on the next tick and the
|
|
/// servant stands there deciding the same thing forever.</summary>
|
|
private const float ShortPenaltySeconds = 20f;
|
|
private const float FleeSeconds = 6f;
|
|
private const float WitherSeconds = 30f;
|
|
private const float HomeCheckRange = 25f;
|
|
|
|
/// <summary>A cooking slot inside this many seconds of burning outranks everything else. Twelve
|
|
/// seconds is a walk of about twenty metres with room to spare, which is the whole radius.</summary>
|
|
private const float SpoilPanicSeconds = 12f;
|
|
|
|
/// <summary>How long a station may sit unserved before its wait starts outweighing distance.
|
|
/// This is what stops a furnace at the edge of the circle from starving while the servant
|
|
/// shuttles between two closer ones.</summary>
|
|
private const float WaitToMetres = 0.25f;
|
|
|
|
private const int PayloadCap = 120;
|
|
|
|
private static readonly System.Reflection.MethodInfo MoveToMethod =
|
|
AccessTools.Method(typeof(BaseAI), "MoveTo",
|
|
new[] { typeof(float), typeof(Vector3), typeof(float), typeof(bool) });
|
|
|
|
private static readonly System.Reflection.FieldInfo AllPiecesField =
|
|
AccessTools.Field(typeof(Piece), "s_allPieces");
|
|
|
|
private static readonly System.Reflection.MethodInfo ContainerSaveMethod =
|
|
AccessTools.Method(typeof(Container), "Save");
|
|
|
|
private static int s_itemMask = -1;
|
|
|
|
/// <summary>Which stations this one serves. Set on the prefab at registration, so it travels
|
|
/// with every instance the table raises.</summary>
|
|
public ButlerFamily m_family = ButlerFamily.Forge;
|
|
|
|
/// <summary>
|
|
/// Whether this one stands and fights instead of walking home when trouble comes. Off for the
|
|
/// Bone Servants, which are pacifists by decision; on for the Sverm's Seeker Workers, which
|
|
/// keep the forge AND defend the nest. See <see cref="HandsToVanilla"/>.
|
|
/// </summary>
|
|
public bool m_fightsBack = false;
|
|
|
|
/// <summary>
|
|
/// How close to the anchor counts as home, and how far past the configured radius it works.
|
|
/// 2.5 and 0 for a table. A Sverm nest is metres of collider that grows with its stage, so
|
|
/// SvermWorkerBehaviour sets both to the nest's measured edge - otherwise an idle worker would
|
|
/// spend its life walking into the trunk, and the work circle would be mostly nest.
|
|
/// </summary>
|
|
public float m_homeDistance = 2.5f;
|
|
public float m_radiusBonus = 0f;
|
|
|
|
/// <summary>For a servant that fights back: how close an enemy has to be to stop the work, how
|
|
/// often that is asked, and how long the fight holds after the last sign of one.</summary>
|
|
private const float FightRange = 12f;
|
|
private const float FightScanInterval = 1f;
|
|
private const float FightLinger = 5f;
|
|
|
|
private float m_nextFightScan;
|
|
private float m_fightUntil;
|
|
|
|
private ZNetView m_nview;
|
|
private Character m_character;
|
|
private MonsterAI m_ai;
|
|
|
|
private readonly object[] m_moveArgs = new object[4];
|
|
private readonly List<Load> m_payload = new List<Load>();
|
|
private readonly Dictionary<ZDOID, float> m_penalties = new Dictionary<ZDOID, float>();
|
|
private readonly Dictionary<ZDOID, float> m_idleSince = new Dictionary<ZDOID, float>();
|
|
|
|
private readonly List<ButlerStation> m_stations = new List<ButlerStation>();
|
|
private readonly List<Container> m_chests = new List<Container>(); // the storage chests
|
|
private Container m_entry; // the entry chest
|
|
private Container m_wood; // the wood-to-burn chest
|
|
private readonly List<WearNTear> m_damaged = new List<WearNTear>();
|
|
|
|
// Farming: where the last harvest was, and what to put back there.
|
|
private Vector3? m_farmSpot;
|
|
private Quaternion m_farmRot;
|
|
private PlantInfo m_farmInfo;
|
|
private float m_farmReadyAt;
|
|
|
|
// Sorting: what was chosen at the entry chest and where it is going.
|
|
private string m_sortItem;
|
|
private ZDOID m_sortDest;
|
|
private float m_scannedAt = -99f;
|
|
|
|
private Job m_job;
|
|
private float m_nextPlan;
|
|
private float m_jobDeadline;
|
|
private float m_fleeUntil;
|
|
private string m_status = "";
|
|
|
|
private class Load
|
|
{
|
|
public string Name;
|
|
public int Count;
|
|
}
|
|
|
|
private class Job
|
|
{
|
|
public string Kind; // load | fuel | collect | deposit | drop
|
|
public ZDOID Target;
|
|
public Vector3 Point;
|
|
public bool Hurry;
|
|
public string Label;
|
|
public ZDOID Claim; // the one target other drones must leave alone
|
|
}
|
|
|
|
// ================================================================ life
|
|
|
|
private void Awake()
|
|
{
|
|
m_nview = GetComponent<ZNetView>();
|
|
m_character = GetComponent<Character>();
|
|
m_ai = GetComponent<MonsterAI>();
|
|
|
|
All.Add(this);
|
|
ReadPayload();
|
|
}
|
|
|
|
private void OnDestroy()
|
|
{
|
|
All.Remove(this);
|
|
|
|
// Only a DEATH scatters the load. A zone unloading destroys this object too, and there the
|
|
// payload must stay in the ZDO where it will be read again on the way back in - dropping it
|
|
// would mint a copy every time the player walked away.
|
|
if (m_character != null && m_character.IsDead()) DropPayload();
|
|
}
|
|
|
|
/// <summary>Called by the table the moment it raises one.</summary>
|
|
public void Bind(Vector3 anchor)
|
|
{
|
|
if (m_nview == null || !m_nview.IsValid()) return;
|
|
|
|
m_nview.GetZDO().Set(KeyAnchor, anchor);
|
|
|
|
if (m_ai != null) m_ai.MakeTame();
|
|
if (m_character != null) m_character.SetTamed(true);
|
|
}
|
|
|
|
public Vector3? Anchor
|
|
{
|
|
get
|
|
{
|
|
if (m_nview == null || !m_nview.IsValid()) return null;
|
|
|
|
Vector3 anchor = m_nview.GetZDO().GetVec3(KeyAnchor, Vector3.zero);
|
|
return anchor == Vector3.zero ? (Vector3?)null : anchor;
|
|
}
|
|
}
|
|
|
|
public bool IsBoundTo(Vector3 anchor)
|
|
{
|
|
Vector3? own = Anchor;
|
|
return own != null && Vector3.SqrMagnitude(own.Value - anchor) < 0.25f;
|
|
}
|
|
|
|
/// <summary>The one line the table's hover shows. Read from the ZDO so a client that does not
|
|
/// own the servant still sees what it is doing.</summary>
|
|
public string Status
|
|
{
|
|
get
|
|
{
|
|
if (m_nview == null || !m_nview.IsValid()) return m_status;
|
|
return m_nview.GetZDO().GetString(KeyStatus, m_status);
|
|
}
|
|
}
|
|
|
|
private void SetStatus(string text)
|
|
{
|
|
if (text == m_status) return;
|
|
|
|
m_status = text;
|
|
if (m_nview != null && m_nview.IsValid() && m_nview.IsOwner())
|
|
{
|
|
m_nview.GetZDO().Set(KeyStatus, text);
|
|
}
|
|
}
|
|
|
|
/// <summary>Hit by something: stop working and walk home. It never fights back - there is
|
|
/// nothing in this class that could. A servant that fights back ignores this: vanilla already
|
|
/// holds the attacker as its target (MonsterAI.OnDamaged calls SetTarget, read off the IL), and
|
|
/// <see cref="HandsToVanilla"/> gives it the tick on the next frame.</summary>
|
|
public void NoteDamage()
|
|
{
|
|
if (m_fightsBack) return;
|
|
|
|
m_fleeUntil = Time.time + FleeSeconds;
|
|
m_job = null;
|
|
}
|
|
|
|
/// <summary>
|
|
/// True while vanilla's MonsterAI should have the tick instead of the work - only ever for a
|
|
/// servant that fights back, and only on the client that runs it.
|
|
///
|
|
/// VANILLA DOES THE FIGHTING, this only decides when. Two things start a fight: a target the
|
|
/// MonsterAI already holds - which covers being hit, see NoteDamage - and an enemy inside
|
|
/// FightRange, found with BaseAI.FindClosestEnemy. That one is a static sweep of distance and
|
|
/// IsEnemy with no line of sight (IL), which is why the range is short. Either holds the fight
|
|
/// for FightLinger seconds, so the worker does not flicker between swinging and walking to the
|
|
/// chest on alternate ticks.
|
|
///
|
|
/// The job is dropped, not the payload: whatever it was carrying stays in the ZDO, and the
|
|
/// first plan after the fight carries it on to where it was going.
|
|
/// </summary>
|
|
public bool HandsToVanilla()
|
|
{
|
|
if (!m_fightsBack || m_ai == null || m_character == null || m_character.IsDead()) return false;
|
|
if (m_nview == null || !m_nview.IsValid() || !m_nview.IsOwner()) return false;
|
|
|
|
Character target = m_ai.GetTargetCreature();
|
|
if (target != null && !target.IsDead())
|
|
{
|
|
m_fightUntil = Time.time + FightLinger;
|
|
}
|
|
else if (Time.time >= m_nextFightScan)
|
|
{
|
|
m_nextFightScan = Time.time + FightScanInterval;
|
|
if (BaseAI.FindClosestEnemy(m_character, transform.position, FightRange) != null)
|
|
{
|
|
m_fightUntil = Time.time + FightLinger;
|
|
}
|
|
}
|
|
|
|
if (Time.time >= m_fightUntil) return false;
|
|
|
|
m_job = null;
|
|
m_nextPlan = 0f; // the fight moved it; plan afresh the moment it hands back
|
|
SetStatus("Fighting.");
|
|
return true;
|
|
}
|
|
|
|
// ================================================================ the tick
|
|
|
|
/// <summary>Everything. Returns what MonsterAI.UpdateAI would have returned.</summary>
|
|
public bool Tick(float dt)
|
|
{
|
|
if (m_nview == null || !m_nview.IsValid() || !m_nview.IsOwner()) return false;
|
|
if (m_character == null || m_character.IsDead()) return false;
|
|
|
|
if (TickWither()) return true;
|
|
|
|
if (Time.time < m_fleeUntil)
|
|
{
|
|
SetStatus("Driven off.");
|
|
GoHome(dt);
|
|
return true;
|
|
}
|
|
|
|
if (Time.time >= m_nextPlan)
|
|
{
|
|
m_nextPlan = Time.time + PlanInterval;
|
|
Plan();
|
|
}
|
|
|
|
Execute(dt);
|
|
return true;
|
|
}
|
|
|
|
/// <summary>
|
|
/// The table is gone: start the clock, and stop when it runs out. Same shape as RaisedThrall's,
|
|
/// and deliberately only asked near home - further out the table's zone is simply not loaded, so
|
|
/// "nothing there" would be a lie.
|
|
/// </summary>
|
|
private bool TickWither()
|
|
{
|
|
Vector3? anchor = Anchor;
|
|
if (anchor == null || ZNet.instance == null) return false;
|
|
|
|
long stamp = m_nview.GetZDO().GetLong(KeyOrphanAt, 0L);
|
|
|
|
if (stamp == 0L)
|
|
{
|
|
if (Vector3.SqrMagnitude(transform.position - anchor.Value) >
|
|
HomeCheckRange * HomeCheckRange) return false;
|
|
if (RaisedThrall.StationStandsAt(anchor.Value)) return false;
|
|
|
|
m_nview.GetZDO().Set(KeyOrphanAt, ZNet.instance.GetTime().Ticks);
|
|
return false;
|
|
}
|
|
|
|
if (RaisedThrall.StationStandsAt(anchor.Value))
|
|
{
|
|
m_nview.GetZDO().Set(KeyOrphanAt, 0L);
|
|
return false;
|
|
}
|
|
|
|
double elapsed = (ZNet.instance.GetTime() - new System.DateTime(stamp)).TotalSeconds;
|
|
if (elapsed < WitherSeconds) return false;
|
|
|
|
HitData hit = new HitData();
|
|
hit.m_damage.m_damage = 1E+10f;
|
|
hit.m_hitType = HitData.HitType.Undefined;
|
|
m_character.ApplyDamage(hit, true, false);
|
|
return true;
|
|
}
|
|
|
|
// ================================================================ planning
|
|
|
|
private void Plan()
|
|
{
|
|
Vector3? anchor = Anchor;
|
|
if (anchor == null) { m_job = null; return; }
|
|
|
|
Scan(anchor.Value);
|
|
ExpirePenalties();
|
|
|
|
// A harvest is in progress: wait for the drops to land, then gather them and replant.
|
|
if (m_farmSpot != null)
|
|
{
|
|
m_job = Time.time < m_farmReadyAt
|
|
? new Job { Kind = "wait", Point = transform.position, Label = "Waiting" }
|
|
: new Job { Kind = "farm_finish", Point = m_farmSpot.Value, Label = "Gathering" };
|
|
return;
|
|
}
|
|
|
|
if (m_payload.Count > 0) { m_job = PlanDelivery(anchor.Value); return; }
|
|
|
|
// The forge has no clock: a smelter holds its ore indefinitely and puts its own output on
|
|
// the floor, so PlanRescue would ask a question whose answer is always no. The smith is a
|
|
// four-state machine and the cook is a five-state one, and that is the whole of the
|
|
// simplification the split bought.
|
|
// REFUEL BEFORE LOAD, and that order is the whole of the blast furnace fix. FreeSlots goes
|
|
// back above zero the instant a furnace eats one ore, so while there is scrap left in any
|
|
// chest PlanLoad always has an answer and PlanFuel, sitting behind it, never got a turn -
|
|
// the furnace was topped up forever and burned down to nothing. Fuel cannot starve loading
|
|
// in return, because FuelWanted is zero for a station with no work: an empty furnace asks
|
|
// for no coal, gets filled, and only then becomes worth stoking.
|
|
// One drone does both trades, so the burn protection is always on. Stations first, then the
|
|
// base: repairs, the fields, and last the tidying of the entry chest.
|
|
Job job = PlanRescue();
|
|
job = job ?? PlanCollect() ?? PlanFuel() ?? PlanLoad();
|
|
job = job ?? PlanRepair(anchor.Value) ?? PlanFarm(anchor.Value) ?? PlanSort();
|
|
|
|
if (job != null && (m_job == null || m_job.Kind != job.Kind || m_job.Target != job.Target))
|
|
{
|
|
m_jobDeadline = Time.time + JobTimeout;
|
|
}
|
|
if (m_job != null && !ReferenceEquals(m_job, job)) Release(m_job.Claim);
|
|
if (job != null) Claim(job.Claim);
|
|
m_job = job;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Everything within the radius, once every planning tick. Piece.s_allPieces is the cheap way in
|
|
/// - it is the list the game already keeps of every built piece - so there is no OverlapSphere
|
|
/// and no guessing at layer masks for the part that runs constantly.
|
|
/// </summary>
|
|
private void Scan(Vector3 anchor)
|
|
{
|
|
if (Time.time - m_scannedAt < PlanInterval * 0.5f) return;
|
|
m_scannedAt = Time.time;
|
|
|
|
m_stations.Clear();
|
|
m_chests.Clear();
|
|
m_damaged.Clear();
|
|
m_entry = null;
|
|
m_wood = null;
|
|
|
|
List<Piece> pieces = AllPiecesField != null ? AllPiecesField.GetValue(null) as List<Piece> : null;
|
|
if (pieces == null) return;
|
|
|
|
float radius = AlfarNexusConfig.NexusRadius.Value + m_radiusBonus;
|
|
float radiusSq = radius * radius;
|
|
|
|
for (int i = 0; i < pieces.Count; i++)
|
|
{
|
|
Piece piece = pieces[i];
|
|
if (piece == null) continue;
|
|
if (Vector3.SqrMagnitude(piece.transform.position - anchor) > radiusSq) continue;
|
|
|
|
// A station of the other trade is not this servant's business, but it is still not a
|
|
// chest - hence the continue either way.
|
|
// Both trades: the drone serves the smelters AND the kitchens.
|
|
ButlerStation station = ButlerStation.From(piece.gameObject);
|
|
if (station != null)
|
|
{
|
|
m_stations.Add(station);
|
|
continue;
|
|
}
|
|
|
|
// Every chest in reach is the drone's, EXCEPT one holding the sigil. The two special
|
|
// chests are told apart by prefab name.
|
|
Container container = piece.GetComponent<Container>();
|
|
if (container != null && !IsMarkedOff(container))
|
|
{
|
|
string chestName = Utils.GetPrefabName(piece.gameObject);
|
|
if (chestName == AlfarChests.EntryName) m_entry = container;
|
|
else if (chestName == AlfarChests.WoodName) m_wood = container;
|
|
else m_chests.Add(container);
|
|
}
|
|
|
|
// Anything damaged is for the drones to mend, towers and chests and walls alike.
|
|
WearNTear wear = piece.GetComponent<WearNTear>();
|
|
if (wear != null && wear.GetHealthPercentage() < 0.999f) m_damaged.Add(wear);
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// The sigil is INVERTED from the Butler's: it marks the chests the drones must NOT look at. A
|
|
/// chest in use by a player is left alone too. The sigil itself is never counted as material and
|
|
/// never carried away - see TakeFrom.
|
|
/// </summary>
|
|
private static bool IsMarkedOff(Container container)
|
|
{
|
|
if (container == null || container.IsInUse()) return true;
|
|
|
|
Inventory inventory = container.GetInventory();
|
|
if (inventory == null) return true;
|
|
|
|
string sigil = SigilSharedName();
|
|
return !string.IsNullOrEmpty(sigil) && inventory.CountItems(sigil) > 0;
|
|
}
|
|
|
|
private static string s_sigilShared;
|
|
private static string s_sigilFor;
|
|
|
|
/// <summary>Inventory.CountItems matches on the SHARED name ($item_...), not on the prefab name
|
|
/// the stations use, so the configured prefab is resolved once into the other kind of name.</summary>
|
|
private static string SigilSharedName()
|
|
{
|
|
string wanted = AlfarSigil.PrefabName;
|
|
if (s_sigilFor == wanted) return s_sigilShared;
|
|
|
|
s_sigilFor = wanted;
|
|
s_sigilShared = null;
|
|
|
|
GameObject prefab = ObjectDB.instance != null ? ObjectDB.instance.GetItemPrefab(wanted) : null;
|
|
ItemDrop drop = prefab != null ? prefab.GetComponent<ItemDrop>() : null;
|
|
if (drop != null && drop.m_itemData != null && drop.m_itemData.m_shared != null)
|
|
{
|
|
s_sigilShared = drop.m_itemData.m_shared.m_name;
|
|
}
|
|
else
|
|
{
|
|
Jotunn.Logger.LogWarning($"[AlfarDrone] No item '{wanted}' to use as the sigil; " +
|
|
"no chest can be marked until that name is right.");
|
|
}
|
|
|
|
return s_sigilShared;
|
|
}
|
|
|
|
// ---------------------------------------------------------------- the five states
|
|
|
|
/// <summary>1. SAVE. A slot about to burn beats everything, and it is the only job it runs to.</summary>
|
|
private Job PlanRescue()
|
|
{
|
|
ButlerStation best = null;
|
|
float soonest = SpoilPanicSeconds;
|
|
|
|
foreach (ButlerStation station in m_stations)
|
|
{
|
|
if (!station.Alive || IsPenalised(station.Id) || ClaimedByOther(station.Id)) continue;
|
|
if (!station.HasOutput) continue; // nothing pullable yet, panic changes nothing
|
|
|
|
float left = station.SecondsToSpoil;
|
|
if (left >= soonest) continue;
|
|
|
|
soonest = left;
|
|
best = station;
|
|
}
|
|
|
|
if (best == null) return null;
|
|
|
|
return new Job
|
|
{
|
|
Kind = "collect",
|
|
Target = best.Id,
|
|
Claim = best.Id,
|
|
Point = best.Position,
|
|
Hurry = true,
|
|
Label = "Saving the food",
|
|
};
|
|
}
|
|
|
|
/// <summary>2. COLLECT. Anything finished, and anything already lying under a station.</summary>
|
|
private Job PlanCollect()
|
|
{
|
|
ButlerStation best = null;
|
|
float bestScore = float.MaxValue;
|
|
|
|
foreach (ButlerStation station in m_stations)
|
|
{
|
|
if (!station.Alive || IsPenalised(station.Id) || ClaimedByOther(station.Id)) continue;
|
|
if (!station.HasOutput && !HasDropsNear(station.Position)) continue;
|
|
|
|
float score = Vector3.Distance(transform.position, station.Position);
|
|
if (score >= bestScore) continue;
|
|
|
|
bestScore = score;
|
|
best = station;
|
|
}
|
|
|
|
if (best == null) return null;
|
|
|
|
return new Job
|
|
{
|
|
Kind = "collect",
|
|
Target = best.Id,
|
|
Claim = best.Id,
|
|
Point = best.Position,
|
|
Label = "Collecting",
|
|
};
|
|
}
|
|
|
|
/// <summary>
|
|
/// 4. LOAD. Urgency, then distance - and the urgency of a station with nothing wrong with it is
|
|
/// how long it has been waiting. A metre of walking is worth four seconds of a station standing
|
|
/// idle, so the far furnace wins eventually instead of never.
|
|
/// </summary>
|
|
private Job PlanLoad()
|
|
{
|
|
ButlerStation best = null;
|
|
string bestItem = null;
|
|
Container bestChest = null;
|
|
float bestScore = float.MaxValue;
|
|
|
|
foreach (ButlerStation station in m_stations)
|
|
{
|
|
if (!station.Alive || IsPenalised(station.Id) || ClaimedByOther(station.Id)) continue;
|
|
if (!station.Operable || station.FreeSlots <= 0) continue;
|
|
|
|
Container chest;
|
|
string item = FindMaterialFor(station, out chest);
|
|
if (item == null) { m_idleSince.Remove(station.Id); continue; }
|
|
|
|
float waited = NoteIdle(station.Id);
|
|
float score = Vector3.Distance(transform.position, chest.transform.position) +
|
|
Vector3.Distance(chest.transform.position, station.Position) -
|
|
waited * WaitToMetres;
|
|
|
|
if (score >= bestScore) continue;
|
|
|
|
bestScore = score;
|
|
best = station;
|
|
bestItem = item;
|
|
bestChest = chest;
|
|
}
|
|
|
|
if (best == null) return null;
|
|
|
|
// The chest first - the station is where the payload goes afterwards, and PlanDelivery
|
|
// works that out from the target written on the load.
|
|
return new Job
|
|
{
|
|
Kind = "load",
|
|
Target = ZdoOf(bestChest),
|
|
Claim = best.Id,
|
|
Point = bestChest.transform.position,
|
|
Label = "Fetching " + bestItem,
|
|
};
|
|
}
|
|
|
|
/// <summary>
|
|
/// 3. REFUEL. Only stations that actually have something to work on.
|
|
///
|
|
/// Scored by the walk, the same way PlanLoad is, and for a reason that only appeared once this
|
|
/// moved up the list: taking the first station in scan order was harmless while refuelling was
|
|
/// the job of last resort, but ahead of loading it lets one furnace at the edge of the circle
|
|
/// hold the servant while a cold one two metres away waits.
|
|
/// </summary>
|
|
private Job PlanFuel()
|
|
{
|
|
Container bestChest = null;
|
|
string bestFuel = null;
|
|
float bestScore = float.MaxValue;
|
|
|
|
foreach (ButlerStation station in m_stations)
|
|
{
|
|
if (!station.Alive || IsPenalised(station.Id) || ClaimedByOther(station.Id)) continue;
|
|
if (!station.Operable) continue;
|
|
|
|
int wanted = station.FuelWanted;
|
|
if (wanted <= 0) continue;
|
|
|
|
string fuel = station.FuelPrefab;
|
|
if (string.IsNullOrEmpty(fuel)) continue;
|
|
|
|
Container chest = FindChestWith(fuel);
|
|
if (chest == null) continue;
|
|
|
|
float score = Vector3.Distance(transform.position, chest.transform.position) +
|
|
Vector3.Distance(chest.transform.position, station.Position);
|
|
if (score >= bestScore) continue;
|
|
|
|
bestScore = score;
|
|
bestChest = chest;
|
|
bestFuel = fuel;
|
|
}
|
|
|
|
if (bestChest == null) return null;
|
|
|
|
return new Job
|
|
{
|
|
Kind = "fuel",
|
|
Target = ZdoOf(bestChest),
|
|
Point = bestChest.transform.position,
|
|
Label = "Fetching " + bestFuel,
|
|
};
|
|
}
|
|
|
|
/// <summary>Where the load in hand is going: on to its station, or back into a chest.</summary>
|
|
private Job PlanDelivery(Vector3 anchor)
|
|
{
|
|
// A sorting trip has a destination chosen at the entry chest: take it there.
|
|
ZDOID dest = m_nview.GetZDO().GetZDOID(KeyDest);
|
|
if (dest != ZDOID.None)
|
|
{
|
|
Container destination = ContainerById(dest);
|
|
if (destination != null && !IsMarkedOff(destination) && !IsPenalised(dest) && HasRoomFor(destination))
|
|
{
|
|
return new Job
|
|
{
|
|
Kind = "deposit",
|
|
Target = dest,
|
|
Point = destination.transform.position,
|
|
Label = "Sorting " + Describe(),
|
|
};
|
|
}
|
|
m_nview.GetZDO().Set(KeyDest, ZDOID.None);
|
|
}
|
|
|
|
ZDOID target = m_nview.GetZDO().GetZDOID(KeyTarget);
|
|
if (target != ZDOID.None)
|
|
{
|
|
// NO FreeSlots CHECK HERE, and that was the first bug found in play: fuel does not go
|
|
// into a slot. A furnace filled to m_maxOre with copper has FreeSlots 0 and still wants
|
|
// coal, so gating the delivery on free slots sent the servant back to the chest with
|
|
// the coal it had just fetched - and then PlanFuel sent it out for the same coal again,
|
|
// forever. AcceptsAnything already asks the right question of both doors.
|
|
ButlerStation station = StationById(target);
|
|
if (station != null && station.Alive && station.Operable && AcceptsAnything(station))
|
|
{
|
|
return new Job
|
|
{
|
|
Kind = "deposit_station",
|
|
Target = target,
|
|
Point = station.Position,
|
|
Label = "Loading " + Describe(),
|
|
};
|
|
}
|
|
|
|
// The station is gone, full or cold. The goods are ours to put back, not to hold.
|
|
m_nview.GetZDO().Set(KeyTarget, ZDOID.None);
|
|
}
|
|
|
|
Container chest = ChestForProduct();
|
|
if (chest != null)
|
|
{
|
|
return new Job
|
|
{
|
|
Kind = "deposit",
|
|
Target = ZdoOf(chest),
|
|
Point = chest.transform.position,
|
|
Label = "Storing " + Describe(),
|
|
};
|
|
}
|
|
|
|
// Every sealed chest is full - but a chest is not the only place a thing can go. A station
|
|
// that BURNS what is in hand is a destination too, and for the smith it is usually the
|
|
// right one: the charcoal kiln releases its whole batch in one go (verified in the IL -
|
|
// UpdateSmelter only calls SpawnProcessed once the ore queue empties), which is exactly the
|
|
// delivery a nearly full chest cannot absorb, and the coal it makes is what the furnace
|
|
// beside it is waiting for. Offering the load to a consumer before giving up is what turns
|
|
// "nowhere to put 20x Coal" into a full blast furnace.
|
|
//
|
|
// It comes AFTER the chest and not before, so a product still goes home to the chest that
|
|
// paid for it whenever there is room; this is the step before the floor, not instead of
|
|
// storing.
|
|
ButlerStation consumer = StationWanting();
|
|
if (consumer != null)
|
|
{
|
|
return new Job
|
|
{
|
|
Kind = "deposit_station",
|
|
Target = consumer.Id,
|
|
Point = consumer.Position,
|
|
Label = "Loading " + Describe(),
|
|
};
|
|
}
|
|
|
|
// Nothing will take it. Beside the table it goes: a stalled chain is worse than a tidy
|
|
// floor, and nothing may vanish (sec. 7.3).
|
|
return new Job
|
|
{
|
|
Kind = "drop",
|
|
Target = ZDOID.None,
|
|
Point = anchor,
|
|
Label = "Nowhere to put " + Describe(),
|
|
};
|
|
}
|
|
|
|
/// <summary>The nearest station that will take something out of the payload, as material or as
|
|
/// fuel. No FreeSlots check, for the reason spelled out above the KeyTarget branch: fuel does
|
|
/// not go into a slot, and AcceptsAnything already asks the right question of both doors.</summary>
|
|
private ButlerStation StationWanting()
|
|
{
|
|
ButlerStation best = null;
|
|
float bestDistance = float.MaxValue;
|
|
|
|
foreach (ButlerStation station in m_stations)
|
|
{
|
|
if (!station.Alive || IsPenalised(station.Id) || ClaimedByOther(station.Id)) continue;
|
|
if (!station.Operable || !AcceptsAnything(station)) continue;
|
|
|
|
float distance = Vector3.Distance(transform.position, station.Position);
|
|
if (distance >= bestDistance) continue;
|
|
|
|
bestDistance = distance;
|
|
best = station;
|
|
}
|
|
|
|
return best;
|
|
}
|
|
|
|
// ================================================================ execution
|
|
|
|
private void Execute(float dt)
|
|
{
|
|
if (m_job == null)
|
|
{
|
|
SetStatus(m_stations.Count == 0 ? "Nothing to serve." : "Nothing to do.");
|
|
GoHome(dt);
|
|
return;
|
|
}
|
|
|
|
SetStatus(m_job.Label);
|
|
|
|
if (!MoveToPoint(dt, m_job.Point, ArriveDistance, m_job.Hurry))
|
|
{
|
|
// Doors do not open for pathfinding. A target it cannot reach goes into the penalty box
|
|
// and the servant gets on with something it can do.
|
|
if (Time.time > m_jobDeadline)
|
|
{
|
|
Penalise(m_job.Target);
|
|
Jotunn.Logger.LogInfo($"[AlfarDrone] Could not reach {m_job.Kind} target; " +
|
|
"setting it aside for a few minutes.");
|
|
m_job = null;
|
|
m_nextPlan = 0f;
|
|
}
|
|
return;
|
|
}
|
|
|
|
bool achieved;
|
|
switch (m_job.Kind)
|
|
{
|
|
case "load": achieved = DoLoad(); break;
|
|
case "fuel": achieved = DoFuel(); break;
|
|
case "collect": achieved = DoCollect(); break;
|
|
case "deposit_station": achieved = DoDepositStation(); break;
|
|
case "deposit": achieved = DoDeposit(); break;
|
|
case "drop": DropPayload(); achieved = true; break;
|
|
case "wait": achieved = true; break;
|
|
case "repair": achieved = DoRepair(); break;
|
|
case "farm": achieved = DoFarm(); break;
|
|
case "farm_finish": achieved = DoFarmFinish(); break;
|
|
case "sortfetch": achieved = DoSortFetch(); break;
|
|
default: achieved = true; break;
|
|
}
|
|
|
|
// Arrived and nothing happened: the world moved while it walked. Set that target aside for
|
|
// twenty seconds so the next plan picks something else instead of re-deciding the same
|
|
// errand on every tick.
|
|
if (!achieved) PenaliseShort(m_job.Target);
|
|
|
|
m_job = null;
|
|
m_nextPlan = 0f; // arriving changes the world; re-plan on the next tick rather than in 1.5 s
|
|
}
|
|
|
|
/// <summary>At the chest: take what the chosen station will eat, and remember where it came from.</summary>
|
|
private bool DoLoad()
|
|
{
|
|
Container chest = ContainerById(m_job.Target);
|
|
if (chest == null) return false;
|
|
|
|
// The station is chosen again here rather than carried on the job, because the walk took
|
|
// time and the world may have moved on.
|
|
ButlerStation station = null;
|
|
string item = null;
|
|
|
|
foreach (ButlerStation candidate in m_stations)
|
|
{
|
|
if (!candidate.Alive || !candidate.Operable || candidate.FreeSlots <= 0) continue;
|
|
if (IsPenalised(candidate.Id)) continue;
|
|
|
|
string found = FirstAccepted(candidate, chest);
|
|
if (found == null) continue;
|
|
|
|
station = candidate;
|
|
item = found;
|
|
break;
|
|
}
|
|
|
|
if (station == null || item == null) return false;
|
|
|
|
int taken = TakeFrom(chest, item, station.FreeSlots);
|
|
if (taken <= 0) return false;
|
|
|
|
AddToPayload(item, taken);
|
|
m_nview.GetZDO().Set(KeySource, ZdoOf(chest));
|
|
m_nview.GetZDO().Set(KeyTarget, station.Id);
|
|
WritePayload();
|
|
return true;
|
|
}
|
|
|
|
/// <summary>At the chest, for fuel. Same shape as DoLoad, and kept separate because fuel goes in
|
|
/// through a different door and is never the thing being processed.</summary>
|
|
private bool DoFuel()
|
|
{
|
|
Container chest = ContainerById(m_job.Target);
|
|
if (chest == null) return false;
|
|
|
|
foreach (ButlerStation station in m_stations)
|
|
{
|
|
if (!station.Alive || !station.Operable || IsPenalised(station.Id)) continue;
|
|
|
|
int wanted = station.FuelWanted;
|
|
string fuel = station.FuelPrefab;
|
|
if (wanted <= 0 || string.IsNullOrEmpty(fuel)) continue;
|
|
|
|
int taken = TakeFrom(chest, fuel, wanted);
|
|
if (taken <= 0) continue;
|
|
|
|
AddToPayload(fuel, taken);
|
|
m_nview.GetZDO().Set(KeySource, ZdoOf(chest));
|
|
m_nview.GetZDO().Set(KeyTarget, station.Id);
|
|
WritePayload();
|
|
return true;
|
|
}
|
|
|
|
return false;
|
|
}
|
|
|
|
/// <summary>
|
|
/// At a station with something finished. Pull first, sweep second - and the sweep is the only
|
|
/// place the servant ever picks anything up off the ground, which is what keeps it from tidying
|
|
/// away things the player left lying about on purpose.
|
|
///
|
|
/// THE ORDER IS THE POINT, and it used to be the other way round. Sweeping first meant every
|
|
/// visit collected what the LAST visit had thrown on the floor and then threw a fresh one down;
|
|
/// since Plan() hands the servant to PlanDelivery the moment it is carrying anything, it walked
|
|
/// off to the chest the instant the sweep landed and abandoned the item it had just pulled.
|
|
/// While a hearth kept working there was therefore always exactly one cooked meat lying on the
|
|
/// ground - the "loses one per batch, whether that is two or five" the testers reported.
|
|
///
|
|
/// The loop is the other half of it. RPC_RemoveDoneItem empties ONE slot per call, so a hearth
|
|
/// with five done slots needs five calls; one per visit turned one batch into five round trips
|
|
/// to the chest. It runs against OutputPulls rather than against HasOutput alone because the
|
|
/// fermenter's Ready survives its own tap for the length of the animation.
|
|
/// </summary>
|
|
private bool DoCollect()
|
|
{
|
|
ButlerStation station = StationById(m_job.Target);
|
|
if (station == null || !station.Alive) return false;
|
|
|
|
bool pulled = false;
|
|
for (int i = 0; i < station.OutputPulls && station.HasOutput; i++)
|
|
{
|
|
station.PullOutput(transform.position);
|
|
pulled = true;
|
|
}
|
|
|
|
int before = PayloadCount();
|
|
SweepDrops(station.Position);
|
|
bool swept = PayloadCount() > before;
|
|
|
|
if (swept)
|
|
{
|
|
// The product belongs to whoever fed the station. If nothing was written there - the
|
|
// player loaded it by hand - it goes to the nearest sealed chest instead, which is the
|
|
// "yes, it collects your work too" decision paying its own way.
|
|
ZDOID fedBy = station.Nview.GetZDO().GetZDOID(KeyFedBy);
|
|
m_nview.GetZDO().Set(KeySource, fedBy);
|
|
m_nview.GetZDO().Set(KeyTarget, ZDOID.None);
|
|
WritePayload();
|
|
}
|
|
|
|
return swept || pulled;
|
|
}
|
|
|
|
/// <summary>At the station, with raw material in hand.</summary>
|
|
private bool DoDepositStation()
|
|
{
|
|
ButlerStation station = StationById(m_job.Target);
|
|
if (station == null || !station.Alive || !station.Operable) return false;
|
|
|
|
bool loadedAny = false;
|
|
|
|
for (int i = m_payload.Count - 1; i >= 0; i--)
|
|
{
|
|
Load load = m_payload[i];
|
|
|
|
while (load.Count > 0 && station.FreeSlots > 0 && station.Accepts(load.Name))
|
|
{
|
|
station.Add(load.Name);
|
|
load.Count--;
|
|
loadedAny = true;
|
|
}
|
|
|
|
// Fuel goes in through its own door, and only for as long as it is wanted.
|
|
if (load.Count > 0 && load.Name == station.FuelPrefab)
|
|
{
|
|
int wanted = station.FuelWanted;
|
|
while (load.Count > 0 && wanted > 0)
|
|
{
|
|
station.AddFuel();
|
|
load.Count--;
|
|
wanted--;
|
|
loadedAny = true;
|
|
}
|
|
}
|
|
|
|
if (load.Count <= 0) m_payload.RemoveAt(i);
|
|
}
|
|
|
|
if (loadedAny)
|
|
{
|
|
// Whoever fed it, gets it back.
|
|
ZDOID source = m_nview.GetZDO().GetZDOID(KeySource);
|
|
if (source != ZDOID.None && station.Nview.IsValid())
|
|
{
|
|
if (!station.Nview.IsOwner()) station.Nview.ClaimOwnership();
|
|
station.Nview.GetZDO().Set(KeyFedBy, source);
|
|
}
|
|
}
|
|
|
|
if (m_payload.Count == 0) m_nview.GetZDO().Set(KeyTarget, ZDOID.None);
|
|
WritePayload();
|
|
return loadedAny;
|
|
}
|
|
|
|
/// <summary>At a chest, with the finished goods.</summary>
|
|
private bool DoDeposit()
|
|
{
|
|
Container chest = ContainerById(m_job.Target);
|
|
if (chest == null) return false;
|
|
|
|
ZNetView nview = chest.GetComponent<ZNetView>();
|
|
if (nview == null || !nview.IsValid()) return false;
|
|
if (!nview.IsOwner()) nview.ClaimOwnership();
|
|
|
|
Inventory inventory = chest.GetInventory();
|
|
if (inventory == null) return false;
|
|
|
|
bool wrote = false;
|
|
|
|
for (int i = m_payload.Count - 1; i >= 0; i--)
|
|
{
|
|
Load load = m_payload[i];
|
|
|
|
GameObject prefab = ObjectDB.instance != null
|
|
? ObjectDB.instance.GetItemPrefab(load.Name)
|
|
: null;
|
|
if (prefab == null) continue;
|
|
|
|
// One at a time: it stacks correctly, it stops exactly when the chest is full, and the
|
|
// counts are small enough that being tidy costs nothing.
|
|
while (load.Count > 0 && inventory.CanAddItem(prefab, 1) && inventory.AddItem(prefab, 1))
|
|
{
|
|
load.Count--;
|
|
wrote = true;
|
|
}
|
|
|
|
if (load.Count <= 0) m_payload.RemoveAt(i);
|
|
}
|
|
|
|
if (wrote && ContainerSaveMethod != null) ContainerSaveMethod.Invoke(chest, null);
|
|
WritePayload();
|
|
|
|
// Still holding something: that chest is full, so do not choose it again on the next pass.
|
|
if (m_payload.Count > 0) Penalise(m_job.Target);
|
|
else m_nview.GetZDO().Set(KeyDest, ZDOID.None);
|
|
return wrote;
|
|
}
|
|
|
|
// ================================================================ claims
|
|
|
|
// Two drones must not take the same station or chest in the same moment. The Butler forbids a
|
|
// second table nearby; with N drones to a Nexus that is impossible, so the choice is made
|
|
// visible between them: a target is CLAIMED by the drone that picked it for a short while. This
|
|
// is the local-client form of the dispatcher the design asks for; two clients owning two
|
|
// drones still cannot see each other's claims (doc 17.14).
|
|
private static readonly Dictionary<ZDOID, KeyValuePair<AlfarDroneAI, float>> s_claims =
|
|
new Dictionary<ZDOID, KeyValuePair<AlfarDroneAI, float>>();
|
|
private const float ClaimSeconds = 30f;
|
|
|
|
private bool ClaimedByOther(ZDOID id)
|
|
{
|
|
if (id == ZDOID.None) return false;
|
|
KeyValuePair<AlfarDroneAI, float> claim;
|
|
if (!s_claims.TryGetValue(id, out claim)) return false;
|
|
|
|
if (claim.Key == null || Time.time >= claim.Value) { s_claims.Remove(id); return false; }
|
|
return claim.Key != this;
|
|
}
|
|
|
|
private void Claim(ZDOID id)
|
|
{
|
|
if (id != ZDOID.None) s_claims[id] = new KeyValuePair<AlfarDroneAI, float>(this, Time.time + ClaimSeconds);
|
|
}
|
|
|
|
private void Release(ZDOID id)
|
|
{
|
|
KeyValuePair<AlfarDroneAI, float> claim;
|
|
if (id != ZDOID.None && s_claims.TryGetValue(id, out claim) && claim.Key == this) s_claims.Remove(id);
|
|
}
|
|
|
|
// ================================================================ repair
|
|
|
|
/// <summary>
|
|
/// Anything damaged in the base, and any other drone that is hurt. Free, like the hammer. NOT the
|
|
/// constructs: their damage is permanent by design (they are Characters and not pieces, and
|
|
/// they are not drones, so they never come up here).
|
|
/// </summary>
|
|
private Job PlanRepair(Vector3 anchor)
|
|
{
|
|
WearNTear bestPiece = null;
|
|
AlfarDroneAI bestDrone = null;
|
|
float bestDistance = float.MaxValue;
|
|
|
|
foreach (WearNTear wear in m_damaged)
|
|
{
|
|
if (wear == null) continue;
|
|
ZDOID id = ZdoOf(wear);
|
|
if (IsPenalised(id) || ClaimedByOther(id)) continue;
|
|
|
|
float distance = Vector3.Distance(transform.position, wear.transform.position);
|
|
if (distance >= bestDistance) continue;
|
|
bestDistance = distance;
|
|
bestPiece = wear;
|
|
}
|
|
|
|
foreach (AlfarDroneAI other in All)
|
|
{
|
|
if (other == null || other == this || other.m_character == null || other.m_character.IsDead()) continue;
|
|
if (other.m_character.GetHealth() >= other.m_character.GetMaxHealth() - 0.5f) continue;
|
|
if (Vector3.Distance(other.transform.position, anchor) > AlfarNexusConfig.NexusRadius.Value) continue;
|
|
|
|
ZDOID id = ZdoOf(other);
|
|
if (IsPenalised(id) || ClaimedByOther(id)) continue;
|
|
|
|
float distance = Vector3.Distance(transform.position, other.transform.position);
|
|
if (distance >= bestDistance) continue;
|
|
bestDistance = distance;
|
|
bestDrone = other;
|
|
bestPiece = null;
|
|
}
|
|
|
|
if (bestPiece != null)
|
|
{
|
|
ZDOID id = ZdoOf(bestPiece);
|
|
return new Job { Kind = "repair", Target = id, Claim = id, Point = bestPiece.transform.position, Label = "Repairing" };
|
|
}
|
|
if (bestDrone != null)
|
|
{
|
|
ZDOID id = ZdoOf(bestDrone);
|
|
return new Job { Kind = "repair", Target = id, Claim = id, Point = bestDrone.transform.position, Label = "Mending a drone" };
|
|
}
|
|
return null;
|
|
}
|
|
|
|
private bool DoRepair()
|
|
{
|
|
if (ZNetScene.instance == null) return false;
|
|
|
|
GameObject go = ZNetScene.instance.FindInstance(m_job.Target);
|
|
if (go == null) return false;
|
|
|
|
WearNTear wear = go.GetComponent<WearNTear>();
|
|
if (wear != null) return wear.Repair();
|
|
|
|
Character character = go.GetComponent<Character>();
|
|
if (character != null && !character.IsDead() && go.GetComponent<AlfarDroneAI>() != null)
|
|
{
|
|
character.Heal(character.GetMaxHealth(), true);
|
|
return true;
|
|
}
|
|
return false;
|
|
}
|
|
|
|
// ================================================================ farming
|
|
|
|
private class PlantInfo
|
|
{
|
|
public GameObject Sapling; // the piece that grows the plant
|
|
public string Item; // the item that piece costs, and so the item to put back
|
|
}
|
|
|
|
// pickable prefab name -> the sapling that grows it and the item that sapling costs
|
|
private static readonly Dictionary<string, PlantInfo> s_plants = new Dictionary<string, PlantInfo>();
|
|
private static bool s_plantsBuilt;
|
|
private static float s_pickScanAt = -99f;
|
|
private static readonly List<Pickable> s_pickables = new List<Pickable>();
|
|
private static readonly System.Reflection.FieldInfo PickedField = AccessTools.Field(typeof(Pickable), "m_picked");
|
|
|
|
/// <summary>
|
|
/// Built from the game, not from a list: every Plant in ZNetScene names the pickable it grows
|
|
/// into and costs one of an item through its Piece. The drone ONLY works plants it can put back
|
|
/// (rule R2): it never harvests something it could not replant.
|
|
/// </summary>
|
|
private static void BuildPlants()
|
|
{
|
|
if (s_plantsBuilt || ZNetScene.instance == null) return;
|
|
s_plantsBuilt = true;
|
|
|
|
foreach (GameObject prefab in ZNetScene.instance.m_prefabs)
|
|
{
|
|
if (prefab == null) continue;
|
|
|
|
Plant plant = prefab.GetComponent<Plant>();
|
|
Piece piece = prefab.GetComponent<Piece>();
|
|
if (plant == null || piece == null || plant.m_grownPrefabs == null) continue;
|
|
if (piece.m_resources == null || piece.m_resources.Length == 0 || piece.m_resources[0].m_resItem == null) continue;
|
|
|
|
string item = piece.m_resources[0].m_resItem.gameObject.name;
|
|
foreach (GameObject grown in plant.m_grownPrefabs)
|
|
{
|
|
if (grown != null && !s_plants.ContainsKey(grown.name))
|
|
{
|
|
s_plants[grown.name] = new PlantInfo { Sapling = prefab, Item = item };
|
|
}
|
|
}
|
|
}
|
|
Jotunn.Logger.LogInfo($"[AlfarDrone] {s_plants.Count} replantable crops known.");
|
|
}
|
|
|
|
private static void RefreshPickables()
|
|
{
|
|
if (Time.time - s_pickScanAt < 4f) return;
|
|
s_pickScanAt = Time.time;
|
|
|
|
s_pickables.Clear();
|
|
s_pickables.AddRange(Object.FindObjectsByType<Pickable>(FindObjectsSortMode.None));
|
|
}
|
|
|
|
private static bool IsPicked(Pickable pickable)
|
|
{
|
|
return PickedField != null && (bool)PickedField.GetValue(pickable);
|
|
}
|
|
|
|
/// <summary>Does picking it give back the item the sapling costs?</summary>
|
|
private static bool Yields(Pickable pickable, string item)
|
|
{
|
|
if (pickable.m_itemPrefab != null && pickable.m_itemPrefab.name == item) return true;
|
|
|
|
if (pickable.m_extraDrops != null && pickable.m_extraDrops.m_drops != null)
|
|
{
|
|
foreach (DropTable.DropData drop in pickable.m_extraDrops.m_drops)
|
|
{
|
|
if (drop.m_item != null && drop.m_item.name == item) return true;
|
|
}
|
|
}
|
|
return false;
|
|
}
|
|
|
|
private static string[] s_wild;
|
|
private static bool IsWildTarget(string prefabName)
|
|
{
|
|
if (s_wild == null) s_wild = AlfarNexusConfig.WildPickables.Value.Split(new[] { ',' }, System.StringSplitOptions.RemoveEmptyEntries);
|
|
foreach (string part in s_wild)
|
|
{
|
|
if (prefabName.IndexOf(part.Trim(), System.StringComparison.OrdinalIgnoreCase) >= 0) return true;
|
|
}
|
|
return false;
|
|
}
|
|
|
|
/// <summary>
|
|
/// FARMING, with the iron rule (doc 9.4): a cultivated plant is harvested only if the drone can
|
|
/// replant one of what it gives; the replant is made RIGHT AWAY, in the SAME place, out of what
|
|
/// was just picked, and the rest is stored. Wild mushrooms, berry bushes and flowers on the list
|
|
/// are picked and NOT replanted (they grow back by themselves, and trees are never touched).
|
|
/// </summary>
|
|
private Job PlanFarm(Vector3 anchor)
|
|
{
|
|
BuildPlants();
|
|
RefreshPickables();
|
|
|
|
float radius = AlfarNexusConfig.NexusRadius.Value;
|
|
Pickable best = null;
|
|
PlantInfo bestInfo = null;
|
|
float bestDistance = float.MaxValue;
|
|
|
|
foreach (Pickable pickable in s_pickables)
|
|
{
|
|
if (pickable == null || !pickable.gameObject.activeInHierarchy) continue;
|
|
if (Vector3.Distance(pickable.transform.position, anchor) > radius) continue;
|
|
if (IsPicked(pickable)) continue;
|
|
|
|
ZDOID id = ZdoOf(pickable);
|
|
if (id == ZDOID.None || IsPenalised(id) || ClaimedByOther(id)) continue;
|
|
|
|
string name = Utils.GetPrefabName(pickable.gameObject);
|
|
PlantInfo info = null;
|
|
|
|
if (pickable.m_respawnTimeMinutes > 0f)
|
|
{
|
|
if (!IsWildTarget(name)) continue; // wild and regrowing: only the listed ones
|
|
}
|
|
else
|
|
{
|
|
if (!s_plants.TryGetValue(name, out info) || !Yields(pickable, info.Item)) continue;
|
|
}
|
|
|
|
float distance = Vector3.Distance(transform.position, pickable.transform.position);
|
|
if (distance >= bestDistance) continue;
|
|
|
|
bestDistance = distance;
|
|
best = pickable;
|
|
bestInfo = info;
|
|
}
|
|
|
|
if (best == null) return null;
|
|
|
|
m_farmInfo = bestInfo;
|
|
ZDOID target = ZdoOf(best);
|
|
return new Job { Kind = "farm", Target = target, Claim = target, Point = best.transform.position, Label = "Harvesting" };
|
|
}
|
|
|
|
private bool DoFarm()
|
|
{
|
|
if (ZNetScene.instance == null) return false;
|
|
|
|
GameObject go = ZNetScene.instance.FindInstance(m_job.Target);
|
|
Pickable pickable = go != null ? go.GetComponent<Pickable>() : null;
|
|
if (pickable == null || IsPicked(pickable)) return false;
|
|
|
|
Humanoid hands = m_character as Humanoid;
|
|
if (hands == null) return false;
|
|
|
|
Vector3 spot = pickable.transform.position;
|
|
Quaternion rot = pickable.transform.rotation;
|
|
|
|
if (!pickable.Interact(hands, false, false)) return false;
|
|
|
|
m_farmSpot = spot;
|
|
m_farmRot = rot;
|
|
m_farmReadyAt = Time.time + 0.8f; // the drops need a moment to land
|
|
return true;
|
|
}
|
|
|
|
private bool DoFarmFinish()
|
|
{
|
|
Vector3? spot = m_farmSpot;
|
|
PlantInfo info = m_farmInfo;
|
|
m_farmSpot = null;
|
|
m_farmInfo = null;
|
|
if (spot == null) return false;
|
|
|
|
SweepDrops(spot.Value);
|
|
|
|
if (info != null)
|
|
{
|
|
// R6: the replant comes OUT OF what was just picked, never out of anyone's stock.
|
|
bool have = false;
|
|
foreach (Load load in m_payload)
|
|
{
|
|
if (load.Name == info.Item && load.Count > 0) { load.Count--; have = true; break; }
|
|
}
|
|
m_payload.RemoveAll(l => l.Count <= 0);
|
|
WritePayload();
|
|
|
|
if (have && info.Sapling != null)
|
|
{
|
|
Object.Instantiate(info.Sapling, spot.Value, m_farmRot);
|
|
}
|
|
else
|
|
{
|
|
Jotunn.Logger.LogWarning($"[AlfarDrone] Harvested a crop but found no '{info.Item}' to put back.");
|
|
}
|
|
}
|
|
|
|
m_nview.GetZDO().Set(KeySource, ZDOID.None);
|
|
m_nview.GetZDO().Set(KeyTarget, ZDOID.None);
|
|
return true;
|
|
}
|
|
|
|
// ================================================================ sorting
|
|
|
|
private bool AnyStationAccepts(string prefabName)
|
|
{
|
|
foreach (ButlerStation station in m_stations)
|
|
{
|
|
if (!station.Alive || !station.Operable) continue;
|
|
if (station.Accepts(prefabName) || prefabName == station.FuelPrefab) return true;
|
|
}
|
|
return false;
|
|
}
|
|
|
|
/// <summary>The storage chest that already holds this item and has room; else the first EMPTY one.</summary>
|
|
private Container DestinationFor(string prefabName)
|
|
{
|
|
GameObject prefab = ObjectDB.instance != null ? ObjectDB.instance.GetItemPrefab(prefabName) : null;
|
|
if (prefab == null) return null;
|
|
|
|
Container firstEmpty = null;
|
|
foreach (Container chest in m_chests)
|
|
{
|
|
if (chest == null || chest.IsInUse()) continue;
|
|
|
|
ZDOID id = ZdoOf(chest);
|
|
if (IsPenalised(id) || ClaimedByOther(id)) continue;
|
|
|
|
Inventory inventory = chest.GetInventory();
|
|
if (inventory == null || !inventory.CanAddItem(prefab, 1)) continue;
|
|
|
|
if (inventory.GetAllItems().Count == 0)
|
|
{
|
|
if (firstEmpty == null) firstEmpty = chest;
|
|
continue;
|
|
}
|
|
|
|
foreach (ItemDrop.ItemData item in inventory.GetAllItems())
|
|
{
|
|
if (item != null && item.m_dropPrefab != null && item.m_dropPrefab.name == prefabName) return chest;
|
|
}
|
|
}
|
|
return firstEmpty;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Tidying the entry chest, last of all. What a station will take is the WORK QUEUE and stays; the
|
|
/// rest (and any wood, which is stock unless it is in the wood chest) goes to the chest that
|
|
/// already holds the same thing, or to an empty one. With nowhere to go it stays where it is.
|
|
/// </summary>
|
|
private Job PlanSort()
|
|
{
|
|
if (m_entry == null || m_entry.IsInUse()) return null;
|
|
|
|
ZDOID entryId = ZdoOf(m_entry);
|
|
if (IsPenalised(entryId)) return null;
|
|
|
|
Inventory inventory = m_entry.GetInventory();
|
|
if (inventory == null) return null;
|
|
|
|
string sigil = AlfarSigil.PrefabName;
|
|
foreach (ItemDrop.ItemData item in inventory.GetAllItems())
|
|
{
|
|
if (item == null || item.m_dropPrefab == null) continue;
|
|
|
|
string name = item.m_dropPrefab.name;
|
|
if (name == sigil) continue;
|
|
if (!IsWood(name) && AnyStationAccepts(name)) continue;
|
|
|
|
Container destination = DestinationFor(name);
|
|
if (destination == null) continue;
|
|
|
|
m_sortItem = name;
|
|
m_sortDest = ZdoOf(destination);
|
|
return new Job
|
|
{
|
|
Kind = "sortfetch",
|
|
Target = entryId,
|
|
Claim = m_sortDest,
|
|
Point = m_entry.transform.position,
|
|
Label = "Sorting " + name,
|
|
};
|
|
}
|
|
return null;
|
|
}
|
|
|
|
private bool DoSortFetch()
|
|
{
|
|
if (m_sortItem == null || m_sortDest == ZDOID.None) return false;
|
|
|
|
Container entry = ContainerById(m_job.Target);
|
|
if (entry == null) return false;
|
|
|
|
int taken = TakeFrom(entry, m_sortItem, 40);
|
|
if (taken <= 0) return false;
|
|
|
|
AddToPayload(m_sortItem, taken);
|
|
m_nview.GetZDO().Set(KeyDest, m_sortDest);
|
|
m_nview.GetZDO().Set(KeyTarget, ZDOID.None);
|
|
WritePayload();
|
|
return true;
|
|
}
|
|
|
|
// ================================================================ moving
|
|
|
|
/// <summary>Vanilla pathing, through the private MoveTo. True the moment it has arrived.</summary>
|
|
private bool MoveToPoint(float dt, Vector3 point, float distance, bool run)
|
|
{
|
|
if (m_ai == null || MoveToMethod == null) return true; // cannot walk: act in place
|
|
|
|
m_moveArgs[0] = dt;
|
|
m_moveArgs[1] = point;
|
|
m_moveArgs[2] = distance;
|
|
m_moveArgs[3] = run;
|
|
|
|
return (bool)MoveToMethod.Invoke(m_ai, m_moveArgs);
|
|
}
|
|
|
|
private void GoHome(float dt)
|
|
{
|
|
Vector3? anchor = Anchor;
|
|
if (anchor == null)
|
|
{
|
|
if (m_ai != null) m_ai.StopMoving();
|
|
return;
|
|
}
|
|
|
|
MoveToPoint(dt, anchor.Value, m_homeDistance, false);
|
|
}
|
|
|
|
// ================================================================ the ground
|
|
|
|
private static int ItemMask()
|
|
{
|
|
if (s_itemMask >= 0) return s_itemMask;
|
|
|
|
int mask = LayerMask.GetMask("item");
|
|
s_itemMask = mask != 0 ? mask : ~0;
|
|
return s_itemMask;
|
|
}
|
|
|
|
private bool HasDropsNear(Vector3 point)
|
|
{
|
|
Collider[] hits = Physics.OverlapSphere(point, CollectRadius, ItemMask());
|
|
foreach (Collider hit in hits)
|
|
{
|
|
if (hit == null) continue;
|
|
ItemDrop drop = hit.GetComponentInParent<ItemDrop>();
|
|
if (drop != null && drop.m_itemData != null) return true;
|
|
}
|
|
return false;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Picks up everything lying around a station. The drop is destroyed and its contents become
|
|
/// entries in the virtual payload, which is the same road the smelter's bars, the oven's bread
|
|
/// and the fermenter's bottles all arrive by - one pickup routine for three families.
|
|
/// </summary>
|
|
private void SweepDrops(Vector3 point)
|
|
{
|
|
Collider[] hits = Physics.OverlapSphere(point, CollectRadius, ItemMask());
|
|
|
|
foreach (Collider hit in hits)
|
|
{
|
|
if (hit == null) continue;
|
|
if (PayloadCount() >= PayloadCap) return;
|
|
|
|
ItemDrop drop = hit.GetComponentInParent<ItemDrop>();
|
|
if (drop == null || drop.m_itemData == null) continue;
|
|
|
|
ZNetView nview = drop.GetComponent<ZNetView>();
|
|
if (nview == null || !nview.IsValid()) continue;
|
|
if (!nview.IsOwner()) nview.ClaimOwnership();
|
|
|
|
string name = drop.m_itemData.m_dropPrefab != null
|
|
? drop.m_itemData.m_dropPrefab.name
|
|
: Utils.GetPrefabName(drop.gameObject);
|
|
if (string.IsNullOrEmpty(name)) continue;
|
|
|
|
AddToPayload(name, Mathf.Max(1, drop.m_itemData.m_stack));
|
|
if (ZNetScene.instance != null) ZNetScene.instance.Destroy(drop.gameObject);
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Puts the virtual load back into the world as real objects. Called when the servant dies and
|
|
/// when there is nowhere left to put anything - the two ends of the same promise, which is that
|
|
/// nothing the player owns is ever deleted by this feature.
|
|
/// </summary>
|
|
public void DropPayload()
|
|
{
|
|
if (m_payload.Count == 0) return;
|
|
if (ObjectDB.instance == null) { m_payload.Clear(); return; }
|
|
|
|
Vector3 at = transform.position + Vector3.up * 0.4f;
|
|
|
|
foreach (Load load in m_payload)
|
|
{
|
|
GameObject prefab = ObjectDB.instance.GetItemPrefab(load.Name);
|
|
ItemDrop template = prefab != null ? prefab.GetComponent<ItemDrop>() : null;
|
|
if (template == null || template.m_itemData == null) continue;
|
|
|
|
int left = load.Count;
|
|
int max = Mathf.Max(1, template.m_itemData.m_shared.m_maxStackSize);
|
|
|
|
while (left > 0)
|
|
{
|
|
int stack = Mathf.Min(left, max);
|
|
|
|
// ItemDrop.DropItem instantiates item.m_dropPrefab - a clone off a raw ObjectDB
|
|
// prefab does not carry that (see AswidBloodPotions.MakeFood for the same fix).
|
|
// Without this, dropping a payload throws instantiating null and never clears
|
|
// it, so the same broken load is retried - and crashes - on every AI tick after.
|
|
ItemDrop.ItemData clone = template.m_itemData.Clone();
|
|
clone.m_dropPrefab = prefab;
|
|
|
|
ItemDrop.DropItem(clone, stack,
|
|
at + Random.insideUnitSphere * 0.3f, Quaternion.identity);
|
|
left -= stack;
|
|
}
|
|
}
|
|
|
|
m_payload.Clear();
|
|
WritePayload();
|
|
}
|
|
|
|
// ================================================================ chests
|
|
|
|
/// <summary>
|
|
/// Takes up to <paramref name="want"/> of a prefab out of a chest. The sigil is skipped by name,
|
|
/// which is the one thing in here that must never be got wrong: carrying it off would unmark the
|
|
/// chest halfway through a job.
|
|
/// </summary>
|
|
private int TakeFrom(Container chest, string prefabName, int want)
|
|
{
|
|
if (chest == null || want <= 0) return 0;
|
|
if (prefabName == AlfarSigil.PrefabName) return 0;
|
|
|
|
ZNetView nview = chest.GetComponent<ZNetView>();
|
|
if (nview == null || !nview.IsValid()) return 0;
|
|
if (!nview.IsOwner()) nview.ClaimOwnership();
|
|
|
|
Inventory inventory = chest.GetInventory();
|
|
if (inventory == null) return 0;
|
|
|
|
List<ItemDrop.ItemData> matches = new List<ItemDrop.ItemData>();
|
|
foreach (ItemDrop.ItemData item in inventory.GetAllItems())
|
|
{
|
|
if (item == null || item.m_dropPrefab == null) continue;
|
|
if (item.m_dropPrefab.name != prefabName) continue;
|
|
matches.Add(item);
|
|
}
|
|
|
|
int taken = 0;
|
|
foreach (ItemDrop.ItemData item in matches)
|
|
{
|
|
if (taken >= want) break;
|
|
|
|
int amount = Mathf.Min(item.m_stack, want - taken);
|
|
if (amount <= 0) continue;
|
|
|
|
inventory.RemoveItem(item, amount);
|
|
taken += amount;
|
|
}
|
|
|
|
if (taken > 0 && ContainerSaveMethod != null) ContainerSaveMethod.Invoke(chest, null);
|
|
return taken;
|
|
}
|
|
|
|
// The wood that may be burnt. Only the wood chest's wood is ever consumed: the same wood in the
|
|
// entry chest is stock to be sorted, never fuel or charcoal.
|
|
private static readonly HashSet<string> s_woodFamily = new HashSet<string>
|
|
{
|
|
"Wood", "FineWood", "RoundLog", "ElderBark", "YggdrasilWood", "Blackwood",
|
|
};
|
|
|
|
private static bool IsWood(string prefabName) => s_woodFamily.Contains(prefabName);
|
|
|
|
/// <summary>
|
|
/// The first thing a station will take, and the chest it is in: raw material from the ENTRY chest
|
|
/// (never its wood), and wood only from the WOOD chest.
|
|
/// </summary>
|
|
private string FindMaterialFor(ButlerStation station, out Container chest)
|
|
{
|
|
foreach (Container candidate in new[] { m_entry, m_wood })
|
|
{
|
|
if (candidate == null || candidate.IsInUse()) continue;
|
|
|
|
string item = FirstAccepted(station, candidate);
|
|
if (item == null) continue;
|
|
|
|
chest = candidate;
|
|
return item;
|
|
}
|
|
|
|
chest = null;
|
|
return null;
|
|
}
|
|
|
|
private string FirstAccepted(ButlerStation station, Container chest)
|
|
{
|
|
Inventory inventory = chest != null ? chest.GetInventory() : null;
|
|
if (inventory == null) return null;
|
|
|
|
bool woodChest = chest == m_wood;
|
|
string sigil = AlfarSigil.PrefabName;
|
|
string fuel = station.FuelPrefab;
|
|
|
|
foreach (ItemDrop.ItemData item in inventory.GetAllItems())
|
|
{
|
|
if (item == null || item.m_dropPrefab == null) continue;
|
|
|
|
string name = item.m_dropPrefab.name;
|
|
if (name == sigil) continue;
|
|
if (name == fuel) continue; // fuel has its own errand
|
|
if (IsWood(name) != woodChest) continue; // wood from the wood chest, the rest from the entry
|
|
if (!station.Accepts(name)) continue;
|
|
|
|
return name;
|
|
}
|
|
|
|
return null;
|
|
}
|
|
|
|
/// <summary>Fuel: wood-type fuel from the wood chest, anything else (coal) from the entry chest.</summary>
|
|
private Container FindChestWith(string prefabName)
|
|
{
|
|
Container chest = IsWood(prefabName) ? m_wood : m_entry;
|
|
if (chest == null || chest.IsInUse()) return null;
|
|
|
|
Inventory inventory = chest.GetInventory();
|
|
if (inventory == null) return null;
|
|
|
|
foreach (ItemDrop.ItemData item in inventory.GetAllItems())
|
|
{
|
|
if (item != null && item.m_dropPrefab != null && item.m_dropPrefab.name == prefabName) return chest;
|
|
}
|
|
return null;
|
|
}
|
|
|
|
/// <summary>
|
|
/// Where the finished goods go: back to the ENTRY chest, which is both the inbox and the outbox;
|
|
/// they are sorted from there. If it is full, the nearest storage chest with room.
|
|
/// </summary>
|
|
private Container ChestForProduct()
|
|
{
|
|
if (m_entry != null && !m_entry.IsInUse() && !IsPenalised(ZdoOf(m_entry)) && HasRoomFor(m_entry)) return m_entry;
|
|
|
|
Container best = null;
|
|
float bestDistance = float.MaxValue;
|
|
|
|
foreach (Container chest in m_chests)
|
|
{
|
|
if (chest == null || chest.IsInUse()) continue;
|
|
if (IsPenalised(ZdoOf(chest))) continue;
|
|
if (!HasRoomFor(chest)) continue;
|
|
|
|
float distance = Vector3.Distance(transform.position, chest.transform.position);
|
|
if (distance >= bestDistance) continue;
|
|
|
|
bestDistance = distance;
|
|
best = chest;
|
|
}
|
|
|
|
return best;
|
|
}
|
|
|
|
private bool HasRoomFor(Container chest)
|
|
{
|
|
Inventory inventory = chest != null ? chest.GetInventory() : null;
|
|
if (inventory == null || ObjectDB.instance == null) return false;
|
|
|
|
foreach (Load load in m_payload)
|
|
{
|
|
GameObject prefab = ObjectDB.instance.GetItemPrefab(load.Name);
|
|
if (prefab != null && inventory.CanAddItem(prefab, 1)) return true;
|
|
}
|
|
|
|
return false;
|
|
}
|
|
|
|
// ================================================================ payload
|
|
|
|
private bool AcceptsAnything(ButlerStation station)
|
|
{
|
|
foreach (Load load in m_payload)
|
|
{
|
|
if (station.Accepts(load.Name)) return true;
|
|
if (load.Name == station.FuelPrefab && station.FuelWanted > 0) return true;
|
|
}
|
|
return false;
|
|
}
|
|
|
|
private void AddToPayload(string name, int count)
|
|
{
|
|
if (string.IsNullOrEmpty(name) || count <= 0) return;
|
|
|
|
foreach (Load load in m_payload)
|
|
{
|
|
if (load.Name != name) continue;
|
|
load.Count += count;
|
|
WritePayload();
|
|
return;
|
|
}
|
|
|
|
m_payload.Add(new Load { Name = name, Count = count });
|
|
WritePayload();
|
|
}
|
|
|
|
private int PayloadCount()
|
|
{
|
|
int total = 0;
|
|
foreach (Load load in m_payload) total += load.Count;
|
|
return total;
|
|
}
|
|
|
|
private string Describe()
|
|
{
|
|
if (m_payload.Count == 0) return "nothing";
|
|
if (m_payload.Count == 1) return m_payload[0].Count + "x " + m_payload[0].Name;
|
|
|
|
return PayloadCount() + " items";
|
|
}
|
|
|
|
/// <summary>"Copper:8;Coal:12". Small, readable in a ZDO dump, and enough to survive a handover
|
|
/// mid-job - which is the whole reason the payload lives in the ZDO instead of in this class.</summary>
|
|
private void WritePayload()
|
|
{
|
|
if (m_nview == null || !m_nview.IsValid()) return;
|
|
|
|
StringBuilder builder = new StringBuilder();
|
|
foreach (Load load in m_payload)
|
|
{
|
|
if (load.Count <= 0) continue;
|
|
if (builder.Length > 0) builder.Append(';');
|
|
builder.Append(load.Name).Append(':').Append(load.Count);
|
|
}
|
|
|
|
m_nview.GetZDO().Set(KeyLoad, builder.ToString());
|
|
}
|
|
|
|
private void ReadPayload()
|
|
{
|
|
m_payload.Clear();
|
|
if (m_nview == null || !m_nview.IsValid()) return;
|
|
|
|
string raw = m_nview.GetZDO().GetString(KeyLoad, "");
|
|
if (string.IsNullOrEmpty(raw)) return;
|
|
|
|
foreach (string entry in raw.Split(';'))
|
|
{
|
|
if (string.IsNullOrEmpty(entry)) continue;
|
|
|
|
int split = entry.LastIndexOf(':');
|
|
if (split <= 0) continue;
|
|
|
|
int count;
|
|
if (!int.TryParse(entry.Substring(split + 1), out count) || count <= 0) continue;
|
|
|
|
m_payload.Add(new Load { Name = entry.Substring(0, split), Count = count });
|
|
}
|
|
}
|
|
|
|
// ================================================================ small change
|
|
|
|
private static ZDOID ZdoOf(Component component)
|
|
{
|
|
ZNetView nview = component != null ? component.GetComponent<ZNetView>() : null;
|
|
return nview != null && nview.IsValid() ? nview.GetZDO().m_uid : ZDOID.None;
|
|
}
|
|
|
|
private Container ContainerById(ZDOID id)
|
|
{
|
|
if (id == ZDOID.None || ZNetScene.instance == null) return null;
|
|
|
|
GameObject go = ZNetScene.instance.FindInstance(id);
|
|
return go != null ? go.GetComponent<Container>() : null;
|
|
}
|
|
|
|
private ButlerStation StationById(ZDOID id)
|
|
{
|
|
foreach (ButlerStation station in m_stations)
|
|
{
|
|
if (station.Id == id) return station;
|
|
}
|
|
|
|
if (id == ZDOID.None || ZNetScene.instance == null) return null;
|
|
|
|
GameObject go = ZNetScene.instance.FindInstance(id);
|
|
return go != null ? ButlerStation.From(go) : null;
|
|
}
|
|
|
|
private void Penalise(ZDOID id)
|
|
{
|
|
if (id == ZDOID.None) return;
|
|
m_penalties[id] = Time.time + PenaltySeconds;
|
|
}
|
|
|
|
/// <summary>Never shortens a penalty already running: a target set aside for three minutes
|
|
/// because it could not be reached must not be let back in after twenty seconds.</summary>
|
|
private void PenaliseShort(ZDOID id)
|
|
{
|
|
if (id == ZDOID.None) return;
|
|
|
|
float until;
|
|
float wanted = Time.time + ShortPenaltySeconds;
|
|
if (m_penalties.TryGetValue(id, out until) && until > wanted) return;
|
|
|
|
m_penalties[id] = wanted;
|
|
}
|
|
|
|
private bool IsPenalised(ZDOID id)
|
|
{
|
|
float until;
|
|
return m_penalties.TryGetValue(id, out until) && Time.time < until;
|
|
}
|
|
|
|
private void ExpirePenalties()
|
|
{
|
|
if (m_penalties.Count == 0) return;
|
|
|
|
List<ZDOID> done = null;
|
|
foreach (KeyValuePair<ZDOID, float> entry in m_penalties)
|
|
{
|
|
if (Time.time < entry.Value) continue;
|
|
if (done == null) done = new List<ZDOID>();
|
|
done.Add(entry.Key);
|
|
}
|
|
|
|
if (done == null) return;
|
|
foreach (ZDOID id in done) m_penalties.Remove(id);
|
|
}
|
|
|
|
/// <summary>Seconds this station has been waiting with work available.</summary>
|
|
private float NoteIdle(ZDOID id)
|
|
{
|
|
float since;
|
|
if (!m_idleSince.TryGetValue(id, out since))
|
|
{
|
|
m_idleSince[id] = Time.time;
|
|
return 0f;
|
|
}
|
|
|
|
return Time.time - since;
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// The whole of the servant's mind, in one prefix.
|
|
///
|
|
/// Returning false skips MonsterAI.UpdateAI entirely - targeting, alerting, fleeing, wandering and
|
|
/// attacking with it - so the servant is peaceful by construction rather than by having its weapon
|
|
/// confiscated. __result is legitimate here and not the old PlacePiece trap: that one threw because
|
|
/// the patched method was VOID. This one returns bool, which is exactly what a prefix may write.
|
|
///
|
|
/// Bound positionally (__0) so a parameter rename in a future patch cannot stop the mod from
|
|
/// applying its patches at startup.
|
|
/// </summary>
|
|
[HarmonyPatch(typeof(MonsterAI), "UpdateAI")]
|
|
public static class AlfarDroneUpdateAIPatch
|
|
{
|
|
public static bool Prefix(MonsterAI __instance, float __0, ref bool __result)
|
|
{
|
|
if (__instance == null) return true;
|
|
|
|
AlfarDroneAI servant = __instance.GetComponent<AlfarDroneAI>();
|
|
if (servant == null) return true;
|
|
|
|
// The one way back into vanilla: a servant that fights back hands over the whole tick for
|
|
// as long as there is a fight. Always false for the Bone Servants themselves.
|
|
if (servant.HandsToVanilla()) return true;
|
|
|
|
__result = servant.Tick(__0);
|
|
return false;
|
|
}
|
|
}
|
|
|
|
/// <summary>Hit and it walks home. The same postfix shape the sentry's regeneration uses, on the
|
|
/// same method, which is a shape known to work in this project.</summary>
|
|
[HarmonyPatch(typeof(Character), "Damage")]
|
|
public static class AlfarDroneDamagePatch
|
|
{
|
|
public static void Postfix(Character __instance)
|
|
{
|
|
if (__instance == null) return;
|
|
|
|
AlfarDroneAI servant = __instance.GetComponent<AlfarDroneAI>();
|
|
if (servant != null) servant.NoteDamage();
|
|
}
|
|
}
|
|
}
|