RacesOfValheim/JotunnModStub/Aswid/AswidRace.cs
Ferdinando a29b7e54b4 fix(aswid): make the Vampiric Aura land, and run it passively in every form
The aura dealt its damage through Character.ApplyDamage, which only edits
the local copy of a character. On anything we do not own - in multiplayer
that is most mobs - the owner overwrote the health change on the next sync,
so the aura neither hurt anything nor showed anything. It also bypassed our
own Character.Damage patches, which is why it never healed and never
triggered devour-on-kill despite being the *vampiric* aura. It now calls
Character.Damage, which routes RPC_Damage to whoever owns the target, and
sets m_dir so the target reacts to the hit.

The aura no longer has to be channelled by holding block in bat or mist
form. It ticks on its own in every form, with no key to hold and no icon or
message of its own; the form only decides how hard it bites - half damage
as a human, full as a bat, double as mist.

Also guarded the sunrise mist auto-revert with isTransformingSequence.
Without it the revert re-triggered on every frame of its own one-second
animation, stacking coroutines that fought over the same visuals and status
effect.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-04 11:04:41 +02:00

1050 lines
44 KiB
C#

using HarmonyLib;
using System;
using UnityEngine;
using System.Collections.Generic;
namespace RacesOfValheim
{
public class AswidRace : MonoBehaviour
{
public static AswidRace Instance { get; private set; }
private static Dictionary<string, string> mobToTrophyMap = new Dictionary<string, string>
{
{ "Boar", "TrophyBoar" },
{ "Greyling", "TrophyGreyling" },
{ "Neck", "TrophyNeck" },
{ "Greydwarf", "TrophyGreydwarf" },
{ "Greydwarf_Elite", "TrophyGreydwarfBrute" },
{ "Greydwarf_Shaman", "TrophyGreydwarfShaman" },
{ "Troll", "TrophyFrostTroll" },
{ "Deer", "TrophyDeer" },
{ "Wolf", "TrophyWolf" },
{ "Fenring", "TrophyFenring" },
{ "Leech", "TrophyLeech" },
{ "Hatchling", "TrophyHatchling" },
{ "Lox", "TrophyLox" },
{ "Fuling", "TrophyGoblin" },
{ "FulingShaman", "TrophyGoblinShaman" },
{ "FulingBerserker", "TrophyGoblinBrute" },
{ "Deathsquito", "TrophyDeathsquito" },
{ "Hare", "TrophyHare" },
{ "Seeker", "TrophySeeker" },
{ "SeekerBrood", "TrophySeekerBrood" },
{ "SeekerBrute", "TrophySeekerBrute" },
{ "Gjall", "TrophyGjall" },
{ "Tick", "TrophyTick" },
{ "Ulv", "TrophyUlv" },
{ "Cultist", "TrophyCultist" },
{ "Asksvin", "TrophyAsksvin" },
{ "Volture", "TrophyVolture" }
};
private static Dictionary<string, string> mobToFoodMap = new Dictionary<string, string>
{
{ "Boar", "CookedMeat" },
{ "Neck", "NeckTailGrilled" },
{ "Deer", "CookedDeerMeat" },
{ "Wolf", "CookedWolfMeat" },
{ "Lox", "CookedLoxMeat" },
{ "Hare", "CookedHareMeat" },
{ "Asksvin", "CookedAsksvinMeat" },
{ "Volture", "CookedVoltureMeat" },
{ "Tick", "BloodPudding" },
{ "Deathsquito", "BloodPudding" },
{ "Leech", "BloodPudding" },
{ "Ulv", "BloodPudding" },
{ "Seeker", "CookedBugMeat" },
{ "SeekerBrute", "CookedBugMeat" },
{ "SeekerBrood", "CookedBugMeat" },
{ "Surtling", "BloodPudding" },
{ "Bear", "CookedBearMeat" }
};
public static bool BypassAswidFoodCheck = false;
private float lastEclipseTime = -900f; // 15 mins cooldown (900 seconds)
public bool IsEclipseActive { get; private set; } = false;
private float updateTimer = 0f;
private const float UpdateInterval = 1f;
public bool IsTransformed { get; private set; } = false;
private bool isTransformingSequence = false;
private GameObject currentTransformation;
private GameObject mistTransformation;
private AswidProgression.FormRules activeRules = null;
private void Awake()
{
Instance = this;
}
public void CreateModAssets()
{
AswidStatusEffects.RegisterStatusEffects();
CreateFoodItems();
GameObject geirrhafa = Jotunn.Managers.PrefabManager.Cache.GetPrefab<GameObject>("Fenring_Cultist_Hildir");
if (geirrhafa != null)
{
Jotunn.Logger.LogInfo("[Aswid] GEIRRHAFA DUMP:");
foreach (var smr in geirrhafa.GetComponentsInChildren<SkinnedMeshRenderer>(true))
{
Jotunn.Logger.LogInfo($"[Aswid] SMR: {smr.name}, RootBone: {(smr.rootBone ? smr.rootBone.name : "none")}, Bones: {smr.bones.Length}");
}
}
}
private void CreateFoodItems()
{
foreach (var kvp in mobToTrophyMap)
{
string mobName = kvp.Key;
string trophyName = kvp.Value;
string foodName = "AswidFood_" + mobName;
Jotunn.Configs.ItemConfig config = new Jotunn.Configs.ItemConfig();
config.Name = "Aswid Food: " + mobName;
config.Description = "The life force of the conquered.";
Jotunn.Entities.CustomItem customItem = null;
if (mobToFoodMap.TryGetValue(mobName, out string baseFoodPrefab))
{
customItem = new Jotunn.Entities.CustomItem(foodName, baseFoodPrefab, config);
// If Jotunn failed to clone because the base prefab doesn't exist, ItemDrop will be null
if (customItem == null || customItem.ItemDrop == null)
{
Jotunn.Logger.LogWarning($"[Aswid] Failed to clone base prefab '{baseFoodPrefab}' for {foodName}. Falling back to 'CookedMeat'.");
customItem = new Jotunn.Entities.CustomItem(foodName, "CookedMeat", config);
}
}
else
{
customItem = new Jotunn.Entities.CustomItem(foodName, "CookedMeat", config);
}
if (customItem != null && customItem.ItemDrop != null)
{
if (!mobToFoodMap.ContainsKey(mobName))
{
GameObject mobPrefab = Jotunn.Managers.PrefabManager.Cache.GetPrefab<GameObject>(mobName);
if (mobPrefab != null)
{
Character c = mobPrefab.GetComponent<Character>();
if (c != null)
{
float foodHp = Mathf.Min(c.m_health / 2f, 150f);
float burnTime = c.m_health * 2f;
if (mobName == "Cultist" || mobName.StartsWith("Fenring") || mobName.StartsWith("Fuling"))
{
burnTime = 1200f; // 20 minutes
}
else if (mobName == "Greyling") { foodHp = 20f; burnTime = 1200f; }
else if (mobName == "Greydwarf") { foodHp = 25f; burnTime = 1200f; }
else if (mobName == "Greydwarf_Shaman") { foodHp = 30f; burnTime = 1200f; }
else if (mobName == "Greydwarf_Elite") { foodHp = 60f; burnTime = 1800f; }
customItem.ItemDrop.m_itemData.m_shared.m_food = foodHp;
customItem.ItemDrop.m_itemData.m_shared.m_foodStamina = 0f;
customItem.ItemDrop.m_itemData.m_shared.m_foodEitr = 0f;
customItem.ItemDrop.m_itemData.m_shared.m_foodBurnTime = burnTime;
customItem.ItemDrop.m_itemData.m_shared.m_foodRegen = Mathf.Max(1f, foodHp / 15f);
}
}
}
GameObject trophyPrefab = Jotunn.Managers.PrefabManager.Cache.GetPrefab<GameObject>(trophyName);
if (trophyPrefab != null)
{
ItemDrop trophyDrop = trophyPrefab.GetComponent<ItemDrop>();
if (trophyDrop != null)
{
customItem.ItemDrop.m_itemData.m_shared.m_icons = trophyDrop.m_itemData.m_shared.m_icons;
}
}
Jotunn.Managers.ItemManager.Instance.AddItem(customItem);
}
}
}
private float m_tintCheckTimer = 0f;
private float sensesCheckTimer = 0f;
private Dictionary<Character, GameObject> activeSensesLight = new Dictionary<Character, GameObject>();
public static float GetEnslaveCooldown()
{
if (Player.m_localPlayer == null) return 0f;
string timeStr;
if (Player.m_localPlayer.m_customData.TryGetValue("AswidEnslaveTime", out timeStr))
{
if (long.TryParse(timeStr, out long ticks))
{
DateTime lastTime = new DateTime(ticks);
float elapsed = (float)(DateTime.Now - lastTime).TotalSeconds;
float cooldown = (15f * 60f) - elapsed;
return Mathf.Max(0f, cooldown);
}
}
return 0f;
}
public static void StartEnslaveCooldown()
{
if (Player.m_localPlayer != null)
{
Player.m_localPlayer.m_customData["AswidEnslaveTime"] = DateTime.Now.Ticks.ToString();
}
}
private void UpdateSuperhumanSenses()
{
try
{
int state = BossProgressionManager.GetCurrentProgressionState();
var seman = Player.m_localPlayer.GetSEMan();
int myHash = "SE_SuperhumanSenses".GetStableHashCode();
bool hasBuff = seman.HaveStatusEffect(myHash);
if (state < 5)
{
if (hasBuff)
{
seman.RemoveStatusEffect(myHash);
}
return;
}
if (!hasBuff)
{
seman.AddStatusEffect(myHash, true);
}
sensesCheckTimer -= Time.deltaTime;
if (sensesCheckTimer <= 0f)
{
sensesCheckTimer = 1.0f; // Refresh every 1 second (TTL is 2s)
List<Character> allChars = Character.GetAllCharacters();
Vector3 myPos = Player.m_localPlayer.transform.position;
int markHash = "SE_AswidSensesMark".GetStableHashCode();
HashSet<Character> inRangeChars = new HashSet<Character>();
foreach (var c in allChars)
{
if (c == null || c == Player.m_localPlayer || c.IsDead() || c.IsTamed()) continue;
float dist = Vector3.Distance(c.transform.position, myPos);
if (dist <= 100f) // 100 meters detection radius
{
try
{
inRangeChars.Add(c);
c.GetSEMan().AddStatusEffect(markHash, true); // Keep the malus as requested
// Locally generate the visual
if (!activeSensesLight.ContainsKey(c))
{
GameObject lightObj = new GameObject("AswidSensesLight");
lightObj.transform.SetParent(c.transform);
lightObj.transform.position = c.GetCenterPoint();
Light pLight = lightObj.AddComponent<Light>();
pLight.type = LightType.Point;
pLight.color = Color.green;
pLight.range = 10f;
pLight.intensity = 2f;
pLight.shadows = LightShadows.None;
activeSensesLight[c] = lightObj;
}
}
catch (Exception ex)
{
Jotunn.Logger.LogError($"[Aswid] Error processing mob {c.name}: {ex}");
}
}
}
List<Character> keysToRemove = new List<Character>();
foreach (var kvp in activeSensesLight)
{
if (kvp.Key == null || kvp.Key.IsDead() || !inRangeChars.Contains(kvp.Key))
{
if (kvp.Value != null) Destroy(kvp.Value);
keysToRemove.Add(kvp.Key);
}
}
foreach (var k in keysToRemove) activeSensesLight.Remove(k);
}
}
catch (Exception ex)
{
Jotunn.Logger.LogError($"[Aswid] Error in SuperhumanSenses: {ex}");
}
}
private void ClearSuperhumanSenses()
{
foreach (var kvp in activeSensesLight)
{
if (kvp.Value != null) Destroy(kvp.Value);
}
activeSensesLight.Clear();
}
private bool? wasNight = null;
private void Update()
{
if (Player.m_localPlayer == null || Player.m_localPlayer.IsDead() || !IsAswid())
{
damageTickTimer = 0f;
wasNight = null; // reset so it triggers correctly on spawn/respawn
if (Player.m_localPlayer != null) AswidSpectralClaw.PurgeAll(Player.m_localPlayer); // feature disabled for now, see AswidSpectralClaw.cs
return;
}
if (EnvMan.instance != null)
{
bool isNight = EnvMan.IsNight();
if (wasNight.HasValue && wasNight.Value != isNight)
{
if (isNight)
{
Player.m_localPlayer.Message(MessageHud.MessageType.Center, "what a horrible night to have a curse");
}
else
{
Player.m_localPlayer.Message(MessageHud.MessageType.Center, "The morning sun has vanquished the horrible night");
}
}
wasNight = isNight;
}
UpdateSuperhumanSenses();
try
{
if (Player.m_localPlayer.GetSEMan().HaveStatusEffect("Cold".GetStableHashCode()))
{
m_tintCheckTimer += Time.deltaTime;
if (m_tintCheckTimer > 0.1f)
{
m_tintCheckTimer = 0f;
ApplyNightAuraTint();
}
}
}
catch (Exception ex)
{
Jotunn.Logger.LogError($"[Aswid] Error in Cold status check: {ex}");
}
updateTimer += Time.deltaTime;
if (updateTimer >= UpdateInterval)
{
updateTimer = 0f;
UpdateAswidState();
}
try
{
HandleVampiricAura();
}
catch (Exception ex)
{
Jotunn.Logger.LogError($"[Aswid] Error in HandleVampiricAura: {ex}");
}
if (isTransformingSequence) return;
// The native Cold status effect will be intercepted by Aswid_ColdStatus_Patch in AswidPatches.cs
if (IsTransformed)
{
bool hasForm = Player.m_localPlayer.GetSEMan().HaveStatusEffect("SE_BatForm".GetStableHashCode());
if (!hasForm)
{
ForceRevert();
return;
}
}
int state = BossProgressionManager.GetCurrentProgressionState();
if (RaceInput.Allowed)
{
if (Input.GetKeyDown(KeyCode.G)) { TryTransformWithRules(AswidProgression.GetGKeyRules(state)); return; }
if (Input.GetKeyDown(KeyCode.H)) { TryToggleMistForm(); return; }
if (Input.GetKeyDown(KeyCode.J))
{
TryCastEclipse(state);
return;
}
if (Input.GetKeyDown(KeyCode.U))
{
TryTameHoverObject(state);
return;
}
}
// Auto revert mist form at sunrise. The isTransformingSequence guard matters: without it
// this fires again on every frame of the one-second revert, stacking a new coroutine each
// time, and they all fight over the same visuals and status effect.
if (EnvMan.instance != null && EnvMan.IsDay() && !isTransformingSequence &&
Player.m_localPlayer.GetSEMan().HaveStatusEffect("SE_MistForm".GetStableHashCode()))
{
StartCoroutine(RevertMistFormRoutine());
}
}
private string DumpGameObject(GameObject go, string indent)
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
sb.AppendLine($"{indent}- {go.name} (Layer: {LayerMask.LayerToName(go.layer)})");
var lights = go.GetComponents<Light>();
foreach (var l in lights) sb.AppendLine($"{indent} [Light] {l.type}, Color: {l.color}, Range: {l.range}");
var ps = go.GetComponents<ParticleSystem>();
foreach (var p in ps) sb.AppendLine($"{indent} [ParticleSystem]");
foreach (Transform child in go.transform)
{
sb.Append(DumpGameObject(child.gameObject, indent + " "));
}
return sb.ToString();
}
private void ApplyNightAuraTint()
{
try
{
foreach (Transform t in Player.m_localPlayer.GetComponentsInChildren<Transform>())
{
if (t.name.StartsWith("vfx_Cold") || t.name.StartsWith("vfx_cold"))
{
if (t.GetComponent<NightAuraTintFlag>() == null)
{
t.gameObject.AddComponent<NightAuraTintFlag>();
var renderers = t.GetComponentsInChildren<ParticleSystemRenderer>(true);
foreach (var r in renderers)
{
if (r.material != null)
{
if (r.material.HasProperty("_Color")) r.material.SetColor("_Color", Color.black);
if (r.material.HasProperty("_TintColor")) r.material.SetColor("_TintColor", Color.black);
if (r.material.HasProperty("_EmissionColor")) r.material.SetColor("_EmissionColor", Color.black);
}
}
var pss = t.GetComponentsInChildren<ParticleSystem>(true);
foreach (var ps in pss)
{
var main = ps.main;
main.startColor = Color.black;
bool hasMistForm = Player.m_localPlayer != null && Player.m_localPlayer.GetSEMan().HaveStatusEffect("SE_MistForm".GetStableHashCode());
float multiplier = hasMistForm ? 10f : 2f;
main.maxParticles = (int)(main.maxParticles * multiplier);
var emission = ps.emission;
emission.rateOverTime = new ParticleSystem.MinMaxCurve(emission.rateOverTime.constant * multiplier);
if (hasMistForm)
{
main.startSpeedMultiplier *= 3f;
main.startSizeMultiplier *= 1.2f;
}
var col = ps.colorOverLifetime;
if (col.enabled)
{
Gradient grad = new Gradient();
grad.SetKeys(
new GradientColorKey[] { new GradientColorKey(Color.black, 0.0f), new GradientColorKey(Color.black, 1.0f) },
new GradientAlphaKey[] { new GradientAlphaKey(1.0f, 0.0f), new GradientAlphaKey(0.0f, 1.0f) }
);
col.color = new ParticleSystem.MinMaxGradient(grad);
}
}
}
}
}
}
catch (Exception ex)
{
Jotunn.Logger.LogError($"[Aswid] Error in ApplyNightAuraTint: {ex}");
}
}
private void TryTransformWithRules(AswidProgression.FormRules rules)
{
if (rules == null || rules.Form == AswidProgression.FormType.None) return;
if (Player.m_localPlayer.GetSEMan().HaveStatusEffect("SE_MistForm".GetStableHashCode())) return;
if (IsTransformed)
{
StartCoroutine(RevertToHumanRoutine());
return;
}
StartCoroutine(TransformIntoBatRoutine(rules));
}
public void ForceRevert()
{
if (IsTransformed && !isTransformingSequence)
{
StartCoroutine(RevertToHumanRoutine());
}
if (Player.m_localPlayer != null && Player.m_localPlayer.GetSEMan().HaveStatusEffect("SE_MistForm".GetStableHashCode()) && !isTransformingSequence)
{
StartCoroutine(RevertMistFormRoutine());
}
}
private System.Collections.IEnumerator TransformIntoBatRoutine(AswidProgression.FormRules rules)
{
isTransformingSequence = true;
activeRules = rules;
ZSyncAnimation zAnim = Player.m_localPlayer.GetComponent<ZSyncAnimation>();
if (zAnim != null)
{
RaceInput.SuppressGuardianPowerBriefly();
zAnim.SetTrigger("gpower");
}
yield return new WaitForSeconds(1.1f);
GameObject poofPrefab = Jotunn.Managers.PrefabManager.Cache.GetPrefab<GameObject>("vfx_boar_death");
if (poofPrefab != null) Instantiate(poofPrefab, Player.m_localPlayer.transform.position, Quaternion.identity);
// Scale down player over time to 5% size
float elapsed = 0f;
float duration = 0.5f;
Vector3 startScale = Vector3.one;
Vector3 endScale = Vector3.one * 0.05f;
while (elapsed < duration)
{
Player.m_localPlayer.transform.localScale = Vector3.Lerp(startScale, endScale, elapsed / duration);
elapsed += Time.deltaTime;
yield return null;
}
Player.m_localPlayer.transform.localScale = endScale;
yield return new WaitForSeconds(0.1f);
Player.m_localPlayer.GetSEMan().AddStatusEffect("SE_BatForm".GetStableHashCode(), true);
if (Player.m_localPlayer.GetComponent<ZNetView>() != null) {
Player.m_localPlayer.GetComponent<ZNetView>().GetZDO().Set("Aswid_IsBatForm", true);
}
Transform playerVisual = Player.m_localPlayer.transform.Find("Visual");
PlayerVisualHider.Hide(playerVisual, "aswid-local-bat");
GameObject batPrefab = Jotunn.Managers.PrefabManager.Cache.GetPrefab<GameObject>("Bat");
if (batPrefab != null)
{
GameObject visualPrefab = batPrefab.GetComponentInChildren<Animator>()?.gameObject;
if (visualPrefab != null)
{
currentTransformation = Instantiate(visualPrefab, Player.m_localPlayer.transform.position, Player.m_localPlayer.transform.rotation, Player.m_localPlayer.transform);
currentTransformation.transform.localPosition = Vector3.zero;
currentTransformation.transform.localScale = Vector3.one;
var behavior = currentTransformation.AddComponent<BatFormBehavior>();
behavior.Initialize(rules);
}
}
IsTransformed = true;
isTransformingSequence = false;
}
private System.Collections.IEnumerator RevertToHumanRoutine()
{
isTransformingSequence = true;
GameObject poofPrefab = Jotunn.Managers.PrefabManager.Cache.GetPrefab<GameObject>("vfx_boar_death");
if (poofPrefab != null) Instantiate(poofPrefab, Player.m_localPlayer.transform.position, Quaternion.identity);
if (currentTransformation != null)
{
Destroy(currentTransformation);
currentTransformation = null;
}
Transform playerVisual = Player.m_localPlayer.transform.Find("Visual");
PlayerVisualHider.Show(playerVisual, "aswid-local-bat-revert");
Player.m_localPlayer.GetSEMan().RemoveStatusEffect("SE_BatForm".GetStableHashCode(), true);
if (Player.m_localPlayer.GetComponent<ZNetView>() != null) {
Player.m_localPlayer.GetComponent<ZNetView>().GetZDO().Set("Aswid_IsBatForm", false);
}
float elapsed = 0f;
float duration = 0.5f;
Vector3 startScale = Vector3.one * 0.05f;
Vector3 endScale = Vector3.one;
while (elapsed < duration)
{
Player.m_localPlayer.transform.localScale = Vector3.Lerp(startScale, endScale, elapsed / duration);
elapsed += Time.deltaTime;
yield return null;
}
Player.m_localPlayer.transform.localScale = endScale;
IsTransformed = false;
activeRules = null;
isTransformingSequence = false;
}
private void TryToggleMistForm()
{
if (BossProgressionManager.GetCurrentProgressionState() < 7) return; // Requires The Queen
if (isTransformingSequence) return;
if (IsTransformed) return; // Don't allow mist form while in bat form
if (Player.m_localPlayer.GetSEMan().HaveStatusEffect("SE_MistForm".GetStableHashCode()))
{
StartCoroutine(RevertMistFormRoutine());
}
else
{
StartCoroutine(TransformIntoMistRoutine());
}
}
private System.Collections.IEnumerator TransformIntoMistRoutine()
{
isTransformingSequence = true;
GameObject poofPrefab = Jotunn.Managers.PrefabManager.Cache.GetPrefab<GameObject>("vfx_surtling_death");
if (poofPrefab != null) Instantiate(poofPrefab, Player.m_localPlayer.transform.position, Quaternion.identity);
Player.m_localPlayer.GetSEMan().AddStatusEffect("SE_MistForm".GetStableHashCode(), true);
if (Player.m_localPlayer.GetComponent<ZNetView>() != null) {
Player.m_localPlayer.GetComponent<ZNetView>().GetZDO().Set("Aswid_IsMistForm", true);
}
Transform playerVisual = Player.m_localPlayer.transform.Find("Visual");
GameObject wraithPrefab = Jotunn.Managers.PrefabManager.Cache.GetPrefab<GameObject>("Wraith");
if (wraithPrefab != null)
{
GameObject visualPrefab = wraithPrefab.transform.Find("Visual")?.gameObject;
if (visualPrefab != null)
{
mistTransformation = Instantiate(visualPrefab, Player.m_localPlayer.transform.position, Player.m_localPlayer.transform.rotation, Player.m_localPlayer.transform);
mistTransformation.transform.localPosition = Vector3.zero;
mistTransformation.transform.localScale = Vector3.one * 0.01f;
foreach (var r in mistTransformation.GetComponentsInChildren<Renderer>())
{
if (r.material != null && r.material.HasProperty("_Color"))
{
Color c = r.material.GetColor("_Color");
c.a = 0.3f; // Make the wraith much more transparent
r.material.SetColor("_Color", c);
}
}
}
}
float elapsed = 0f;
float duration = 1.0f;
while (elapsed < duration)
{
float t = elapsed / duration;
if (playerVisual != null) playerVisual.localScale = Vector3.Lerp(Vector3.one, Vector3.one * 0.01f, t);
if (mistTransformation != null) mistTransformation.transform.localScale = Vector3.Lerp(Vector3.one * 0.01f, Vector3.one, t);
elapsed += Time.deltaTime;
yield return null;
}
PlayerVisualHider.Hide(playerVisual, "aswid-local-mist");
if (mistTransformation != null) mistTransformation.transform.localScale = Vector3.one;
isTransformingSequence = false;
yield return null;
}
private System.Collections.IEnumerator RevertMistFormRoutine()
{
isTransformingSequence = true;
GameObject poofPrefab = Jotunn.Managers.PrefabManager.Cache.GetPrefab<GameObject>("vfx_surtling_death");
if (poofPrefab != null) Instantiate(poofPrefab, Player.m_localPlayer.transform.position, Quaternion.identity);
Transform playerVisual = Player.m_localPlayer.transform.Find("Visual");
// Renderers come back on here; the loop below still grows the body out of the mist.
PlayerVisualHider.Show(playerVisual, "aswid-local-mist-revert");
float elapsed = 0f;
float duration = 1.0f;
while (elapsed < duration)
{
float t = elapsed / duration;
if (playerVisual != null) playerVisual.localScale = Vector3.Lerp(Vector3.one * 0.01f, Vector3.one, t);
if (mistTransformation != null) mistTransformation.transform.localScale = Vector3.Lerp(Vector3.one, Vector3.one * 0.01f, t);
elapsed += Time.deltaTime;
yield return null;
}
if (playerVisual != null)
{
playerVisual.localScale = Vector3.one;
}
if (mistTransformation != null)
{
Destroy(mistTransformation);
mistTransformation = null;
}
Player.m_localPlayer.GetSEMan().RemoveStatusEffect("SE_MistForm".GetStableHashCode(), true);
if (Player.m_localPlayer.GetComponent<ZNetView>() != null) {
Player.m_localPlayer.GetComponent<ZNetView>().GetZDO().Set("Aswid_IsMistForm", false);
}
isTransformingSequence = false;
yield return null;
}
private void TryTameHoverObject(int state)
{
GameObject hoverObject = Player.m_localPlayer.GetHoverObject();
if (hoverObject != null)
{
Tameable tameable = hoverObject.GetComponentInParent<Tameable>();
if (tameable != null)
{
Character c = tameable.GetComponent<Character>();
if (c != null && !c.IsTamed())
{
string prefabName = c.gameObject.name.ToLower();
bool canTame = false;
if (state >= 2 && prefabName.Contains("boar")) canTame = true;
if (state >= 5 && prefabName.Contains("wolf")) canTame = true;
if (state >= 6 && prefabName.Contains("lox")) canTame = true;
if (state >= 8 && prefabName.Contains("asksvin")) canTame = true;
if (canTame)
{
c.SetTamed(true);
HarmonyLib.Traverse.Create(tameable).Method("Tame").GetValue(); // attempt to call Tame for VFX if it exists
tameable.Command(Player.m_localPlayer);
Player.m_localPlayer.Message(MessageHud.MessageType.Center, "Tamed!");
}
}
}
}
}
private void TryCastEclipse(int state)
{
if (state < 6) return; // Requires Yagluth
if (EnvMan.instance != null && EnvMan.IsNight()) return; // Fails silently at night
if (IsEclipseActive) return;
float cooldown = 900f; // 15 minutes
if (Time.time - lastEclipseTime < cooldown)
{
int remaining = (int)(cooldown - (Time.time - lastEclipseTime));
Player.m_localPlayer.Message(MessageHud.MessageType.Center, $"Eclipse is on cooldown. Remaining: {remaining}s");
return;
}
StartCoroutine(EclipseRoutine());
}
private System.Collections.IEnumerator EclipseRoutine()
{
IsEclipseActive = true;
lastEclipseTime = Time.time;
// Trigger animation (Dead Raiser uses staff_summon or galdr_cast)
var zanim = HarmonyLib.Traverse.Create(Player.m_localPlayer).Field("m_zanim").GetValue<ZSyncAnimation>();
if (zanim != null)
{
zanim.SetTrigger("galdr_cast");
}
// Lock player for the duration of the cast (approx 2 seconds)
Player.m_localPlayer.Message(MessageHud.MessageType.Center, "An Eclipse descends...");
float castTimer = 0f;
while(castTimer < 2.0f)
{
// Force root player physically if possible without breaking their animator
HarmonyLib.Traverse.Create(Player.m_localPlayer).Method("SetRun", false).GetValue();
castTimer += Time.deltaTime;
yield return null;
}
// Force night client-side
if (EnvMan.instance != null)
{
HarmonyLib.Traverse.Create(EnvMan.instance).Field("m_debugTime").SetValue(true);
HarmonyLib.Traverse.Create(EnvMan.instance).Field("m_debugTimeOfDay").SetValue(0.5f); // Midnight
}
yield return new WaitForSeconds(60f);
// Revert to server time
if (EnvMan.instance != null)
{
HarmonyLib.Traverse.Create(EnvMan.instance).Field("m_debugTime").SetValue(false);
}
IsEclipseActive = false;
Player.m_localPlayer.Message(MessageHud.MessageType.Center, "The Eclipse has ended.");
}
private float damageTickTimer = 0f;
/// <summary>
/// The Vampiric Aura is passive: it drains on its own, in every form, with no key to hold and
/// no icon or message of its own. The form only decides how hard it bites.
/// </summary>
private void HandleVampiricAura()
{
damageTickTimer += Time.deltaTime;
if (damageTickTimer < 0.25f) return;
damageTickTimer = 0f;
PerformLifeDrain();
}
/// <summary>Half damage as a human, full as a bat, double as mist.</summary>
private float GetAuraFormMultiplier()
{
SEMan seman = Player.m_localPlayer.GetSEMan();
if (seman.HaveStatusEffect("SE_MistForm".GetStableHashCode())) return 2f;
if (seman.HaveStatusEffect("SE_BatForm".GetStableHashCode())) return 1f;
return 0.5f;
}
private void PerformLifeDrain()
{
if (Player.m_localPlayer == null) return;
try
{
Vector3 center = Player.m_localPlayer.transform.position;
float radius = 3f;
if (EnvMan.instance != null && EnvMan.IsNight()) radius = 6f;
int layerMask = LayerMask.GetMask("character", "character_net", "character_ghost");
var colliders = Physics.OverlapSphere(center, radius, layerMask);
foreach (var col in colliders)
{
Character c = col.GetComponentInParent<Character>();
if (c != null && c != Player.m_localPlayer && !c.IsDead() && !c.IsTamed())
{
if (c.IsPlayer() && (!c.IsPVPEnabled() || !Player.m_localPlayer.IsPVPEnabled()))
{
continue;
}
float maxHp = c.GetMaxHealth();
float currentHp = c.GetHealth();
float baseDamage = 1.0f;
float bloodMagicFactor = Player.m_localPlayer.GetSkillFactor(Skills.SkillType.BloodMagic);
// Lo scaling aggiunge un massimo di +5.0 danni (al livello 100), indipendentemente dal danno base
float totalDamage = (baseDamage + bloodMagicFactor * 5f) * GetAuraFormMultiplier();
if (currentHp > 0 && currentHp <= maxHp * 0.20f && !c.IsBoss())
{
totalDamage = currentHp * 2f; // Lethal damage for execute
TryConsumeMob(c, maxHp, true); // Automatically devour when executed, bypassing cooldown
}
HitData hd = new HitData();
hd.m_damage.m_damage = totalDamage;
hd.m_point = c.GetCenterPoint();
hd.m_dir = (c.GetCenterPoint() - center).normalized;
hd.m_attacker = Player.m_localPlayer.GetZDOID();
// Damage() sends RPC_Damage to whoever owns the target, so the hit lands for
// everyone and still runs our Character.Damage patches (lifesteal, devour on
// kill). ApplyDamage() skipped all of that: it edited the local copy of a
// character we usually do not own, and the owner overwrote it on the next sync.
c.Damage(hd);
SpawnBloodVFX(c);
}
}
}
catch (Exception ex)
{
Jotunn.Logger.LogError($"[Aswid] Error in PerformLifeDrain: {ex}");
}
}
public static bool DevourEnabled = true;
private static float lastConsumeTime = 0f;
public static void TryConsumeMob(Character c, float maxHp, bool bypassCooldown = false)
{
if (!DevourEnabled) return;
if (!bypassCooldown && Time.time - lastConsumeTime < 5f)
{
return; // Cooldown active
}
string cleanName = c.name.Replace("(Clone)", "").Trim();
string customFoodName = "AswidFood_" + cleanName;
GameObject foodPrefab = Jotunn.Managers.ItemManager.Instance.GetItem(customFoodName)?.ItemPrefab;
// Fallback to PrefabManager cache if ItemManager doesn't find it
if (foodPrefab == null)
{
foodPrefab = Jotunn.Managers.PrefabManager.Cache.GetPrefab<GameObject>(customFoodName);
}
// Fallback to RawMeat if no specific custom item was generated (e.g. mob not in trophy map)
if (foodPrefab == null)
{
return; // Mob is not edible
}
if (foodPrefab != null)
{
ItemDrop foodDrop = foodPrefab.GetComponent<ItemDrop>();
if (foodDrop != null)
{
// Suppress "New Material" popup by marking it as known beforehand using reflection
var knownMaterials = HarmonyLib.Traverse.Create(Player.m_localPlayer).Field("m_knownMaterial").GetValue<System.Collections.Generic.HashSet<string>>();
if (knownMaterials != null) knownMaterials.Add(foodDrop.m_itemData.m_shared.m_name);
// Create an invisible virtual inventory so the food never goes to the real bag
Inventory virtualInv = new Inventory("AswidStomach", null, 1, 1);
ItemDrop.ItemData addedItem = virtualInv.AddItem(foodPrefab.name, 1, 1, 0, 0, "");
if (addedItem != null)
{
lastConsumeTime = Time.time;
// UseItem natively plays animation and consumes it.
// If stomach is full, EatFood fails, UseItem does not consume the item, and virtualInv is destroyed (disintegrated)
AswidRace.BypassAswidFoodCheck = true;
bool successfullyEaten = Player.m_localPlayer.EatFood(addedItem);
AswidRace.BypassAswidFoodCheck = false;
if (successfullyEaten)
{
// Show the Vae Victis message in the center of the screen
Player.m_localPlayer.Message(MessageHud.MessageType.Center, "Vae Victis");
Player.m_localPlayer.Message(MessageHud.MessageType.TopLeft, "$msg_ate " + addedItem.m_shared.m_name);
// Vae Victis XP logic - similar to Dead Raiser
Player.m_localPlayer.RaiseSkill(Skills.SkillType.BloodMagic, 1f);
}
// If it was not eaten the stomach was full: the item disintegrates with
// the virtual inventory, so there is nothing to clean up.
}
else
{
Jotunn.Logger.LogWarning($"[Aswid] Failed to add '{customFoodName}' to the virtual inventory.");
}
}
}
}
private static void SpawnBloodVFX(Character target)
{
try
{
GameObject bloodHitPrefab = Jotunn.Managers.PrefabManager.Cache.GetPrefab<GameObject>("vfx_BloodHit");
if (bloodHitPrefab != null)
{
Instantiate(bloodHitPrefab, target.GetCenterPoint(), Quaternion.identity);
}
}
catch (Exception ex)
{
Jotunn.Logger.LogError($"[Aswid] Error in SpawnBloodVFX: {ex}");
}
}
private void UpdateAswidState()
{
AswidSpectralClaw.PurgeAll(Player.m_localPlayer); // feature disabled for now, see AswidSpectralClaw.cs
int currentState = BossProgressionManager.GetCurrentProgressionState();
var rules = AswidProgression.GetRules(currentState);
ZNetView nview = Player.m_localPlayer.GetComponent<ZNetView>();
if (nview != null && nview.IsValid())
{
nview.GetZDO().Set("RacesOfValheim_AswidState", currentState);
}
var aswidSE = Player.m_localPlayer.GetSEMan().GetStatusEffect("SE_AswidStats".GetStableHashCode()) as SE_AswidStats;
if (aswidSE != null)
{
aswidSE.UpdateStats(currentState);
}
else
{
Player.m_localPlayer.GetSEMan().AddStatusEffect("SE_AswidStats".GetStableHashCode(), true);
}
}
public static bool IsAswid()
{
return Player.m_localPlayer != null &&
Player.m_localPlayer.m_customData.ContainsKey("Race") &&
Player.m_localPlayer.m_customData["Race"] == "Aswid";
}
}
public class BloodVFXMover : MonoBehaviour
{
public Transform target;
private float speed = 10f;
private void Update()
{
if (target == null)
{
Destroy(gameObject);
return;
}
transform.position = Vector3.MoveTowards(transform.position, target.position, speed * Time.deltaTime);
if (Vector3.Distance(transform.position, target.position) < 0.2f)
{
Destroy(gameObject);
}
}
}
public class NightAuraTintFlag : MonoBehaviour { }
}