RacesOfValheim/JotunnModStub/Alfar/AlfarDrones.cs
kanym be8c7c59d3 fix: Grafvaettir miners fly low enough to strike deposits
Vanilla's flying MoveTo lifts the goal to m_flyAltitudeMin above whatever solid lies under it, the rock top included, so the miners hovered over a deposit just out of the 3.5 m reach and never struck. The Grafvaettir now flies 0.5-2 m up and strikes within 4 m.

Mining Targets is read again when the config line changes, so an edit in game counts without a restart. F8 also prints what the camera looks at (deposit kind, on the list or not) and each live miner's target, distance and strikes.
2026-10-29 19:33:08 +01:00

457 lines
20 KiB
C#

using System.Collections.Generic;
using HarmonyLib;
using Jotunn.Entities;
using Jotunn.Managers;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The LJOSVAETTIR, the Alfar's drones (Alfar_Progettazione.txt sec. 9): a Deathsquito without legs,
/// stinger or buzz, bronze, with blue light. One kind of drone does every job (the work itself is
/// AlfarDroneWork); the only thing apart is the GRAFVAETTIR, the same creature thrown like a
/// grenade to dig the precious ores around a point for two minutes and then vanish.
///
/// What a drone is by itself: 25 hp and a shield of 25, tamed, tied to its Ljoskjarne, and able to
/// defend itself with a lightning zap of 1 damage every two seconds. It never attacks anything
/// outside the Nexus's radius and never goes after anything: it is a worker, not a soldier.
///
/// The Deathsquito is ONE skinned mesh with one material (probe, doc 16C P1): the legs are bones, so
/// they are hidden by scaling the bones to zero, and the blue is an emission on a bronze body, not
/// separate eyes and wings - a true repaint is still to do.
/// </summary>
public static class AlfarDrones
{
public const string DroneName = "AlfarDrone";
public const string MinerName = "AlfarGrafvaettir";
public const string ZapWeapon = "AlfarDroneZap";
private static readonly Color Bronze = new Color(1f, 0.62f, 0.25f, 1f);
private static readonly Color ElectricBlue = new Color(0.25f, 0.65f, 1f, 1f);
public static void Register()
{
GameObject source = PrefabManager.Cache.GetPrefab<GameObject>("Deathsquito");
if (source == null)
{
Jotunn.Logger.LogWarning("[Alfar] No 'Deathsquito' to build the drones from.");
return;
}
bool zap = RegisterZap(source);
RegisterOne(source, DroneName, "$rov_creature_alfar_drone_name", zap, miner: false);
RegisterOne(source, MinerName, "$rov_creature_alfar_grafvaettir_name", zap, miner: true);
}
/// <summary>The Deathsquito's sting turned into a zap: 1 lightning, every two seconds.</summary>
private static bool RegisterZap(GameObject deathsquito)
{
Humanoid humanoid = deathsquito.GetComponent<Humanoid>();
GameObject sting = humanoid != null && humanoid.m_defaultItems != null && humanoid.m_defaultItems.Length > 0
? humanoid.m_defaultItems[0]
: null;
if (sting == null) return false;
GameObject weapon = PrefabManager.Instance.CreateClonedPrefab(ZapWeapon, sting);
if (weapon == null) return false;
ItemDrop drop = weapon.GetComponent<ItemDrop>();
if (drop == null || drop.m_itemData == null || drop.m_itemData.m_shared == null) return false;
ItemDrop.ItemData.SharedData shared = drop.m_itemData.m_shared;
shared.m_name = "$rov_item_alfar_zap_name";
HitData.DamageTypes damage = default(HitData.DamageTypes);
damage.m_lightning = AlfarNexusConfig.DroneZapDamage.Value;
shared.m_damages = damage;
shared.m_aiAttackInterval = AlfarNexusConfig.DroneZapInterval.Value;
ItemManager.Instance.AddItem(new CustomItem(weapon, fixReference: false));
return true;
}
private static void RegisterOne(GameObject source, string prefabName, string display, bool zap, bool miner)
{
GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(prefabName, source);
if (prefab == null) return;
Character character = prefab.GetComponent<Character>();
if (character != null)
{
character.m_name = display;
character.m_faction = Character.Faction.Players;
character.m_health = AlfarNexusConfig.DroneHealth.Value;
}
Humanoid humanoid = prefab.GetComponent<Humanoid>();
if (humanoid != null)
{
GameObject weapon = zap ? PrefabManager.Instance.GetPrefab(ZapWeapon) : null;
// A miner does not fight at all; the worker only defends itself.
humanoid.m_defaultItems = !miner && weapon != null ? new[] { weapon } : new GameObject[0];
humanoid.m_randomWeapon = new GameObject[0];
humanoid.m_randomArmor = new GameObject[0];
humanoid.m_randomShield = new GameObject[0];
humanoid.m_randomSets = new Humanoid.ItemSet[0];
}
MonsterAI monster = prefab.GetComponent<MonsterAI>();
if (monster != null)
{
monster.m_attackPlayerObjects = false;
monster.m_alertRange = AlfarNexusConfig.NexusRadius.Value;
monster.m_maxChaseDistance = AlfarNexusConfig.NexusRadius.Value;
}
BaseAI ai = prefab.GetComponent<BaseAI>();
if (ai != null) ai.m_randomMoveRange = 5f;
// A flyer's MoveTo lifts its goal to m_flyAltitudeMin above whatever solid is under it,
// the rock top included: at the vanilla height the miners hovered over a deposit out of
// reach and never struck.
if (ai != null && miner) { ai.m_flyAltitudeMin = 0.5f; ai.m_flyAltitudeMax = 2f; }
foreach (CharacterDrop drops in prefab.GetComponentsInChildren<CharacterDrop>(true))
{
if (drops != null) Object.DestroyImmediate(drops);
}
// The buzz: the continuous sound child, and the flying loop effect.
foreach (Transform child in prefab.GetComponentsInChildren<Transform>(true))
{
if (child != null && child.name == "SFX") Object.DestroyImmediate(child.gameObject);
}
if (character != null) character.m_flyingContinuousEffect = new EffectList { m_effectPrefabs = new EffectList.EffectData[0] };
HideLegs(prefab);
Look(prefab);
prefab.AddComponent<AlfarDroneLook>();
AlfarMark mark = prefab.AddComponent<AlfarMark>();
mark.Role = miner ? "miner" : "drone";
AlfarCreatureShield shield = prefab.AddComponent<AlfarCreatureShield>();
shield.MaxShield = AlfarNexusConfig.DroneHealth.Value;
shield.Shield = shield.MaxShield;
if (miner)
{
// The mining drone has no anchor and no leash: it lives two minutes and vanishes.
prefab.AddComponent<AlfarMiner>();
}
else
{
// The worker is NOT a RaisedThrall: that brings the follow command on E, and a drone
// that can be walked out of the base stops working (the Butler's reasoning, Butler 9).
// AlfarDroneAI keeps its own anchor to the Nexus and its own wither.
AlfarDroneAI work = prefab.AddComponent<AlfarDroneAI>();
work.m_fightsBack = true; // it defends itself with the zap
work.m_homeDistance = 4f;
}
PrefabManager.Instance.AddPrefab(prefab);
Jotunn.Logger.LogInfo($"[Alfar] Registered '{prefabName}'.");
}
/// <summary>
/// No legs: the mesh is one skinned body, so the leg bones are scaled to zero and take their
/// part of the mesh with them. The stinger has no bone of its own and is left (doc 16C P1).
/// </summary>
private static void HideLegs(GameObject prefab)
{
foreach (Transform bone in prefab.GetComponentsInChildren<Transform>(true))
{
string n = bone.name;
if (n == "L.leg1" || n == "R.leg1") bone.localScale = Vector3.zero;
}
}
private static void Look(GameObject prefab)
{
foreach (Renderer renderer in prefab.GetComponentsInChildren<SkinnedMeshRenderer>(true))
{
Material[] materials = renderer.materials;
foreach (Material material in materials)
{
if (material == null) continue;
if (material.HasProperty("_Color")) material.color = Bronze;
if (material.HasProperty("_EmissionColor"))
{
material.SetColor("_EmissionColor", ElectricBlue * 0.15f);
material.EnableKeyword("_EMISSION");
}
}
renderer.materials = materials;
}
foreach (Light light in prefab.GetComponentsInChildren<Light>(true)) light.color = ElectricBlue;
}
/// <summary>
/// The same look, applied to the LIVE body at spawn and re-applied after the animator every
/// frame for the bones: edits made on the registered clone may not reach the instance, and the
/// animator can write the leg scale back.
/// </summary>
public class AlfarDroneLook : MonoBehaviour
{
private Transform[] legs;
private void Awake()
{
var list = new System.Collections.Generic.List<Transform>();
foreach (Transform bone in GetComponentsInChildren<Transform>(true))
{
if (bone.name == "L.leg1" || bone.name == "R.leg1") list.Add(bone);
}
legs = list.ToArray();
Look(gameObject);
}
private void LateUpdate()
{
foreach (Transform leg in legs) if (leg != null) leg.localScale = Vector3.zero;
}
}
// ─── Counting and spawning ───────────────────────────────────────────
public static int CountAlive(Vector3 anchor)
{
int count = 0;
foreach (AlfarDroneAI drone in AlfarDroneAI.All)
{
if (drone != null && drone.IsBoundTo(anchor)) count++;
}
return count;
}
public static bool Spawn(Vector3 anchor)
{
GameObject prefab = ZNetScene.instance != null ? ZNetScene.instance.GetPrefab(DroneName) : null;
if (prefab == null)
{
Jotunn.Logger.LogWarning($"[Alfar] No '{DroneName}' in ZNetScene: no drone can be made.");
return false;
}
Vector3 where = AlfarConstructs.SpawnSpot(anchor) + Vector3.up * 1.5f;
GameObject spawned = Object.Instantiate(prefab, where, Quaternion.identity);
AlfarDroneAI work = spawned != null ? spawned.GetComponent<AlfarDroneAI>() : null;
if (work != null) work.Bind(anchor);
return spawned != null;
}
}
/// <summary>
/// A MINING DRONE: thrown to a point, it digs the precious ores around that point for a fixed time
/// and then vanishes (design sec. 9.3). It takes over its own AI tick like the Butler's servants do
/// (a prefix on MonsterAI.UpdateAI), flies to the nearest deposit on the list and strikes it with
/// pickaxe damage at a tool tier high enough for any of them. The ore falls where it stands.
///
/// Whatever it breaks is on the list in AlfarMiner.Deposits; a name list in the config so a
/// wrong or missing name is a config edit, not a rebuild.
/// </summary>
public class AlfarMiner : MonoBehaviour
{
public Vector3 Centre;
public float Radius = 12f;
public float LiveSeconds = 120f;
private const float Reach = 4f;
private float born;
private float nextStrike;
private Component target;
private float lastDistance = -1f;
private int strikes;
public static readonly List<AlfarMiner> All = new List<AlfarMiner>();
private void OnEnable() { All.Add(this); }
private void OnDisable() { All.Remove(this); }
private static readonly System.Reflection.MethodInfo MoveToMethod =
AccessTools.Method(typeof(BaseAI), "MoveTo", new[] { typeof(float), typeof(Vector3), typeof(float), typeof(bool) });
private void Start()
{
born = Time.time;
}
public bool Tick(MonsterAI ai, float dt)
{
if (Time.time - born >= LiveSeconds)
{
ZNetView nview = GetComponent<ZNetView>();
if (nview != null && nview.IsValid() && nview.IsOwner()) ZNetScene.instance.Destroy(gameObject);
return true;
}
if (target == null || !target.gameObject.activeInHierarchy) target = FindDeposit();
Vector3 point = Vector3.zero;
Collider area = target != null ? NearestArea(target, out point) : null;
if (area == null) { target = null; ai.StopMoving(); return true; }
// Measured to the closest point of the rock, not to its root: a copper deposit's root
// sits at its base inside the mesh, so a drone aiming there stopped on top of the rock
// and never came within reach.
float distance = Vector3.Distance(transform.position, point);
lastDistance = distance;
if (distance > Reach)
{
if (MoveToMethod != null) MoveToMethod.Invoke(ai, new object[] { dt, point + Vector3.up * 1.5f, 2f, true });
return true;
}
ai.StopMoving();
if (Time.time < nextStrike) return true;
nextStrike = Time.time + 1f;
Strike(target, area, point);
strikes++;
return true;
}
private static string[] names;
private static string namesSource;
// Read again when the config line changes, so an edit in game counts without a restart.
private static string[] Deposits
{
get
{
string value = AlfarNexusConfig.MinerDeposits.Value;
if (names == null || namesSource != value)
{
namesSource = value;
names = value.Split(new[] { ',' }, System.StringSplitOptions.RemoveEmptyEntries);
}
return names;
}
}
private static bool IsPrecious(string prefabName)
{
foreach (string wanted in Deposits)
{
if (prefabName.IndexOf(wanted.Trim(), System.StringComparison.OrdinalIgnoreCase) >= 0) return true;
}
return false;
}
private Component FindDeposit()
{
Component best = null;
float bestDistance = float.MaxValue;
foreach (Collider collider in Physics.OverlapSphere(Centre, Radius, ~0, QueryTriggerInteraction.Ignore))
{
Component deposit = DepositOf(collider);
if (deposit == null) continue;
string prefabName = Utils.GetPrefabName(deposit.gameObject);
if (!IsPrecious(prefabName)) continue;
float distance = Vector3.Distance(transform.position, deposit.transform.position);
if (distance < bestDistance) { best = deposit; bestDistance = distance; }
}
return best;
}
/// <summary>
/// The live hit area of the deposit closest to the drone, and the closest point on it.
/// MineRock and MineRock5 only take a hit on one of their own areas; a MineRock with an area
/// root (tin) keeps its base model collider apart, and a hit on that one is thrown away.
/// Broken areas are switched off, so only active colliders count.
/// </summary>
private Collider NearestArea(Component deposit, out Vector3 point)
{
point = Vector3.zero;
MineRock rock = deposit as MineRock;
GameObject root = rock != null && rock.m_areaRoot != null ? rock.m_areaRoot : deposit.gameObject;
Collider best = null;
float bestDistance = float.MaxValue;
foreach (Collider collider in root.GetComponentsInChildren<Collider>())
{
if (collider == null || !collider.enabled) continue;
Vector3 closest = collider.bounds.ClosestPoint(transform.position);
float distance = Vector3.Distance(transform.position, closest);
if (distance < bestDistance) { best = collider; bestDistance = distance; point = closest; }
}
return best;
}
private void Strike(Component deposit, Collider area, Vector3 point)
{
IDestructible destructible = deposit as IDestructible;
if (destructible == null) return;
HitData hit = new HitData();
hit.m_damage.m_pickaxe = AlfarNexusConfig.MinerDamage.Value;
hit.m_toolTier = 100;
hit.m_dodgeable = false;
hit.m_blockable = false;
hit.m_hitCollider = area;
hit.m_point = point;
hit.m_dir = (area.bounds.center - transform.position).normalized;
// Vanilla MineRock (tin) reads the attacker's ZDOID for its hit effects without a null
// check: a hit with no attacker throws before the area can break.
hit.SetAttacker(GetComponent<Character>());
destructible.Damage(hit);
}
private static Component DepositOf(Collider collider)
{
Component deposit = collider.GetComponentInParent<MineRock5>();
if (deposit == null) deposit = collider.GetComponentInParent<MineRock>();
if (deposit == null) deposit = collider.GetComponentInParent<Destructible>();
return deposit;
}
/// <summary>
/// F8 readout: what the camera looks at (is it a deposit, of which kind, on the list?) and
/// what each live miner is doing (its target, how far, how many strikes).
/// </summary>
public static void DebugReport(Player player)
{
var lines = new List<string>();
Transform aim = GameCamera.instance != null ? GameCamera.instance.transform : player.transform;
if (Physics.Raycast(aim.position, aim.forward, out RaycastHit hit, 50f, ~0, QueryTriggerInteraction.Ignore))
{
Component deposit = DepositOf(hit.collider);
string prefabName = deposit != null ? Utils.GetPrefabName(deposit.gameObject) : Utils.GetPrefabName(hit.collider.transform.root.gameObject);
lines.Add($"[RoV graf] look: {hit.collider.name} on {prefabName} " +
(deposit != null ? $"{deposit.GetType().Name} listed={IsPrecious(prefabName)}" : "not a deposit"));
}
else lines.Add("[RoV graf] look: nothing within 50m");
foreach (AlfarMiner miner in All)
{
if (miner == null) continue;
string targetName = miner.target != null ? Utils.GetPrefabName(miner.target.gameObject) : "none";
lines.Add($"[RoV graf] miner {Vector3.Distance(miner.transform.position, player.transform.position):0}m away: " +
$"target {targetName} dist {miner.lastDistance:0.0} strikes {miner.strikes} " +
$"age {Time.time - miner.born:0}s centre {miner.Centre} r {miner.Radius:0}");
}
foreach (string line in lines)
{
Debug.Log(line);
player.Message(MessageHud.MessageType.TopLeft, line);
}
}
[HarmonyPatch(typeof(MonsterAI), "UpdateAI")]
public static class Alfar_Miner_UpdateAI_Patch
{
public static bool Prefix(MonsterAI __instance, float __0, ref bool __result)
{
if (__instance == null) return true;
AlfarMiner miner = __instance.GetComponent<AlfarMiner>();
if (miner == null) return true;
__result = miner.Tick(__instance, __0);
return false;
}
}
}
}