Stationary Hammer piece cloned from DvergerMageFire: scans a configurable radius for hostile, non-Mountain-faction, non-player Characters and fires its own fireball (real attack data pulled off Humanoid.m_defaultItems, grounded in an in-game dumpelder dump, not guessed). Fire-only for this first pass; Ice/Support are a later append to the same pattern. Several in-game fixes along the way: a missing piece icon (Jotunn silently drops any piece without one), a missing known-piece teach on spawn (same fix RaceMenuWard already needed), a kinematic Rigidbody fighting Character's own velocity writes, and MonsterAI needing to be disabled rather than destroyed - several vanilla systems (EnemyHud, most likely damage registration too) assume any combat-relevant Character has one. FactionHostilityPatch gains a public IsMountainFactionMob accessor so the construct's target filter shares the same Mountain roster as the rest of Factions instead of a second hand-maintained list.
266 lines
13 KiB
C#
266 lines
13 KiB
C#
using System.Collections;
|
|
using UnityEngine;
|
|
using Jotunn.Configs;
|
|
using Jotunn.Entities;
|
|
using Jotunn.Managers;
|
|
|
|
namespace RacesOfValheim
|
|
{
|
|
/// <summary>
|
|
/// A stationary base-defense piece: a bound DvergerMageFire, stripped of its AI and loot, that
|
|
/// scans for hostile Characters in range and fires its own fireball at them.
|
|
///
|
|
/// Grounded in an in-game dump (`dumpelder DvergerMageFire`, see MOUNTAIN-FACTION-BRAINSTORM.md)
|
|
/// rather than guessed: the source prefab is Humanoid-based with no embedded offensive
|
|
/// component (unlike Aswid's eitrrefinery/Radiator case), so all we need is its real attack
|
|
/// data off Humanoid.m_defaultItems - DvergerStaffFire_fireball (fire damage, projectile
|
|
/// velocity) and its projectile prefab, DvergerStaffFire_fireball_projectile - and to trigger
|
|
/// the same animation trigger it already uses, "attack_cast".
|
|
///
|
|
/// Fire-only for this first pass; DvergerMageIce/DvergerMageSupport are a later append to this
|
|
/// same clone/strip/behavior shape, not a redesign.
|
|
/// </summary>
|
|
public static class DvergarFireConstruct
|
|
{
|
|
public const string PrefabName = "DvergarFireConstruct";
|
|
private const string SourcePrefab = "DvergerMageFire";
|
|
public const string WeaponPrefabName = "DvergerStaffFire_fireball";
|
|
public const string ProjectilePrefabName = "DvergerStaffFire_fireball_projectile";
|
|
|
|
public static void Register()
|
|
{
|
|
GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(PrefabName, SourcePrefab);
|
|
if (prefab == null)
|
|
{
|
|
Jotunn.Logger.LogWarning("[Dvergar] Could not clone DvergerMageFire; Fire Construct not registered.");
|
|
return;
|
|
}
|
|
|
|
// MonsterAI is DISABLED, not destroyed - confirmed via IL that several vanilla systems
|
|
// assume any combat-relevant Character has one and reach for it unconditionally:
|
|
// EnemyHud.UpdateHuds calls Character.GetBaseAI() and immediately .HaveTarget() with no
|
|
// null check (MonsterAI extends BaseAI), which NRE'd every frame once it was gone -
|
|
// that same method also reads BaseAI.IsEnemy(Character,Character), the same check combat
|
|
// hit-registration very plausibly gates on too, which lines up with attacks not landing
|
|
// on a first in-game test. Disabling still stops it from ever wandering, targeting, or
|
|
// auto-attacking on its own (Update/FixedUpdate never run on a disabled component) -
|
|
// the same practical effect as destroying it - while GetComponent<MonsterAI>() keeps
|
|
// finding a real (just inactive) one for everything else that expects to.
|
|
MonsterAI monsterAI = prefab.GetComponent<MonsterAI>();
|
|
if (monsterAI != null) monsterAI.enabled = false;
|
|
|
|
DestroyComponent<CharacterDrop>(prefab);
|
|
DestroyComponent<NpcTalk>(prefab);
|
|
|
|
// Constraints only, NOT kinematic - Character's own base FixedUpdate keeps calling
|
|
// rigidbody.velocity = ... every frame on its own (gravity/grounding logic that has no
|
|
// idea MonsterAI is gone), and Unity refuses that specific assignment on a kinematic
|
|
// body, which spammed "Setting linear velocity of a kinematic body is not supported"
|
|
// forever once this was in-game. Freezing position/rotation via constraints instead
|
|
// keeps it stationary while leaving the body non-kinematic, so those internal velocity
|
|
// writes stay legal - they just can't move anything, since translation is locked.
|
|
Rigidbody body = prefab.GetComponent<Rigidbody>();
|
|
if (body != null)
|
|
{
|
|
body.constraints = RigidbodyConstraints.FreezeAll;
|
|
}
|
|
|
|
// Humanoid is deliberately kept, not stripped: it's what equips DvergerStaffFire and
|
|
// DvergerSuitFire into VisEquipment in the first place, so removing it risked a bare
|
|
// model. Its own health/death system also gives this piece its durability, in place
|
|
// of the WearNTear every other piece in this mod uses - see the doc comment on
|
|
// DvergarFireConstructBehavior for that tradeoff.
|
|
|
|
prefab.AddComponent<DvergarFireConstructBehavior>();
|
|
|
|
Piece piece = prefab.GetComponent<Piece>();
|
|
if (piece == null) piece = prefab.AddComponent<Piece>();
|
|
|
|
// DvergerMageFire is a monster, not a piece, so unlike RaceMenuWard's clone (guard_stone,
|
|
// already a valid vanilla piece with its own icon) this Piece starts completely bare.
|
|
// Jotunn's CustomPiece rejects (logs "is not valid" and never registers it) any piece
|
|
// with no icon. DvergerStaffFire_fireball's own icon turned out empty - it's a
|
|
// monster-only weapon, never shown in a player inventory slot, so nobody ever gave it
|
|
// one. TrophyDvergr is real player-facing loot (sold in DvergShop) and always has one.
|
|
GameObject trophyPrefab = PrefabManager.Cache.GetPrefab<GameObject>("TrophyDvergr");
|
|
ItemDrop trophyDrop = trophyPrefab != null ? trophyPrefab.GetComponent<ItemDrop>() : null;
|
|
if (trophyDrop != null && trophyDrop.m_itemData.m_shared.m_icons.Length > 0)
|
|
{
|
|
piece.m_icon = trophyDrop.m_itemData.m_shared.m_icons[0];
|
|
}
|
|
else
|
|
{
|
|
Jotunn.Logger.LogWarning("[Dvergar] Could not find an icon for the Fire Construct piece - it will fail Jotunn's validity check.");
|
|
}
|
|
|
|
PieceConfig config = new PieceConfig
|
|
{
|
|
Name = "Fire Construct",
|
|
Description = "A bound Dverger fire-mage, still loyal to whoever built it. Attacks anything hostile in range.",
|
|
PieceTable = PieceTables.Hammer,
|
|
Category = PieceCategories.Crafting,
|
|
// No CraftingStation - the RaceMenuWard lesson: a station-gated piece vanishes
|
|
// from the hammer wheel the moment you step out of range. Plain materials for now,
|
|
// same reasoning as the Skadi trinket: prove the mechanic in-game before wiring in
|
|
// the Factions merchant-gate item (see MOUNTAIN-FACTION-BRAINSTORM.md).
|
|
Requirements = new[]
|
|
{
|
|
new RequirementConfig("Stone", 10, 0, true),
|
|
new RequirementConfig("Bronze", 5, 0, true)
|
|
}
|
|
};
|
|
|
|
PieceManager.Instance.AddPiece(new CustomPiece(prefab, fixReference: false, config));
|
|
}
|
|
|
|
/// <summary>
|
|
/// A build piece only appears in the hammer once its name is in the player's known
|
|
/// recipes (PieceTable.UpdateAvailable filters on exactly that) - the same Jotunn quirk
|
|
/// RaceMenuWard.EnsureKnown already works around for its own piece. Without this, the
|
|
/// construct is fully registered and buildable in principle but never actually shows up
|
|
/// in the hammer wheel for anyone.
|
|
/// </summary>
|
|
public static void EnsureKnown(Player player)
|
|
{
|
|
if (player == null) return;
|
|
|
|
GameObject prefab = PrefabManager.Instance.GetPrefab(PrefabName);
|
|
if (prefab == null)
|
|
{
|
|
Jotunn.Logger.LogWarning($"{PrefabName} prefab missing; cannot teach the piece.");
|
|
return;
|
|
}
|
|
|
|
Piece piece = prefab.GetComponent<Piece>();
|
|
if (piece == null)
|
|
{
|
|
Jotunn.Logger.LogWarning($"{PrefabName} has no Piece component.");
|
|
return;
|
|
}
|
|
|
|
var traverse = HarmonyLib.Traverse.Create(player);
|
|
traverse.Method("AddKnownPiece", piece).GetValue();
|
|
traverse.Method("UpdateAvailablePiecesList").GetValue();
|
|
}
|
|
|
|
private static void DestroyComponent<T>(GameObject go) where T : Component
|
|
{
|
|
T component = go.GetComponent<T>();
|
|
if (component != null) Object.DestroyImmediate(component);
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Durability tradeoff, not yet verified in-game: this piece has no WearNTear. The source
|
|
/// prefab is a full Humanoid/Character, and stacking WearNTear's structural HP on top of
|
|
/// Character's own health/death system would mean two damage pipelines fighting over the same
|
|
/// piece, so Character's own health is used instead. That means it dies (and presumably
|
|
/// ragdolls) the way any monster does, rather than being "demolished" through the normal
|
|
/// hammer repair/remove flow, which relies on WearNTear. Whether that reads as a problem in
|
|
/// practice is one of the first things to check once this is in-game.
|
|
/// </summary>
|
|
public class DvergarFireConstructBehavior : MonoBehaviour
|
|
{
|
|
private Animator anim;
|
|
private Character self;
|
|
private Transform eyePos;
|
|
|
|
private GameObject projectilePrefab;
|
|
private HitData.DamageTypes damage;
|
|
private float projectileVel;
|
|
private bool dataResolved;
|
|
|
|
private float nextScanTime;
|
|
private float nextFireTime;
|
|
|
|
private void Awake()
|
|
{
|
|
anim = GetComponentInChildren<Animator>();
|
|
self = GetComponent<Character>();
|
|
eyePos = transform.Find("EyePos");
|
|
}
|
|
|
|
private void Update()
|
|
{
|
|
if (Time.time < nextScanTime) return;
|
|
nextScanTime = Time.time + DvergarConfigManagement.ConstructScanInterval.Value;
|
|
|
|
if (!dataResolved) ResolveWeaponData();
|
|
if (projectilePrefab == null) return;
|
|
|
|
Character target = FindTarget();
|
|
if (target != null && Time.time >= nextFireTime)
|
|
{
|
|
nextFireTime = Time.time + DvergarConfigManagement.ConstructFireCooldown.Value;
|
|
StartCoroutine(FireCoroutine(target));
|
|
}
|
|
}
|
|
|
|
// Read once, lazily rather than in Awake - PrefabManager.Cache may not be fully populated
|
|
// the instant a placed piece wakes up.
|
|
private void ResolveWeaponData()
|
|
{
|
|
GameObject weaponPrefab = PrefabManager.Cache.GetPrefab<GameObject>(DvergarFireConstruct.WeaponPrefabName);
|
|
ItemDrop weaponDrop = weaponPrefab != null ? weaponPrefab.GetComponent<ItemDrop>() : null;
|
|
if (weaponDrop == null) return;
|
|
|
|
damage = weaponDrop.m_itemData.m_shared.m_damages;
|
|
projectileVel = weaponDrop.m_itemData.m_shared.m_attack.m_projectileVel;
|
|
projectilePrefab = PrefabManager.Cache.GetPrefab<GameObject>(DvergarFireConstruct.ProjectilePrefabName);
|
|
dataResolved = true;
|
|
}
|
|
|
|
private Character FindTarget()
|
|
{
|
|
float radius = DvergarConfigManagement.ConstructScanRadius.Value;
|
|
int mask = LayerMask.GetMask("character", "character_net", "hitbox");
|
|
Collider[] hits = Physics.OverlapSphere(transform.position, radius, mask);
|
|
|
|
Character best = null;
|
|
float bestDist = float.MaxValue;
|
|
|
|
foreach (Collider hit in hits)
|
|
{
|
|
Character c = hit.GetComponentInParent<Character>();
|
|
if (c == null || c == self || c.IsDead() || c.IsPlayer()) continue;
|
|
|
|
// Never target Mountain-faction fauna (Wolf, Ulv, Dverger, ...) - same roster
|
|
// FactionHostilityPatch already uses to keep those creatures at peace with the
|
|
// three Mountain races, so this construct doesn't shoot its own neighbours.
|
|
string prefabName = c.gameObject.name.Replace("(Clone)", "").Trim();
|
|
if (FactionHostilityPatch.IsMountainFactionMob(prefabName)) continue;
|
|
|
|
float dist = Vector3.Distance(transform.position, c.transform.position);
|
|
if (dist < bestDist)
|
|
{
|
|
bestDist = dist;
|
|
best = c;
|
|
}
|
|
}
|
|
|
|
return best;
|
|
}
|
|
|
|
private IEnumerator FireCoroutine(Character target)
|
|
{
|
|
if (anim != null) anim.SetTrigger("attack_cast");
|
|
yield return new WaitForSeconds(0.5f);
|
|
|
|
if (target == null || target.IsDead() || projectilePrefab == null) yield break;
|
|
|
|
Vector3 spawnPos = eyePos != null ? eyePos.position : transform.position + Vector3.up * 1.5f;
|
|
Vector3 targetPos = target.transform.position + Vector3.up * 1f;
|
|
Vector3 dir = (targetPos - spawnPos).normalized;
|
|
|
|
GameObject projInstance = Object.Instantiate(projectilePrefab, spawnPos, Quaternion.LookRotation(dir));
|
|
Projectile proj = projInstance.GetComponent<Projectile>();
|
|
if (proj != null)
|
|
{
|
|
HitData hitData = new HitData();
|
|
hitData.m_damage = damage;
|
|
hitData.SetAttacker(self);
|
|
proj.Setup(self, dir * projectileVel, -1f, hitData, null, null);
|
|
}
|
|
}
|
|
}
|
|
}
|