RacesOfValheim/JotunnModStub/Alfar/AlfarPowers.cs
kanym db9aac2bf6 fix: Draugh Ashlands meats, rebindable flight keys, Geisli on gamepad
Draugh: add AsksvinMeat and BoneMawSerpentMeat to the shared raw-to-cooked
table; the Aswid blood refinery no longer adds them on its own copy.

DirectedFlight (drake, bat): read ZInput Forward/Backward/Run instead of
raw W, S and Shift, so keys rebound in the settings work.

Geisli: the pad has no free button in vanilla's Classic layout, so the
beam is held on the pad's secondary attack, bare-handed or in the
Archon form, as Skadi's Cold Spell does. The unarmed kick is swallowed
while it fires. RaceInput.EmptyHanded is shared with Skadi. Compendium
text mentions the pad in English, Italian and Russian.
2026-10-27 19:33:17 +01:00

644 lines
28 KiB
C#

using System.Collections.Generic;
using System.Linq;
using HarmonyLib;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The Alfar's powers (Alfar_Progettazione.txt sec. 13): caster tools, one per boss from Eikthyr.
///
/// Skrid Eikthyr blink
/// Grafvaettir Eikthyr mining drones thrown like a grenade (AlfarMiners)
/// Utsog Elder damage dealt returns as eitr (passive, below)
/// Kall Bonemass telekinesis
/// Ljosstorm Moder psionic storm on the ground
/// Geisli Yagluth continuous beam (hold the key)
/// Kyrr Queen stasis
/// Sameining Fader the archon (AlfarArchon)
///
/// Every power costs eitr from the SAME pool as the shield, which is the whole tension of the race
/// (doc sec. 4.4). Eitr is spent through AlfarEitr.Spend so the vanilla regeneration delay arms.
/// </summary>
public static class AlfarPowers
{
private static readonly Dictionary<string, float> cooldownUntil = new Dictionary<string, float>();
public static void ResetCooldowns(Player player)
{
cooldownUntil.Clear();
StopBeam();
AlfarArchon.ForceClear(player);
foreach (string id in AlfarStatusEffects.TimerIds) AlfarStatusEffects.ClearTimer(id);
}
private static bool Ready(string id) => !cooldownUntil.TryGetValue(id, out float until) || Time.time >= until;
private static void StartCooldown(string id, float seconds)
{
cooldownUntil[id] = Time.time + seconds;
AlfarStatusEffects.ShowTimer(id, seconds);
}
private static bool Unlocked(int need) => BossProgressionManager.GetCurrentProgressionState() >= need;
/// <summary>
/// The eitr a power costs: nothing for Ljosstorm and Geisli inside the archon form.
/// </summary>
private static float CostOf(float cost, bool freeInArchon) =>
freeInArchon && AlfarArchon.Active ? 0f : cost;
private static float CooldownOf(float cooldown, bool freeInArchon) =>
freeInArchon && AlfarArchon.Active ? AlfarArchon.FreePowerCooldown : cooldown;
/// <summary>Pays for a power, or says so and returns false.</summary>
private static bool Pay(Player player, float cost)
{
if (cost <= 0f) return true;
if (player.GetEitr() < cost)
{
player.Message(MessageHud.MessageType.Center, ModText.Get("rov_msg_alfar_no_eitr"));
return false;
}
AlfarEitr.Spend(player, cost);
return true;
}
// ─── The loop ────────────────────────────────────────────────────────
/// <summary>Called every frame for the LOCAL Alfr, from the Player.Update postfix.</summary>
public static void Tick(Player player)
{
AlfarArchon.Tick(player);
AlfarHeimkall.SyncIcon(player);
AlfarMiners.Tick(player);
TickBeam(player);
if (!RaceInput.Allowed || player.IsDead()) return;
if (Unlocked(AlfarPowerConfig.SkridState) && AlfarPowerConfig.SkridKey.Value.IsDownIgnoringHeldKeys()) Skrid(player);
if (Unlocked(AlfarPowerConfig.GrafvaettirState) && AlfarPowerConfig.GrafvaettirKey.Value.IsDownIgnoringHeldKeys()) AlfarMiners.Throw(player);
if (Unlocked(AlfarPowerConfig.KallState) && AlfarPowerConfig.KallKey.Value.IsDownIgnoringHeldKeys()) Kall(player);
if (Unlocked(AlfarPowerConfig.LjosstormState) && AlfarPowerConfig.LjosstormKey.Value.IsDownIgnoringHeldKeys()) Ljosstorm(player);
if (Unlocked(AlfarPowerConfig.KyrrState) && AlfarPowerConfig.KyrrKey.Value.IsDownIgnoringHeldKeys()) Kyrr(player);
if (Unlocked(AlfarPowerConfig.SameiningState) && AlfarPowerConfig.SameiningKey.Value.IsDownIgnoringHeldKeys()) AlfarArchon.TryActivate(player);
}
// ─── Aim ─────────────────────────────────────────────────────────────
private static Transform AimTransform(Player player)
{
return GameCamera.instance != null ? GameCamera.instance.transform : player.transform;
}
/// <summary>
/// What the crosshair is on: the first thing the ray hits that is not the Alfr, with the
/// character under it if there is one. Triggers are ignored. With nothing hit, the point is at
/// the end of the range.
/// </summary>
private static bool Aim(Player player, float range, out Vector3 point, out Character target)
{
Transform aim = AimTransform(player);
Vector3 origin = aim.position;
Vector3 direction = aim.forward;
target = null;
point = origin + direction * range;
RaycastHit[] hits = Physics.RaycastAll(origin, direction, range, ~0, QueryTriggerInteraction.Ignore);
System.Array.Sort(hits, (a, b) => a.distance.CompareTo(b.distance));
foreach (RaycastHit hit in hits)
{
if (hit.collider == null) continue;
if (hit.collider.GetComponentInParent<Player>() == player) continue;
point = hit.point;
target = hit.collider.GetComponentInParent<Character>();
return true;
}
return false;
}
private static bool IsHostile(Player player, Character other)
{
return other != null && other != player && !other.IsDead() && !other.IsTamed() &&
BaseAI.IsEnemy(player, other);
}
// ─── Damage ──────────────────────────────────────────────────────────
/// <summary>
/// One lightning strike on a character. Not blockable and not dodgeable: a power that can be
/// blocked is a weapon, and these are not.
/// </summary>
public static void Strike(Player attacker, Character target, float lightning, Vector3 point)
{
if (target == null || lightning <= 0f) return;
HitData hit = new HitData();
hit.m_damage.m_lightning = lightning;
hit.m_point = point;
hit.m_dir = (target.transform.position - attacker.transform.position).normalized;
hit.m_dodgeable = false;
hit.m_blockable = false;
hit.m_hitType = HitData.HitType.PlayerHit;
hit.SetAttacker(attacker);
target.Damage(hit);
}
/// <summary>A pulse of lightning on every hostile creature within a radius of the Alfr.</summary>
public static void Pulse(Player player, float radius, float damage)
{
foreach (Character character in CharactersIn(player.transform.position, radius))
{
if (IsHostile(player, character)) Strike(player, character, damage, character.GetCenterPoint());
}
}
private static IEnumerable<Character> CharactersIn(Vector3 center, float radius)
{
var seen = new HashSet<Character>();
foreach (Collider collider in Physics.OverlapSphere(center, radius, ~0, QueryTriggerInteraction.Ignore))
{
Character character = collider.GetComponentInParent<Character>();
if (character != null && seen.Add(character)) yield return character;
}
}
// ─── Skrid: blink ────────────────────────────────────────────────────
private static void Skrid(Player player)
{
if (!Ready("skrid")) return;
Transform aim = AimTransform(player);
Vector3 origin = player.transform.position + Vector3.up * 1.0f;
Vector3 direction = aim.forward;
float distance = AlfarPowerConfig.SkridDistance.Value;
if (!Pay(player, AlfarPowerConfig.SkridCost.Value)) return;
// Stop short of whatever is in the way, so the blink never ends inside a wall.
Vector3 destination = origin + direction * distance;
RaycastHit[] hits = Physics.RaycastAll(origin, direction, distance, ~0, QueryTriggerInteraction.Ignore);
float nearest = float.MaxValue;
foreach (RaycastHit hit in hits)
{
if (hit.collider.GetComponentInParent<Player>() == player) continue;
if (hit.distance < nearest)
{
nearest = hit.distance;
destination = hit.point - direction * 0.6f;
}
}
// Back down to the player's own height: the origin was at the chest.
destination.y -= 1.0f;
if (ZoneSystem.instance != null)
{
float ground = ZoneSystem.instance.GetSolidHeight(destination);
if (destination.y < ground) destination.y = ground + 0.1f;
}
Teleport(player, destination);
StartCooldown("skrid", AlfarPowerConfig.SkridCooldown.Value);
AlfarFx.Spawn("fx_JotunWitch_LightningBolt_Explosion", origin);
}
/// <summary>
/// Moves the body without the teleport fade: the rigidbody is repositioned and its velocity
/// zeroed, and the fall tracker is reset so a blink up a cliff does not count as a fall.
/// </summary>
private static void Teleport(Player player, Vector3 destination)
{
Rigidbody body = Traverse.Create(player).Field("m_body").GetValue<Rigidbody>();
player.transform.position = destination;
if (body != null)
{
body.position = destination;
body.linearVelocity = Vector3.zero;
}
Traverse.Create(player).Field("m_maxAirAltitude").SetValue(destination.y);
}
// ─── Utsog: damage dealt returns as eitr ─────────────────────────────
/// <summary>
/// After a blow lands on something that is not a player: if the local Alfr struck it, a share
/// of the damage comes back as eitr. Runs only where the victim is owned, which is here for
/// anything this client owns (singleplayer and the host in practice): a monster owned by
/// another client feeds no eitr. Known limit, doc sec. 17.
/// </summary>
[HarmonyPatch(typeof(Character), "ApplyDamage",
new[] { typeof(HitData), typeof(bool), typeof(bool), typeof(HitData.DamageModifier) })]
public static class Alfar_Utsog_Patch
{
public static void Postfix(Character __instance, HitData __0)
{
if (__instance == null || __0 == null || __instance is Player) return;
Player local = Player.m_localPlayer;
if (local == null || __0.GetAttacker() != local) return;
if (!AlfarVisuals.IsAlfarPlayer(local) || !Unlocked(AlfarPowerConfig.UtsogState)) return;
if (__instance.IsTamed()) return;
float returned = __0.GetTotalDamage() * AlfarPowerConfig.UtsogPercent.Value / 100f;
if (returned > 0f) local.AddEitr(returned);
}
}
// ─── Kall: telekinesis ───────────────────────────────────────────────
private static void Kall(Player player)
{
if (!Ready("kall")) return;
if (!Pay(player, AlfarPowerConfig.KallCost.Value)) return;
Vector3 target = player.GetCenterPoint();
int pulled = 0;
var seen = new HashSet<ItemDrop>();
foreach (Collider collider in Physics.OverlapSphere(player.transform.position, AlfarPowerConfig.KallRadius.Value,
~0, QueryTriggerInteraction.Ignore))
{
ItemDrop item = collider.GetComponentInParent<ItemDrop>();
if (item == null || !seen.Add(item)) continue;
Rigidbody body = item.GetComponent<Rigidbody>();
ZNetView nview = item.GetComponent<ZNetView>();
if (body == null || nview == null || !nview.IsValid()) continue;
// The item's physics belong to whoever owns it; take it so the pull is not undone.
nview.ClaimOwnership();
Vector3 direction = (target - item.transform.position).normalized;
body.WakeUp();
body.linearVelocity = direction * AlfarPowerConfig.KallSpeed.Value;
pulled++;
}
StartCooldown("kall", AlfarPowerConfig.KallCooldown.Value);
Jotunn.Logger.LogInfo($"[Alfar] Kall pulled {pulled} item(s).");
}
// ─── Ljosstorm: the psionic storm ────────────────────────────────────
private static void Ljosstorm(Player player)
{
if (!Ready("storm")) return;
float cost = CostOf(AlfarPowerConfig.StormCost.Value, true);
if (!Pay(player, cost)) return;
Aim(player, AlfarPowerConfig.StormRange.Value, out Vector3 point, out Character _);
GameObject storm = new GameObject("AlfarStorm");
storm.transform.position = point;
AlfarStormZone zone = storm.AddComponent<AlfarStormZone>();
zone.Owner = player;
zone.Radius = AlfarPowerConfig.StormRadius.Value;
zone.Seconds = AlfarPowerConfig.StormSeconds.Value;
zone.DamagePerSecond = AlfarPowerConfig.StormDps.Value;
StartCooldown("storm", CooldownOf(AlfarPowerConfig.StormCooldown.Value, true));
}
// ─── Geisli: the beam ────────────────────────────────────────────────
/// <summary>
/// The pad's way to hold the beam. Every pad button is taken in vanilla's Classic layout, so,
/// like Skadi's Cold Spell, the beam borrows the secondary attack: bare-handed, or in the
/// archon form, which has no weapons anyway. The radial entry only gives a single press,
/// which cannot hold a beam.
/// </summary>
private static bool PadBeamHeld(Player player) =>
!RaceInput.RadialOpen && RaceInput.PadAttackHeld(2) &&
(AlfarArchon.Active || RaceInput.EmptyHanded(player));
/// <summary>
/// Swallows the unarmed secondary (the kick) while the pad's secondary attack is the beam,
/// the same way SkadiAttackPatch does for the Cold Spell.
/// </summary>
[HarmonyPatch(typeof(Humanoid), "StartAttack")]
public static class Alfar_GeisliPadKick_Patch
{
public static bool Prefix(Humanoid __instance, bool secondaryAttack, ref bool __result)
{
if (!secondaryAttack || __instance != Player.m_localPlayer) return true;
Player player = (Player)__instance;
if (!AlfarVisuals.IsAlfarPlayer(player) || !Unlocked(AlfarPowerConfig.GeisliState)) return true;
if (!PadBeamHeld(player)) return true;
__result = false;
return false;
}
}
private static LineRenderer beamLine;
private static readonly List<LineRenderer> beamArcs = new List<LineRenderer>();
private static GameObject beamFx;
private static bool beamOn;
private static float beamStarted;
private static float beamNextTick;
private static float beamNextAnim;
private static float beamNextArcs;
/// <summary>
/// The beam leaves the RIGHT HAND, raised with the palm open: the borrowed "gpower" gesture (the
/// arms-raised cast the other races use too, with the real Guardian Power swallowed for a moment),
/// repeated while the key is held so the arm stays up. A quiet electric hum comes from the
/// vanilla lightning staff's charge effect hung on the hand, turned down, and a few jagged arcs
/// flicker round the line.
/// </summary>
private static void TickBeam(Player player)
{
bool wanted = RaceInput.Allowed && !player.IsDead() && Unlocked(AlfarPowerConfig.GeisliState) &&
(AlfarPowerConfig.GeisliKey.Value.IsPressedIgnoringHeldKeys() || PadBeamHeld(player));
if (!wanted)
{
if (beamOn) StopBeam(startCooldown: true);
return;
}
if (!beamOn)
{
if (!Ready("beam")) return;
if (player.GetEitr() <= 0f && !AlfarArchon.Active) { Pay(player, 1f); return; }
beamOn = true;
beamStarted = Time.time;
beamNextTick = Time.time;
beamNextAnim = 0f;
StartBeamFx(player);
}
if (Time.time - beamStarted > AlfarPowerConfig.BeamMaxSeconds.Value) { StopBeam(startCooldown: true); return; }
if (Time.time >= beamNextAnim)
{
beamNextAnim = Time.time + 1.6f;
RaiseHand(player);
}
Transform aim = AimTransform(player);
Transform hand = AlfarVisuals.RightHand(player);
Vector3 start = hand != null ? hand.position : player.GetEyePoint() + Vector3.down * 0.35f + aim.forward * 0.5f;
Aim(player, AlfarPowerConfig.BeamRange.Value, out Vector3 end, out Character target);
DrawBeam(start, end);
if (Time.time < beamNextTick) return;
const float tick = 0.2f;
beamNextTick = Time.time + tick;
float cost = CostOf(AlfarPowerConfig.BeamCostPerSecond.Value * tick, true);
if (cost > 0f)
{
if (player.GetEitr() < cost) { StopBeam(startCooldown: true); return; }
AlfarEitr.Spend(player, cost);
}
if (IsHostile(player, target)) Strike(player, target, AlfarPowerConfig.BeamDps.Value * tick, end);
}
private static void RaiseHand(Player player)
{
ZSyncAnimation animation = player.GetComponent<ZSyncAnimation>();
if (animation == null) return;
RaceInput.SuppressGuardianPowerBriefly(3f);
animation.SetTrigger("gpower");
}
private static void StartBeamFx(Player player)
{
Transform hand = AlfarVisuals.RightHand(player);
if (hand == null || ZNetScene.instance == null) return;
GameObject prefab = ZNetScene.instance.GetPrefab("fx_lightningstaff_charge");
if (prefab == null) return;
beamFx = Object.Instantiate(prefab, hand.position, hand.rotation, hand);
// Not too loud: a hum, not a thunderclap.
foreach (AudioSource source in beamFx.GetComponentsInChildren<AudioSource>(true))
{
source.volume *= 0.35f;
}
}
private static LineRenderer NewLine(string name, float width)
{
GameObject go = new GameObject(name);
LineRenderer line = go.AddComponent<LineRenderer>();
line.material = new Material(Shader.Find("Sprites/Default"));
line.startWidth = width;
line.endWidth = width * 0.5f;
line.useWorldSpace = true;
return line;
}
private static void DrawBeam(Vector3 start, Vector3 end)
{
Color color = AlfarPowerConfig.ArchonColor.Value;
if (beamLine == null)
{
beamLine = NewLine("AlfarBeam", 0.12f);
beamLine.positionCount = 2;
}
beamLine.startColor = color;
beamLine.endColor = new Color(color.r, color.g, color.b, 0.4f);
beamLine.SetPosition(0, start);
beamLine.SetPosition(1, end);
// A few jagged arcs round the line, redrawn about twenty times a second.
if (beamArcs.Count == 0)
{
for (int i = 0; i < 3; i++)
{
LineRenderer arc = NewLine("AlfarBeamArc" + i, 0.04f);
arc.positionCount = 9;
beamArcs.Add(arc);
}
}
if (Time.time >= beamNextArcs)
{
beamNextArcs = Time.time + 0.05f;
Vector3 direction = end - start;
foreach (LineRenderer arc in beamArcs)
{
arc.startColor = new Color(1f, 1f, 1f, 0.9f);
arc.endColor = new Color(color.r, color.g, color.b, 0.2f);
for (int i = 0; i < arc.positionCount; i++)
{
float t = i / (float)(arc.positionCount - 1);
Vector3 point = start + direction * t;
if (i > 0 && i < arc.positionCount - 1) point += Random.insideUnitSphere * 0.35f;
arc.SetPosition(i, point);
}
}
}
}
private static void StopBeam(bool startCooldown = false)
{
if (beamLine != null) { Object.Destroy(beamLine.gameObject); beamLine = null; }
foreach (LineRenderer arc in beamArcs) if (arc != null) Object.Destroy(arc.gameObject);
beamArcs.Clear();
if (beamFx != null) { Object.Destroy(beamFx); beamFx = null; }
if (beamOn && startCooldown) StartCooldown("beam", CooldownOf(AlfarPowerConfig.BeamCooldown.Value, true));
beamOn = false;
}
// ─── Kyrr: stasis ────────────────────────────────────────────────────
private static void Kyrr(Player player)
{
if (!Ready("kyrr")) return;
Transform aim = AimTransform(player);
Character best = null;
float bestDistance = float.MaxValue;
foreach (RaycastHit hit in Physics.SphereCastAll(aim.position, 0.8f, aim.forward,
AlfarPowerConfig.StasisRange.Value, ~0, QueryTriggerInteraction.Ignore))
{
Character character = hit.collider.GetComponentInParent<Character>();
if (!IsHostile(player, character) || hit.distance >= bestDistance) continue;
best = character;
bestDistance = hit.distance;
}
if (best == null) return;
if (!Pay(player, AlfarPowerConfig.StasisCost.Value)) return;
float seconds = best.IsBoss() ? AlfarPowerConfig.StasisBossSeconds.Value : AlfarPowerConfig.StasisSeconds.Value;
AlfarStasis.Apply(best, seconds);
StartCooldown("kyrr", AlfarPowerConfig.StasisCooldown.Value);
AlfarFx.Spawn("fx_JotunWitch_LightningBolt_Explosion", best.GetCenterPoint());
}
}
/// <summary>A storm on the ground that strikes every hostile creature inside it, twice a second.</summary>
public class AlfarStormZone : MonoBehaviour
{
public Player Owner;
public float Radius;
public float Seconds;
public float DamagePerSecond;
private float born;
private float nextTick;
private Light glow;
private void Start()
{
born = Time.time;
glow = gameObject.AddComponent<Light>();
glow.color = AlfarPowerConfig.ArchonColor.Value;
glow.range = Radius * 1.5f;
glow.intensity = 2f;
}
private void Update()
{
if (Owner == null || Time.time - born >= Seconds) { Destroy(gameObject); return; }
if (Time.time < nextTick) return;
const float tick = 0.5f;
nextTick = Time.time + tick;
foreach (Collider collider in Physics.OverlapSphere(transform.position, Radius, ~0, QueryTriggerInteraction.Ignore))
{
Character character = collider.GetComponentInParent<Character>();
if (character == null || character == Owner || character.IsDead() || character.IsTamed()) continue;
if (!BaseAI.IsEnemy(Owner, character)) continue;
AlfarPowers.Strike(Owner, character, DamagePerSecond * tick, character.GetCenterPoint());
}
Vector2 offset = Random.insideUnitCircle * Radius;
AlfarFx.Spawn("fx_JotunWitch_LightningBolt_Explosion", transform.position + new Vector3(offset.x, 0f, offset.y));
}
}
/// <summary>
/// Holds a creature still and untouchable for a few seconds (Kyrr). Frozen means the AI is off, the
/// animator stopped and the body locked; untouchable is the prefix at the bottom, which cancels
/// every blow on a creature that carries this. Everything is put back when it runs out.
/// </summary>
public class AlfarStasis : MonoBehaviour
{
private float until;
private Animator animator;
private float animatorSpeed;
private MonoBehaviour ai;
private Rigidbody body;
private RigidbodyConstraints constraints;
public static void Apply(Character target, float seconds)
{
AlfarStasis existing = target.GetComponent<AlfarStasis>();
if (existing != null) { existing.until = Time.time + seconds; return; }
ZNetView nview = target.GetComponent<ZNetView>();
if (nview != null && nview.IsValid()) nview.ClaimOwnership();
AlfarStasis stasis = target.gameObject.AddComponent<AlfarStasis>();
stasis.until = Time.time + seconds;
}
private void Awake()
{
animator = GetComponentInChildren<Animator>();
if (animator != null) { animatorSpeed = animator.speed; animator.speed = 0f; }
ai = GetComponent<BaseAI>();
if (ai != null) ai.enabled = false;
body = GetComponent<Rigidbody>();
if (body != null)
{
constraints = body.constraints;
body.linearVelocity = Vector3.zero;
body.constraints = RigidbodyConstraints.FreezeAll;
}
}
private void Update()
{
if (Time.time >= until) Destroy(this);
}
private void OnDestroy()
{
if (animator != null) animator.speed = animatorSpeed;
if (ai != null) ai.enabled = true;
if (body != null) body.constraints = constraints;
}
[HarmonyPatch(typeof(Character), "ApplyDamage",
new[] { typeof(HitData), typeof(bool), typeof(bool), typeof(HitData.DamageModifier) })]
public static class Alfar_Stasis_Patch
{
public static void Prefix(Character __instance, HitData __0)
{
if (__0 != null && __instance != null && __instance.GetComponent<AlfarStasis>() != null)
{
__0.m_damage = default(HitData.DamageTypes);
}
}
}
}
/// <summary>Spawns a vanilla effect prefab by name, and says nothing if the name is not there.</summary>
public static class AlfarFx
{
public static void Spawn(string prefabName, Vector3 position)
{
if (ZNetScene.instance == null) return;
GameObject prefab = ZNetScene.instance.GetPrefab(prefabName);
if (prefab == null) return;
Object.Instantiate(prefab, position, Quaternion.identity);
}
}
}