RacesOfValheim/JotunnModStub/Trenta/TrentaHornetsNest.cs
Ferdinando 1a741978bf feat(trenta): composter and heartwood grove
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-07 17:02:47 +02:00

286 lines
12 KiB
C#

using HarmonyLib;
using Jotunn.Managers;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The swarm itself. Not a Character - it has no health, no hitbox anything else can target,
/// so "indistruttibile" falls out of what it simply isn't rather than needing invulnerability
/// code of its own. Idles in a slow orbit around whatever it is tied to; the instant an enemy
/// comes within range it breaks off, hovers over that enemy instead, and sting-ticks it on a
/// timer until it dies or leaves range, then returns to orbiting.
///
/// Two things it can be tied to, and the difference is only in what counts as an enemy:
/// - a Trenta player (the Hornet's Nest perk), which can be asked BaseAI.IsEnemy directly;
/// - a Heartwood Grove's trunk (the tier-2 station), which cannot, because a piece is not a
/// Character. See IsHostile.
/// Deliberately one class rather than two copies: the sting is combat logic, and a second copy
/// means the next tweak to the venom gets made in one place and forgotten in the other.
/// </summary>
public class TrentaHornetSwarm : MonoBehaviour
{
private Player owner; // null for a grove swarm
private Transform anchor; // what it orbits; the owner's own transform for a player swarm
private float engageRadius;
private Character target;
private float tickTimer;
private float orbitAngle;
private AudioSource buzz;
public static GameObject Spawn(Player player)
{
GameObject go = Build("TrentaHornetsNest", player.transform.position + Vector3.up);
TrentaHornetSwarm swarm = go.GetComponent<TrentaHornetSwarm>();
swarm.owner = player;
swarm.anchor = player.transform;
swarm.engageRadius = TrentaConfig.HornetsNestEngageRadius;
return go;
}
/// <summary>
/// The grove's swarm: same bees, tied to a fixed point instead of to a player. The radius is
/// its own number because 6 metres is tuned for something that walks - a tree that cannot
/// chase has to reach further, and it matches the ground the grove fertilises.
/// </summary>
public static GameObject SpawnAtAnchor(Transform anchorPoint, float radius)
{
GameObject go = Build("TrentaGroveBees", anchorPoint.position + Vector3.up);
TrentaHornetSwarm swarm = go.GetComponent<TrentaHornetSwarm>();
swarm.anchor = anchorPoint;
swarm.engageRadius = radius;
return go;
}
private static GameObject Build(string name, Vector3 position)
{
GameObject go = new GameObject(name);
go.transform.position = position;
TrentaHornetSwarm swarm = go.AddComponent<TrentaHornetSwarm>();
BuildFliesVfx(go.transform);
swarm.buzz = BuildBuzzAudio(go.transform);
return go;
}
private Vector3 AnchorPosition => anchor != null ? anchor.position : transform.position;
private void Update()
{
// A player swarm dies with its player; a grove swarm dies with its tree. Either way the
// check is "is there still something to orbit", which is also what makes the swarm clean
// itself up when the grove is destroyed without the grove having to say so.
if (anchor == null || (owner != null && owner.IsDead()))
{
Destroy(gameObject);
return;
}
if (target != null && (target.IsDead() || Vector3.Distance(target.transform.position, AnchorPosition) > engageRadius * 1.5f))
{
target = null;
}
if (target == null)
{
target = FindTarget();
}
if (target != null)
{
Vector3 hoverPoint = target.transform.position + Vector3.up * TrentaConfig.HornetsNestAttackHeight;
transform.position = Vector3.MoveTowards(transform.position, hoverPoint, TrentaConfig.HornetsNestFollowSpeed * Time.deltaTime);
if (!buzz.isPlaying) buzz.Play();
tickTimer += Time.deltaTime;
if (tickTimer >= TrentaConfig.HornetsNestTickInterval)
{
tickTimer = 0f;
Sting(target);
}
}
else
{
if (buzz.isPlaying) buzz.Stop();
tickTimer = 0f;
// A slow, lazy orbit around the Trenta rather than sitting dead-still on top of
// them - reads as "trying to stay on him" without looking glued in place.
orbitAngle += Time.deltaTime * 60f;
Vector3 orbitOffset = new Vector3(Mathf.Cos(orbitAngle * Mathf.Deg2Rad), 0.3f, Mathf.Sin(orbitAngle * Mathf.Deg2Rad)) * TrentaConfig.HornetsNestOrbitRadius;
Vector3 restPoint = AnchorPosition + Vector3.up + orbitOffset;
transform.position = Vector3.MoveTowards(transform.position, restPoint, TrentaConfig.HornetsNestFollowSpeed * Time.deltaTime);
}
}
private Character FindTarget()
{
Character nearest = null;
float nearestDist = float.MaxValue;
Vector3 centre = AnchorPosition;
foreach (Collider collider in Physics.OverlapSphere(centre, engageRadius))
{
if (collider == null) continue;
Character character = collider.GetComponentInParent<Character>();
if (character == null || character == owner) continue;
if (!IsHostile(character)) continue;
float dist = Vector3.Distance(character.transform.position, centre);
if (dist < nearestDist)
{
nearestDist = dist;
nearest = character;
}
}
return nearest;
}
/// <summary>
/// Who gets stung.
///
/// For a player swarm this is one line - BaseAI.IsEnemy - and it is the most valuable line in
/// the file: RaceHostilityManager is a postfix on that very method, so the Trenta's own
/// alliances (greyling, greydwarf, fuling, troll, leech, deathsquito) are honoured for free.
///
/// A grove has no Character to ask on its own behalf, so the rule is rebuilt from parts:
/// never players, never tamed, and only things carrying a MonsterAI - which is the cut that
/// spares wild deer and boar, since vanilla gives passive animals AnimalAI instead. And if
/// there is a Trenta standing inside the radius, IsEnemy is consulted against them too, so
/// the alliances come back the moment someone is there to carry them.
/// </summary>
private bool IsHostile(Character character)
{
if (character == null || character.IsDead()) return false;
if (character.IsPlayer()) return false;
if (character.IsTamed()) return false;
if (owner != null) return BaseAI.IsEnemy(owner, character);
if (character.GetComponent<MonsterAI>() == null) return false;
Player trenta = NearestTrenta();
return trenta == null || BaseAI.IsEnemy(trenta, character);
}
/// <summary>
/// The nearest Trenta inside the swarm's own radius, or null. Used both to borrow their
/// alliances and to attribute the sting - a hit with no attacker at all is what the old eitr
/// refinery's mystery damage looked like, and worth avoiding whenever there is a real one.
/// </summary>
private Player NearestTrenta()
{
Player nearest = null;
float nearestDist = float.MaxValue;
Vector3 centre = AnchorPosition;
foreach (Player player in Player.GetAllPlayers())
{
if (player == null || player.IsDead() || !TrentaVisuals.IsTrentaPlayer(player)) continue;
float dist = Vector3.Distance(player.transform.position, centre);
if (dist <= engageRadius && dist < nearestDist)
{
nearestDist = dist;
nearest = player;
}
}
return nearest;
}
/// <summary>
/// Two hits, matching "come se il giocatore fosse costantemente avvelenato dalle api, più
/// lo stesso danno ma perforante da sopra" literally: one Poison hit at the wild Bee
/// Nest's own numbers, and one Pierce hit of the same size, its direction pointed straight
/// down since the swarm is hovering above the target when it lands.
/// </summary>
private void Sting(Character victim)
{
// A grove's bees are still somebody's bees when a Trenta is standing under the tree;
// when nobody is, the sting lands with no attacker rather than picking one at random.
Character attacker = owner != null ? owner : NearestTrenta();
HitData poison = new HitData();
poison.m_damage.m_poison = TrentaConfig.HornetsNestDamagePerTick;
if (attacker != null) poison.SetAttacker(attacker);
poison.m_point = victim.GetCenterPoint();
poison.m_dir = Vector3.zero;
victim.Damage(poison);
HitData pierce = new HitData();
pierce.m_damage.m_pierce = TrentaConfig.HornetsNestDamagePerTick;
if (attacker != null) pierce.SetAttacker(attacker);
pierce.m_point = victim.GetCenterPoint();
pierce.m_dir = Vector3.down;
victim.Damage(pierce);
}
/// <summary>
/// Clones only the "flies" particle system off the Draugr prefab, discarding smoke and
/// drip - the exact filtering rule DraughRace.EnsureVFX already uses for its own aura, off
/// the same prefab, just keeping the opposite subset.
/// </summary>
private static void BuildFliesVfx(Transform parent)
{
GameObject draugrPrefab = PrefabManager.Cache.GetPrefab<GameObject>(TrentaConfig.HornetsNestFliesSourcePrefab);
if (draugrPrefab == null)
{
Jotunn.Logger.LogWarning($"[Trenta] Hornet's Nest: could not find VFX source prefab '{TrentaConfig.HornetsNestFliesSourcePrefab}'.");
return;
}
foreach (ParticleSystem ps in draugrPrefab.GetComponentsInChildren<ParticleSystem>(true))
{
if (!ps.main.loop) continue;
if (!ps.gameObject.name.ToLower().Contains("flies")) continue;
GameObject copy = Object.Instantiate(ps.gameObject, parent);
copy.name = ps.gameObject.name;
copy.SetActive(true);
copy.transform.localPosition = Vector3.zero;
copy.transform.localRotation = ps.transform.localRotation;
}
}
/// <summary>
/// Borrows only the AudioClip off the Beehive's ambient bee-swarm effect - read straight
/// off the prefab asset, never instantiated, so none of that effect's own visuals or
/// scripts ever come along with it.
/// </summary>
private static AudioSource BuildBuzzAudio(Transform parent)
{
AudioSource source = parent.gameObject.AddComponent<AudioSource>();
source.loop = true;
source.spatialBlend = 1f; // 3D - it should sound like it is coming from the swarm
source.volume = 0.6f;
// Resolved through TrentaConfig, which tries "piece_beehive" before "Beehive". This used
// to look up "Beehive" alone and got nothing, every time, which is why the swarm has been
// silent since it was written - found in the BepInEx log, not by listening.
Beehive beehive = TrentaConfig.FindVanillaBeehive();
GameObject beeEffect = beehive != null ? Traverse.Create(beehive).Field<GameObject>("m_beeEffect").Value : null;
AudioSource sourceClipHolder = beeEffect != null ? beeEffect.GetComponentInChildren<AudioSource>(true) : null;
if (sourceClipHolder != null && sourceClipHolder.clip != null)
{
source.clip = sourceClipHolder.clip;
}
else
{
Jotunn.Logger.LogWarning("[Trenta] Hornet's Nest: could not find a buzzing AudioClip on the Beehive's bee effect.");
}
return source;
}
}
}