diff --git a/JotunnModStub/PieceDensityLimit.cs b/JotunnModStub/PieceDensityLimit.cs index b872263..076f246 100644 --- a/JotunnModStub/PieceDensityLimit.cs +++ b/JotunnModStub/PieceDensityLimit.cs @@ -35,6 +35,20 @@ namespace RacesOfValheim private static readonly Dictionary Limits = new Dictionary(); + /// + /// Extra placement rules, one per piece, for the chains whose cap cannot be expressed as + /// "how many of THIS piece stand nearby". + /// + /// The Skadi's golem is the case that forced this: the piece it builds removes itself a frame + /// later and leaves a creature behind, so counting the piece counts nothing, and one of its two + /// caps is per-stonecutter rather than per-area. A gate is handed the same player and the same + /// placement point the simple limit gets, says yes or no, and is responsible for its own + /// refusal message - which is the whole extension: the counting is the chain's business, being + /// the ONE Player.PlacePiece prefix in the mod is still this class's. + /// + private static readonly Dictionary> Gates = + new Dictionary>(); + /// /// The radius of a circle with the given area, so a limit can be written the way it is /// actually discussed - "five per 1.6 square kilometres" - instead of as a magic distance. @@ -61,6 +75,45 @@ namespace RacesOfValheim Jotunn.Logger.LogInfo($"[Density] {piecePrefabName}: at most {max} within {radius:0} m."); } + /// + /// Adds a rule of the chain's own to a piece. Same call-once-from-Register() contract as + /// , and a second call replaces the first rather than stacking. + /// + public static void RegisterGate(string piecePrefabName, System.Func gate) + { + if (string.IsNullOrEmpty(piecePrefabName) || gate == null) + { + Jotunn.Logger.LogWarning($"[Density] Refusing a nonsense gate for '{piecePrefabName}'."); + return; + } + + Gates[piecePrefabName] = gate; + Jotunn.Logger.LogInfo($"[Density] {piecePrefabName}: a rule of its own runs at placement."); + } + + /// + /// Every ZDO in the world carrying that prefab. False when the world cannot be asked right + /// now, which callers must read as "no information" rather than as "none". + /// + /// ZDOs and not loaded GameObjects, for the reason at the top of this file, and public + /// because the Skadi's golem counts by an anchor written INTO each ZDO rather than by + /// distance - so it needs the ZDOs themselves and not a tally of them. + /// + public static bool Gather(string prefabName, List into) + { + if (ZDOMan.instance == null || into == null) return false; + + int index = 0; + // The iterative sweep hands back a chunk per call and reports true when it is done. The + // guard is so a pathological world cannot spin here forever. + for (int guard = 0; guard < 1000; guard++) + { + if (ZDOMan.instance.GetAllZDOsWithPrefabIterative(prefabName, into, ref index)) break; + } + + return true; + } + /// /// How many of that piece already stand within the radius of a point, or -1 if the world /// cannot be asked right now - in which case callers must let the placement through rather @@ -68,16 +121,8 @@ namespace RacesOfValheim /// public static int Count(string piecePrefabName, Vector3 position, float radius) { - if (ZDOMan.instance == null) return -1; - List zdos = new List(); - int index = 0; - // The iterative sweep hands back a chunk per call and reports true when it is done. The - // guard is so a pathological world cannot spin here forever. - for (int guard = 0; guard < 1000; guard++) - { - if (ZDOMan.instance.GetAllZDOsWithPrefabIterative(piecePrefabName, zdos, ref index)) break; - } + if (!Gather(piecePrefabName, zdos)) return -1; float rangeSq = radius * radius; int count = 0; @@ -96,6 +141,14 @@ namespace RacesOfValheim /// public static bool Allow(Player player, string piecePrefabName, Vector3 position) { + // The chain's own rule first: it is the more specific of the two, so it should be the one + // that gets to explain itself when both would refuse. + if (Gates.TryGetValue(piecePrefabName, out System.Func gate) && + !gate(player, position)) + { + return false; + } + if (!Limits.TryGetValue(piecePrefabName, out Limit limit)) return true; int nearby = Count(piecePrefabName, position, limit.Radius); diff --git a/JotunnModStub/RacesOfValheim.cs b/JotunnModStub/RacesOfValheim.cs index 4b69a34..c04e8d5 100644 --- a/JotunnModStub/RacesOfValheim.cs +++ b/JotunnModStub/RacesOfValheim.cs @@ -36,6 +36,9 @@ namespace RacesOfValheim SkeletonConfig.Bind(Config); TrentaConfigManagement.Bind(Config); TrolConfig.Bind(Config); + // Not a race: a summoned mount two races share, so it binds after the races rather + // than inside the alphabetical run above. + WarVultureConfig.Bind(Config); harmony.PatchAll(); gameObject.AddComponent(); gameObject.AddComponent(); @@ -119,6 +122,7 @@ namespace RacesOfValheim DraughRace.Instance.CreateModAssets(); DvergarRace.Instance.CreateModAssets(); TrentaRace.Instance.CreateModAssets(); + WarVultureItem.Register(); } // --- RACE SELECTION UI --- public void ShowRaceSelectionMenu() diff --git a/JotunnModStub/Skadi/SkadiGolem.cs b/JotunnModStub/Skadi/SkadiGolem.cs new file mode 100644 index 0000000..07e6aeb --- /dev/null +++ b/JotunnModStub/Skadi/SkadiGolem.cs @@ -0,0 +1,460 @@ +using System.Collections.Generic; +using HarmonyLib; +using Jotunn.Configs; +using Jotunn.Entities; +using Jotunn.Managers; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// 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. + /// + 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"; + + /// + /// 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. + /// + 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 ────────────────────────────────────────────────────── + + /// + /// 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. + /// + public const float LeashRange = 20f; + + /// + /// 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. + /// + 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; + + /// + /// 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. + /// + public const float WitherSeconds = 60f; + + /// Slack when asking "is my stonecutter still there" - a station never moves. + public const float StationCheckRange = 2f; + + /// + /// 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. + /// + public const float HomeCheckRange = 40f; + + // ─── Behaviour ─────────────────────────────────────────────────────── + + /// Idle wander around the stonecutter. Half the leash, so it never idles onto it. + private const float WanderRange = 10f; + + /// + /// 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. + /// + 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(StationPrefab); + CraftingStation component = station != null ? station.GetComponent() : 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 + + /// + /// 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. + /// + 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(); + if (character != null) character.m_name = DisplayName; + + SkadiIce.Apply(prefab); + + BaseAI ai = prefab.GetComponent(); + if (ai != null) + { + ai.m_randomMoveRange = WanderRange; + ai.m_avoidWater = true; + } + + MonsterAI monster = prefab.GetComponent(); + 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(true)) + { + if (drops != null) Object.DestroyImmediate(drops); + } + + foreach (Procreation breeding in prefab.GetComponentsInChildren(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(); + + prefab.AddComponent(); + + PrefabManager.Instance.AddPrefab(prefab); + Jotunn.Logger.LogInfo($"[Skadi] {GolemName} from '{SourceGolem}': awake, tame, leashed, " + + "blind to structures, drops nothing."); + return true; + } + + // ---------------------------------------------------------------- the seed piece + + /// + /// 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. + /// + 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(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(); + + Piece piece = prefab.GetComponent() ?? prefab.AddComponent(); + 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 + + /// + /// 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. + /// + 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; + } + + /// + /// 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. + /// + public static CraftingStation FindStonecutter(Vector3 position) + { + return CraftingStation.HaveBuildStationInRange(StationName, position); + } + + /// True if a stonecutter still stands at that exact point. + public static bool StonecutterStandsAt(Vector3 position) + { + return CraftingStation.FindClosestStationInRange(StationName, position, StationCheckRange) != null; + } + + /// + /// 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. + /// + public static int CountBoundTo(Vector3 station) + { + List zdos = new List(); + 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 + + /// + /// 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. + /// + public static void EnsureKnown(Player player) + { + if (player == null || !SkadiRace.IsLocalSkadi()) return; + + GameObject prefab = PrefabManager.Instance.GetPrefab(SeedPieceName); + Piece piece = prefab != null ? prefab.GetComponent() : 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(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); + } + } + + /// + /// 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. + /// + [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() == null; + } + } +} diff --git a/JotunnModStub/Skadi/SkadiGolemBehaviour.cs b/JotunnModStub/Skadi/SkadiGolemBehaviour.cs new file mode 100644 index 0000000..b21621a --- /dev/null +++ b/JotunnModStub/Skadi/SkadiGolemBehaviour.cs @@ -0,0 +1,302 @@ +using System; +using HarmonyLib; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// 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. + /// + public class SkadiGolemGuard : MonoBehaviour + { + public const string KeyAnchor = "RoV_golemAnchor"; + public const string KeyOrphanAt = "RoV_golemOrphanAt"; + + /// + /// 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. + /// + 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(); + m_ai = GetComponent(); + m_monsterAI = GetComponent(); + m_nview = GetComponent(); + m_body = GetComponent(); + + InvokeRepeating("Tick", TickSeconds, TickSeconds); + } + + /// Where the stonecutter that cut this one stands, or null if it was cut by none. + 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; + } + } + + /// + /// 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. + /// + 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(); + } + + /// + /// 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. + /// + 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; + } + + /// Starts the wither clock, once. Idempotent, so it cannot be restarted and keep an + /// orphan alive forever. + 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."); + } + } + + /// + /// 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. + /// + 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); + } + } + + /// Forgets whatever it was going after, creature or otherwise. + 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); + } + + /// + /// 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. + /// + 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); + } + } + + /// + /// 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. + /// + public class SkadiGolemSeed : MonoBehaviour + { + private void Start() + { + ZNetView nview = GetComponent(); + 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(); + if (guard != null) guard.Bind(station.transform.position); + + ZNetScene.instance.Destroy(gameObject); + } + } +} diff --git a/JotunnModStub/Skadi/SkadiRace.cs b/JotunnModStub/Skadi/SkadiRace.cs index 75e2602..9d1084c 100644 --- a/JotunnModStub/Skadi/SkadiRace.cs +++ b/JotunnModStub/Skadi/SkadiRace.cs @@ -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.name = "SE_SkadiStats"; diff --git a/JotunnModStub/WarVulture/WarVultureConfig.cs b/JotunnModStub/WarVulture/WarVultureConfig.cs new file mode 100644 index 0000000..1903f4a --- /dev/null +++ b/JotunnModStub/WarVulture/WarVultureConfig.cs @@ -0,0 +1,109 @@ +using BepInEx.Configuration; + +namespace RacesOfValheim +{ + /// + /// Every tunable number behind the War Vulture, bound as BepInEx ConfigEntry so it shows up in + /// Configuration Manager - same shape as TrolConfig, which is the house model for this. + /// + /// The three numbers most likely to need a pass in game are deliberately here rather than in + /// code: MountSize, MountOffsetY and MountOffsetZ. Where a bird sits under a rider is the one + /// thing the last attempt lost three rounds to (section 16.6 of the design doc: measure a + /// relation, never pick a number in metres from the armchair), and a value that can be dragged + /// in the menu while standing in the world beats another compile. + /// + /// No keybind is bound here on purpose. The mount answers to LEFT CLICK on the item and to the + /// vanilla run key, so there is nothing new to learn and nothing new to rebind. + /// + public static class WarVultureConfig + { + // ─── Access ──────────────────────────────────────────────────────────── + public static ConfigEntry AllowedRaces; + + // ─── Flight ──────────────────────────────────────────────────────────── + public static ConfigEntry CruiseSpeed; + public static ConfigEntry SprintSpeed; + public static ConfigEntry SprintSeconds; + public static ConfigEntry RechargeSeconds; + public static ConfigEntry LandingSpeed; + + // ─── Model ───────────────────────────────────────────────────────────── + public static ConfigEntry HandModelScale; + public static ConfigEntry MountSize; + public static ConfigEntry SeatBone; + public static ConfigEntry SeatNudgeY; + public static ConfigEntry SeatNudgeZ; + + // ─── Interface ───────────────────────────────────────────────────────── + public static ConfigEntry ShowStaminaBar; + + public static void Bind(ConfigFile config) + { + const string access = "War Vulture - Access"; + AllowedRaces = config.Bind(access, "Allowed races", "Furling,Dvergar", + new ConfigDescription("Comma separated list of race ids that can call the vulture. " + + "In anyone else's hands the item is an inert trophy on a stick. " + + "Leave empty to let every race ride.")); + + const string flight = "War Vulture - Flight"; + // 7 and 13 are not proposals: they are m_flySlowSpeed and m_flyFastSpeed read off the + // vanilla Volture at runtime (design doc 15.13). A number read from the game survives a + // Valheim patch; a number invented here does not. + CruiseSpeed = config.Bind(flight, "Cruise speed", 7f, + new ConfigDescription("Metres per second with the run key up. This one is unlimited - " + + "vultures stay up for hours.")); + SprintSpeed = config.Bind(flight, "Sprint speed", 13f, + new ConfigDescription("Metres per second while the run key is held and the bird still " + + "has wind in it.")); + SprintSeconds = config.Bind(flight, "Sprint seconds", 10f, + new ConfigDescription("How long full speed lasts before the bird drops back to cruise.")); + RechargeSeconds = config.Bind(flight, "Recharge seconds", 10f, + new ConfigDescription("How long a spent bird takes to fill up again. It recharges in the " + + "air as soon as the run key is released - landing is not required.")); + LandingSpeed = config.Bind(flight, "Landing speed", 12f, + new ConfigDescription("Metres per second of the automatic descent after the dismount " + + "click. The controls are ignored until the ground arrives.")); + + const string model = "War Vulture - Model"; + HandModelScale = config.Bind(model, "Hand model scale", 0.6f, + new ConfigDescription("Size of the vulture trophy carried in hand, as a fraction of the " + + "real trophy. 0.6 is the 40% smaller that was asked for.")); + MountSize = config.Bind(model, "Mount size", 7.75f, + new ConfigDescription("Largest dimension of the bird under the rider, in metres. 7.75 is " + + "the vanilla Volture's own mesh, wings included.")); + // The rider is glued to a BONE, not to a height: the bird's back rises and falls with + // every wingbeat, and any offset in metres can only be right on one frame of that. + SeatBone = config.Bind(model, "Seat bone", "", + new ConfigDescription("Name (or part of a name) of the bone on the vulture's skeleton the " + + "rider sits on. Empty picks the last spine/chest bone automatically, " + + "which is what the bird actually flies with.")); + SeatNudgeY = config.Bind(model, "Seat nudge Y", 0f, + new ConfigDescription("Fine adjustment up (+) or down (-) from the seat bone, in metres. " + + "Zero means exactly on the bone.")); + SeatNudgeZ = config.Bind(model, "Seat nudge Z", 0f, + new ConfigDescription("Fine adjustment forward (+) or back (-) from the seat bone, in metres.")); + + const string ui = "War Vulture - Interface"; + ShowStaminaBar = config.Bind(ui, "Show stamina bar", true, + new ConfigDescription("Draws the bird's own wind as a bar under the player's stamina, " + + "cloned from vanilla's mount stamina bar.")); + } + + /// + /// Whether a race id may call the bird. An empty list means everyone, which is the honest + /// reading of "no restriction" and is also what makes this testable on any character. + /// + public static bool RaceAllowed(string race) + { + string list = AllowedRaces != null ? AllowedRaces.Value : null; + if (string.IsNullOrEmpty(list)) return true; + if (string.IsNullOrEmpty(race)) return false; + + foreach (string entry in list.Split(',')) + { + if (entry.Trim().Equals(race.Trim(), System.StringComparison.OrdinalIgnoreCase)) return true; + } + return false; + } + } +} diff --git a/JotunnModStub/WarVulture/WarVultureHud.cs b/JotunnModStub/WarVulture/WarVultureHud.cs new file mode 100644 index 0000000..0f63814 --- /dev/null +++ b/JotunnModStub/WarVulture/WarVultureHud.cs @@ -0,0 +1,116 @@ +using System.Reflection; +using HarmonyLib; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// The bird's wind, as a bar under the player's stamina. + /// + /// It is a CLONE of vanilla's own mount stamina bar, not a bar drawn from scratch, for two + /// reasons: it is already skinned, sized and animated like every other bar in the game, and it + /// is semantically the same thing - Hud.UpdateMount drives that bar from Sadle.GetStamina for + /// the asksvin. Ours is the same idea with a different animal underneath. + /// + /// Vanilla's copy cannot simply be borrowed where it stands: Hud.UpdateMount switches the whole + /// mount panel off on every frame in which the player is not on a Sadle, and it would take the + /// bar with it. The clone is reparented out of that panel, so vanilla never touches it again. + /// + /// Everything here is reflection because GuiBar lives in assembly_guiutils, which this project + /// does not reference - and adding a reference to the csproj is a bigger change than a bar is + /// worth. Every step is null-checked: a bar that fails to build costs the bar and nothing else, + /// which is the right trade for an ornament on a flying mount. + /// + public class WarVultureHud + { + private const float BelowStaminaPixels = 24f; + + private readonly WarVultureMount mount; + private readonly GameObject barObject; + private readonly Component guiBar; + private readonly MethodInfo setValue; + + private WarVultureHud(WarVultureMount mount, GameObject barObject, Component guiBar, MethodInfo setValue) + { + this.mount = mount; + this.barObject = barObject; + this.guiBar = guiBar; + this.setValue = setValue; + } + + public static WarVultureHud Create(WarVultureMount mount) + { + Hud hud = Hud.instance; + if (hud == null) return null; + + Component template = Traverse.Create(hud).Field("m_mountStaminaBar").GetValue(); + RectTransform staminaRoot = hud.m_staminaBar2Root; + if (template == null || staminaRoot == null || staminaRoot.parent == null) + { + Jotunn.Logger.LogWarning("[WarVulture] The vanilla mount stamina bar or the stamina bar root " + + "could not be found, so the bird flies without a gauge."); + return null; + } + + GameObject clone = Object.Instantiate(template.gameObject, staminaRoot.parent); + clone.name = "WarVultureWindBar"; + + // Anchored off the stamina bar rather than off the screen: the stamina bar moves with + // the player's HUD layout, and anything positioned against the screen would drift away + // from it the moment that layout changes. + RectTransform rect = clone.GetComponent(); + if (rect != null) + { + rect.anchorMin = staminaRoot.anchorMin; + rect.anchorMax = staminaRoot.anchorMax; + rect.pivot = staminaRoot.pivot; + rect.anchoredPosition = staminaRoot.anchoredPosition + new Vector2(0f, -BelowStaminaPixels); + rect.localScale = staminaRoot.localScale; + } + + clone.SetActive(true); + + Component bar = clone.GetComponent("GuiBar"); + MethodInfo setter = bar != null + ? bar.GetType().GetMethod("SetValue", new[] { typeof(float) }) + : null; + + if (setter == null) + { + Jotunn.Logger.LogWarning("[WarVulture] The cloned bar has no GuiBar.SetValue(float) to drive, " + + "so it would have sat there full forever; it was removed."); + Object.Destroy(clone); + return null; + } + + TintBrown(bar); + + return new WarVultureHud(mount, clone, bar, setter); + } + + /// + /// Optional, and treated as such: if GuiBar ever loses SetColor the bar simply keeps + /// vanilla's colour instead of costing an exception every summon. + /// + private static void TintBrown(Component bar) + { + MethodInfo setColor = bar.GetType().GetMethod("SetColor", new[] { typeof(Color) }); + if (setColor == null) return; + + setColor.Invoke(bar, new object[] { new Color(0.72f, 0.55f, 0.32f, 1f) }); + } + + public void Refresh() + { + if (barObject == null || guiBar == null || setValue == null) return; + if (mount == null) return; + + setValue.Invoke(guiBar, new object[] { mount.WindFraction }); + } + + public void Dispose() + { + if (barObject != null) Object.Destroy(barObject); + } + } +} diff --git a/JotunnModStub/WarVulture/WarVultureItem.cs b/JotunnModStub/WarVulture/WarVultureItem.cs new file mode 100644 index 0000000..03d105c --- /dev/null +++ b/JotunnModStub/WarVulture/WarVultureItem.cs @@ -0,0 +1,308 @@ +using HarmonyLib; +using Jotunn.Entities; +using Jotunn.Managers; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// The War Vulture item: a Dead Raiser with the skeleton taken out of it and a vulture trophy + /// hung in its place. Clicked, it puts the player on a flying bird; clicked again, it brings + /// them down and takes the bird away. + /// + /// Why a staff and not a trinket: the game lets a WEAPON be used without any trickery. Cloning + /// StaffSkeleton buys the click, the cast gesture and the effects for free - which is exactly + /// the reasoning that produced SkadiNokkel, and this file is deliberately that file's twin. If + /// one of them ever needs a fix, the other almost certainly needs the same one. + /// + /// Three things are removed from the vanilla staff, and each is removed TWICE on purpose: + /// - the eitr, health and stamina costs are zeroed on the clone AND forced to zero in the + /// getters every cost check flows through (WarVultureFreeCastPatch). The eitr cost is not + /// cosmetic: it is checked BEFORE the attack starts, so a player without eitr would never + /// reach the code that summons; + /// - the summon is nulled on the clone AND the attack trigger itself is taken over, so + /// vanilla's spawn code is not merely defused but unreachable (WarVultureCastPatch); + /// - the staff's model is replaced by the trophy under the item's "attach" child, which is + /// the ONLY child VisEquipment draws - a model hung anywhere else is present, correct and + /// invisible (design doc 15.11, half an hour paid for once already). + /// + public static class WarVultureItem + { + public const string PrefabName = "WarVulture"; + public const string DisplayName = "War Vulture"; + + private const string SourcePrefab = "StaffSkeleton"; + private const string TrophyPrefab = "TrophyVolture"; + private const string Label = "WarVulture"; + + public static void Register() + { + GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(PrefabName, SourcePrefab); + if (prefab == null) + { + Jotunn.Logger.LogWarning($"[{Label}] Could not clone {SourcePrefab}; {DisplayName} not registered."); + return; + } + + ItemDrop drop = prefab.GetComponent(); + if (drop == null || drop.m_itemData == null || drop.m_itemData.m_shared == null) + { + Jotunn.Logger.LogWarning($"[{Label}] {SourcePrefab} clone has no usable ItemDrop; {DisplayName} not registered."); + return; + } + + ItemDrop.ItemData.SharedData shared = drop.m_itemData.m_shared; + shared.m_name = DisplayName; + shared.m_description = "A vulture's head, kept. Raise it and the bird comes back under you, " + + "and it will carry you as long as you care to stay up - though it only " + + "has so much haste in it before it settles into a glide."; + shared.m_useDurability = false; + + // ItemType is left exactly as the vanilla staff has it: it decides the equip slot and + // which animation set the arms use, and the cast gesture is the whole reason this is a + // staff rather than a trinket. + + Strip(shared); + SwapHandModel(prefab); + + ItemManager.Instance.AddItem(new CustomItem(prefab, fixReference: false)); + + // Built HERE and not at the summon, and the comment on WarVultureVisual explains why in + // full: this is a context where components may be destroyed immediately, and the summon + // is not. Getting that wrong once put a live Ashlands predator in the player's world. + WarVultureVisual.BuildTemplate(); + + // No recipe, on purpose and for now: the item is spawned from the console + // ("spawn WarVulture") while the flight is being proven. A recipe costs nothing to add + // later and would only be materials invented before anyone knows what this is worth. + Jotunn.Logger.LogInfo($"[{Label}] {DisplayName} registered: no eitr, no health, no stamina, no skeleton."); + } + + /// + /// Takes the skeleton staff apart. Every field is zeroed on BOTH attacks, because the + /// secondary is a separate Attack carrying its own copy of every cost. + /// + /// The summon hangs off a SpawnAbility on a prefab referenced by the attack, and WHICH + /// field carries it is not knowable from the game files - so all three candidates go. + /// Nulling three fields that might each be the culprit costs nothing; guessing wrong costs + /// a skeleton on every click. + /// + /// The animation is the one thing deliberately left alone. It is the whole point: the + /// player raises the trophy, and the bird answers. + /// + private static void Strip(ItemDrop.ItemData.SharedData shared) + { + StripAttack(shared.m_attack); + StripAttack(shared.m_secondaryAttack); + } + + private static void StripAttack(Attack attack) + { + if (attack == null) return; + + attack.m_attackEitr = 0f; + attack.m_drawEitrDrain = 0f; + attack.m_reloadEitrDrain = 0f; + + attack.m_attackHealth = 0f; + attack.m_attackHealthPercentage = 0f; + attack.m_attackHealthLowBlockUse = false; + attack.m_attackHealthReturnHit = 0f; + + attack.m_attackStamina = 0f; + attack.m_drawStaminaDrain = 0f; + attack.m_reloadStaminaDrain = 0f; + + attack.m_attackProjectile = null; + attack.m_spawnOnTrigger = null; + attack.m_spawnOnHit = null; + attack.m_spawnOnHitChance = 0f; + } + + /// + /// Puts the vulture trophy in the hand where the staff's model was. + /// + /// "attach" is not a name picked for tidiness: VisEquipment instantiates that child and + /// nothing else, so this is the only place a held model can live. + /// + /// The size is a MULTIPLIER rather than a measurement in metres, which is the opposite of + /// what ModelBorrow does and is right here for one reason: the brief was "the trophy, 40% + /// smaller". The trophy's own size is the measurement; 0.6 is the relation applied to it. + /// + private static void SwapHandModel(GameObject prefab) + { + Transform attach = FindChild(prefab.transform, "attach"); + if (attach == null) + { + Jotunn.Logger.LogWarning($"[{Label}] The {SourcePrefab} clone has no 'attach' child, so the " + + "held model was left as the vanilla staff. VisEquipment draws " + + "nothing else, so there was nowhere else to put it."); + return; + } + + GameObject trophy = PrefabManager.Cache.GetPrefab(TrophyPrefab); + if (trophy == null) + { + Jotunn.Logger.LogWarning($"[{Label}] No '{TrophyPrefab}' to borrow; the item keeps the " + + "skeleton staff's look."); + return; + } + + // The old staff mesh goes first, or the hand holds both. + for (int i = attach.childCount - 1; i >= 0; i--) + { + Object.DestroyImmediate(attach.GetChild(i).gameObject); + } + foreach (Renderer renderer in attach.GetComponents()) + { + if (renderer != null) Object.DestroyImmediate(renderer); + } + + // Instantiate into a holder that is ALREADY INACTIVE - the one line ModelBorrow exists + // for. A trophy is an ItemDrop, and Instantiate runs Awake first: waking one for a + // single frame drops a real trophy on the floor. + GameObject holder = new GameObject("WarVultureTrophy"); + holder.transform.SetParent(attach, false); + holder.SetActive(false); + + GameObject copy = Object.Instantiate(trophy, holder.transform); + copy.name = "model"; + copy.transform.localPosition = Vector3.zero; + copy.transform.localRotation = Quaternion.identity; + copy.transform.localScale = Vector3.one * WarVultureConfig.HandModelScale.Value; + + StripToMeshesOnly(copy); + + holder.SetActive(true); + } + + /// + /// The trophy reduced to nothing but its shape. + /// + /// This used to be a BLACKLIST - scripts, colliders, rigidbodies, ZNetView - and it let + /// through exactly what a blacklist always lets through: the things nobody thought to name. + /// A vanilla item prefab carries the sparkle that makes dropped loot findable in long grass, + /// and that lives in ParticleSystems, ParticleSystemRenderers and Lights. None of those is a + /// MonoBehaviour, so all of them survived, and the item glittered in the player's hand like + /// something they had just thrown away. + /// + /// So it is a whitelist now, the same shape as WarVultureVisual's: MeshFilter, + /// MeshRenderer, SkinnedMeshRenderer, Transform. Note it is deliberately NARROWER than the + /// mount's whitelist - "Renderer" would be wrong here, because ParticleSystemRenderer IS a + /// Renderer and it is half of what we are trying to be rid of. + /// + /// Passes, because Unity refuses to destroy a component another one still requires, and the + /// refusal only unblocks once the dependent is gone. + /// + private static void StripToMeshesOnly(GameObject copy) + { + for (int pass = 0; pass < 6; pass++) + { + bool destroyedSomething = false; + + foreach (Component component in copy.GetComponentsInChildren(true)) + { + if (component == null) continue; + if (component is Transform) continue; + if (component is MeshFilter) continue; + if (component is MeshRenderer) continue; + if (component is SkinnedMeshRenderer) continue; + + Object.DestroyImmediate(component); + + if (component == null) destroyedSomething = true; + } + + if (!destroyedSomething) break; + } + } + + private static Transform FindChild(Transform root, string name) + { + if (root.name == name) return root; + for (int i = 0; i < root.childCount; i++) + { + Transform found = FindChild(root.GetChild(i), name); + if (found != null) return found; + } + return null; + } + + public static bool IsWarVulture(ItemDrop.ItemData item) + { + return item != null && item.m_dropPrefab != null && item.m_dropPrefab.name == PrefabName; + } + + /// + /// True when a cost being asked about belongs to this item. + /// + /// The fallback on the equipped weapon is necessary rather than belt-and-braces: the cost + /// getters are called from Attack.Start and m_weapon is not guaranteed to be assigned yet. + /// It is only consulted when m_weapon is null, so a creature's own attack cannot be zeroed + /// just because the player happens to be holding the trophy at the time. + /// + public static bool IsWarVultureContext(ItemDrop.ItemData weapon) + { + if (weapon != null) return IsWarVulture(weapon); + + Player local = Player.m_localPlayer; + return local != null && IsWarVulture(local.GetCurrentWeapon()); + } + } + + /// + /// The click. Attack.OnAttackTrigger is used rather than Attack.Start because it takes NO + /// parameters - its signature cannot drift - and it fires when the animation reaches its + /// release point, which is when a summon should land. + /// + /// A Prefix returning FALSE, so for this item vanilla's attack-trigger code never runs at all. + /// m_weapon and m_character are private on Attack and arrive through Harmony's triple + /// underscore injection, which is checked at patch time: a rename becomes a startup error + /// instead of a silent null on every click. + /// + [HarmonyPatch(typeof(Attack), "OnAttackTrigger")] + public static class WarVultureCastPatch + { + public static bool Prefix(ItemDrop.ItemData ___m_weapon, Humanoid ___m_character) + { + if (!WarVultureItem.IsWarVulture(___m_weapon)) return true; + + // Still returns false while riding, so vanilla's trigger never runs - but the dismount + // is NOT taken from here. In the saddle this event is unreliable: the cast clip loses + // to the sitting pose before its event fires. WarVultureMount reads the button itself. + WarVultureMount.Toggle(___m_character as Player); + return false; + } + } + + /// + /// The item costs nothing, guaranteed. + /// + /// Zeroing the fields on the clone ought to be enough by every reading of the game's own code. + /// On the Skadi staff the cost came back in game anyway, which means the write to a clone's + /// SharedData does not survive something - so relying on it alone is relying on a mechanism + /// already observed to fail. These three getters are the single funnel every cost check flows + /// through: Attack.Start asks them before it will start, and the tooltip asks them for what to + /// print. All three are private and take no parameters, so they are addressed by name. + /// + [HarmonyPatch] + public static class WarVultureFreeCastPatch + { + [HarmonyTargetMethods] + private static System.Collections.Generic.IEnumerable TargetMethods() + { + yield return AccessTools.Method(typeof(Attack), "GetAttackEitr"); + yield return AccessTools.Method(typeof(Attack), "GetAttackHealth"); + yield return AccessTools.Method(typeof(Attack), "GetAttackStamina"); + } + + [HarmonyPostfix] + private static void Postfix(ItemDrop.ItemData ___m_weapon, ref float __result) + { + if (__result == 0f) return; + if (!WarVultureItem.IsWarVultureContext(___m_weapon)) return; + + __result = 0f; + } + } +} diff --git a/JotunnModStub/WarVulture/WarVultureMount.cs b/JotunnModStub/WarVulture/WarVultureMount.cs new file mode 100644 index 0000000..027a540 --- /dev/null +++ b/JotunnModStub/WarVulture/WarVultureMount.cs @@ -0,0 +1,389 @@ +using HarmonyLib; +using Jotunn.Managers; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// The ride itself. Lives on the local player while they are mounted, and nowhere else. + /// + /// THE ONE IDEA THIS FILE IS BUILT ON: the PLAYER flies, the bird is how it looks from outside. + /// That inversion is what makes a flying mount a small feature instead of a large one - it + /// removes the ZDO owner problem, the AI, the taming, the passivity and the whole saddle, all + /// of which cost a session each the first time round. The flight itself is the Aswid's bat + /// form: Player.m_debugFly, and nothing else. + /// + /// THE ONE TRAP: a real attach and a self-driven player are enemies in vanilla, and the game + /// says so twice. + /// - Player.SetControls: if the player is attached, has no doodad controller and presses ANY + /// movement key, vanilla calls AttachStop. That is how you stand up from a chair. + /// - Player.SetDoodadControlls: giving it a doodad controller instead is worse - it zeroes + /// moveDir, run and autoRun unconditionally after handing them to the controller, so the + /// rider could not move at all. + /// Both were read out of the assembly, not guessed. The way through is the third door: the + /// attach point is the PLAYER'S OWN TRANSFORM, so Player.UpdateAttach - which copies position + /// and rotation from the attach point every frame, and would otherwise nail the rider in place + /// - provably copies the player onto themselves and does nothing. The bird hangs off the + /// player, not the other way round. The one remaining conflict, the AttachStop above, is + /// switched off for the duration in WarVultureControlsPatch. + /// + /// What the attach is still there FOR, after all that, is the pose: AttachStart ends with + /// m_zanim.SetBool(attachAnimation, true), and ZSyncAnimation replicates it - so every other + /// player sees the rider sitting, for free, with no code of ours involved. + /// + public class WarVultureMount : MonoBehaviour + { + /// The ZDO flag other clients watch to know they should draw a bird under this player. + public const string MountedKey = "WarVulture_Mounted"; + + private const string Label = "WarVulture"; + private const string HolderName = "WarVultureMountModel"; + + /// How long after the summon a click is ignored, so one press cannot do both. + private const float ClickGuardSeconds = 0.6f; + + /// The one live mount. There is at most one: this is the local player's own ride. + public static WarVultureMount Active { get; private set; } + + private Player player; + private WarVultureRig rig; + private Transform seat; + private WarVultureHud hud; + + private float wind; // seconds of full speed left in the bird + private bool landing; // dismount asked for; coming down before it takes effect + private float landingStartedAt; + private float summonedAt; + + // ---------------------------------------------------------------- public surface + + public static bool IsRiding(Player candidate) + { + return Active != null && candidate != null && Active.player == candidate; + } + + /// Fraction of the bird's wind left, for the bar. 1 = fresh, 0 = spent. + public float WindFraction + { + get + { + float max = Mathf.Max(0.01f, WarVultureConfig.SprintSeconds.Value); + return Mathf.Clamp01(wind / max); + } + } + + /// + /// The SUMMON, and only the summon. Called from WarVultureCastPatch, which has already + /// established that the thing being swung is ours and that the player is not already up. + /// + /// The dismount used to come through here too, and it did not work: the click fires + /// Attack.OnAttackTrigger, which the game raises from an animation event partway through + /// the cast clip - and in the saddle that clip loses to the sitting pose before it ever + /// gets there. The rider was trapped in the air with a click that did nothing. The dismount + /// is now read straight off the button in Update, where no animation can swallow it. + /// + public static void Toggle(Player caster) + { + if (caster == null || caster != Player.m_localPlayer) return; + if (Active != null && Active.player == caster) return; + + Summon(caster); + } + + /// + /// The dismount button, read from the device rather than from the animation. + /// + /// RaceInput.Allowed is the same gate every ability in this mod uses, and it is here for a + /// reason worth remembering: it reads Player.TakeInput, which is FALSE while the console is + /// open. A dismount that "does not work" during a test session is usually the console. + /// + private static bool DismountPressed() + { + if (!RaceInput.Allowed) return false; + return ZInput.GetButtonDown("Attack") || ZInput.GetButtonDown("JoyAttack"); + } + + // ---------------------------------------------------------------- summon + + private static void Summon(Player rider) + { + string race = null; + if (rider.m_customData != null) rider.m_customData.TryGetValue("Race", out race); + + if (!WarVultureConfig.RaceAllowed(race)) + { + rider.Message(MessageHud.MessageType.Center, "The bird does not know you."); + return; + } + + if (!WarVultureVisual.Ready) + { + rider.Message(MessageHud.MessageType.Center, "The vulture does not answer."); + Jotunn.Logger.LogWarning($"[{Label}] Call refused: the stripped model template was never built, " + + "so there is no bird to show. The reason is logged at startup - and " + + "refusing is deliberate, because the alternative is putting an unstripped " + + "creature prefab in the world."); + return; + } + + ZNetView nview = rider.GetComponent(); + if (nview == null || !nview.IsValid()) + { + Jotunn.Logger.LogWarning($"[{Label}] Call refused: the player has no valid ZNetView yet, so " + + "the flight state could not be published and no one else would see " + + "the bird."); + return; + } + + WarVultureMount mount = rider.gameObject.AddComponent(); + mount.player = rider; + mount.Begin(nview); + } + + private void Begin(ZNetView nview) + { + Active = this; + summonedAt = Time.time; + wind = WarVultureConfig.SprintSeconds.Value; + + // No lift, and that is the point: the rider is not raised above anything. The bird is + // moved so that its BACK BONE arrives under the rider, every frame, in WarVultureRig. + rig = WarVultureVisual.Spawn(player.transform, HolderName); + Seat(); + SetFlying(nview, true); + nview.GetZDO().Set(MountedKey, true); + + if (WarVultureConfig.ShowStaminaBar.Value) hud = WarVultureHud.Create(this); + } + + /// + /// The attach, and the reason it is harmless: the seat is a child of the player sitting + /// exactly on the player's own origin, so UpdateAttach's every-frame "put the rider on the + /// attach point" is the identity. + /// + /// The pose string is READ from the lox's own Sadle rather than typed from memory - the + /// same rule as prefab names, applied to an animation. + /// + /// hideWeapons is false on purpose: hiding the hand items unequips them, and the item in + /// that hand is the only way back down. + /// + private void Seat() + { + seat = new GameObject("WarVultureSeat").transform; + seat.SetParent(player.transform, false); + seat.localPosition = Vector3.zero; + seat.localRotation = Quaternion.identity; + + player.AttachStart(seat, null, false, false, false, ReadSaddlePose(), Vector3.zero, null); + } + + private static string ReadSaddlePose() + { + GameObject lox = PrefabManager.Cache.GetPrefab("Lox"); + Sadle sadle = lox != null ? lox.GetComponentInChildren(true) : null; + if (sadle != null && !string.IsNullOrEmpty(sadle.m_attachAnimation)) return sadle.m_attachAnimation; + + Jotunn.Logger.LogWarning($"[{Label}] Could not read the lox saddle's attach animation; " + + "falling back to 'attach_chair'. The rider may sit oddly."); + return "attach_chair"; + } + + // ---------------------------------------------------------------- per frame + + private void Update() + { + if (player == null || player != Player.m_localPlayer) { Dismount(); return; } + if (player.IsDead()) { Dismount(); return; } + + ZNetView nview = player.GetComponent(); + if (nview == null || !nview.IsValid()) + { + // Not an ordinary way down: the rider's own networking went away mid-flight, so it + // is worth a line even though the dismount itself is silent. + Jotunn.Logger.LogWarning($"[{Label}] The rider's ZNetView went away mid-flight; dismounting."); + Dismount(); + return; + } + + // Held on every frame rather than set once: the same thing BatFormBehavior does, for + // the same reason - anything else in the game (or in this mod) that clears debug fly + // would otherwise drop the rider out of the sky without a word. + SetFlying(nview, true); + + DriveAnimator(); + + // The guard is not superstition: the summoning click is still physically down on the + // frame the mount is created, and without it the bird would be called and dismissed by + // the same press. + if (Time.time - summonedAt > ClickGuardSeconds && DismountPressed()) + { + // A second click during the descent lets go there and then. + if (landing) Dismount(); + else BeginLanding(); + return; + } + + if (landing) UpdateLanding(); + + if (hud != null) hud.Refresh(); + } + + private void DriveAnimator() + { + if (rig == null) return; + + Vector3 velocity = player.GetVelocity(); + rig.Drive(new Vector3(velocity.x, 0f, velocity.z).magnitude); + } + + /// + /// The descent. The rider's own controls are not disabled - they are simply overruled in + /// ApplyFlight, which writes the velocity last and therefore wins. + /// + private void BeginLanding() + { + landing = true; + landingStartedAt = Time.time; + player.Message(MessageHud.MessageType.Center, "The vulture spirals down."); + } + + private void UpdateLanding() + { + Vector3 position = player.transform.position; + + float floor = -10000f; + if (ZoneSystem.instance != null) + { + // Over open water the solid height is the seabed, which would mean a long swim + // down. The surface is the floor there. + floor = Mathf.Max(ZoneSystem.instance.GetSolidHeight(position), ZoneSystem.instance.m_waterLevel); + } + + if (position.y - floor <= 0.6f) { Dismount(); return; } + + // A descent that never ends is worse than a hard landing: if the ground cannot be + // found at all, let go anyway rather than trap the rider in a falling animation. + if (Time.time - landingStartedAt > 20f) + { + Jotunn.Logger.LogWarning($"[{Label}] The descent found no ground in 20s; letting go anyway."); + Dismount(); + } + } + + // ---------------------------------------------------------------- flight, called from the physics step + + /// + /// Called from WarVultureFlightPatch, right after vanilla's UpdateDebugFly has written the + /// rider's velocity for this physics step. + /// + /// Speed is applied as a FACTOR on what vanilla just computed rather than as a fresh + /// velocity, and that is deliberate: vanilla lerps towards its target, so scaling the + /// result keeps every bit of its smoothing - the ramp up, the ease off, the standstill at + /// zero input - and only changes how fast the whole thing runs. Writing a velocity of our + /// own would have thrown all of that away. + /// + /// The wind is spent here, in the physics step, because this is the only place that knows + /// the rider is actually flying. + /// + public void ApplyFlight(bool runHeld, ref Vector3 currentVelocity, Rigidbody body) + { + float dt = Time.fixedDeltaTime; + + if (landing) + { + currentVelocity = Vector3.down * WarVultureConfig.LandingSpeed.Value; + if (body != null) body.linearVelocity = currentVelocity; + return; + } + + bool sprinting = runHeld && wind > 0f && currentVelocity.sqrMagnitude > 0.01f; + + if (sprinting) + { + wind = Mathf.Max(0f, wind - dt); + if (wind <= 0f) + { + player.Message(MessageHud.MessageType.Center, "The vulture settles into a glide."); + } + } + else if (wind < WarVultureConfig.SprintSeconds.Value) + { + // Refills in the air the moment the run key is released. A vulture can stay up for + // hours; what it cannot do is keep stooping. + float perSecond = WarVultureConfig.SprintSeconds.Value / + Mathf.Max(0.01f, WarVultureConfig.RechargeSeconds.Value); + wind = Mathf.Min(WarVultureConfig.SprintSeconds.Value, wind + perSecond * dt); + } + + float wanted = sprinting ? WarVultureConfig.SprintSpeed.Value : WarVultureConfig.CruiseSpeed.Value; + + // What vanilla aimed for this step: m_debugFlySpeed, times 2.5 when the run key is + // down. Read from the game rather than assumed, so a Valheim retune cannot silently + // double our speeds. + float vanilla = WarVultureFlightPatch.DebugFlySpeed * (runHeld ? 2.5f : 1f); + if (vanilla <= 0.01f) return; + + currentVelocity *= wanted / vanilla; + if (body != null) body.linearVelocity = currentVelocity; + } + + // ---------------------------------------------------------------- dismount + + private void Dismount() + { + Player rider = player; + + if (rider != null) + { + ZNetView nview = rider.GetComponent(); + if (nview != null && nview.IsValid()) + { + SetFlying(nview, false); + nview.GetZDO().Set(MountedKey, false); + } + else + { + // No ZDO to write to, but the local field still has to come off or the player + // keeps flying on foot. + Traverse.Create(rider).Field("m_debugFly").SetValue(false); + } + + rider.AttachStop(); + } + + if (hud != null) { hud.Dispose(); hud = null; } + // Destroy, never DestroyImmediate: a dismount can be a click, which arrives from an + // animation event callback where immediate destruction is refused. The whole reason + // this feature had a live vulture in it once. + if (rig != null) { Destroy(rig.gameObject); rig = null; } + if (seat != null) { Destroy(seat.gameObject); seat = null; } + + if (Active == this) Active = null; + + Destroy(this); + } + + private void OnDestroy() + { + // Belt and braces for a component torn off by something other than Dismount (a scene + // change, a reload). Leaving debug fly on would be the worst possible parting gift. + if (Active != this) return; + Active = null; + + if (player == null) return; + Traverse.Create(player).Field("m_debugFly").SetValue(false); + } + + /// + /// Both halves of debug fly. The field is what the local rider's own physics reads; the ZDO + /// var is what every OTHER client reads (Character.IsDebugFlying consults the ZDO when it + /// is not the owner). BatFormBehavior only ever wrote the field, which is why a bat looked + /// wrong to everyone else - this writes both. + /// + private void SetFlying(ZNetView nview, bool flying) + { + Traverse.Create(player).Field("m_debugFly").SetValue(flying); + nview.GetZDO().Set(ZDOVars.s_debugFly, flying); + } + } +} diff --git a/JotunnModStub/WarVulture/WarVulturePatches.cs b/JotunnModStub/WarVulture/WarVulturePatches.cs new file mode 100644 index 0000000..73bc532 --- /dev/null +++ b/JotunnModStub/WarVulture/WarVulturePatches.cs @@ -0,0 +1,193 @@ +using System.Reflection; +using HarmonyLib; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// The one patch that makes a seated player able to fly. + /// + /// Player.SetControls opens with: if the player is attached and presses any movement key, and + /// there is no doodad controller, call AttachStop. That is vanilla's "stand up from the chair", + /// read straight out of the assembly - and against a rider who drives themselves it fires on + /// the first tap of W. + /// + /// Giving the game a doodad controller instead is not the way out: SetDoodadControlls zeroes + /// moveDir, run and autoRun unconditionally afterwards, so the rider would stay attached and + /// be unable to move. Both doors are shut, which is why this one is a patch. + /// + /// So m_attached is lifted for the duration of SetControls and put straight back. Nothing else + /// in that method reads it (checked instruction by instruction), and everything else in the + /// game still sees an attached player - including ZSyncAnimation, which is what keeps the + /// sitting pose on everyone else's screen. + /// + /// AND THE SECOND HALF, added after the first flight. Lifting m_attached hands the rider back + /// every action a standing player has, and three of them have no business happening in a + /// saddle: jump, dodge and crouch each played their own animation for half a second before the + /// sitting pose snapped back, which is what a rider trying to gain height actually saw. + /// + /// They are suppressed here, at the source, and it costs nothing that was wanted: vanilla's + /// UpdateDebugFly does NOT read these arguments. It reads ZInput directly - GetButton("Jump") + /// to climb and KeyCode.LeftControl to descend - so taking them out of SetControls removes the + /// jump and keeps the climb. Same for the click: while riding, the dismount is read straight + /// off ZInput in WarVultureMount, so the attack is suppressed here rather than left to fight + /// the saddle pose for an animation it was never going to win. + /// + /// It costs one boolean read per frame when nobody is riding. + /// + [HarmonyPatch(typeof(Player), "SetControls")] + public static class WarVultureControlsPatch + { + public static void Prefix(Player __instance, ref bool ___m_attached, + ref bool attack, ref bool attackHold, + ref bool secondaryAttack, ref bool secondaryAttackHold, + ref bool jump, ref bool crouch, ref bool dodge, + out bool __state) + { + __state = false; + if (!WarVultureMount.IsRiding(__instance)) return; + + attack = false; + attackHold = false; + secondaryAttack = false; + secondaryAttackHold = false; + jump = false; + crouch = false; + dodge = false; + + if (!___m_attached) return; + + ___m_attached = false; + __state = true; + } + + public static void Postfix(ref bool ___m_attached, bool __state) + { + if (__state) ___m_attached = true; + } + } + + /// + /// The speed of the ride, and the bird's wind. + /// + /// Character.UpdateDebugFly has just written this physics step's velocity when this runs, so + /// this is the last word on it. The mount scales what vanilla computed rather than replacing + /// it - see WarVultureMount.ApplyFlight for why that keeps the flight feeling smooth. + /// + /// m_currentVel, m_body and m_run are all private on Character and arrive through Harmony's + /// field injection, which is verified when the patch is applied: a Valheim rename becomes a + /// startup error instead of a mount that silently stops working. + /// + [HarmonyPatch(typeof(Character), "UpdateDebugFly")] + public static class WarVultureFlightPatch + { + private static readonly FieldInfo DebugFlySpeedField = AccessTools.Field(typeof(Character), "m_debugFlySpeed"); + private static bool warnedAboutSpeedField; + + /// + /// Vanilla's own debug fly speed, read live rather than cached: the game exposes it as a + /// static that can be retuned, and a stale copy here would quietly scale the whole ride. + /// + public static float DebugFlySpeed + { + get + { + if (DebugFlySpeedField != null) return System.Convert.ToSingle(DebugFlySpeedField.GetValue(null)); + + if (!warnedAboutSpeedField) + { + warnedAboutSpeedField = true; + Jotunn.Logger.LogWarning("[WarVulture] Character.m_debugFlySpeed could not be found, so the " + + "mount's speeds are being scaled against an assumed 10 m/s. If the " + + "bird flies wrong, this line is why."); + } + return 10f; + } + } + + public static void Postfix(Character __instance, ref Vector3 ___m_currentVel, Rigidbody ___m_body, bool ___m_run) + { + WarVultureMount mount = WarVultureMount.Active; + if (mount == null) return; + + Player player = __instance as Player; + if (player == null || !WarVultureMount.IsRiding(player)) return; + + mount.ApplyFlight(___m_run, ref ___m_currentVel, ___m_body); + } + } + + /// + /// Gives every player a watcher, so a rider on someone else's screen gets a bird under them. + /// + /// A second Player.Awake postfix alongside the one in ZdoVisualSync rather than an edit to it: + /// that file belongs to the shared race visuals, this belongs to the vulture, and Harmony is + /// perfectly happy to hold both. + /// + [HarmonyPatch(typeof(Player), "Awake")] + public static class WarVulturePlayerAwakePatch + { + public static void Postfix(Player __instance) + { + if (__instance.GetComponent() == null) + { + __instance.gameObject.AddComponent(); + } + } + } + + /// + /// The bird as everyone ELSE sees it. + /// + /// The rider's own client draws its bird from WarVultureMount; this draws one for every other + /// player who has the flag set on their ZDO. It never touches flight, attachment or input - + /// remote players are moved by their own owner and the pose replicates itself through + /// ZSyncAnimation, so there is nothing here but a model that appears and disappears. + /// + public class WarVultureRemoteVisual : MonoBehaviour + { + private const string HolderName = "WarVultureRemoteModel"; + + private Player player; + private WarVultureRig rig; + + private void Awake() + { + player = GetComponent(); + } + + private void Update() + { + if (player == null) return; + + // The local rider is drawn by their own mount; two birds is one too many. + if (player == Player.m_localPlayer) { Hide(); return; } + + ZNetView nview = player.GetComponent(); + if (nview == null || !nview.IsValid()) { Hide(); return; } + + bool mounted = nview.GetZDO().GetBool(WarVultureMount.MountedKey, false) && !player.IsDead(); + + if (mounted && rig == null) rig = WarVultureVisual.Spawn(player.transform, HolderName); + else if (!mounted && rig != null) Hide(); + + if (rig != null) + { + Vector3 velocity = player.GetVelocity(); + rig.Drive(new Vector3(velocity.x, 0f, velocity.z).magnitude); + } + } + + private void Hide() + { + if (rig == null) return; + Destroy(rig.gameObject); + rig = null; + } + + private void OnDestroy() + { + Hide(); + } + } +} diff --git a/JotunnModStub/WarVulture/WarVultureVisual.cs b/JotunnModStub/WarVulture/WarVultureVisual.cs new file mode 100644 index 0000000..cf42a91 --- /dev/null +++ b/JotunnModStub/WarVulture/WarVultureVisual.cs @@ -0,0 +1,376 @@ +using UnityEngine; +using Jotunn.Managers; + +namespace RacesOfValheim +{ + /// + /// The bird's body: built dead once, then copied. + /// + /// WHY IT IS BUILT AT REGISTRATION AND NOT AT THE SUMMON. The first version borrowed the model + /// the way ModelBorrow does it - instantiate into an inactive holder, then DestroyImmediate + /// everything that is not a renderer. That is correct at registration time and wrong at summon + /// time, and the game says so out loud: + /// + /// Destroying components immediately is not permitted during physics trigger/contact, + /// animation event callbacks, rendering callbacks or OnValidate. + /// + /// The summon runs from Attack.OnAttackTrigger, which the game calls from CharacterAnimEvent - + /// an animation event callback. Every DestroyImmediate was refused, the model kept its + /// Character, its MonsterAI and its ZNetView, and the moment the holder was switched on Awake + /// ran and a real Ashlands predator was born under the player. A live rigidbody ignores its + /// parent transform, so it flew off. Eleven refusal lines sat in the log directly above the + /// "Borrowed 'Volture'" line, which is exactly how it was found. + /// + /// So: the stripping happens once, during CreateAllModAssets, where DestroyImmediate is legal. + /// What is kept is a TEMPLATE - an inactive, script-free carcass held in DontDestroyOnLoad - + /// and a summon is a plain Instantiate of it. Instantiate is allowed in any context. + /// + /// And it is CHECKED, not assumed. If a single MonoBehaviour survives the strip, the template + /// is thrown away and the item refuses to summon. A bird that does not appear is a bug report; + /// a bird that appears with an AI is a predator in the player's world with a saved ZDO. + /// + public static class WarVultureVisual + { + private const string SourcePrefab = "Volture"; + private const string Label = "WarVulture"; + + // The three parameters DrakeFormBehavior drives, which is the only animated borrowed + // creature in this mod known to look right. + private const string FlyingParam = "flying"; + private const string GroundParam = "onGround"; + private const string SpeedParam = "forward_speed"; + + private static GameObject template; + private static float templateSize = 1f; + + public static bool Ready => template != null; + + // ---------------------------------------------------------------- the template + + /// + /// Called once from WarVultureItem.Register, i.e. from CreateAllModAssets, i.e. from a + /// context where components may be destroyed immediately. + /// + public static void BuildTemplate() + { + if (template != null) return; + + GameObject source = PrefabManager.Cache.GetPrefab(SourcePrefab); + if (source == null) + { + Jotunn.Logger.LogWarning($"[{Label}] No '{SourcePrefab}' prefab to copy; the mount will refuse " + + "to summon rather than put an invisible rider in the sky."); + return; + } + + // Inactive BEFORE the Instantiate - the one line that keeps Awake from running on a + // live predator. Everything else here depends on it. + GameObject root = new GameObject("WarVultureTemplate"); + root.SetActive(false); + Object.DontDestroyOnLoad(root); + + GameObject copy = Object.Instantiate(source, root.transform); + copy.name = "VoltureModel"; + copy.transform.localPosition = Vector3.zero; + copy.transform.localRotation = Quaternion.identity; + copy.transform.localScale = Vector3.one; + + int refused = StripToRenderers(copy); + + int alive = CountBehaviours(copy); + if (alive > 0) + { + Jotunn.Logger.LogError($"[{Label}] {alive} script(s) survived the strip on '{SourcePrefab}' " + + $"({refused} destroy calls were refused). The template is being thrown " + + "away and the War Vulture will not summon - a half-stripped creature " + + "prefab is a live animal, not a model."); + Object.DestroyImmediate(root); + return; + } + + PrepareAnimator(copy); + templateSize = Mathf.Max(0.01f, LargestDimension(copy)); + template = copy; + } + + /// + /// Everything that is not geometry or animation, removed in passes. + /// + /// Passes rather than one sweep because Unity refuses to destroy a component another + /// component still requires, and the refusal is silent as far as the caller is concerned - + /// it logs and moves on. Repeating until a pass changes nothing lets a dependency chain + /// unwind in whatever order it needs to. + /// + /// Returns how many destroy calls were refused on the last pass, purely so the failure + /// above can say something useful. + /// + private static int StripToRenderers(GameObject copy) + { + int stubborn = 0; + + for (int pass = 0; pass < 6; pass++) + { + bool destroyedSomething = false; + stubborn = 0; + + foreach (Component component in copy.GetComponentsInChildren(true)) + { + if (component == null) continue; + if (IsKept(component)) continue; + + Object.DestroyImmediate(component); + + if (component == null) destroyedSomething = true; + else stubborn++; + } + + if (!destroyedSomething) break; + } + + return stubborn; + } + + /// + /// The whitelist. Anything not on it goes - colliders, rigidbodies, ZNetView, Character, + /// MonsterAI, the lot. Keeping a list of what to KEEP rather than a list of what to remove + /// is the difference between a model and an animal: a new component in a future Valheim + /// patch is removed by default instead of surviving by omission. + /// + /// The two MESH renderers by name rather than Renderer as a family, which looks like + /// pedantry and is not: ParticleSystemRenderer is a Renderer, and "keep every Renderer" is + /// how the trophy in the player's hand ended up carrying the sparkle vanilla puts on + /// dropped loot. Meshes and the animator that poses them - nothing else. + /// + private static bool IsKept(Component component) + { + return component is Transform + || component is MeshFilter + || component is MeshRenderer + || component is SkinnedMeshRenderer + || component is Animator + || component is LODGroup; + } + + private static int CountBehaviours(GameObject copy) + { + int alive = 0; + foreach (MonoBehaviour behaviour in copy.GetComponentsInChildren(true)) + { + if (behaviour != null) alive++; + } + return alive; + } + + /// + /// Three settings, each preventing one specific failure rather than tidying anything. + /// + /// applyRootMotion: clips authored to walk a creature through the world would walk the + /// model out from under its rider. + /// + /// cullingMode: the default stops animating when no renderer is on screen, and this bird + /// lives half off the bottom of the screen - a frozen mid-flap reads as a bug. + /// + /// fireEvents: the flight clips carry animation events aimed at CharacterAnimEvent, which + /// has just been stripped off. Left on, every wingbeat would log "has no receiver". + /// + private static void PrepareAnimator(GameObject copy) + { + Animator animator = copy.GetComponentInChildren(true); + if (animator == null) + { + Jotunn.Logger.LogWarning($"[{Label}] The stripped '{SourcePrefab}' has no Animator, so the bird " + + "will hang in its bind pose - wings out, legs straight."); + return; + } + + animator.applyRootMotion = false; + animator.cullingMode = AnimatorCullingMode.AlwaysAnimate; + animator.fireEvents = false; + animator.enabled = true; + } + + // ---------------------------------------------------------------- summoning a copy + + /// + /// Hangs a copy of the template under a rider and returns the rig that keeps it there. + /// Null when the template could not be built, which the caller must treat as "do not + /// summon" rather than "summon an invisible bird". + /// + public static WarVultureRig Spawn(Transform rider, string holderName) + { + if (template == null || rider == null) return null; + + GameObject holder = new GameObject(holderName); + holder.transform.SetParent(rider, false); + holder.transform.localPosition = Vector3.zero; + holder.transform.localRotation = Quaternion.identity; + + GameObject model = Object.Instantiate(template, holder.transform); + model.name = "model"; + model.transform.localPosition = Vector3.zero; + model.transform.localRotation = Quaternion.identity; + model.transform.localScale = Vector3.one * (WarVultureConfig.MountSize.Value / templateSize); + model.SetActive(true); + + WarVultureRig rig = holder.AddComponent(); + rig.Bind(rider, model); + return rig; + } + + // ---------------------------------------------------------------- animation + + /// + /// One frame of flight, told to the animator. Any parameter this controller does not have + /// is skipped, so a Valheim animator rename costs a stiff-looking bird rather than a wall + /// of errors every frame. + /// + public static void Drive(Animator animator, float forwardSpeed) + { + if (animator == null || animator.runtimeAnimatorController == null) return; + + if (Has(animator, FlyingParam, AnimatorControllerParameterType.Bool)) animator.SetBool(FlyingParam, true); + if (Has(animator, GroundParam, AnimatorControllerParameterType.Bool)) animator.SetBool(GroundParam, false); + if (Has(animator, SpeedParam, AnimatorControllerParameterType.Float)) animator.SetFloat(SpeedParam, forwardSpeed); + } + + private static bool Has(Animator animator, string name, AnimatorControllerParameterType type) + { + foreach (AnimatorControllerParameter parameter in animator.parameters) + { + if (parameter.type == type && parameter.name == name) return true; + } + return false; + } + + // ---------------------------------------------------------------- the seat bone + + /// + /// The bone the rider sits on. + /// + /// A bone rather than an offset in metres, because that is the difference between sitting + /// on the bird and hovering above it: the back moves with every wingbeat, and a fixed + /// offset can only ever be right on one frame of the animation. + /// + /// The name is guessed from a priority list and can be overridden in config, because the + /// rig's bone names are not knowable from outside the game. The automatic pick was the right + /// one in play, so the startup dump that found it has been retired. + /// + public static Transform FindSeatBone(GameObject model) + { + if (model == null) return null; + + Transform[] bones = model.GetComponentsInChildren(true); + + string wanted = WarVultureConfig.SeatBone.Value; + if (!string.IsNullOrEmpty(wanted)) + { + Transform named = Match(bones, wanted); + if (named != null) return named; + + Jotunn.Logger.LogWarning($"[{Label}] No bone matching '{wanted}' on the vulture; falling back " + + "to the automatic pick. The bone list is in the log from startup."); + } + + // Deliberately in this order: the back of a bird is its spine and chest, and the hips + // and root are last-ditch so that SOMETHING is anchored rather than nothing. + foreach (string candidate in new[] { "spine", "chest", "back", "torso", "body", "pelvis", "hip", "root" }) + { + Transform found = Match(bones, candidate); + if (found != null) return found; + } + + return null; + } + + /// + /// Last match rather than first, on purpose: rigs number their spines outward from the + /// hips, so the last "spine" is the one furthest along the back - which is where a saddle + /// goes, not where the tail joins. + /// + private static Transform Match(Transform[] bones, string needle) + { + Transform best = null; + foreach (Transform bone in bones) + { + if (bone.name.IndexOf(needle, System.StringComparison.OrdinalIgnoreCase) >= 0) best = bone; + } + return best; + } + + // ---------------------------------------------------------------- measuring + + private static float LargestDimension(GameObject model) + { + bool any = false; + Bounds bounds = new Bounds(); + + foreach (Renderer renderer in model.GetComponentsInChildren(true)) + { + Mesh mesh = renderer is SkinnedMeshRenderer skinned + ? skinned.sharedMesh + : renderer.GetComponent()?.sharedMesh; + if (mesh == null) continue; + + Bounds local = mesh.bounds; + Matrix4x4 toModel = model.transform.worldToLocalMatrix * renderer.transform.localToWorldMatrix; + + for (int corner = 0; corner < 8; corner++) + { + Vector3 point = toModel.MultiplyPoint3x4(local.center + new Vector3( + (corner & 1) == 0 ? -local.extents.x : local.extents.x, + (corner & 2) == 0 ? -local.extents.y : local.extents.y, + (corner & 4) == 0 ? -local.extents.z : local.extents.z)); + + if (!any) { bounds = new Bounds(point, Vector3.zero); any = true; } + else bounds.Encapsulate(point); + } + } + + return any ? Mathf.Max(bounds.size.x, Mathf.Max(bounds.size.y, bounds.size.z)) : 1f; + } + } + + /// + /// Keeps the bird under its rider, one bone at a time. + /// + /// In LateUpdate, after the animator has posed the skeleton for this frame, the whole model is + /// slid so that the seat bone lands exactly on the rider's own origin. That is what "sitting on + /// the bird's back" means as a piece of code, and it is why there is no height offset anywhere + /// in this feature any more: the back tells us where it is, every frame, including while it + /// rises and falls with the wingbeat. + /// + /// Shared by the rider's own copy and by the copy other players see, so the bird cannot sit in + /// two different places depending on who is looking. + /// + public class WarVultureRig : MonoBehaviour + { + private Transform rider; + private Transform model; + private Transform seatBone; + private Animator animator; + + public void Bind(Transform rider, GameObject model) + { + this.rider = rider; + this.model = model.transform; + seatBone = WarVultureVisual.FindSeatBone(model); + animator = model.GetComponentInChildren(true); + } + + public void Drive(float forwardSpeed) + { + WarVultureVisual.Drive(animator, forwardSpeed); + } + + private void LateUpdate() + { + if (rider == null || model == null) return; + + Vector3 seat = rider.position + rider.rotation * new Vector3( + 0f, WarVultureConfig.SeatNudgeY.Value, WarVultureConfig.SeatNudgeZ.Value); + + if (seatBone != null) model.position += seat - seatBone.position; + else model.position = seat; + } + } +}