RacesOfValheim/JotunnModStub/Aswid/AswidRace.cs
kanym e75c7072c4 fix(prefabs): replace every lookup name that does not exist in vanilla
An audit of all 59 prefab names the mod resolves, against the game's own
asset manifests, found nine that are not in Valheim at all. A name vanilla
does not use has no vanilla candidate to beat in Jotunn's name cache, so it
is a free slot for whoever ships one - which is how another mod's weapon
trail became the Skeleton's fire aura in 00d4fd6.

Eight of the nine failed in silence, which is why none of them was ever
reported:

  vfx_corpse_destruction  ->  _medium, _large for the Muspell. The puff that
      covers a transformation. Fenrir and Skadi at least had their sparks;
      the Muspell swapped bodies in plain view with nothing at all.
  vfx_surtling_death      ->  vfx_wraith_death for the Aswid's Mist Form,
      which reads as mist by construction and is the same creature the form
      already borrows its Visual from; vfx_corpse_destruction_medium for the
      thrall, where nothing is misty. Vanilla has no surtling death effect
      under any spelling.
  TrophyTroll             ->  TrophyForestTroll.
  TrophyBat               ->  TrophyDeathsquito. Vanilla ships no bat trophy,
      so the Aswid's two status effects and its radial entry had no icon.
  vfx_smoke               ->  gone. It was the Trenta's fallback for Purple
      Rain's particle material behind Greydwarf_Shaman, and the day the
      Shaman failed to resolve it would have worn whatever a mod supplies.
      Purple Rain is purple by design, so nobody would ever have reported it.

The ninth did not fail in silence. vfx_OozeHit was passed to Instantiate
unguarded, so every successful Draugh parry threw ArgumentException and took
the North Wind nova below it down as well. It is vfx_blob_hit.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-26 00:20:02 +02:00

