RacesOfValheim/JotunnModStub/Alfar/AlfarHeimkall.cs
Ferdinando 3f8cf1ee27 feat(alfar): v1.6.0 - the Alfar, an eleventh race
Grey, tall and thin, with black eyes. Eitr is armour and fuel (shield,
diet, soft fall, levitation), Heimkall sends a lethal blow home at one
health every 20 minutes. Caster powers from Skrid to the archon
Sameining, with on-screen cooldowns. Automated base around the
Ljoskjarne: drones, three constructs, crystals, Ljosgard, Prismavard.
Compendium page in EN/IT/RU.

README: New in block, race section, progression, station line, changelog.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-25 17:38:28 +01:00

171 lines
8.5 KiB
C#

using System.Globalization;
using HarmonyLib;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// HEIMKALL: a lethal blow does not kill an Alfr, it sends them to their bed with one hit point
/// (Alfar_Progettazione.txt sec. 6). Then a wait: 20 minutes, 15 after Yagluth, 10 after Fader.
/// Inside the wait a lethal blow kills like it does anyone.
///
/// HOW IT AVOIDS DEATH (read from the IL, doc sec. 16B V5):
/// Character.ApplyDamage ends with the health at zero, and the death itself is not decided
/// there but in Character.CheckDeath, which Character.CustomFixedUpdate calls on its next step.
/// So a POSTFIX on ApplyDamage that puts one hit point back, the same frame, means the check
/// finds a living body and there is no death routine, no tomb, no skill loss, no message.
///
/// The timer lives in m_customData as a world-time stamp, so it survives a logout.
/// </summary>
public static class AlfarHeimkall
{
private const string TimerKey = "Alfar_HeimkallAt";
/// <summary>Time.time until which nothing may hurt the local Alfr (the arrival grace).</summary>
public static float InvulnerableUntil;
// ─── The timer ───────────────────────────────────────────────────────
/// <summary>The cooldown for the current boss progress, in seconds.</summary>
public static float CooldownSeconds()
{
int state = BossProgressionManager.GetCurrentProgressionState();
float minutes = state >= 8 ? AlfarConfig.HeimkallMinutesAfterFader.Value
: state >= 6 ? AlfarConfig.HeimkallMinutesAfterYagluth.Value
: AlfarConfig.HeimkallMinutes.Value;
return minutes * 60f;
}
/// <summary>Seconds left before the next Heimkall; 0 when it is ready.</summary>
public static float Remaining(Player player)
{
if (player == null || player.m_customData == null || ZNet.instance == null) return 0f;
if (!player.m_customData.TryGetValue(TimerKey, out string stamp)) return 0f;
if (!double.TryParse(stamp, NumberStyles.Float, CultureInfo.InvariantCulture, out double at)) return 0f;
double elapsed = ZNet.instance.GetTimeSeconds() - at;
// A stamp from a different world (its clock is another clock) reads as the future, or as
// a wait longer than any cooldown. Either way the timer is not this world's: ready.
float cooldown = CooldownSeconds();
if (elapsed < 0d || elapsed > 1e9) return 0f;
return Mathf.Max(0f, cooldown - (float)elapsed);
}
public static bool IsReady(Player player) => Remaining(player) <= 0f;
public static void StartTimer(Player player)
{
if (player == null || ZNet.instance == null) return;
player.m_customData[TimerKey] =
ZNet.instance.GetTimeSeconds().ToString("R", CultureInfo.InvariantCulture);
}
public static void ResetTimer(Player player)
{
if (player != null && player.m_customData != null) player.m_customData.Remove(TimerKey);
AlfarStatusEffects.ClearTimer("heimkall");
}
private static float nextIconSync;
/// <summary>
/// Keeps the on-screen Heimkall countdown honest: status effects are not saved, so after a
/// reload the wait is put back on screen with what is really left of it, and removed when over.
/// </summary>
public static void SyncIcon(Player player)
{
if (Time.time < nextIconSync) return;
nextIconSync = Time.time + 2f;
float left = Remaining(player);
bool shown = AlfarStatusEffects.HasTimer("heimkall");
if (left > 0f && !shown) AlfarStatusEffects.ShowTimer("heimkall", left);
else if (left <= 0f && shown) AlfarStatusEffects.ClearTimer("heimkall");
}
// ─── The call home ───────────────────────────────────────────────────
/// <summary>
/// Teleports to the bed (or the world spawn when there is none) at one hit point, clears what
/// was killing the body, and starts the wait. Returns false when it is not ready.
/// </summary>
public static bool TryTrigger(Player player, string reason, bool force = false)
{
// force: the archon form ends with a Heimkall that it already paid for at the start.
if (player == null || (!force && !IsReady(player))) return false;
bool bed;
Vector3 destination = FindDestination(out bed);
// distantTeleport tells Valheim to stream the destination zone in first. Anything past a
// couple of zone-widths needs it.
bool distant = Vector3.Distance(player.transform.position, destination) > 100f;
bool teleported = player.TeleportTo(destination, player.transform.rotation, distant);
// Whether or not the teleport was accepted (it refuses for two seconds after another
// one), the body must not die this frame.
player.SetHealth(1f);
// What was killing the body goes with it: burning, poison, the cold, being wet. Cleared
// before the passive is put back, since RemoveAll takes that too.
player.GetSEMan().RemoveAllStatusEffects(true);
AlfarStatusEffects.Ensure(player);
InvulnerableUntil = Time.time + AlfarConfig.HeimkallInvulnerableSeconds.Value;
StartTimer(player);
AlfarStatusEffects.ShowTimer("heimkall", CooldownSeconds());
Jotunn.Logger.LogInfo($"[Alfar] Heimkall ({reason}): teleported={teleported} to {destination}; " +
$"next in {CooldownSeconds() / 60f:0} min.");
player.Message(MessageHud.MessageType.Center, ModText.Get(bed ? "rov_msg_alfar_heimkall" : "rov_msg_alfar_heimkall_nobed"));
return true;
}
/// <summary>
/// The bed the player set, else the world's original spawn. A bed point already has its height;
/// the world spawn is stored with a placeholder height (50), so its ground is worked out from the
/// world generator, which answers even when the zone there is not loaded yet - the first version
/// stood the Alfr at 50.5 m in the air or inside a hill. A bed counts only after the player has
/// SET it (sleeping in it, or interacting with it); an unused bed is not a spawn point.
/// </summary>
private static Vector3 FindDestination(out bool bed)
{
PlayerProfile profile = Game.instance != null ? Game.instance.GetPlayerProfile() : null;
bed = profile != null && profile.HaveCustomSpawnPoint();
if (bed) return profile.GetCustomSpawnPoint() + Vector3.up * 0.5f;
Vector3 point = PlayerProfile.m_originalSpawnPoint;
if (WorldGenerator.instance != null)
{
float ground = WorldGenerator.instance.GetHeight(point.x, point.z);
point.y = Mathf.Max(ground, 30f) + 1f; // 30 is the sea level: never under the water
}
return point;
}
// ─── The patch ───────────────────────────────────────────────────────
/// <summary>
/// After the blow has landed: if it left the body at zero, call it home instead. The shield
/// prefix has already taken what it could, so this only fires for the blow the eitr could
/// not cover (or a fall at eitr zero, a drowning, the edge of the world).
/// </summary>
[HarmonyPatch(typeof(Character), "ApplyDamage",
new[] { typeof(HitData), typeof(bool), typeof(bool), typeof(HitData.DamageModifier) })]
public static class Alfar_Heimkall_Patch
{
public static void Postfix(Character __instance)
{
Player player = __instance as Player;
if (player == null || player != Player.m_localPlayer) return;
if (!AlfarVisuals.IsAlfarPlayer(player)) return;
if (player.IsDead() || player.GetHealth() > 0f) return;
TryTrigger(player, "lethal blow");
}
}
}
}