warvulture
This commit is contained in:
parent
5c5b8c34d2
commit
e9f41a86e3
11 changed files with 2318 additions and 7 deletions
460
JotunnModStub/Skadi/SkadiGolem.cs
Normal file
460
JotunnModStub/Skadi/SkadiGolem.cs
Normal file
|
|
@ -0,0 +1,460 @@
|
|||
using System.Collections.Generic;
|
||||
using HarmonyLib;
|
||||
using Jotunn.Configs;
|
||||
using Jotunn.Entities;
|
||||
using Jotunn.Managers;
|
||||
using UnityEngine;
|
||||
|
||||
namespace RacesOfValheim
|
||||
{
|
||||
/// <summary>
|
||||
/// The Skadi station: crystal golems, cut at a stonecutter and bound to it.
|
||||
///
|
||||
/// Eighth of the per-race item-progression chains, and the odd one out in two ways that decide
|
||||
/// everything else in this file.
|
||||
///
|
||||
/// FIRST, the station is not ours. Every other chain builds its own bench - a trough, a bone pile,
|
||||
/// a composter - and can therefore hang a MonoBehaviour on it, count its own garrison from it, and
|
||||
/// mark its thralls when it falls. The stonecutter is vanilla's, and nothing here modifies it: the
|
||||
/// golem carries the stonecutter's position in its own ZDO and asks the world whether one still
|
||||
/// stands there. That is why this chain does not use RaisedThrall, which is otherwise exactly the
|
||||
/// right component - RaisedThrall's wither depends on the station registering itself, and a vanilla
|
||||
/// piece never will.
|
||||
///
|
||||
/// SECOND, a golem is not a follower. RaisedThrall's whole vocabulary - follow me, stand down, call
|
||||
/// to arms - is wrong for something that may not leave a twenty metre circle. There is deliberately
|
||||
/// no Tameable on it either: it is tame, so it will never turn on anyone, but it cannot be named,
|
||||
/// ordered, or walked away with. It guards the stone that shaped it, and that is all it does.
|
||||
///
|
||||
/// The three limits are the design, not decoration:
|
||||
/// never further than 20 m from its stonecutter (the vanilla station build range)
|
||||
/// two per stonecutter
|
||||
/// ten per square mile
|
||||
/// The first is enforced on the golem (SkadiGolemGuard), the other two at the moment of building,
|
||||
/// through PieceDensityLimit's single Player.PlacePiece prefix - refusing later would spend a
|
||||
/// dragon tear before telling anyone no.
|
||||
/// </summary>
|
||||
public static class SkadiGolem
|
||||
{
|
||||
// ─── Names ───────────────────────────────────────────────────────────
|
||||
public const string GolemName = "SkadiCrystalGolem";
|
||||
public const string SeedPieceName = "SkadiCrystalGolemSeed";
|
||||
public const string DisplayName = "Crystal Golem";
|
||||
|
||||
private const string SourceGolem = "StoneGolem";
|
||||
|
||||
/// <summary>
|
||||
/// The seed piece's model, and it is chosen for its BUILD GHOST: the golem itself only exists
|
||||
/// a frame later, so a standing stone is what the player actually aims with. Everything the
|
||||
/// ward DOES - the private area above all - is stripped off the clone below; a chain that
|
||||
/// quietly planted a ward every time you cut a golem would be a much worse bug than a wrong
|
||||
/// silhouette.
|
||||
/// </summary>
|
||||
private const string SourcePiece = "guard_stone";
|
||||
|
||||
public const string StationPrefab = "piece_stonecutter";
|
||||
|
||||
// ─── The price ───────────────────────────────────────────────────────
|
||||
// Moder needs no state check of her own to BUILD one - her drop is in the recipe - but the
|
||||
// gate asks anyway, because the recipe is not the only way an item reaches an inventory.
|
||||
public const string GolemTrophy = "TrophySGolem";
|
||||
public const string CrystalItem = "Crystal";
|
||||
public const int CrystalCost = 10;
|
||||
public const string ModerDrop = "DragonTear";
|
||||
public const int ModerProgressionState = 5;
|
||||
|
||||
// ─── The limits ──────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// How far a golem may get from its stonecutter. Twenty metres because that is the
|
||||
/// stonecutter's own build range in vanilla, so the circle a golem defends is exactly the
|
||||
/// circle it could have been built in - one number, visible in game, not two that nearly
|
||||
/// agree.
|
||||
/// </summary>
|
||||
public const float LeashRange = 20f;
|
||||
|
||||
/// <summary>
|
||||
/// Past this it has stopped walking home and started failing to. A golem that has been pushed
|
||||
/// into water, or that stands on the wrong side of something it cannot path around, would
|
||||
/// otherwise sit outside its leash forever - so at half again the leash it is simply put back.
|
||||
/// It is a failsafe for a stuck pathfinder, not a movement mechanic.
|
||||
/// </summary>
|
||||
public const float HardLeashRange = 30f;
|
||||
|
||||
public const int MaxPerStation = 2;
|
||||
|
||||
// Ten per square mile. 2.59 km2, the same area the Fenrir's trough is measured in, so the two
|
||||
// stations are spaced by the same yardstick even though the numbers differ.
|
||||
public const int MaxInArea = 10;
|
||||
public const float DensityAreaKm2 = 2.59f;
|
||||
|
||||
/// <summary>
|
||||
/// How long a golem outlives the stonecutter that cut it. Shorter than the Fenrir trough's
|
||||
/// five minutes because there is nothing to rebuild: a stonecutter costs ten stone and two
|
||||
/// wood, so "put it back" is a moment's work, and a longer grace would just mean a garrison
|
||||
/// that survives being moved.
|
||||
/// </summary>
|
||||
public const float WitherSeconds = 60f;
|
||||
|
||||
/// <summary>Slack when asking "is my stonecutter still there" - a station never moves.</summary>
|
||||
public const float StationCheckRange = 2f;
|
||||
|
||||
/// <summary>
|
||||
/// Only asked this close to home, for the reason RaisedThrall's wither carries the same guard:
|
||||
/// further out the station's zone is probably not loaded, so "nothing stands there" would be a
|
||||
/// lie. A golem is leashed to 20 m anyway, so this is never the reason one survives.
|
||||
/// </summary>
|
||||
public const float HomeCheckRange = 40f;
|
||||
|
||||
// ─── Behaviour ───────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>Idle wander around the stonecutter. Half the leash, so it never idles onto it.</summary>
|
||||
private const float WanderRange = 10f;
|
||||
|
||||
/// <summary>
|
||||
/// The station's m_name, read off the stonecutter prefab once at registration.
|
||||
///
|
||||
/// It is NOT the prefab name: CraftingStation.HaveBuildStationInRange compares against
|
||||
/// m_name, which is a localisation token, while Jotunn's PieceConfig.CraftingStation wants the
|
||||
/// prefab name. Both spellings are needed and they are not the same string, which is exactly
|
||||
/// the kind of thing worth reading off the game once instead of guessing at twice.
|
||||
/// </summary>
|
||||
private static string StationName = "$piece_stonecutter";
|
||||
|
||||
public static void Register()
|
||||
{
|
||||
CacheStationName();
|
||||
|
||||
if (!RegisterGolem()) return;
|
||||
RegisterSeedPiece();
|
||||
|
||||
PieceDensityLimit.RegisterGate(SeedPieceName, MayRaise);
|
||||
}
|
||||
|
||||
private static void CacheStationName()
|
||||
{
|
||||
GameObject station = PrefabManager.Cache.GetPrefab<GameObject>(StationPrefab);
|
||||
CraftingStation component = station != null ? station.GetComponent<CraftingStation>() : null;
|
||||
|
||||
if (component == null || string.IsNullOrEmpty(component.m_name))
|
||||
{
|
||||
Jotunn.Logger.LogWarning($"[Skadi] Could not read the stonecutter's station name off " +
|
||||
$"'{StationPrefab}'; falling back to '{StationName}'.");
|
||||
return;
|
||||
}
|
||||
|
||||
StationName = component.m_name;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- the golem
|
||||
|
||||
/// <summary>
|
||||
/// A vanilla stone golem, tamed, frozen over, and made incapable of the three things it must
|
||||
/// never do.
|
||||
///
|
||||
/// Health, damage and resistances stay exactly as vanilla has them. A mountain golem is a slow
|
||||
/// wall with a great deal of health, which is precisely what a defender that cannot leave its
|
||||
/// circle should be - there is nothing to retune, and nothing here does.
|
||||
///
|
||||
/// What IS written over:
|
||||
/// - it does not sleep. Vanilla golems start as rocks and wake when something comes near;
|
||||
/// a guard that has to be woken up is not a guard.
|
||||
/// - it does not target player-built anything (m_attackPlayerObjects). That is the first
|
||||
/// half of "never attacks structures"; the second half is the WearNTear guard below,
|
||||
/// because an area attack aimed at a greydwarf can still land on a wall.
|
||||
/// - it does not flee. A golem holds its ground or it dies on it.
|
||||
/// - it gives up a chase past its leash, measured from its own spawn point, which
|
||||
/// SkadiGolemGuard pins to the stonecutter. That is vanilla's own leash, used as intended
|
||||
/// rather than reimplemented.
|
||||
/// - it drops nothing. Two golems per stonecutter that could be farmed for crystals and
|
||||
/// trophies would be a mint, and the trophy is this chain's own gate item.
|
||||
/// It never attacks tamed creatures or players for free: Attack.DoMeleeAttack only lets a
|
||||
/// tamed attacker through to targets its own AI counts as enemies, which is checked in the
|
||||
/// game's code rather than assumed here.
|
||||
/// </summary>
|
||||
private static bool RegisterGolem()
|
||||
{
|
||||
GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(GolemName, SourceGolem);
|
||||
if (prefab == null)
|
||||
{
|
||||
Jotunn.Logger.LogWarning($"[Skadi] Could not clone {SourceGolem}; {DisplayName} not registered.");
|
||||
return false;
|
||||
}
|
||||
|
||||
Character character = prefab.GetComponent<Character>();
|
||||
if (character != null) character.m_name = DisplayName;
|
||||
|
||||
SkadiIce.Apply(prefab);
|
||||
|
||||
BaseAI ai = prefab.GetComponent<BaseAI>();
|
||||
if (ai != null)
|
||||
{
|
||||
ai.m_randomMoveRange = WanderRange;
|
||||
ai.m_avoidWater = true;
|
||||
}
|
||||
|
||||
MonsterAI monster = prefab.GetComponent<MonsterAI>();
|
||||
if (monster != null)
|
||||
{
|
||||
monster.m_sleeping = false;
|
||||
monster.m_attackPlayerObjects = false;
|
||||
|
||||
// It notices what comes into the circle it defends, and nothing outside it. Being
|
||||
// hit still turns it around - OnDamaged sets a target whatever the alert range says -
|
||||
// which is the difference between a defender and a statue.
|
||||
monster.m_alertRange = LeashRange;
|
||||
monster.m_maxChaseDistance = LeashRange;
|
||||
monster.m_fleeIfLowHealth = 0f;
|
||||
monster.m_fleeIfNotAlerted = false;
|
||||
monster.m_fleeIfHurtWhenTargetCantBeReached = false;
|
||||
}
|
||||
|
||||
foreach (CharacterDrop drops in prefab.GetComponentsInChildren<CharacterDrop>(true))
|
||||
{
|
||||
if (drops != null) Object.DestroyImmediate(drops);
|
||||
}
|
||||
|
||||
foreach (Procreation breeding in prefab.GetComponentsInChildren<Procreation>(true))
|
||||
{
|
||||
if (breeding != null) Object.DestroyImmediate(breeding);
|
||||
}
|
||||
|
||||
// "Ten seconds unhurt, then 2% a second" - the Skeleton's sentry regeneration, which three
|
||||
// chains now share. A guard that cannot heal between raids is a guard you rebuild.
|
||||
prefab.AddComponent<SkeletonSentryBehaviour>();
|
||||
|
||||
prefab.AddComponent<SkadiGolemGuard>();
|
||||
|
||||
PrefabManager.Instance.AddPrefab(prefab);
|
||||
Jotunn.Logger.LogInfo($"[Skadi] {GolemName} from '{SourceGolem}': awake, tame, leashed, " +
|
||||
"blind to structures, drops nothing.");
|
||||
return true;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- the seed piece
|
||||
|
||||
/// <summary>
|
||||
/// The hammer entry, and the same trick SkeletonSentry uses for the same reason: the hammer
|
||||
/// builds Piece, a golem is a Character, so a piece is placed and swaps itself for one.
|
||||
/// </summary>
|
||||
private static void RegisterSeedPiece()
|
||||
{
|
||||
GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(SeedPieceName, SourcePiece);
|
||||
if (prefab == null)
|
||||
{
|
||||
Jotunn.Logger.LogWarning($"[Skadi] Could not clone {SourcePiece}; {DisplayName} cannot be built.");
|
||||
return;
|
||||
}
|
||||
|
||||
// Everything the ward does goes - PrivateArea and its effect areas above all. What is
|
||||
// wanted is a placeable shell with the right outline, alive for one frame.
|
||||
foreach (MonoBehaviour behaviour in prefab.GetComponentsInChildren<MonoBehaviour>(true))
|
||||
{
|
||||
if (behaviour == null) continue;
|
||||
if (behaviour is Piece || behaviour is ZNetView || behaviour is WearNTear) continue;
|
||||
Object.DestroyImmediate(behaviour);
|
||||
}
|
||||
|
||||
AswidBloodRefinery.StripOffensive(prefab, SeedPieceName);
|
||||
SkadiIce.Apply(prefab);
|
||||
|
||||
prefab.AddComponent<SkadiGolemSeed>();
|
||||
|
||||
Piece piece = prefab.GetComponent<Piece>() ?? prefab.AddComponent<Piece>();
|
||||
piece.m_resources = new Piece.Requirement[0];
|
||||
piece.m_name = DisplayName;
|
||||
piece.m_canBeRemoved = true;
|
||||
piece.m_groundPiece = true;
|
||||
piece.m_groundOnly = true;
|
||||
piece.m_icon = BorrowIcon(CrystalItem);
|
||||
|
||||
PieceManager.Instance.AddPiece(new CustomPiece(prefab, fixReference: false, new PieceConfig
|
||||
{
|
||||
Name = DisplayName,
|
||||
Description = "Cut at the stone and woken with a tear. It will not follow you, and it " +
|
||||
"will not leave the stonecutter that shaped it.",
|
||||
PieceTable = PieceTables.Hammer,
|
||||
Category = PieceCategories.Crafting,
|
||||
// The stonecutter is the station, so vanilla itself refuses to place one anywhere its
|
||||
// golem could not then be bound - the gate below never has to be the first to say no.
|
||||
CraftingStation = CraftingStations.Stonecutter,
|
||||
Icon = BorrowIcon(CrystalItem),
|
||||
Requirements = new[]
|
||||
{
|
||||
new RequirementConfig(GolemTrophy, 1, 0, true),
|
||||
new RequirementConfig(CrystalItem, CrystalCost, 0, true),
|
||||
new RequirementConfig(ModerDrop, 1, 0, true),
|
||||
}
|
||||
}));
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- the gate
|
||||
|
||||
/// <summary>
|
||||
/// The two caps that cannot live on the golem, asked at the moment of building.
|
||||
///
|
||||
/// Order matters: race, then boss, then the stonecutter, then its own two, so the first thing
|
||||
/// a player is told is the thing they can actually do something about.
|
||||
///
|
||||
/// HONEST LIMIT, inherited from PieceDensityLimit and worth repeating: the counts are over
|
||||
/// ZDOs, which on a remote client are only the ZDOs the server has sent. On the host they are
|
||||
/// exact. Where a count cannot be taken at all the placement is allowed - refusing on no
|
||||
/// information is worse than a cap that occasionally misses.
|
||||
/// </summary>
|
||||
public static bool MayRaise(Player player, Vector3 position)
|
||||
{
|
||||
if (player == null) return true;
|
||||
|
||||
if (!SkadiRace.IsLocalSkadi())
|
||||
{
|
||||
player.Message(MessageHud.MessageType.Center, "The stone does not answer to you.");
|
||||
return false;
|
||||
}
|
||||
|
||||
if (BossProgressionManager.GetCurrentProgressionState() < ModerProgressionState)
|
||||
{
|
||||
player.Message(MessageHud.MessageType.Center,
|
||||
"The tear is cold. Nothing wakes in the stone until the mountain's queen has fallen.");
|
||||
return false;
|
||||
}
|
||||
|
||||
CraftingStation station = FindStonecutter(position);
|
||||
if (station == null)
|
||||
{
|
||||
player.Message(MessageHud.MessageType.Center, "It needs a stonecutter to be cut at.");
|
||||
return false;
|
||||
}
|
||||
|
||||
int bound = CountBoundTo(station.transform.position);
|
||||
if (bound >= MaxPerStation)
|
||||
{
|
||||
player.Message(MessageHud.MessageType.Center,
|
||||
$"That stonecutter already holds {bound}. It will not hold more.");
|
||||
return false;
|
||||
}
|
||||
|
||||
int nearby = PieceDensityLimit.Count(GolemName, position, PieceDensityLimit.RadiusForArea(DensityAreaKm2));
|
||||
if (nearby >= MaxInArea)
|
||||
{
|
||||
player.Message(MessageHud.MessageType.Center,
|
||||
$"There are already {nearby} of these within a day's walk. The stone is spent.");
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The stonecutter that owns a point, by the station's OWN build range rather than by a number
|
||||
/// of ours - so the circle a golem may be cut in and the circle it may stand in are the same
|
||||
/// circle, and stay the same if a game update retunes the station.
|
||||
/// </summary>
|
||||
public static CraftingStation FindStonecutter(Vector3 position)
|
||||
{
|
||||
return CraftingStation.HaveBuildStationInRange(StationName, position);
|
||||
}
|
||||
|
||||
/// <summary>True if a stonecutter still stands at that exact point.</summary>
|
||||
public static bool StonecutterStandsAt(Vector3 position)
|
||||
{
|
||||
return CraftingStation.FindClosestStationInRange(StationName, position, StationCheckRange) != null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// How many golems already answer to the stonecutter at that point, counted over ZDOs and not
|
||||
/// over loaded creatures.
|
||||
///
|
||||
/// That distinction is the whole cap: a golem in an unloaded zone is still a golem, and
|
||||
/// counting only what is loaded would make walking away and coming back the way to hold six.
|
||||
/// Dead ones are gone from the world entirely, so a slot frees itself with no bookkeeping.
|
||||
/// </summary>
|
||||
public static int CountBoundTo(Vector3 station)
|
||||
{
|
||||
List<ZDO> zdos = new List<ZDO>();
|
||||
if (!PieceDensityLimit.Gather(GolemName, zdos)) return 0;
|
||||
|
||||
int count = 0;
|
||||
foreach (ZDO zdo in zdos)
|
||||
{
|
||||
if (zdo == null) continue;
|
||||
|
||||
// A generous epsilon: a station never moves, so this only has to survive float
|
||||
// round-tripping through the ZDO.
|
||||
Vector3 anchor = zdo.GetVec3(SkadiGolemGuard.KeyAnchor, Vector3.zero);
|
||||
if (anchor != Vector3.zero && Vector3.SqrMagnitude(anchor - station) < 0.25f) count++;
|
||||
}
|
||||
|
||||
return count;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- known pieces
|
||||
|
||||
/// <summary>
|
||||
/// Learnt by being Skadi, and not by having killed Moder.
|
||||
///
|
||||
/// Deliberate: the entry shows up greyed out with its price on it, which is how every vanilla
|
||||
/// recipe tells you what to go and get. Gating the entry itself on the boss would hide it
|
||||
/// until a relog anyway - OnSpawned is the only moment this is asked - so the boss check lives
|
||||
/// where it can be asked every time instead, in MayRaise.
|
||||
/// </summary>
|
||||
public static void EnsureKnown(Player player)
|
||||
{
|
||||
if (player == null || !SkadiRace.IsLocalSkadi()) return;
|
||||
|
||||
GameObject prefab = PrefabManager.Instance.GetPrefab(SeedPieceName);
|
||||
Piece piece = prefab != null ? prefab.GetComponent<Piece>() : null;
|
||||
if (piece == null) return;
|
||||
|
||||
Traverse traverse = Traverse.Create(player);
|
||||
traverse.Method("AddKnownPiece", piece).GetValue();
|
||||
traverse.Method("UpdateAvailablePiecesList").GetValue();
|
||||
}
|
||||
|
||||
private static Sprite BorrowIcon(string prefabName)
|
||||
{
|
||||
ItemDrop drop = PrefabManager.Cache.GetPrefab<ItemDrop>(prefabName);
|
||||
Sprite[] icons = drop != null && drop.m_itemData != null && drop.m_itemData.m_shared != null
|
||||
? drop.m_itemData.m_shared.m_icons
|
||||
: null;
|
||||
if (icons != null && icons.Length > 0 && icons[0] != null) return icons[0];
|
||||
|
||||
Jotunn.Logger.LogWarning($"[Skadi] Could not borrow the icon from '{prefabName}'.");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
[HarmonyPatch(typeof(Player), "OnSpawned")]
|
||||
public static class SkadiGolemKnownPatch
|
||||
{
|
||||
public static void Postfix(Player __instance)
|
||||
{
|
||||
if (__instance != Player.m_localPlayer) return;
|
||||
SkadiGolem.EnsureKnown(__instance);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The second half of "it never attacks structures".
|
||||
///
|
||||
/// m_attackPlayerObjects stops a golem CHOOSING a wall as a target; it does not stop one landing a
|
||||
/// swing on the wall behind a greydwarf, because Attack.DoMeleeAttack has no tamed check on the
|
||||
/// destructible path at all - only on the character one. Read off the game's own code rather than
|
||||
/// assumed, and it is why this patch exists instead of one field being trusted to do both jobs.
|
||||
///
|
||||
/// The signature is spelled out and bound positionally for the reason PieceDensityLimitPatch
|
||||
/// carries in its own comment: Damage returns VOID, so a prefix returning false is the whole
|
||||
/// mechanism, and asking for a __result on a void method throws at patch time and takes the rest
|
||||
/// of the mod's patches down with it.
|
||||
/// </summary>
|
||||
[HarmonyPatch(typeof(WearNTear), "Damage", new[] { typeof(HitData) })]
|
||||
public static class SkadiGolemStructureGuardPatch
|
||||
{
|
||||
public static bool Prefix(HitData __0)
|
||||
{
|
||||
if (__0 == null) return true;
|
||||
|
||||
Character attacker = __0.GetAttacker();
|
||||
return attacker == null || attacker.GetComponent<SkadiGolemGuard>() == null;
|
||||
}
|
||||
}
|
||||
}
|
||||
302
JotunnModStub/Skadi/SkadiGolemBehaviour.cs
Normal file
302
JotunnModStub/Skadi/SkadiGolemBehaviour.cs
Normal file
|
|
@ -0,0 +1,302 @@
|
|||
using System;
|
||||
using HarmonyLib;
|
||||
using UnityEngine;
|
||||
|
||||
namespace RacesOfValheim
|
||||
{
|
||||
/// <summary>
|
||||
/// One crystal golem: tame, bound to a stonecutter, and unable to get more than its leash away
|
||||
/// from it.
|
||||
///
|
||||
/// Same shape as RaisedThrall - an anchor in the creature's own ZDO, a leash pinned to it, a
|
||||
/// wither clock that starts when the station is gone - and deliberately NOT that class. Two
|
||||
/// differences make it a copy rather than a reuse, and both are in SkadiGolem's own comment: the
|
||||
/// station is vanilla's and cannot register itself, and a golem takes no orders, so the follow,
|
||||
/// stand-down and call-to-arms half of RaisedThrall is not merely unused here but wrong.
|
||||
///
|
||||
/// The leash is three layers, weakest first, because each one covers the case the one before it
|
||||
/// cannot:
|
||||
/// - vanilla's own chase limit (m_maxChaseDistance, measured from m_spawnPoint, which is pinned
|
||||
/// to the stonecutter below) makes it GIVE UP on anything it would have to leave home for;
|
||||
/// - the patrol point, re-pinned every tick, is what brings it back and what keeps it wandering
|
||||
/// around the station rather than drifting after it has been pushed or knocked back;
|
||||
/// - and past half again the leash it is simply put back, because at that distance it is not
|
||||
/// walking home slowly, it is failing to walk home at all.
|
||||
/// </summary>
|
||||
public class SkadiGolemGuard : MonoBehaviour
|
||||
{
|
||||
public const string KeyAnchor = "RoV_golemAnchor";
|
||||
public const string KeyOrphanAt = "RoV_golemOrphanAt";
|
||||
|
||||
/// <summary>
|
||||
/// One second, and not the two RaisedThrall uses. Vanilla will not drop a target it can still
|
||||
/// SEE, whatever m_maxChaseDistance says - read off MonsterAI.UpdateTarget, where the give-up
|
||||
/// test also wants a second of having lost sight of it - so this tick is what actually holds
|
||||
/// the leash, and how far past twenty metres a golem gets is how far it walks between two of
|
||||
/// them. A stone golem is slow; at one second that is a stride.
|
||||
/// </summary>
|
||||
private const float TickSeconds = 1f;
|
||||
|
||||
// SetPatrolPoint(Vector3) is private - only the parameterless overload, which uses the
|
||||
// creature's current position, is public. Resolved once here rather than per call, exactly as
|
||||
// RaisedThrall does it.
|
||||
private static readonly System.Reflection.MethodInfo SetPatrolPointMethod =
|
||||
AccessTools.Method(typeof(BaseAI), "SetPatrolPoint", new[] { typeof(Vector3) });
|
||||
|
||||
// m_spawnPoint is protected, and it is the point vanilla measures m_maxChaseDistance from -
|
||||
// read off MonsterAI.UpdateTarget rather than assumed, because "chase distance" could just as
|
||||
// easily have meant distance from the target.
|
||||
private static readonly System.Reflection.FieldInfo SpawnPointField =
|
||||
AccessTools.Field(typeof(BaseAI), "m_spawnPoint");
|
||||
|
||||
private Character m_character;
|
||||
private BaseAI m_ai;
|
||||
private MonsterAI m_monsterAI;
|
||||
private ZNetView m_nview;
|
||||
private Rigidbody m_body;
|
||||
|
||||
private void Awake()
|
||||
{
|
||||
m_character = GetComponent<Character>();
|
||||
m_ai = GetComponent<BaseAI>();
|
||||
m_monsterAI = GetComponent<MonsterAI>();
|
||||
m_nview = GetComponent<ZNetView>();
|
||||
m_body = GetComponent<Rigidbody>();
|
||||
|
||||
InvokeRepeating("Tick", TickSeconds, TickSeconds);
|
||||
}
|
||||
|
||||
/// <summary>Where the stonecutter that cut this one stands, or null if it was cut by none.</summary>
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Called once, by the seed piece that placed it. Tames it, marks whose stonecutter it is, and
|
||||
/// sends it home - all three, so nothing else has to remember to do any of them.
|
||||
/// </summary>
|
||||
public void Bind(Vector3 anchor)
|
||||
{
|
||||
if (m_nview == null || !m_nview.IsValid()) return;
|
||||
|
||||
m_nview.GetZDO().Set(KeyAnchor, anchor);
|
||||
|
||||
if (m_monsterAI != null) m_monsterAI.MakeTame();
|
||||
if (m_character != null) m_character.SetTamed(true);
|
||||
|
||||
GoHome();
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- the tick
|
||||
|
||||
private void Tick()
|
||||
{
|
||||
if (m_nview == null || !m_nview.IsValid() || !m_nview.IsOwner()) return;
|
||||
if (m_character == null || m_character.IsDead()) return;
|
||||
|
||||
if (TickWither()) return;
|
||||
|
||||
Vector3? anchor = Anchor;
|
||||
if (anchor == null) return;
|
||||
|
||||
float distance = Vector3.Distance(transform.position, anchor.Value);
|
||||
|
||||
if (distance > SkadiGolem.LeashRange)
|
||||
{
|
||||
// Whatever it was going after is outside the circle it defends, so it stops going
|
||||
// after it. Vanilla would drop the target itself a second or so later through
|
||||
// m_maxChaseDistance; doing it here as well means the leash does not depend on that
|
||||
// one field surviving a game update.
|
||||
ClearTarget();
|
||||
}
|
||||
|
||||
if (distance > SkadiGolem.HardLeashRange) SnapHome(anchor.Value);
|
||||
|
||||
// Every tick, and not only when it has strayed: this is also what pins m_spawnPoint after
|
||||
// a zone reload, where Bind is never called again.
|
||||
GoHome();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Starts the clock when the stonecutter is gone, and stops the golem when it runs out.
|
||||
/// Returns true once it has done so, so the caller stops bothering with it.
|
||||
///
|
||||
/// Without some form of this a stonecutter is a duplication exploit: cut two golems, take the
|
||||
/// stonecutter down, put it up somewhere else, and keep both from every round.
|
||||
/// </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)
|
||||
{
|
||||
// Only asked from close to home - see SkadiGolem.HomeCheckRange. Being leashed to
|
||||
// twenty metres, a golem is essentially always close enough, so this guard is about
|
||||
// the moment after a zone loads rather than about distance.
|
||||
if (Vector3.SqrMagnitude(transform.position - anchor.Value) >
|
||||
SkadiGolem.HomeCheckRange * SkadiGolem.HomeCheckRange) return false;
|
||||
|
||||
if (SkadiGolem.StonecutterStandsAt(anchor.Value)) return false;
|
||||
|
||||
MarkOrphaned();
|
||||
return false;
|
||||
}
|
||||
|
||||
// Put back in time, on the same spot: the clock is cleared and the golem lives. It opens
|
||||
// no exploit - a stonecutter on the same spot owns these golems by anchor anyway.
|
||||
if (SkadiGolem.StonecutterStandsAt(anchor.Value))
|
||||
{
|
||||
m_nview.GetZDO().Set(KeyOrphanAt, 0L);
|
||||
return false;
|
||||
}
|
||||
|
||||
double elapsed = (ZNet.instance.GetTime() - new DateTime(stamp)).TotalSeconds;
|
||||
if (elapsed < SkadiGolem.WitherSeconds) return false;
|
||||
|
||||
Crumble();
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>Starts the wither clock, once. Idempotent, so it cannot be restarted and keep an
|
||||
/// orphan alive forever.</summary>
|
||||
private void MarkOrphaned()
|
||||
{
|
||||
if (m_nview == null || !m_nview.IsValid() || ZNet.instance == null) return;
|
||||
if (m_nview.GetZDO().GetLong(KeyOrphanAt, 0L) != 0L) return;
|
||||
|
||||
m_nview.ClaimOwnership();
|
||||
m_nview.GetZDO().Set(KeyOrphanAt, ZNet.instance.GetTime().Ticks);
|
||||
|
||||
if (Player.m_localPlayer != null &&
|
||||
Vector3.Distance(Player.m_localPlayer.transform.position, transform.position) < 30f)
|
||||
{
|
||||
Player.m_localPlayer.Message(MessageHud.MessageType.Center,
|
||||
"The stonecutter is gone. What it cut will not outlast it by long.");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Pins the patrol point - and the spawn point vanilla measures its own chase limit from -
|
||||
/// back onto the stonecutter. Cheap enough to call on a timer, and calling it repeatedly is
|
||||
/// what stops a golem drifting after it has been pushed or knocked back.
|
||||
/// </summary>
|
||||
private void GoHome()
|
||||
{
|
||||
Vector3? anchor = Anchor;
|
||||
if (anchor == null || m_ai == null) return;
|
||||
|
||||
if (SpawnPointField != null) SpawnPointField.SetValue(m_ai, anchor.Value);
|
||||
|
||||
if (SetPatrolPointMethod != null)
|
||||
{
|
||||
SetPatrolPointMethod.Invoke(m_ai, new object[] { anchor.Value });
|
||||
}
|
||||
else
|
||||
{
|
||||
// Fall back to writing the two fields the private method writes.
|
||||
Traverse traverse = Traverse.Create(m_ai);
|
||||
traverse.Field("m_patrolPoint").SetValue(anchor.Value);
|
||||
traverse.Field("m_patrol").SetValue(true);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Forgets whatever it was going after, creature or otherwise.</summary>
|
||||
private void ClearTarget()
|
||||
{
|
||||
if (m_monsterAI == null) return;
|
||||
|
||||
Traverse traverse = Traverse.Create(m_monsterAI);
|
||||
traverse.Field("m_targetCreature").SetValue(null);
|
||||
traverse.Field("m_targetStatic").SetValue(null);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The failsafe, and only that. A golem that is this far out has not wandered - it has been
|
||||
/// pushed somewhere it cannot path back from, and the alternative to putting it back is one
|
||||
/// that stands in a lake until its stonecutter falls.
|
||||
/// </summary>
|
||||
private void SnapHome(Vector3 anchor)
|
||||
{
|
||||
Vector2 offset = UnityEngine.Random.insideUnitCircle * 3f;
|
||||
Vector3 destination = anchor + new Vector3(offset.x, 0.5f, offset.y);
|
||||
|
||||
transform.position = destination;
|
||||
if (m_body != null) m_body.linearVelocity = Vector3.zero;
|
||||
|
||||
ClearTarget();
|
||||
|
||||
Jotunn.Logger.LogWarning($"[Skadi] A golem was {SkadiGolem.HardLeashRange:0} m or more from its " +
|
||||
"stonecutter and could not walk back; it was put back.");
|
||||
}
|
||||
|
||||
private void Crumble()
|
||||
{
|
||||
if (m_character == null || m_character.IsDead()) return;
|
||||
|
||||
HitData hit = new HitData();
|
||||
hit.m_damage.m_damage = 1E+10f;
|
||||
hit.m_hitType = HitData.HitType.Undefined;
|
||||
m_character.ApplyDamage(hit, true, false);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Lives for one frame: swaps itself for the golem and goes. Owner only, so in multiplayer exactly
|
||||
/// one golem stands up rather than one per client.
|
||||
///
|
||||
/// The stonecutter is looked up again here rather than handed over by the placement gate, and that
|
||||
/// is deliberate: both call SkadiGolem.FindStonecutter with the same point, so both get the same
|
||||
/// answer, and there is no piece of state between them that can go stale or arrive out of order.
|
||||
///
|
||||
/// If the lookup comes back empty the materials are lost, and that is the honest outcome rather
|
||||
/// than an oversight: it can only happen if the stonecutter was taken down between the gate saying
|
||||
/// yes and this frame, and the alternative - a golem anchored to nothing - would wither in a
|
||||
/// minute anyway while looking like a bug.
|
||||
/// </summary>
|
||||
public class SkadiGolemSeed : MonoBehaviour
|
||||
{
|
||||
private void Start()
|
||||
{
|
||||
ZNetView nview = GetComponent<ZNetView>();
|
||||
if (nview == null || !nview.IsValid() || !nview.IsOwner()) return;
|
||||
|
||||
GameObject prefab = ZNetScene.instance != null
|
||||
? ZNetScene.instance.GetPrefab(SkadiGolem.GolemName)
|
||||
: null;
|
||||
|
||||
if (prefab == null)
|
||||
{
|
||||
Jotunn.Logger.LogWarning($"[Skadi] No '{SkadiGolem.GolemName}' in ZNetScene; nothing was cut.");
|
||||
ZNetScene.instance.Destroy(gameObject);
|
||||
return;
|
||||
}
|
||||
|
||||
CraftingStation station = SkadiGolem.FindStonecutter(transform.position);
|
||||
if (station == null)
|
||||
{
|
||||
Jotunn.Logger.LogWarning("[Skadi] No stonecutter in range at the moment of cutting; " +
|
||||
"nothing was raised.");
|
||||
ZNetScene.instance.Destroy(gameObject);
|
||||
return;
|
||||
}
|
||||
|
||||
GameObject spawned = Instantiate(prefab, transform.position, transform.rotation);
|
||||
|
||||
// Bind tames it, marks whose stonecutter it is, and sends it home - all three.
|
||||
SkadiGolemGuard guard = spawned.GetComponent<SkadiGolemGuard>();
|
||||
if (guard != null) guard.Bind(station.transform.position);
|
||||
|
||||
ZNetScene.instance.Destroy(gameObject);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -56,6 +56,7 @@ namespace RacesOfValheim
|
|||
// bench - and the staff's recipe references it by name too.
|
||||
SkadiFrostHeart.Register();
|
||||
SkadiNokkel.Register();
|
||||
SkadiGolem.Register();
|
||||
|
||||
var se = ScriptableObject.CreateInstance<SE_SkadiStats>();
|
||||
se.name = "SE_SkadiStats";
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue