RacesOfValheim/JotunnModStub/Skadi/SkadiNokkel.cs
Ferdinando 5c5b8c34d2 feat(races): Skadi hollow chain, plus the pending Dvergar and Fenrir ones
Three per-race item chains had accumulated uncommitted. They land
together because FactionMerchantCatalog.cs carries hunks from all
three and cannot be split without interactive staging.

Skadi (new this session):
- SkadiNokkel - "Skadis Nokkel", a StaffSkeleton clone recoloured to
  ice, stripped of its eitr and health costs and of the skeleton
  summon, opening an ice-blue portal to a troll cave the player
  claims as their own. Crafted at the forge after Moder from a
  1500-coin Greater Frost Heart, a DragonTear and a TrophySkeleton.
- SkadiFrostHeart - the bought leg of that recipe, sold by the
  Cultist bench.
- SkadiHollow / SkadiHollowPortal - claims one existing TrollCave02
  in the Black Forest, half a world radius out and south of the
  equator, and opens a linked local portal pair to it.
- RaceCaveBuilding - Skadi and Trol may build inside any troll cave.

Two facts worth keeping, both paid for the hard way:
- a troll cave counts as a DUNGEON, so the flag that refuses a piece
  there is the per-piece Piece.m_allowedInDungeons, not the
  per-location Location.m_noBuild. Player.m_placementStatus names the
  exact refusal reason and is now logged.
- Object.DestroyImmediate is forbidden inside an animation event
  callback, and a staff cast runs in one - it fails silently there.

Also carried in, from earlier sessions and unverified in game:
- Dvergar contract bank and barrel (DvergarBanco*, DvergarBotte*)
- Fenrir Ulvsblod trough (FenrirMangiatoia*)
- the Wolf -> Ulv merchant bench move, so tameable wolves stop
  answering the E key with a shop window

Status: compiles clean with no new warnings. The Skadi chain has NOT
been confirmed working in game - the most recent fix to the troll
cave detection is still untested.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-08 14:58:43 +02:00

396 lines
20 KiB
C#

using HarmonyLib;
using Jotunn.Configs;
using Jotunn.Entities;
using Jotunn.Managers;
using UnityEngine;
namespace RacesOfValheim
{
/// <summary>
/// The one ice palette the whole Skadi chain shares. Taken from the Fader recolour in
/// SkadiRace.ExecuteTransformation rather than picked fresh, so the staff, the reagent and the
/// portal are all the same ice as the Skeleton Dragon the race turns into at tier 8.
/// </summary>
public static class SkadiIce
{
public static readonly Color Albedo = new Color(0.6f, 0.8f, 1f, 1f);
public static readonly Color Emission = new Color(0f, 0.5f, 1f, 1f);
public static readonly Color PortalSwirl = new Color(0.55f, 0.85f, 1f, 1f);
/// <summary>
/// Multiplies the ice tint over whatever the base texture already carries instead of
/// overwriting it, so the model keeps its detail and reads as frozen bone rather than as a
/// flat blue silhouette. Same approach as AswidSpectralClaw.ApplySpectralVisual, and like
/// that one it copies each material first so the vanilla asset is never touched.
/// </summary>
public static void Apply(GameObject root)
{
if (root == null) return;
foreach (Renderer renderer in root.GetComponentsInChildren<Renderer>(true))
{
if (renderer == null || renderer is ParticleSystemRenderer) continue;
Material[] source = renderer.sharedMaterials;
Material[] tinted = new Material[source.Length];
for (int i = 0; i < source.Length; i++)
{
if (source[i] == null) continue;
Material material = new Material(source[i]);
if (material.HasProperty("_Color"))
{
Color baseColor = material.GetColor("_Color");
material.SetColor("_Color", new Color(baseColor.r * Albedo.r,
baseColor.g * Albedo.g,
baseColor.b * Albedo.b,
baseColor.a));
}
if (material.HasProperty("_EmissionColor")) material.SetColor("_EmissionColor", Emission);
tinted[i] = material;
}
renderer.sharedMaterials = tinted;
}
}
}
/// <summary>
/// Skadis Nokkel - "Skadi's key". A StaffSkeleton with the skeleton taken out of it: it costs no
/// eitr, no health and no stamina, it summons nothing, and what it does instead is open a portal
/// into the player's own hidden hollow (SkadiHollow).
///
/// The name is the point. It is not a weapon that happens to open a door, it is a key - and a
/// reproducible one: losing it costs a trip to the forge, not the hollow.
///
/// Two layers keep the vanilla staff's behaviour from leaking through, deliberately overlapping:
/// - every field that could carry a cost or a summon is zeroed on the clone (Strip below);
/// - the attack trigger itself is intercepted and vanilla's never runs for this staff
/// (SkadiNokkelCastPatch). Nulling a projectile field would leave vanilla walking into it;
/// taking over the method means that code path is not merely defused, it is unreachable.
/// </summary>
public static class SkadiNokkel
{
public const string PrefabName = "SkadiNokkel";
public const string DisplayName = "Skadis Nokkel";
private const string SourcePrefab = "StaffSkeleton";
private const string ModerDrop = "DragonTear";
private const string SkullTrophy = "TrophySkeleton";
public static void Register()
{
GameObject prefab = PrefabManager.Instance.CreateClonedPrefab(PrefabName, SourcePrefab);
if (prefab == null)
{
Jotunn.Logger.LogWarning($"[Skadi] Could not clone {SourcePrefab}; {DisplayName} not registered.");
return;
}
ItemDrop drop = prefab.GetComponent<ItemDrop>();
if (drop == null || drop.m_itemData == null || drop.m_itemData.m_shared == null)
{
Jotunn.Logger.LogWarning($"[Skadi] {SourcePrefab} clone has no usable ItemDrop; {DisplayName} not registered.");
return;
}
ItemDrop.ItemData.SharedData shared = drop.m_itemData.m_shared;
shared.m_name = DisplayName;
shared.m_description = "A staff of frozen bone. It raises nothing. Used, it opens the way to a hollow " +
"that is yours and no one else's - and used again, it lets you out.";
shared.m_useDurability = false;
// ItemType is left exactly as the vanilla staff has it, on purpose: it decides the
// equip slot and which animation set the character uses, and the cast gesture is the
// whole reason this is a staff and not a trinket.
Strip(shared);
SkadiIce.Apply(prefab);
ItemManager.Instance.AddItem(new CustomItem(prefab, fixReference: false));
LogCosts("straight after registering", shared);
ItemManager.Instance.AddRecipe(new CustomRecipe(new RecipeConfig
{
Item = PrefabName,
Amount = 1,
CraftingStation = CraftingStations.Forge,
Requirements = new[]
{
new RequirementConfig(SkadiFrostHeart.PrefabName, 1, 0, true),
new RequirementConfig(ModerDrop, 1, 0, true),
new RequirementConfig(SkullTrophy, 1, 0, true),
},
}));
Jotunn.Logger.LogInfo($"[Skadi] {DisplayName} registered: no eitr, no health, no summon.");
}
/// <summary>
/// Takes the skeleton staff apart. Every field is zeroed on BOTH attacks, because the
/// secondary is a separate Attack with its own copy of every cost.
///
/// The summon is the interesting one: it comes from a SpawnAbility component (verified class,
/// field GameObject[] m_spawnPrefab) which does not live on the item but on a prefab hung off
/// the attack. WHICH field hangs it - m_attackProjectile or m_spawnOnTrigger - is not
/// knowable from the game files, so all of them go. Nulling three fields that might each be
/// the culprit costs nothing; guessing wrong costs a skeleton every cast.
///
/// m_attackStamina goes to zero too, and that is a decision, not thoroughness: the moment
/// someone wants to flee into their hollow is exactly the moment they have no stamina left.
/// The only brake on this staff is its cooldown.
/// </summary>
private static void Strip(ItemDrop.ItemData.SharedData shared)
{
StripAttack(shared.m_attack);
StripAttack(shared.m_secondaryAttack);
}
private static void StripAttack(Attack attack)
{
if (attack == null) return;
attack.m_attackEitr = 0f;
attack.m_drawEitrDrain = 0f;
attack.m_reloadEitrDrain = 0f;
attack.m_attackHealth = 0f;
attack.m_attackHealthPercentage = 0f;
attack.m_attackHealthLowBlockUse = false;
attack.m_attackHealthReturnHit = 0f;
attack.m_attackStamina = 0f;
attack.m_drawStaminaDrain = 0f;
attack.m_reloadStaminaDrain = 0f;
attack.m_attackProjectile = null;
attack.m_spawnOnTrigger = null;
attack.m_spawnOnHit = null;
attack.m_spawnOnHitChance = 0f;
// The animation stays. It is the summoning gesture, which is the right gesture for
// opening a way, and it is the same one TrentaAbilities plays by hand for its portal.
}
/// <summary>
/// Runs on the cast. Race-gated: the hollow belongs to the Skadi, so in anyone else's hands
/// this is an inert stick - the same shape as Aswid_SpectralClawDamage_Patch, which asks
/// AswidRace.IsAswid() before doing anything at all.
/// </summary>
public static void OnCast(Player player)
{
if (player == null || player != Player.m_localPlayer) return;
if (!SkadiRace.IsLocalSkadi())
{
player.Message(MessageHud.MessageType.Center, "The staff is cold and answers to someone else.");
return;
}
SkadiHollow.Cast(player);
}
public static bool IsNokkel(ItemDrop.ItemData item)
{
return item != null && item.m_dropPrefab != null && item.m_dropPrefab.name == PrefabName;
}
/// <summary>
/// True when a cost being asked about belongs to this staff.
///
/// The fallback on the equipped weapon is not belt-and-braces, it is necessary: the cost
/// getters are called from Attack.Start, and m_weapon is not guaranteed to have been assigned
/// by the time the cost is checked. It is deliberately only consulted when m_weapon is null,
/// so a creature's own attack cannot be zeroed just because the player happens to be holding
/// the staff at the time.
/// </summary>
public static bool IsNokkelContext(ItemDrop.ItemData weapon)
{
if (weapon != null) return IsNokkel(weapon);
Player local = Player.m_localPlayer;
return local != null && IsNokkel(local.GetCurrentWeapon());
}
/// <summary>
/// Prints what the clone's attack actually costs, so "the eitr cost came back" stops being a
/// mystery and becomes a number with a timestamp. Called once at registration and again from
/// the F8 dump, which between them say whether the zeroes were never written or were written
/// and then overwritten by something else.
/// </summary>
public static void LogCosts(string when, ItemDrop.ItemData.SharedData shared)
{
if (shared == null) { Jotunn.Logger.LogWarning($"[Skadi] Nokkel costs {when}: no shared data."); return; }
Attack primary = shared.m_attack;
Attack secondary = shared.m_secondaryAttack;
Jotunn.Logger.LogInfo($"[Skadi] Nokkel costs {when}: " +
$"primary eitr={Describe(primary, a => a.m_attackEitr)} " +
$"health={Describe(primary, a => a.m_attackHealth)} " +
$"health%={Describe(primary, a => a.m_attackHealthPercentage)} " +
$"stamina={Describe(primary, a => a.m_attackStamina)} | " +
$"secondary eitr={Describe(secondary, a => a.m_attackEitr)} " +
$"stamina={Describe(secondary, a => a.m_attackStamina)}");
}
private static string Describe(Attack attack, System.Func<Attack, float> read)
{
return attack == null ? "<no attack>" : read(attack).ToString("0.##");
}
/// <summary>
/// What the F8 dump prints for this chain. Two unknowns, both settled by reading them once
/// off a running game: which field of the vanilla staff carries the summon, and what the
/// troll cave location is really called in this build.
/// </summary>
public static void DumpSource()
{
Jotunn.Logger.LogInfo("=== SKADI NOKKEL SOURCE DUMP ===");
GameObject staff = PrefabManager.Cache.GetPrefab<GameObject>(SourcePrefab);
ItemDrop staffDrop = staff != null ? staff.GetComponent<ItemDrop>() : null;
if (staffDrop == null)
{
Jotunn.Logger.LogWarning($"{SourcePrefab} not found.");
}
else
{
Attack attack = staffDrop.m_itemData.m_shared.m_attack;
Jotunn.Logger.LogInfo($" m_attackType : {attack.m_attackType}");
Jotunn.Logger.LogInfo($" m_attackAnimation : {attack.m_attackAnimation}");
Jotunn.Logger.LogInfo($" m_attackProjectile : {(attack.m_attackProjectile != null ? attack.m_attackProjectile.name : "<null>")}");
Jotunn.Logger.LogInfo($" m_spawnOnTrigger : {(attack.m_spawnOnTrigger != null ? attack.m_spawnOnTrigger.name : "<null>")}");
Jotunn.Logger.LogInfo($" m_attackEitr : {attack.m_attackEitr}");
Jotunn.Logger.LogInfo($" m_attackHealth : {attack.m_attackHealth} / {attack.m_attackHealthPercentage}%");
foreach (GameObject candidate in new[] { attack.m_attackProjectile, attack.m_spawnOnTrigger })
{
if (candidate == null) continue;
foreach (SpawnAbility ability in candidate.GetComponentsInChildren<SpawnAbility>(true))
{
string spawns = "<none>";
if (ability.m_spawnPrefab != null && ability.m_spawnPrefab.Length > 0)
{
string[] names = new string[ability.m_spawnPrefab.Length];
for (int i = 0; i < names.Length; i++)
{
names[i] = ability.m_spawnPrefab[i] != null ? ability.m_spawnPrefab[i].name : "<null>";
}
spawns = string.Join(", ", names);
}
Jotunn.Logger.LogInfo($" SpawnAbility on '{candidate.name}' spawns: {spawns}");
}
}
}
// The clone as the game currently holds it, not as Register() left it. If these are not
// zero, the write in Strip() did not survive - which is the whole reason
// SkadiNokkelFreeCastPatch exists, and this line is how we find out whether it is still
// needed or whether the fields hold after all.
GameObject clone = PrefabManager.Cache.GetPrefab<GameObject>(PrefabName);
ItemDrop cloneDrop = clone != null ? clone.GetComponent<ItemDrop>() : null;
if (cloneDrop == null)
{
Jotunn.Logger.LogWarning($" {PrefabName} is not in the prefab cache.");
}
else
{
LogCosts("as the game holds it now", cloneDrop.m_itemData.m_shared);
Jotunn.Logger.LogInfo($" shared data instance is {(ReferenceEquals(cloneDrop.m_itemData.m_shared, staffDrop != null ? staffDrop.m_itemData.m_shared : null) ? "THE SAME OBJECT as the vanilla staff's - that is the bug" : "its own copy, as expected")}");
}
// The other half: is 'TrollCave02' actually what it is called here?
Jotunn.Logger.LogInfo($"--- locations matching 'cave' (looking for {SkadiHollow.SourceLocation}) ---");
if (ZoneSystem.instance == null || ZoneSystem.instance.m_locations == null)
{
Jotunn.Logger.LogWarning(" ZoneSystem not up yet; load a world first.");
}
else
{
// m_locations, not GetLocationList(): the latter is public but returns the locations
// PLACED in this world, and the hollow needs the definition, not an instance.
foreach (ZoneSystem.ZoneLocation location in ZoneSystem.instance.m_locations)
{
if (location == null || string.IsNullOrEmpty(location.m_prefabName)) continue;
if (location.m_prefabName.IndexOf("cave", System.StringComparison.OrdinalIgnoreCase) < 0) continue;
Jotunn.Logger.LogInfo($" {location.m_prefabName} (biome {location.m_biome}, " +
$"interior r{location.m_interiorRadius}, clearArea {location.m_clearArea})");
}
}
Jotunn.Logger.LogInfo("=== END SKADI NOKKEL SOURCE DUMP ===");
}
}
/// <summary>
/// The cast hook, and the second half of "remove the unwanted components".
///
/// Attack.OnAttackTrigger() is used rather than Attack.Start because it takes NO parameters -
/// its signature cannot drift and cannot be got wrong, which matters here because Attack.Start's
/// parameter types could not even be loaded for inspection outside the game. It also fires at
/// the moment the animation reaches its release point, which is exactly when a cast should land.
///
/// It is a Prefix returning FALSE, not a postfix, and that is the whole trick: for this staff
/// vanilla's attack-trigger code never executes at all. The summon and the projectile are not
/// just defused by the zeroed fields, they are unreachable - and vanilla cannot trip over the
/// nulls we left behind either, which a postfix would have been at the mercy of.
///
/// m_weapon and m_character are both PRIVATE on Attack, so they arrive through Harmony's triple
/// underscore field injection rather than off __instance - which is also why they are spelled
/// out here instead of being read with Traverse: the injection is checked at patch time, so a
/// rename shows up as a startup error instead of a silent null every cast.
/// </summary>
[HarmonyPatch(typeof(Attack), "OnAttackTrigger")]
public static class SkadiNokkelCastPatch
{
public static bool Prefix(ItemDrop.ItemData ___m_weapon, Humanoid ___m_character)
{
if (!SkadiNokkel.IsNokkel(___m_weapon)) return true;
SkadiNokkel.OnCast(___m_character as Player);
return false;
}
}
/// <summary>
/// The staff costs nothing, guaranteed - and this is what guarantees it.
///
/// Zeroing m_attackEitr, m_attackHealth and m_attackStamina on the clone is still done in
/// Strip(), and by every reading of the game's own code it ought to be enough: those three, plus
/// the two drain fields, are the ONLY eitr costs that exist anywhere on Attack, and SharedData
/// carries none at all (checked field by field). In game the cost came back anyway, which means
/// the write to the clone's own SharedData does not survive something - so relying on that write
/// is relying on a mechanism that has already been observed to fail.
///
/// These three getters are the single funnel every cost check flows through: Attack.Start asks
/// them before it will start, and the tooltip asks them for what to print. Forcing them to zero
/// makes the staff free no matter what any field says, which is the same reasoning as the prefix
/// above - do not defuse the code path, remove it.
///
/// All three are PRIVATE and take no parameters, so they are addressed by name through
/// AccessTools and share one postfix.
/// </summary>
[HarmonyPatch]
public static class SkadiNokkelFreeCastPatch
{
[HarmonyTargetMethods]
private static System.Collections.Generic.IEnumerable<System.Reflection.MethodBase> TargetMethods()
{
yield return AccessTools.Method(typeof(Attack), "GetAttackEitr");
yield return AccessTools.Method(typeof(Attack), "GetAttackHealth");
yield return AccessTools.Method(typeof(Attack), "GetAttackStamina");
}
[HarmonyPostfix]
private static void Postfix(ItemDrop.ItemData ___m_weapon, ref float __result)
{
if (__result == 0f) return;
if (!SkadiNokkel.IsNokkelContext(___m_weapon)) return;
__result = 0f;
}
}
}