RacesOfValheim/JotunnModStub/Sverm/SvermStingerForm.cs
2026-08-11 16:30:20 +02:00

375 lines
16 KiB
C#

using HarmonyLib;
using Jotunn.Managers;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// Stinger Morph: from Yagluth on, a Sverm can become a Deathsquito for two minutes.
///
/// It is the one thing in the race that is not armour. Everything else the Sverm has says
/// "stand there and survive"; this says the opposite, and it is deliberate that the two do not
/// overlap - in form there is no carapace, no claws, no inventory and no hammer, only a needle
/// and the ability to leave. A glass cannon that flies is the role the tank was missing.
///
/// Built on two things that already work: BatFormBehavior for flight (Valheim's own
/// m_debugFly, held on every frame) and PlayerVisualHider for swapping the body out. The
/// duration and cooldown follow FenrirProgression.FormRules' shape - a timer and a status
/// effect the HUD can count down - without borrowing that race's tables.
/// </summary>
public static class SvermStingerForm
{
public static bool IsActive { get; private set; }
private static GameObject model;
private static float expiresAt;
private static float nextAllowedAt;
private static HitData.DamageTypes stingerDamage;
private static bool stingerDamageRead;
// ─── Driver ──────────────────────────────────────────────────────────
public static void Tick(Player player)
{
if (player == null || player != Player.m_localPlayer)
{
return;
}
// Death ends it immediately, and so does ceasing to be a Sverm. Both leave a body
// hidden and a bug that is very hard to read, so they are checked before anything else.
if (IsActive && (player.IsDead() || !SvermVisuals.IsSvermPlayer(player)))
{
Exit(player, spendCooldown: false);
return;
}
if (IsActive && Time.time >= expiresAt)
{
Exit(player, spendCooldown: true);
player.Message(MessageHud.MessageType.Center, "The wings fold away.");
return;
}
if (!SvermConfigManagement.StingerKey.Value.IsDown()) return;
if (!SvermVisuals.IsSvermPlayer(player)) return;
if (IsActive)
{
Exit(player, spendCooldown: true);
return;
}
if (!SvermProgression.Current.StingerMorph)
{
player.Message(MessageHud.MessageType.Center, "Your wings are still vestigial.");
return;
}
if (Time.time < nextAllowedAt)
{
player.Message(MessageHud.MessageType.Center, "The wings are spent.");
return;
}
Enter(player);
}
// ─── Enter and leave ─────────────────────────────────────────────────
private static void Enter(Player player)
{
// THE CLAWS STAY ON, and everything else comes off.
//
// The first version emptied the hands completely and the form could not attack: with
// nothing equipped there is no weapon to swing, and Valheim's bare fist is not the
// thing this form is supposed to be throwing. Leaving the Maulclaws equipped makes the
// sting an ordinary weapon attack - which works - and costs nothing visually, because
// the whole body is hidden a line later. Fist weapons report Skills.SkillType.Unarmed,
// so the damage patch still recognises the blow and swaps the deathsquito's figure in.
ItemDrop.ItemData held = Traverse.Create((Humanoid)player).Field<ItemDrop.ItemData>("m_rightItem").Value;
if (held != null && !SvermClawSlot.IsClaws(held))
{
player.UnequipItem(held, false);
SvermClawSlot.Maintain(player); // hands back the claws in its place
}
IsActive = true;
expiresAt = Time.time + SvermConfig.StingerDurationSeconds;
player.GetSEMan().AddStatusEffect(SvermConfig.StingerSE.GetStableHashCode(), true);
Transform visual = player.transform.Find("Visual");
PlayerVisualHider.Hide(visual, "sverm-stinger");
GameObject source = PrefabManager.Cache.GetPrefab<GameObject>(SvermConfig.StingerCreature);
GameObject animated = source != null ? source.GetComponentInChildren<Animator>()?.gameObject : null;
if (animated != null)
{
model = Object.Instantiate(animated, player.transform.position, player.transform.rotation, player.transform);
model.transform.localPosition = Vector3.zero;
// SCALE COMES FROM THE SOURCE, not from 1.
//
// Forcing Vector3.one is what the Aswid does for the bat and it happens to be
// right there, because a bat's animated child is authored at 1. A deathsquito's is
// not - forcing 1 blew it up to something the size of a house. Keeping the source's
// own scale means the model arrives the size the game draws it, and the multiplier
// is there only for taste.
model.transform.localScale = animated.transform.localScale * SvermConfigManagement.StingerScale;
// AND IT FACES THE WRONG WAY without this. The creature's own forward is not the
// player's, so the model arrived looking back at the camera. Which way to turn it
// is a thing only an eye can settle, so it is a config value and not a constant.
model.transform.localRotation = Quaternion.Euler(0f, SvermConfigManagement.StingerYaw, 0f);
model.AddComponent<StingerFormBehavior>();
}
else
{
// No model is survivable - you fly as an invisible insect - but it is worth saying
// out loud rather than leaving someone to wonder why they turned into nothing.
Jotunn.Logger.LogWarning($"[Sverm] No '{SvermConfig.StingerCreature}' model to wear; " +
"Stinger Morph flies without a body.");
GameObject bare = new GameObject("SvermStingerFlight");
bare.transform.SetParent(player.transform, false);
bare.AddComponent<StingerFormBehavior>();
model = bare;
}
PlayEffect(SvermConfig.MorphInEffects, player.transform.position);
SummonEscort(player);
player.Message(MessageHud.MessageType.Center, "You take to the air.");
}
/// <summary>
/// Two deathsquitoes, tamed, that outlive the form by a minute.
///
/// They are NOT tied to the form's lifetime and that is the point: the form ends where it
/// ends, usually mid-air, and the player becomes a slow armoured thing halfway through a
/// fall. The escort covers exactly that minute and then dies on its own.
///
/// Tamed rather than merely friendly, because tamed is the one state every part of the
/// game already understands - they will not be attacked by the player, they will not
/// attack the player, and BaseAI already knows to fight what fights them.
/// </summary>
private static void SummonEscort(Player player)
{
GameObject prefab = PrefabManager.Cache.GetPrefab<GameObject>(SvermConfig.StingerCreature);
if (prefab == null) return;
for (int i = 0; i < SvermConfig.EscortCount; i++)
{
// Spread them apart, and above: spawning two creatures inside each other and
// inside the player is how you get three things shoved through the floor.
float angle = 360f / Mathf.Max(1, SvermConfig.EscortCount) * i;
Vector3 offset = Quaternion.Euler(0f, angle, 0f) * Vector3.forward * SvermConfig.EscortSpawnSpread;
Vector3 where = player.transform.position + offset + Vector3.up * 1.5f;
GameObject spawned = Object.Instantiate(prefab, where, Quaternion.identity);
if (spawned == null) continue;
Character character = spawned.GetComponent<Character>();
if (character != null) character.SetTamed(true);
// Nothing to farm: an escort that dropped trophies would be a deathsquito printer
// on an eight minute cooldown. Same reasoning as the thralls' stripped drop tables.
CharacterDrop drop = spawned.GetComponent<CharacterDrop>();
if (drop != null) Object.Destroy(drop);
spawned.AddComponent<SvermEscortLife>().Expires = Time.time + SvermConfig.EscortLifetimeSeconds;
}
}
private static void PlayEffect(string[] candidates, Vector3 where)
{
foreach (string name in candidates)
{
GameObject fx = PrefabManager.Cache.GetPrefab<GameObject>(name);
if (fx == null) continue;
Object.Instantiate(fx, where, Quaternion.identity);
return;
}
}
private static void Exit(Player player, bool spendCooldown)
{
IsActive = false;
PlayEffect(SvermConfig.MorphOutEffects, player.transform.position);
// The escort is deliberately NOT dismissed here. It has its own minute left to run.
if (model != null)
{
Object.Destroy(model);
model = null;
}
player.GetSEMan().RemoveStatusEffect(SvermConfig.StingerSE.GetStableHashCode());
Transform visual = player.transform.Find("Visual");
PlayerVisualHider.Show(visual, "sverm-stinger-revert");
if (spendCooldown)
{
nextAllowedAt = Time.time + SvermConfig.StingerCooldownSeconds;
player.GetSEMan().AddStatusEffect(SvermConfig.StingerCdSE.GetStableHashCode(), true);
}
}
// ─── The sting ───────────────────────────────────────────────────────
/// <summary>
/// The Deathsquito's own damage, read off the creature rather than invented.
///
/// Vanilla's deathsquito hits harder per blow than anything else in the Plains, and that
/// number is the entire reason the form is worth its cooldown. Reading it means the form
/// tracks whatever the game says a deathsquito is worth, forever.
/// </summary>
public static HitData.DamageTypes GetStingDamage()
{
if (stingerDamageRead) return stingerDamage;
GameObject creature = PrefabManager.Cache.GetPrefab<GameObject>(SvermConfig.StingerCreature);
Humanoid humanoid = creature != null ? creature.GetComponent<Humanoid>() : null;
if (humanoid != null && humanoid.m_defaultItems != null)
{
foreach (GameObject weapon in humanoid.m_defaultItems)
{
ItemDrop drop = weapon != null ? weapon.GetComponent<ItemDrop>() : null;
if (drop == null || drop.m_itemData == null || drop.m_itemData.m_shared == null) continue;
stingerDamage = drop.m_itemData.m_shared.m_damages;
stingerDamageRead = true;
Jotunn.Logger.LogInfo($"[Sverm] Stinger reads {stingerDamage.m_pierce:0.#} pierce " +
$"off '{weapon.name}'.");
return stingerDamage;
}
}
Jotunn.Logger.LogWarning($"[Sverm] Could not read a weapon off '{SvermConfig.StingerCreature}'; " +
"the sting falls back to the Maulclaws.");
stingerDamageRead = true;
return stingerDamage; // all zeroes: the damage patch then leaves the claw values alone
}
// ─── What the form may not do ────────────────────────────────────────
/// <summary>
/// No weapons in form, which also means no hammer - so "cannot build" needs no patch of
/// its own, it falls out of having nothing to build with.
/// </summary>
[HarmonyPatch(typeof(Humanoid), nameof(Humanoid.EquipItem))]
public static class Sverm_StingerEquip_Patch
{
public static bool Prefix(Humanoid __instance, ItemDrop.ItemData item, ref bool __result)
{
if (!IsActive) return true;
Player player = __instance as Player;
if (player == null || player != Player.m_localPlayer) return true;
// The claws are the exception, and they have to be: they are what the form
// attacks with, and SvermClawSlot.Maintain hands them back whenever the hands go
// empty. Refusing them here would fight that loop every half second.
if (SvermClawSlot.IsClaws(item)) return true;
player.Message(MessageHud.MessageType.Center, "An insect carries nothing.");
__result = false;
return false;
}
}
/// <summary>No food, no mead, no potions. The form is meant to be survived, not sustained.</summary>
[HarmonyPatch(typeof(Humanoid), "UseItem")]
public static class Sverm_StingerUseItem_Patch
{
public static bool Prefix(Humanoid __instance)
{
if (!IsActive) return true;
return !(__instance is Player player) || player != Player.m_localPlayer;
}
}
}
/// <summary>
/// An escort deathsquito's own clock.
///
/// It dies rather than vanishing - Character.Damage with enough to finish it - so the death
/// plays its effects and reads as the summon running out rather than as a creature popping out
/// of existence. The drop table was stripped at spawn, so dying costs the world nothing.
/// </summary>
public class SvermEscortLife : MonoBehaviour
{
public float Expires;
private void Update()
{
if (Time.time < Expires) return;
Character character = GetComponent<Character>();
if (character == null || character.IsDead())
{
Destroy(gameObject);
return;
}
HitData hit = new HitData();
hit.m_damage.m_damage = character.GetMaxHealth() * 10f;
hit.m_point = character.GetCenterPoint();
character.Damage(hit);
enabled = false; // the death takes a moment; do not queue another blow every frame
}
}
/// <summary>
/// Flight, held on every frame.
///
/// m_debugFly is Valheim's own free-flight switch and it is re-asserted every Update rather
/// than set once, because plenty of things in the game turn it back off - the same reason
/// BatFormBehavior does it that way. OnDestroy putting it back is what stops a Sverm from
/// walking on air after the form ends.
/// </summary>
public class StingerFormBehavior : MonoBehaviour
{
private Animator anim;
private void Start()
{
anim = GetComponentInChildren<Animator>();
SetFly(true);
}
private void Update()
{
if (Player.m_localPlayer == null || Player.m_localPlayer.IsDead()) return;
SetFly(true);
if (anim == null) return;
Vector3 velocity = Player.m_localPlayer.GetVelocity();
velocity.y = 0f;
anim.SetFloat("forward_speed", velocity.magnitude);
anim.SetBool("flying", true);
}
private void OnDestroy()
{
SetFly(false);
}
private static void SetFly(bool on)
{
if (Player.m_localPlayer == null) return;
Traverse.Create(Player.m_localPlayer).Field("m_debugFly").SetValue(on);
}
}
}