1221 lines
54 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" },
// The Fuling family is named Goblin* in code - "Fuling" is only ever the display name,
// and no prefab by that name exists. These three keys never matched anything, so the
// Aswid could not drain a Fuling of any kind. Verified against the asset manifest.
{ "Goblin", "TrophyGoblin" },
{ "GoblinArcher", "TrophyGoblin" },
{ "GoblinShaman", "TrophyGoblinShaman" },
{ "GoblinBrute", "TrophyGoblinBrute" },
{ "Deathsquito", "TrophyDeathsquito" },
{ "Hare", "TrophyHare" },
{ "Seeker", "TrophySeeker" },
{ "SeekerBrood", "TrophySeekerBrood" },
{ "SeekerBrute", "TrophySeekerBrute" },
{ "Gjall", "TrophyGjall" },
{ "Tick", "TrophyTick" },
{ "Ulv", "TrophyUlv" },
{ "Fenring_Cultist", "TrophyCultist" }, // the prefab is Fenring_Cultist, not "Cultist"
{ "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();
AswidBloodRefinery.Register();
// Registered HERE and not lazily from the maintain tick: this method runs on
// PrefabManager.OnVanillaPrefabsAvailable, which is the one moment Jotunn will take a
// new item into ObjectDB. Registered later, the prefab is built and logged and looks
// entirely healthy - and then nobody can spawn it, which is exactly how the first
// version of the claws failed: two empty hands and a log full of success.
AswidClaws.Instance.EnsureRegistered();
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;
// StartsWith("Fenring") already covers Fenring_Cultist. "Fuling" was
// never a prefab prefix - the family is Goblin* - so that arm of the
// test matched nothing until now.
if (mobName == "Cultist" || mobName.StartsWith("Fenring") || mobName.StartsWith("Goblin"))
{
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 = AswidConfig.EnslaveCooldown.Value - 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 = AswidConfig.SensesRefreshInterval.Value; // 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 <= AswidConfig.SensesRadius.Value)
{
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 = AswidConfig.SensesLightRange.Value;
pLight.intensity = AswidConfig.SensesLightIntensity.Value;
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 (AswidConfig.BatFormKey.Value.IsDownIgnoringHeldKeys()) { TryTransformWithRules(AswidProgression.GetGKeyRules(state)); return; }
if (AswidConfig.MistFormKey.Value.IsDownIgnoringHeldKeys()) { TryToggleMistForm(); return; }
if (AswidConfig.EclipseKey.Value.IsDownIgnoringHeldKeys())
{
TryCastEclipse(state);
return;
}
if (AswidConfig.TameKey.Value.IsDownIgnoringHeldKeys())
{
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());
}
// Same rule for a night-only bat: a form the sun forbids cannot be kept through the
// sunrise, or the daylight gate above would only be one night's patience away from
// meaningless. activeRules is what the transform was actually granted under, so an
// Aswid who has killed The Elder (NeedsNight false) keeps flying into the morning.
if (IsTransformed && !isTransformingSequence && activeRules != null && activeRules.NeedsNight &&
EnvMan.instance != null && EnvMan.IsDay())
{
Player.m_localPlayer.Message(MessageHud.MessageType.Center, "The morning sun drives the bat back into your body");
StartCoroutine(RevertToHumanRoutine());
}
}
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;
}
// The night gate lives here, not in GetGKeyRules: the rules only say WHETHER night is
// required (state 2, Eikthyr) or not (state 3+, The Elder). Nothing ever read the
// NeedsNight flag, so an Aswid who had only killed Eikthyr could turn into a bat in
// broad daylight. Placed after the revert branch on purpose - a bat caught by the
// sunrise must always be able to turn back.
if (rules.NeedsNight && (EnvMan.instance == null || !EnvMan.IsNight()))
{
Player.m_localPlayer.Message(MessageHud.MessageType.Center, "The sun burns. You can only take bat form at night.");
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());
}
}
/// <summary>
/// Everything RevertToHumanRoutine does, minus the puff of smoke and the scale animation,
/// and without a coroutine - because the one moment this exists for is death, and by then
/// Update() has already bailed out on IsDead(), so a coroutine started here would be the
/// only thing still running on a corpse.
///
/// Leaving the form up costs more than a missing animation: m_debugFly stays on, so the
/// respawned player floats; Aswid_IsBatForm stays true in the ZDO, so every other client
/// keeps drawing a bat over a body that is walking around as a person; and the 5% scale
/// stays on the transform. Called from Aswid_BatDiesAsBat_Patch.
/// </summary>
public void HardResetBatForm()
{
Player player = Player.m_localPlayer;
if (player == null) return;
if (!IsTransformed && !isTransformingSequence) return;
if (currentTransformation != null)
{
Destroy(currentTransformation);
currentTransformation = null;
}
PlayerVisualHider.Show(player.transform.Find("Visual"), "aswid-bat-death-reset");
if (player.GetSEMan() != null)
player.GetSEMan().RemoveStatusEffect("SE_BatForm".GetStableHashCode(), true);
ZNetView nview = player.GetComponent<ZNetView>();
if (nview != null && nview.IsValid())
{
nview.GetZDO().Set("Aswid_IsBatForm", false);
nview.GetZDO().Set(ZDOVars.s_debugFly, false);
}
Traverse.Create(player).Field("m_debugFly").SetValue(false);
player.transform.localScale = Vector3.one;
IsTransformed = false;
activeRules = null;
isTransformingSequence = false;
}
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;
// WAS "vfx_surtling_death", WHICH IS NOT A PREFAB IN THIS GAME. The surtling has no
// death effect under any spelling, so this resolved to nothing and the Mist Form has
// always appeared and disappeared with no puff at all - both here and in
// RevertMistFormRoutine. Kept as a note rather than a fallback: a name vanilla does not
// use is a free slot for any mod that ships one, which is how another mod's weapon trail
// became the Skeleton's fire aura (see SkeletonVisuals.EnsureFireAura).
//
// The Wraith's own death effect reads as mist by construction, which is what this wanted,
// and it is already the right creature: the form borrows the Wraith's Visual a few lines
// below. If the look wants changing, that effect is the thing to alter.
GameObject poofPrefab = Jotunn.Managers.PrefabManager.Cache.GetPrefab<GameObject>("vfx_wraith_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;
// The same puff as going in - see TransformIntoMistRoutine for why the old name never
// resolved to anything.
GameObject poofPrefab = Jotunn.Managers.PrefabManager.Cache.GetPrefab<GameObject>("vfx_wraith_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 = AswidConfig.EclipseCooldown.Value;
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 < AswidConfig.EclipseCastTime.Value)
{
// 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(AswidConfig.EclipseDuration.Value);
// 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 drains on its own, in every form, with no key to hold - but it does not
/// distinguish traders from monsters, so it can execute Haldor/Hildir on approach. AuraEnabled
/// (toggled with Devour on the same key) is the escape hatch for that.
/// </summary>
private void HandleVampiricAura()
{
if (!AuraEnabled)
{
damageTickTimer = 0f;
return;
}
damageTickTimer += Time.deltaTime;
if (damageTickTimer < AswidConfig.AuraTickInterval.Value) 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 = AswidConfig.AuraRadiusDay.Value;
if (EnvMan.instance != null && EnvMan.IsNight()) radius = AswidConfig.AuraRadiusNight.Value;
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;
}
// The truce holds here too, or it holds nowhere. This aura is always on
// and asks nothing of the player, so before RaceGrudge it quietly drained
// and executed the race's own kin while they stood there and took it;
// after RaceGrudge that same drain would have kept every leech, draugr and
// blob in the swamp permanently angry at an Aswid who never raised a hand.
// Asking BaseAI.IsEnemy is what the Skeleton's fire aura already does, and
// it is the one question both truce patches answer, so the aura now agrees
// with everything else by construction. The execute is untouched: it still
// fires, on anything the Aswid is actually at war with.
if (!c.IsPlayer() && !BaseAI.IsEnemy(Player.m_localPlayer, c))
{
continue;
}
float maxHp = c.GetMaxHealth();
float currentHp = c.GetHealth();
float baseDamage = AswidConfig.AuraBaseDamage.Value;
float bloodMagicFactor = Player.m_localPlayer.GetSkillFactor(Skills.SkillType.BloodMagic);
// Lo scaling aggiunge un massimo di +AuraBloodMagicScaling danni (al livello 100), indipendentemente dal danno base
float totalDamage = (baseDamage + bloodMagicFactor * AswidConfig.AuraBloodMagicScaling.Value) * GetAuraFormMultiplier();
if (currentHp > 0 && currentHp <= maxHp * AswidConfig.AuraExecuteThreshold.Value && !c.IsBoss())
{
totalDamage = currentHp * 2f; // Lethal damage for execute
TryConsumeMob(c, maxHp); // Automatically devour when executed
}
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;
public static bool AuraEnabled = true;
/// <summary>
/// When each corpse was last drunk from, so one body is never devoured twice.
///
/// This used to be a single timestamp shared by every corpse in the world, which is what
/// testers hit as "killing with the claws or the aura sometimes adds nothing at all":
/// clear a pack with one blast and the first body ate the cooldown for all of them, the
/// rest dying unnoticed inside the window. The guard was never about pacing kills - it is
/// there because a single death reaches TryConsumeMob from more than one place (two
/// Character.Damage postfixes, the aura's own execute, a thrall's kill), and without it
/// one corpse could feed the player twice. Keyed per corpse it does that job exactly and
/// stops taxing the kills that follow.
/// </summary>
private static readonly Dictionary<ZDOID, float> lastConsumedCorpse = new Dictionary<ZDOID, float>();
private static float lastCorpseSweep = 0f;
public static void TryConsumeMob(Character c, float maxHp)
{
if (!DevourEnabled) return;
if (c == null) return;
// The window is the config's own "Consume Cooldown", scoped to the body it is about.
// Floored at a second even when that is set to zero: the paths that report one death
// all arrive within the same frame or two, and letting a corpse feed the player twice
// is a bug rather than a setting.
float window = Mathf.Max(AswidConfig.DevourCooldown != null ? AswidConfig.DevourCooldown.Value : 5f, 1f);
ZDOID corpse = c.GetZDOID();
if (lastConsumedCorpse.TryGetValue(corpse, out float drunkAt) && Time.time - drunkAt < window)
{
return; // This body has already been drunk from.
}
SweepConsumedCorpses(window);
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)
{
// Logged rather than shown: a creature with no blood food of its own is a whole
// category, not an event, and a message on every such kill would be noise. It is
// here at all because from the player's chair this looks exactly like a devour
// that failed, and the log is the only way to tell the two apart.
Jotunn.Logger.LogDebug($"[Aswid] '{cleanName}' has no '{customFoodName}' to drink - not edible.");
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, "", false);
if (addedItem != null)
{
lastConsumedCorpse[corpse] = 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);
}
else
{
// The stomach was full and had nothing worth refreshing, so the food
// disintegrates with the virtual inventory - there is nothing to clean
// up, but there used to be nothing to see either. Silence is what made
// a refused meal indistinguishable from a devour that never fired:
// vanilla's own "can't eat more" line, localized for free.
Player.m_localPlayer.Message(MessageHud.MessageType.TopLeft, "$msg_nomore");
}
}
else
{
Jotunn.Logger.LogWarning($"[Aswid] Failed to add '{customFoodName}' to the virtual inventory.");
}
}
}
}
/// <summary>
/// Drops corpses the window has passed, so a long session does not carry a growing list of
/// bodies nobody will ever drink from again. Once every window at most - this runs off
/// kills, and a pack dying together should not walk the list once per body.
/// </summary>
private static void SweepConsumedCorpses(float window)
{
if (Time.time - lastCorpseSweep < window) return;
lastCorpseSweep = Time.time;
if (lastConsumedCorpse.Count == 0) return;
List<ZDOID> stale = null;
foreach (var entry in lastConsumedCorpse)
{
if (Time.time - entry.Value < window) continue;
if (stale == null) stale = new List<ZDOID>();
stale.Add(entry.Key);
}
if (stale == null) return;
foreach (ZDOID id in stale) lastConsumedCorpse.Remove(id);
}
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 { }
}