feat(dvergar): rename from Dvergur, and give it a lightning affinity
Rename covers the folder, all seven filenames and every identifier, status effect name and display string. Valheim's own Dverger/dvergr prefab references are untouched - the names never collided. The race id is what sits in m_customData and the ZDO, so renaming it alone would have handed every existing character the selection menu again. DvergarRace migrates the old id on spawn, before anything else reads it. Runic Spark is modelled on Skadi's Ice Affinity and deliberately shares its shape: live from the base tier and growing a flat step per progression state, so +2 at Base through +16 after Fader. Lightning rather than frost, and like Skadi's it rides every blow rather than melee only. AddFlat gained the elemental channels while it was there - lightning would otherwise have landed in generic damage. The Trol remote-sync trace fired on a two-second timer for as long as a remote player existed, which in the main menu is forever: Player.m_localPlayer is null there, so the character preview counts as remote and it never stopped. Keyed on the state it reports instead, so it still catches a remote player being sized wrongly without narrating an idle menu.
This commit is contained in:
parent
11fd68757a
commit
5febc588ea
12 changed files with 287 additions and 219 deletions
207
JotunnModStub/Dvergar/DvergarAbilities.cs
Normal file
207
JotunnModStub/Dvergar/DvergarAbilities.cs
Normal file
|
|
@ -0,0 +1,207 @@
|
|||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
|
||||
namespace RacesOfValheim
|
||||
{
|
||||
/// <summary>
|
||||
/// The Dvergar's two eitr abilities.
|
||||
///
|
||||
/// Runic Ping (Yagluth) - spend eitr to light up ore veins and hidden enemies nearby.
|
||||
/// Runic Overcharge (Fader) - spend eitr to load the next blow of a favoured weapon.
|
||||
///
|
||||
/// Both are driven from DvergarRace.Update and both read their cost, radius, duration and
|
||||
/// cooldown out of DvergarConfig.
|
||||
/// </summary>
|
||||
public static class DvergarAbilities
|
||||
{
|
||||
private static float lastPingTime = -1000f;
|
||||
private static float lastOverchargeTime = -1000f;
|
||||
|
||||
public static void Tick(Player player, int state)
|
||||
{
|
||||
// Ability input is gated exactly like every other race's: RaceInput mirrors
|
||||
// Player.TakeInput, so nothing fires while a map, chest or chat window has focus.
|
||||
if (!RaceInput.Allowed) return;
|
||||
|
||||
DvergarProgression.DvergarRules rules = DvergarProgression.GetRules(state);
|
||||
|
||||
if (rules.RunicPing && Input.GetKeyDown(DvergarConfig.RunicPingKey))
|
||||
{
|
||||
TryRunicPing(player);
|
||||
}
|
||||
|
||||
if (rules.RunicOvercharge && Input.GetKeyDown(DvergarConfig.RunicOverchargeKey))
|
||||
{
|
||||
TryRunicOvercharge(player);
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Runic Ping ──────────────────────────────────────────────────────
|
||||
|
||||
private static void TryRunicPing(Player player)
|
||||
{
|
||||
if (Time.time - lastPingTime < DvergarConfig.RunicPingCooldown) return;
|
||||
|
||||
if (player.GetEitr() < DvergarConfig.RunicPingEitrCost)
|
||||
{
|
||||
player.Message(MessageHud.MessageType.Center, "Not enough eitr");
|
||||
return;
|
||||
}
|
||||
|
||||
player.UseEitr(DvergarConfig.RunicPingEitrCost);
|
||||
lastPingTime = Time.time;
|
||||
DvergarStatusEffects.ApplyCooldownIcon(DvergarConfig.RunicPingCdSE, DvergarConfig.RunicPingCooldown);
|
||||
|
||||
int marked = MarkSurroundings(player);
|
||||
player.Message(MessageHud.MessageType.Center,
|
||||
marked > 0 ? $"Runic Ping: {marked} echoes answer" : "Runic Ping: the stone is silent");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Lights every ore vein and every hostile within the radius for the duration. The marker
|
||||
/// is a local point light parented to the target, the same trick the Aswid's Auspex uses -
|
||||
/// nothing is replicated, so it costs other players nothing.
|
||||
/// </summary>
|
||||
private static int MarkSurroundings(Player player)
|
||||
{
|
||||
Vector3 center = player.transform.position;
|
||||
HashSet<GameObject> alreadyMarked = new HashSet<GameObject>();
|
||||
int marked = 0;
|
||||
|
||||
foreach (Collider collider in Physics.OverlapSphere(center, DvergarConfig.RunicPingRadius))
|
||||
{
|
||||
if (collider == null) continue;
|
||||
|
||||
GameObject vein = FindVeinRoot(collider);
|
||||
if (vein == null || !alreadyMarked.Add(vein)) continue;
|
||||
|
||||
SpawnMarker(vein.transform, DvergarConfig.RunicPingOreColor);
|
||||
marked++;
|
||||
}
|
||||
|
||||
foreach (Character character in Character.GetAllCharacters())
|
||||
{
|
||||
if (character == null || character == player || character.IsDead() || character.IsTamed()) continue;
|
||||
if (Vector3.Distance(character.transform.position, center) > DvergarConfig.RunicPingRadius) continue;
|
||||
if (!BaseAI.IsEnemy(player, character)) continue;
|
||||
if (!alreadyMarked.Add(character.gameObject)) continue;
|
||||
|
||||
SpawnMarker(character.transform, DvergarConfig.RunicPingEnemyColor);
|
||||
marked++;
|
||||
}
|
||||
|
||||
return marked;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The mineable object a collider belongs to, or null. Both halves matter: the component
|
||||
/// check keeps ordinary terrain out, and the name check keeps plain rock and trees out of
|
||||
/// what is meant to read as an ore reading.
|
||||
/// </summary>
|
||||
private static GameObject FindVeinRoot(Collider collider)
|
||||
{
|
||||
GameObject root = null;
|
||||
|
||||
MineRock5 mineRock5 = collider.GetComponentInParent<MineRock5>();
|
||||
if (mineRock5 != null) root = mineRock5.gameObject;
|
||||
|
||||
if (root == null)
|
||||
{
|
||||
MineRock mineRock = collider.GetComponentInParent<MineRock>();
|
||||
if (mineRock != null) root = mineRock.gameObject;
|
||||
}
|
||||
|
||||
if (root == null)
|
||||
{
|
||||
Destructible destructible = collider.GetComponentInParent<Destructible>();
|
||||
if (destructible != null && destructible.m_destructibleType != DestructibleType.Tree)
|
||||
{
|
||||
root = destructible.gameObject;
|
||||
}
|
||||
}
|
||||
|
||||
if (root == null) return null;
|
||||
|
||||
string name = root.name.ToLower();
|
||||
foreach (string veinName in DvergarConfig.RunicPingVeinNames)
|
||||
{
|
||||
if (name.Contains(veinName)) return root;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static void SpawnMarker(Transform target, Color color)
|
||||
{
|
||||
GameObject markerObj = new GameObject("DvergarRunicMark");
|
||||
markerObj.transform.SetParent(target, false);
|
||||
markerObj.transform.localPosition = Vector3.up;
|
||||
|
||||
Light light = markerObj.AddComponent<Light>();
|
||||
light.type = LightType.Point;
|
||||
light.color = color;
|
||||
light.range = DvergarConfig.RunicPingLightRange;
|
||||
light.intensity = DvergarConfig.RunicPingLightIntensity;
|
||||
light.shadows = LightShadows.None;
|
||||
|
||||
if (DvergarRace.Instance != null)
|
||||
{
|
||||
DvergarRace.Instance.StartCoroutine(DestroyAfter(markerObj, DvergarConfig.RunicPingDuration));
|
||||
}
|
||||
else
|
||||
{
|
||||
// No driver to run the coroutine on: better a marker that never appears than one
|
||||
// that never goes away.
|
||||
Object.Destroy(markerObj);
|
||||
}
|
||||
}
|
||||
|
||||
private static IEnumerator DestroyAfter(GameObject obj, float seconds)
|
||||
{
|
||||
yield return new WaitForSeconds(seconds);
|
||||
if (obj != null) Object.Destroy(obj);
|
||||
}
|
||||
|
||||
// ─── Runic Overcharge ────────────────────────────────────────────────
|
||||
|
||||
private static void TryRunicOvercharge(Player player)
|
||||
{
|
||||
if (Time.time - lastOverchargeTime < DvergarConfig.RunicOverchargeCooldown) return;
|
||||
|
||||
int overchargeHash = DvergarConfig.OverchargeSE.GetStableHashCode();
|
||||
if (player.GetSEMan().HaveStatusEffect(overchargeHash)) return; // already loaded
|
||||
|
||||
if (player.GetEitr() < DvergarConfig.RunicOverchargeEitrCost)
|
||||
{
|
||||
player.Message(MessageHud.MessageType.Center, "Not enough eitr");
|
||||
return;
|
||||
}
|
||||
|
||||
player.UseEitr(DvergarConfig.RunicOverchargeEitrCost);
|
||||
lastOverchargeTime = Time.time;
|
||||
DvergarStatusEffects.ApplyCooldownIcon(DvergarConfig.OverchargeCdSE, DvergarConfig.RunicOverchargeCooldown);
|
||||
|
||||
player.GetSEMan().AddStatusEffect(overchargeHash, true);
|
||||
StatusEffect se = player.GetSEMan().GetStatusEffect(overchargeHash);
|
||||
// The charge is held, not permanent: it lapses if no favoured blow lands in time.
|
||||
if (se != null) se.m_ttl = DvergarConfig.RunicOverchargeWindow;
|
||||
|
||||
player.Message(MessageHud.MessageType.Center, "Runic Overcharge: your next blow is loaded");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Spends a held charge. Called from the damage patch once it has confirmed the blow was
|
||||
/// struck with a weapon the Dvergar is at home with.
|
||||
/// </summary>
|
||||
public static bool ConsumeOvercharge(Player player)
|
||||
{
|
||||
if (player == null) return false;
|
||||
|
||||
int hash = DvergarConfig.OverchargeSE.GetStableHashCode();
|
||||
if (!player.GetSEMan().HaveStatusEffect(hash)) return false;
|
||||
|
||||
player.GetSEMan().RemoveStatusEffect(hash, true);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
283
JotunnModStub/Dvergar/DvergarConfig.cs
Normal file
283
JotunnModStub/Dvergar/DvergarConfig.cs
Normal file
|
|
@ -0,0 +1,283 @@
|
|||
using UnityEngine;
|
||||
|
||||
namespace RacesOfValheim
|
||||
{
|
||||
/// <summary>
|
||||
/// Every tunable number the Dvergar uses, in one place.
|
||||
///
|
||||
/// The race was specced with most percentages still open, so nothing here is baked into the
|
||||
/// logic: DvergarProgression reads these to build its per-tier rules and the patches read the
|
||||
/// rules, never a literal. Retuning the race means editing this file only.
|
||||
///
|
||||
/// Values still marked TODO are placeholders chosen to be playable, not final.
|
||||
/// </summary>
|
||||
public static class DvergarConfig
|
||||
{
|
||||
// ─── Identity ────────────────────────────────────────────────────────
|
||||
// "Dvergar" is provisional. It is the value stored in m_customData["Race"] and in the
|
||||
// ZDO, so renaming it after players have chosen the race would orphan their characters.
|
||||
public const string RaceId = "Dvergar";
|
||||
|
||||
public const string StatsSE = "SE_DvergarStats";
|
||||
public const string OverchargeSE = "SE_DvergarOvercharge";
|
||||
public const string RunicPingCdSE = "SE_DvergarRunicPingCooldown";
|
||||
public const string OverchargeCdSE = "SE_DvergarOverchargeCooldown";
|
||||
|
||||
// Mirrors the ZDO key layout the other races use, so remote clients can read the tier
|
||||
// without having the local player's progression state.
|
||||
public const string StateZdoKey = "RacesOfValheim_DvergarState";
|
||||
|
||||
// ─── Model ───────────────────────────────────────────────────────────
|
||||
// Applied to the player's "Visual" child rather than the root transform, the way Furling
|
||||
// does it: scaling the root would drag the collider and camera pivot along with it.
|
||||
// Tuning knobs are static readonly rather than const throughout: a const folds at compile
|
||||
// time, which turns "is this perk switched off?" guards into dead code the moment a knob
|
||||
// is set to zero, and would bake the old value into any assembly built against this one.
|
||||
// Nudged up from the 0.70 the spec asked for: -30% read as too small next to a human once
|
||||
// it was actually on screen.
|
||||
public static readonly float VisualScale = 0.78f; // -22% versus a human
|
||||
|
||||
// ─── Skin ────────────────────────────────────────────────────────────
|
||||
// Written straight onto the body material's _SkinColor by the UpdateColors postfix, which
|
||||
// is the only thing that actually tints a player - see the comment on that patch.
|
||||
//
|
||||
// This is a multiplier over the human skin texture, not a replacement, so a value near
|
||||
// (1,1,1) changes nothing anyone can see. The first attempt at (0.72, 0.74, 0.82) was
|
||||
// exactly that mistake: correct code, invisible result. Every race that reads clearly
|
||||
// commits to a channel - Trol (0.1, 0.6, 0.7), Furling (0.3, 0.8, 0.3) - so the Dvergar
|
||||
// does too: a cold, dark slate blue-grey.
|
||||
public static readonly Color SkinColor = new Color(0.42f, 0.52f, 0.68f, 1f);
|
||||
|
||||
// Dvergr are white-haired. The hood hides most of it, but the beard shows.
|
||||
public static readonly Color HairColor = new Color(0.85f, 0.87f, 0.92f, 1f);
|
||||
|
||||
// ─── Cosmetic hood ───────────────────────────────────────────────────
|
||||
// The helmet slot itself stays free — whatever the player equips keeps all of its stats,
|
||||
// only the mesh is swapped.
|
||||
//
|
||||
// The hood is lifted straight off the Dvergr NPC rather than off the Dverger Circlet item:
|
||||
// the circlet is a metal band, not the hood the race is meant to wear.
|
||||
//
|
||||
// Two facts out of dumpdverger decide how this is done.
|
||||
//
|
||||
// The prefab holds one renderer, 'dvergr', whose mesh reports zero triangles - it ships
|
||||
// with Read/Write disabled, so its vertices and indices cannot be touched at runtime and
|
||||
// no amount of submesh carving will ever produce geometry.
|
||||
//
|
||||
// But its rig carries a dedicated hat1/hat2/hat3 bone chain under 'head'. The hood is
|
||||
// skinned to those bones and nothing else is, so the hood can be isolated by collapsing
|
||||
// every other bone to zero scale rather than by editing the mesh at all.
|
||||
public const string DvergerPrefabName = "Dverger";
|
||||
|
||||
// The child of the prefab holding the armature and the renderer.
|
||||
public const string DvergerVisualName = "Visual";
|
||||
|
||||
// Root of the hat bone chain, and the bone whose collapse hides everything else.
|
||||
public const string HoodBoneName = "hat1";
|
||||
public const string BodyRootBoneName = "Root";
|
||||
|
||||
// Bone the hood is hung from on the player's own rig.
|
||||
public const string PlayerHeadBoneName = "Head";
|
||||
|
||||
// Nudges on top of the automatic alignment, which already puts the hat bone on the player's
|
||||
// head bone. Scale is the one most likely to need a look: the hood is authored for a Dvergr
|
||||
// skull, not a human one.
|
||||
public static readonly Vector3 HoodOffsetPosition = Vector3.zero;
|
||||
public static readonly Vector3 HoodOffsetRotation = Vector3.zero;
|
||||
public static readonly float HoodExtraScale = 1f;
|
||||
|
||||
|
||||
// ─── Health malus ────────────────────────────────────────────────────
|
||||
// Indexed by progression state; index 0 is unused so the state number indexes directly.
|
||||
// Base -10, growing to -20 once The Queen falls.
|
||||
public static readonly float[] HealthMalusByState =
|
||||
{
|
||||
0f, // (unused)
|
||||
10f, // 1 Base
|
||||
10f, // 2 Eikthyr
|
||||
10f, // 3 The Elder
|
||||
13f, // 4 Bonemass
|
||||
15f, // 5 Moder
|
||||
17.5f, // 6 Yagluth TODO: spec says -17/-18, pick one
|
||||
20f, // 7 The Queen
|
||||
20f // 8 Fader
|
||||
};
|
||||
|
||||
// A Dvergar must never be reduced below this, however the malus and food line up.
|
||||
public static readonly float MinMaxHealth = 5f;
|
||||
|
||||
// ─── Elemental affinity ──────────────────────────────────────────────
|
||||
// Runes in the blood: every blow the Dvergar lands carries lightning.
|
||||
//
|
||||
// Deliberately the same shape as Skadi's Ice Affinity - live from the base tier and
|
||||
// growing by a flat step per progression state, so +2 at Base through +16 after Fader -
|
||||
// with lightning in place of frost. SkadiDamagePatch is the reference; like it, this
|
||||
// applies to every blow the player lands, not only melee.
|
||||
public static readonly float ElementalDamagePerState = 2f;
|
||||
|
||||
public static readonly HitData.DamageType ElementalDamageType = HitData.DamageType.Lightning;
|
||||
|
||||
// ─── Weapon affinity ─────────────────────────────────────────────────
|
||||
// Bonus damage plus a stamina discount on the attack. Neither scales with the tier - a
|
||||
// tier only ever adds a new weapon to the list - and skill XP is deliberately untouched.
|
||||
public struct WeaponAffinity
|
||||
{
|
||||
public Skills.SkillType Skill;
|
||||
public int UnlockState;
|
||||
public HitData.DamageType FlatDamageType; // channel the flat bonus lands on
|
||||
public float FlatDamage; // TODO
|
||||
public float DamagePercent; // TODO, share of physical damage added
|
||||
public float StaminaPercent; // TODO, share of attack stamina refunded
|
||||
public float StaminaFlat; // TODO, flat stamina refunded
|
||||
public string DisplayName;
|
||||
}
|
||||
|
||||
public static readonly WeaponAffinity[] WeaponAffinities =
|
||||
{
|
||||
new WeaponAffinity
|
||||
{
|
||||
Skill = Skills.SkillType.Clubs, UnlockState = 1,
|
||||
FlatDamageType = HitData.DamageType.Blunt,
|
||||
FlatDamage = 0f, DamagePercent = 0.15f,
|
||||
StaminaPercent = 0.20f, StaminaFlat = 0f,
|
||||
DisplayName = "Hammer"
|
||||
},
|
||||
new WeaponAffinity
|
||||
{
|
||||
Skill = Skills.SkillType.Bows, UnlockState = 2,
|
||||
FlatDamageType = HitData.DamageType.Pierce,
|
||||
FlatDamage = 0f, DamagePercent = 0.15f,
|
||||
StaminaPercent = 0.20f, StaminaFlat = 0f,
|
||||
DisplayName = "Bow"
|
||||
},
|
||||
new WeaponAffinity
|
||||
{
|
||||
Skill = Skills.SkillType.Axes, UnlockState = 3,
|
||||
FlatDamageType = HitData.DamageType.Slash,
|
||||
FlatDamage = 0f, DamagePercent = 0.15f,
|
||||
StaminaPercent = 0.20f, StaminaFlat = 0f,
|
||||
DisplayName = "Axe"
|
||||
},
|
||||
new WeaponAffinity
|
||||
{
|
||||
Skill = Skills.SkillType.Crossbows, UnlockState = 6,
|
||||
FlatDamageType = HitData.DamageType.Pierce,
|
||||
FlatDamage = 0f, DamagePercent = 0.15f,
|
||||
StaminaPercent = 0.20f, StaminaFlat = 0f,
|
||||
DisplayName = "Crossbow"
|
||||
}
|
||||
};
|
||||
|
||||
// ─── Mining affinity ─────────────────────────────────────────────────
|
||||
// Unlocks alongside the antler pickaxe.
|
||||
public const int MiningAffinityState = 2;
|
||||
|
||||
// Faster mining is modelled as extra pickaxe damage per swing rather than a swing-rate
|
||||
// change: rock HP is what actually gates how long a vein takes.
|
||||
public static readonly float MiningDamageMultiplier = 1.20f; // TODO: 20% faster?
|
||||
public static readonly float MiningStaminaPercent = 0.40f; // TODO: or 40% less stamina?
|
||||
|
||||
// Chance for a mined vein to yield an extra unit of ore. 0 disables the yield half of
|
||||
// the affinity and leaves it purely a speed/stamina perk.
|
||||
public static readonly float MiningExtraDropChance = 0.25f; // TODO
|
||||
|
||||
// Matched against the drop prefab name, lowercased, by Contains.
|
||||
public static readonly string[] OreDropNames =
|
||||
{
|
||||
"copperore", "tinore", "ironscrap", "silverore", "blackmetalscrap", "flametalore"
|
||||
};
|
||||
|
||||
// ─── Smithing / jewelry ──────────────────────────────────────────────
|
||||
// Percentage saved on the metal cost of crafting and upgrading. Starts at Bonemass and
|
||||
// caps at Moder. Indexed by progression state.
|
||||
public static readonly float[] SmithingDiscountByState =
|
||||
{
|
||||
0f, // (unused)
|
||||
0f, // 1 Base
|
||||
0f, // 2 Eikthyr
|
||||
0f, // 3 The Elder
|
||||
0.20f, // 4 Bonemass
|
||||
0.40f, // 5 Moder - cap
|
||||
0.40f, // 6 Yagluth
|
||||
0.40f, // 7 The Queen
|
||||
0.40f // 8 Fader
|
||||
};
|
||||
|
||||
// Only these resources are discounted, which is what keeps the perk to smithing and
|
||||
// jewelry rather than quietly cheapening every wooden wall the player puts up.
|
||||
public static readonly string[] DiscountedResourceNames =
|
||||
{
|
||||
"copper", "tin", "bronze", "iron", "silver", "blackmetal", "flametal",
|
||||
"ironnails", "bronzenails", "copperore", "tinore", "silverore", "flametalore",
|
||||
"ruby", "amber", "amberpearl", "coins", "silvernecklace"
|
||||
};
|
||||
|
||||
// ─── Haldor / Hildir favour ──────────────────────────────────────────
|
||||
// Both halves of the trade: a discount on what the traders charge, and a bonus on what
|
||||
// they pay for trophies and hunting rewards. Indexed by progression state.
|
||||
public static readonly float[] TraderBuyDiscountByState =
|
||||
{
|
||||
0f, // (unused)
|
||||
0f, // 1 Base
|
||||
0f, // 2 Eikthyr
|
||||
0f, // 3 The Elder
|
||||
0.10f, // 4 Bonemass - step 1 TODO
|
||||
0.15f, // 5 Moder - step 2 TODO
|
||||
0.20f, // 6 Yagluth - step 3 TODO
|
||||
0.25f, // 7 The Queen - full TODO
|
||||
0.25f // 8 Fader
|
||||
};
|
||||
|
||||
public static readonly float[] TraderSellBonusByState =
|
||||
{
|
||||
0f, // (unused)
|
||||
0f, // 1 Base
|
||||
0f, // 2 Eikthyr
|
||||
0f, // 3 The Elder
|
||||
0.10f, // 4 Bonemass - step 1 TODO
|
||||
0.20f, // 5 Moder - step 2 TODO
|
||||
0.30f, // 6 Yagluth - step 3 TODO
|
||||
0.40f, // 7 The Queen - full TODO
|
||||
0.40f // 8 Fader
|
||||
};
|
||||
|
||||
// ─── Runic Ping (Yagluth) ────────────────────────────────────────────
|
||||
public const int RunicPingState = 6;
|
||||
public const KeyCode RunicPingKey = KeyCode.G;
|
||||
|
||||
public static readonly float RunicPingEitrCost = 25f; // TODO
|
||||
public static readonly float RunicPingRadius = 40f; // TODO
|
||||
public static readonly float RunicPingDuration = 10f; // TODO
|
||||
public static readonly float RunicPingCooldown = 20f; // TODO
|
||||
|
||||
public static readonly Color RunicPingOreColor = new Color(0.4f, 0.8f, 1f);
|
||||
public static readonly Color RunicPingEnemyColor = new Color(1f, 0.35f, 0.35f);
|
||||
public static readonly float RunicPingLightRange = 8f;
|
||||
public static readonly float RunicPingLightIntensity = 2f;
|
||||
|
||||
// Vein prefabs are matched on name, lowercased, by Contains - MineRock5_Copper,
|
||||
// silvervein, rock4_copper and friends all fall out of this list.
|
||||
public static readonly string[] RunicPingVeinNames =
|
||||
{
|
||||
"copper", "tin", "silvervein", "obsidian", "meteorite", "flametal", "mudpile", "leviathan"
|
||||
};
|
||||
|
||||
// ─── Runic Overcharge (Fader) ────────────────────────────────────────
|
||||
public const int RunicOverchargeState = 8;
|
||||
public const KeyCode RunicOverchargeKey = KeyCode.H;
|
||||
|
||||
public static readonly float RunicOverchargeEitrCost = 60f; // TODO
|
||||
public static readonly float RunicOverchargeMultiplier = 4f; // TODO, applied to physical damage
|
||||
public static readonly float RunicOverchargeWindow = 15f; // seconds the charge is held
|
||||
public static readonly float RunicOverchargeCooldown = 60f; // TODO
|
||||
|
||||
// ─── Helpers ─────────────────────────────────────────────────────────
|
||||
/// <summary>Clamped table lookup, so a state outside 1..8 can never index out of range.</summary>
|
||||
public static float Lookup(float[] table, int state)
|
||||
{
|
||||
if (table == null || table.Length == 0) return 0f;
|
||||
int index = Mathf.Clamp(state, BossProgressionManager.MinState, table.Length - 1);
|
||||
return table[index];
|
||||
}
|
||||
}
|
||||
}
|
||||
384
JotunnModStub/Dvergar/DvergarPatches.cs
Normal file
384
JotunnModStub/Dvergar/DvergarPatches.cs
Normal file
|
|
@ -0,0 +1,384 @@
|
|||
using System.Collections.Generic;
|
||||
using System.Reflection;
|
||||
using HarmonyLib;
|
||||
using UnityEngine;
|
||||
|
||||
namespace RacesOfValheim
|
||||
{
|
||||
/// <summary>
|
||||
/// Every hook the Dvergar needs. The patches only ever decide *whether* a perk applies; *how
|
||||
/// much* it applies always comes from DvergarProgression, which in turn reads DvergarConfig.
|
||||
/// </summary>
|
||||
public static class DvergarPatches
|
||||
{
|
||||
// ─── Health malus ────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// The Dvergar is a small frame, and carries less health for it.
|
||||
///
|
||||
/// The malus is taken off the food total rather than off Character.GetMaxHealth, which is
|
||||
/// what the first attempt did and what produced the bug where the bar shrank but the
|
||||
/// number stayed put and the border flashed. Patching the getter makes it lie to the rest
|
||||
/// of the game: Character.SetMaxHealth is the only thing that clamps current health down
|
||||
/// to the new maximum, and it never saw a lower number, so m_health stayed at 58. Worse,
|
||||
/// Player.SetMaxHealth flashes the bar whenever the new maximum is above GetMaxHealth() -
|
||||
/// against a getter that always read low, every food tick looked like a health *increase*
|
||||
/// and re-triggered the flash.
|
||||
///
|
||||
/// GetTotalFoodValue is upstream of both: UpdateFood feeds its result straight into
|
||||
/// SetMaxHealth, so Valheim does its own clamping and its own flash logic on an honest
|
||||
/// number and bar, value and animation all agree.
|
||||
/// </summary>
|
||||
[HarmonyPatch(typeof(Player), "GetTotalFoodValue")]
|
||||
public static class Dvergar_GetTotalFoodValue_Patch
|
||||
{
|
||||
public static void Postfix(Player __instance, ref float hp)
|
||||
{
|
||||
if (__instance == null || __instance != Player.m_localPlayer) return;
|
||||
if (!DvergarRace.IsDvergar()) return;
|
||||
|
||||
float malus = DvergarProgression.Current.HealthMalus;
|
||||
if (malus <= 0f) return;
|
||||
|
||||
hp = Mathf.Max(DvergarConfig.MinMaxHealth, hp - malus);
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Scale ───────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// Sizing runs off Player.Update, which is where the Trol does it and the only place it
|
||||
/// holds: Trol's own postfix forces every non-Trol player's visual back to scale 1 on the
|
||||
/// same frame, so a scale applied from anywhere else was simply overwritten. Being a
|
||||
/// postfix on the same method puts the Dvergar on equal footing, and RaceScale keeps the
|
||||
/// two from undoing each other.
|
||||
/// </summary>
|
||||
[HarmonyPatch(typeof(Player), "Update")]
|
||||
public static class Dvergar_PlayerUpdate_Scale_Patch
|
||||
{
|
||||
public static void Postfix(Player __instance)
|
||||
{
|
||||
if (__instance == null) return;
|
||||
DvergarVisuals.ApplyScale(__instance, DvergarVisuals.IsDvergarPlayer(__instance));
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Weapon affinity: damage ─────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// Bonus damage with hammer, bow, axe and crossbow as each is unlocked, and the payoff for
|
||||
/// a held Runic Overcharge. Neither touches skill XP: the Dvergar is at home with these
|
||||
/// weapons, not faster at learning them.
|
||||
/// </summary>
|
||||
[HarmonyPatch(typeof(Character), "Damage")]
|
||||
public static class Dvergar_WeaponAffinity_Damage_Patch
|
||||
{
|
||||
public static void Prefix(Character __instance, HitData hit)
|
||||
{
|
||||
if (hit == null || Player.m_localPlayer == null) return;
|
||||
if (hit.GetAttacker() != Player.m_localPlayer) return;
|
||||
if (!DvergarRace.IsDvergar()) return;
|
||||
|
||||
int state = BossProgressionManager.GetCurrentProgressionState();
|
||||
|
||||
// Runic Spark, before the weapon check: the lightning rides every blow the Dvergar
|
||||
// lands, favoured weapon or not, exactly as Skadi's frost does in SkadiDamagePatch.
|
||||
float elemental = DvergarProgression.GetRules(state).ElementalDamage;
|
||||
if (elemental > 0f)
|
||||
{
|
||||
AddFlat(hit, DvergarConfig.ElementalDamageType, elemental);
|
||||
}
|
||||
|
||||
DvergarConfig.WeaponAffinity? found = DvergarProgression.GetAffinity(hit.m_skill, state);
|
||||
if (!found.HasValue) return;
|
||||
|
||||
DvergarConfig.WeaponAffinity affinity = found.Value;
|
||||
|
||||
if (affinity.DamagePercent > 0f)
|
||||
{
|
||||
ScalePhysical(hit, 1f + affinity.DamagePercent);
|
||||
}
|
||||
|
||||
if (affinity.FlatDamage > 0f)
|
||||
{
|
||||
AddFlat(hit, affinity.FlatDamageType, affinity.FlatDamage);
|
||||
}
|
||||
|
||||
// Overcharge only ever discharges into a favoured weapon, which is why it is
|
||||
// spent here rather than on the first hit of any kind.
|
||||
if (DvergarProgression.GetRules(state).RunicOvercharge &&
|
||||
DvergarAbilities.ConsumeOvercharge(Player.m_localPlayer))
|
||||
{
|
||||
ScalePhysical(hit, DvergarConfig.RunicOverchargeMultiplier);
|
||||
Player.m_localPlayer.Message(MessageHud.MessageType.TopLeft, "Runic Overcharge discharges");
|
||||
}
|
||||
}
|
||||
|
||||
private static void ScalePhysical(HitData hit, float multiplier)
|
||||
{
|
||||
hit.m_damage.m_blunt *= multiplier;
|
||||
hit.m_damage.m_slash *= multiplier;
|
||||
hit.m_damage.m_pierce *= multiplier;
|
||||
}
|
||||
|
||||
private static void AddFlat(HitData hit, HitData.DamageType type, float amount)
|
||||
{
|
||||
switch (type)
|
||||
{
|
||||
case HitData.DamageType.Blunt: hit.m_damage.m_blunt += amount; break;
|
||||
case HitData.DamageType.Slash: hit.m_damage.m_slash += amount; break;
|
||||
case HitData.DamageType.Pierce: hit.m_damage.m_pierce += amount; break;
|
||||
case HitData.DamageType.Fire: hit.m_damage.m_fire += amount; break;
|
||||
case HitData.DamageType.Frost: hit.m_damage.m_frost += amount; break;
|
||||
case HitData.DamageType.Lightning: hit.m_damage.m_lightning += amount; break;
|
||||
case HitData.DamageType.Poison: hit.m_damage.m_poison += amount; break;
|
||||
case HitData.DamageType.Spirit: hit.m_damage.m_spirit += amount; break;
|
||||
default: hit.m_damage.m_damage += amount; break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Mining affinity ─────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// Set for the duration of a mining hit so the drop patch below can tell an ore roll made
|
||||
/// by this player apart from every other DropTable call in the world. Same flag-around-the
|
||||
/// -call approach the Furling uses for its doubled ore.
|
||||
/// </summary>
|
||||
private static bool isDvergarMining = false;
|
||||
|
||||
private static bool BeginMiningHit(HitData hit)
|
||||
{
|
||||
if (hit == null || Player.m_localPlayer == null) return false;
|
||||
if (hit.GetAttacker() != Player.m_localPlayer) return false;
|
||||
if (!DvergarRace.IsDvergar()) return false;
|
||||
if (!DvergarProgression.Current.MiningAffinity) return false;
|
||||
|
||||
// A pickaxe swing is what the affinity is about - chopping and combat hits on the same
|
||||
// objects go through here too and must be left alone.
|
||||
if (hit.m_damage.m_pickaxe <= 0f) return false;
|
||||
|
||||
hit.m_damage.m_pickaxe *= DvergarConfig.MiningDamageMultiplier;
|
||||
isDvergarMining = true;
|
||||
return true;
|
||||
}
|
||||
|
||||
private static void EndMiningHit(bool began)
|
||||
{
|
||||
if (began) isDvergarMining = false;
|
||||
}
|
||||
|
||||
[HarmonyPatch(typeof(MineRock5), "DamageArea")]
|
||||
public static class Dvergar_MineRock5_DamageArea_Patch
|
||||
{
|
||||
public static void Prefix(HitData hit, out bool __state) => __state = BeginMiningHit(hit);
|
||||
public static void Postfix(bool __state) => EndMiningHit(__state);
|
||||
}
|
||||
|
||||
[HarmonyPatch(typeof(MineRock), "RPC_Hit")]
|
||||
public static class Dvergar_MineRock_RPC_Hit_Patch
|
||||
{
|
||||
public static void Prefix(HitData hit, out bool __state) => __state = BeginMiningHit(hit);
|
||||
public static void Postfix(bool __state) => EndMiningHit(__state);
|
||||
}
|
||||
|
||||
[HarmonyPatch(typeof(Destructible), "RPC_Damage")]
|
||||
public static class Dvergar_Destructible_RPC_Damage_Patch
|
||||
{
|
||||
public static void Prefix(HitData hit, out bool __state) => __state = BeginMiningHit(hit);
|
||||
public static void Postfix(bool __state) => EndMiningHit(__state);
|
||||
}
|
||||
|
||||
[HarmonyPatch(typeof(DropTable), "GetDropList", new System.Type[] { typeof(int) })]
|
||||
public static class Dvergar_DropTable_GetDropList_Patch
|
||||
{
|
||||
public static void Postfix(ref List<GameObject> __result)
|
||||
{
|
||||
if (!isDvergarMining || __result == null) return;
|
||||
if (DvergarConfig.MiningExtraDropChance <= 0f) return;
|
||||
|
||||
List<GameObject> extra = new List<GameObject>();
|
||||
foreach (GameObject drop in __result)
|
||||
{
|
||||
if (drop == null || !IsOre(drop.name)) continue;
|
||||
if (Random.value <= DvergarConfig.MiningExtraDropChance) extra.Add(drop);
|
||||
}
|
||||
__result.AddRange(extra);
|
||||
}
|
||||
|
||||
private static bool IsOre(string prefabName)
|
||||
{
|
||||
string lower = prefabName.ToLower();
|
||||
foreach (string ore in DvergarConfig.OreDropNames)
|
||||
{
|
||||
if (lower.Contains(ore)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Smithing and jewelry ────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// Metal saved when crafting and upgrading. Requirement.GetAmount is the single point both
|
||||
/// the crafting panel and Player.ConsumeResources go through, so the figure the player is
|
||||
/// quoted and the figure they are charged can never drift apart.
|
||||
///
|
||||
/// Scoped to the metals and gems in DvergarConfig.DiscountedResourceNames, which is what
|
||||
/// keeps this a smithing perk rather than a blanket discount on every wooden wall.
|
||||
/// </summary>
|
||||
[HarmonyPatch(typeof(Piece.Requirement), "GetAmount")]
|
||||
public static class Dvergar_Requirement_GetAmount_Patch
|
||||
{
|
||||
public static void Postfix(Piece.Requirement __instance, ref int __result)
|
||||
{
|
||||
if (__result <= 1 || Player.m_localPlayer == null) return;
|
||||
if (!DvergarRace.IsDvergar()) return;
|
||||
|
||||
float discount = DvergarProgression.Current.SmithingDiscount;
|
||||
if (discount <= 0f) return;
|
||||
|
||||
if (__instance == null || __instance.m_resItem == null) return;
|
||||
if (!IsDiscounted(__instance.m_resItem.gameObject.name)) return;
|
||||
|
||||
__result = Mathf.Max(1, Mathf.RoundToInt(__result * (1f - discount)));
|
||||
}
|
||||
|
||||
private static bool IsDiscounted(string prefabName)
|
||||
{
|
||||
string lower = prefabName.ToLower();
|
||||
foreach (string resource in DvergarConfig.DiscountedResourceNames)
|
||||
{
|
||||
if (lower == resource || lower.Contains(resource)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Haldor and Hildir's favour ──────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// The buying half. Both traders are Trader components, so patching the shared source of
|
||||
/// the stock list covers Haldor and Hildir at once.
|
||||
///
|
||||
/// The discounted entries are fresh TradeItem instances rather than edited originals: the
|
||||
/// list Valheim hands back holds the trader's own objects, and rewriting their prices in
|
||||
/// place would permanently mark down the shop for everyone, Dvergar or not.
|
||||
/// </summary>
|
||||
[HarmonyPatch(typeof(Trader), "GetAvailableItems")]
|
||||
public static class Dvergar_Trader_GetAvailableItems_Patch
|
||||
{
|
||||
public static void Postfix(ref List<Trader.TradeItem> __result)
|
||||
{
|
||||
if (__result == null || Player.m_localPlayer == null) return;
|
||||
if (!DvergarRace.IsDvergar()) return;
|
||||
|
||||
float discount = DvergarProgression.Current.TraderBuyDiscount;
|
||||
if (discount <= 0f) return;
|
||||
|
||||
List<Trader.TradeItem> discounted = new List<Trader.TradeItem>(__result.Count);
|
||||
foreach (Trader.TradeItem item in __result)
|
||||
{
|
||||
if (item == null) continue;
|
||||
|
||||
discounted.Add(new Trader.TradeItem
|
||||
{
|
||||
m_prefab = item.m_prefab,
|
||||
m_stack = item.m_stack,
|
||||
m_price = Mathf.Max(1, Mathf.RoundToInt(item.m_price * (1f - discount))),
|
||||
m_requiredGlobalKey = item.m_requiredGlobalKey
|
||||
});
|
||||
}
|
||||
|
||||
__result = discounted;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The selling half - trophies and hunting rewards fetch more. GetValue is what the sell
|
||||
/// button both displays and pays out, and it is not consulted for purchases, so the bonus
|
||||
/// lands on exactly the side of the counter it is meant to.
|
||||
/// </summary>
|
||||
[HarmonyPatch(typeof(ItemDrop.ItemData), "GetValue")]
|
||||
public static class Dvergar_ItemData_GetValue_Patch
|
||||
{
|
||||
public static void Postfix(ref int __result)
|
||||
{
|
||||
if (__result <= 0 || Player.m_localPlayer == null) return;
|
||||
if (!DvergarRace.IsDvergar()) return;
|
||||
|
||||
float bonus = DvergarProgression.Current.TraderSellBonus;
|
||||
if (bonus <= 0f) return;
|
||||
|
||||
__result = Mathf.RoundToInt(__result * (1f + bonus));
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Skin ────────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// Tints the Dvergar ashen grey.
|
||||
///
|
||||
/// The first attempt did this the way the race-selection menu appears to - VisEquipment's
|
||||
/// SetSkinColor followed by UpdateColors - and nothing happened, because that pair is not
|
||||
/// what actually colours a player. UpdateColors rebuilds the body material from Valheim's
|
||||
/// own state on every refresh, so any tint has to be written *after* it runs. That is why
|
||||
/// every race in this mod that visibly changes colour has a postfix here writing
|
||||
/// _SkinColor onto the material directly, and why the SetSkinColor calls in the selection
|
||||
/// menu are, on their own, decorative.
|
||||
///
|
||||
/// No local-player check and no saved original: the race is read from the ZDO with a
|
||||
/// m_customData fallback so the main-menu preview and the first spawn frame are covered
|
||||
/// too, and the tint simply stops being applied once the player is no longer a Dvergar.
|
||||
/// </summary>
|
||||
[HarmonyPatch(typeof(VisEquipment), "UpdateColors")]
|
||||
public static class Dvergar_VisEquipment_UpdateColors_Patch
|
||||
{
|
||||
public static void Postfix(VisEquipment __instance)
|
||||
{
|
||||
if (__instance == null || !__instance.m_isPlayer) return;
|
||||
|
||||
Player player = __instance.GetComponent<Player>();
|
||||
if (player == null || !DvergarVisuals.IsDvergarPlayer(player)) return;
|
||||
|
||||
if (__instance.m_bodyModel != null && __instance.m_bodyModel.material != null)
|
||||
{
|
||||
__instance.m_bodyModel.material.SetColor("_SkinColor", DvergarConfig.SkinColor);
|
||||
}
|
||||
|
||||
TintRenderers(Traverse.Create(__instance).Field("m_hairItemInstance").GetValue<GameObject>());
|
||||
TintRenderers(Traverse.Create(__instance).Field("m_beardItemInstance").GetValue<GameObject>());
|
||||
}
|
||||
|
||||
private static void TintRenderers(GameObject instance)
|
||||
{
|
||||
if (instance == null) return;
|
||||
foreach (Renderer renderer in instance.GetComponentsInChildren<Renderer>())
|
||||
{
|
||||
if (renderer.material != null) renderer.material.SetColor("_SkinColor", DvergarConfig.HairColor);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Cosmetic hood ───────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// Runs for every player, local and remote, whenever Valheim rebuilds their visuals - the
|
||||
/// point at which a newly equipped helmet has just been instantiated and needs hiding
|
||||
/// again behind the hood.
|
||||
/// </summary>
|
||||
[HarmonyPatch(typeof(VisEquipment), "UpdateVisuals")]
|
||||
public static class Dvergar_VisEquipment_UpdateVisuals_Patch
|
||||
{
|
||||
public static void Postfix(VisEquipment __instance)
|
||||
{
|
||||
if (__instance == null || !__instance.m_isPlayer) return;
|
||||
|
||||
Player player = __instance.GetComponent<Player>();
|
||||
if (player == null) return;
|
||||
|
||||
DvergarVisuals.ApplyHood(player);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
86
JotunnModStub/Dvergar/DvergarProgression.cs
Normal file
86
JotunnModStub/Dvergar/DvergarProgression.cs
Normal file
|
|
@ -0,0 +1,86 @@
|
|||
using System.Collections.Generic;
|
||||
using UnityEngine;
|
||||
|
||||
namespace RacesOfValheim
|
||||
{
|
||||
/// <summary>
|
||||
/// Turns a boss progression state into the set of Dvergar perks active at that tier, the same
|
||||
/// way SkeletonProgression and SkadiProgression do for their races.
|
||||
///
|
||||
/// Nothing is decided here - every figure comes out of DvergarConfig - so the tuning pass can
|
||||
/// happen without touching a single patch.
|
||||
/// </summary>
|
||||
public static class DvergarProgression
|
||||
{
|
||||
public struct DvergarRules
|
||||
{
|
||||
/// <summary>Points subtracted from max health at this tier.</summary>
|
||||
public float HealthMalus;
|
||||
|
||||
/// <summary>Lightning added to every blow at this tier. Live from the base tier.</summary>
|
||||
public float ElementalDamage;
|
||||
|
||||
/// <summary>Weapon skills the Dvergar is at home with, already filtered by tier.</summary>
|
||||
public List<DvergarConfig.WeaponAffinity> Affinities;
|
||||
|
||||
public bool MiningAffinity;
|
||||
public float SmithingDiscount;
|
||||
public float TraderBuyDiscount;
|
||||
public float TraderSellBonus;
|
||||
public bool RunicPing;
|
||||
public bool RunicOvercharge;
|
||||
}
|
||||
|
||||
// GetRules runs from Update loops and from damage patches, so the per-state result is
|
||||
// built once and handed back on every later call.
|
||||
private static readonly DvergarRules[] cache = new DvergarRules[BossProgressionManager.MaxState + 1];
|
||||
private static readonly bool[] cached = new bool[BossProgressionManager.MaxState + 1];
|
||||
|
||||
public static DvergarRules GetRules(int state)
|
||||
{
|
||||
state = Mathf.Clamp(state, BossProgressionManager.MinState, BossProgressionManager.MaxState);
|
||||
if (cached[state]) return cache[state];
|
||||
|
||||
List<DvergarConfig.WeaponAffinity> affinities = new List<DvergarConfig.WeaponAffinity>();
|
||||
foreach (DvergarConfig.WeaponAffinity affinity in DvergarConfig.WeaponAffinities)
|
||||
{
|
||||
if (state >= affinity.UnlockState) affinities.Add(affinity);
|
||||
}
|
||||
|
||||
DvergarRules rules = new DvergarRules
|
||||
{
|
||||
HealthMalus = DvergarConfig.Lookup(DvergarConfig.HealthMalusByState, state),
|
||||
ElementalDamage = DvergarConfig.ElementalDamagePerState * state,
|
||||
Affinities = affinities,
|
||||
MiningAffinity = state >= DvergarConfig.MiningAffinityState,
|
||||
SmithingDiscount = DvergarConfig.Lookup(DvergarConfig.SmithingDiscountByState, state),
|
||||
TraderBuyDiscount = DvergarConfig.Lookup(DvergarConfig.TraderBuyDiscountByState, state),
|
||||
TraderSellBonus = DvergarConfig.Lookup(DvergarConfig.TraderSellBonusByState, state),
|
||||
RunicPing = state >= DvergarConfig.RunicPingState,
|
||||
RunicOvercharge = state >= DvergarConfig.RunicOverchargeState
|
||||
};
|
||||
|
||||
cache[state] = rules;
|
||||
cached[state] = true;
|
||||
return rules;
|
||||
}
|
||||
|
||||
/// <summary>Rules for whatever tier the local player is currently on.</summary>
|
||||
public static DvergarRules Current => GetRules(BossProgressionManager.GetCurrentProgressionState());
|
||||
|
||||
/// <summary>
|
||||
/// The affinity covering a weapon skill at the current tier, or null when the Dvergar has
|
||||
/// no particular feel for it. Mining counts as an affinity for stamina purposes only, so
|
||||
/// it is deliberately not part of this list.
|
||||
/// </summary>
|
||||
public static DvergarConfig.WeaponAffinity? GetAffinity(Skills.SkillType skill, int state)
|
||||
{
|
||||
DvergarRules rules = GetRules(state);
|
||||
foreach (DvergarConfig.WeaponAffinity affinity in rules.Affinities)
|
||||
{
|
||||
if (affinity.Skill == skill) return affinity;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
107
JotunnModStub/Dvergar/DvergarRace.cs
Normal file
107
JotunnModStub/Dvergar/DvergarRace.cs
Normal file
|
|
@ -0,0 +1,107 @@
|
|||
using HarmonyLib;
|
||||
using UnityEngine;
|
||||
|
||||
namespace RacesOfValheim
|
||||
{
|
||||
/// <summary>
|
||||
/// Driver for the Dvergar: a short, stocky smith who trades a slice of health for an affinity
|
||||
/// with hammer, bow, axe and crossbow, a knack for mining and the ear of Haldor and Hildir.
|
||||
///
|
||||
/// Only the per-frame upkeep lives here. Body scale is a Player.Update postfix in
|
||||
/// DvergarPatches, since that is the one place it survives; the perks are the other patches in
|
||||
/// that file; the two eitr abilities are in DvergarAbilities; and every number they use comes
|
||||
/// from DvergarConfig by way of DvergarProgression.
|
||||
/// </summary>
|
||||
public class DvergarRace : MonoBehaviour
|
||||
{
|
||||
public static DvergarRace Instance;
|
||||
|
||||
// NaN so that the very first frame always counts as a change and pushes the malus through.
|
||||
private float lastAppliedMalus = float.NaN;
|
||||
|
||||
private void Awake()
|
||||
{
|
||||
Instance = this;
|
||||
}
|
||||
|
||||
public void CreateModAssets()
|
||||
{
|
||||
DvergarStatusEffects.RegisterStatusEffects();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The race was called "Dvergur" before it was renamed, and that string is what got written
|
||||
/// into m_customData and the ZDO. Without this, every character created under the old name
|
||||
/// would come back with no race at all and be handed the selection menu again.
|
||||
/// </summary>
|
||||
public const string LegacyRaceId = "Dvergur";
|
||||
|
||||
public static void MigrateLegacyRaceId(Player player)
|
||||
{
|
||||
if (player == null || player.m_customData == null) return;
|
||||
if (!player.m_customData.TryGetValue("Race", out string race) || race != LegacyRaceId) return;
|
||||
|
||||
player.m_customData["Race"] = DvergarConfig.RaceId;
|
||||
|
||||
ZNetView nview = player.GetComponent<ZNetView>();
|
||||
if (nview != null && nview.IsValid())
|
||||
{
|
||||
nview.GetZDO().Set("RacesOfValheim_Race", DvergarConfig.RaceId);
|
||||
}
|
||||
|
||||
Jotunn.Logger.LogInfo($"[Dvergar] Migrated '{LegacyRaceId}' to '{DvergarConfig.RaceId}' for {player.GetPlayerName()}.");
|
||||
}
|
||||
|
||||
public static bool IsDvergar()
|
||||
{
|
||||
return Player.m_localPlayer != null &&
|
||||
Player.m_localPlayer.m_customData.ContainsKey("Race") &&
|
||||
Player.m_localPlayer.m_customData["Race"] == DvergarConfig.RaceId;
|
||||
}
|
||||
|
||||
private void Update()
|
||||
{
|
||||
Player player = Player.m_localPlayer;
|
||||
if (player == null) return;
|
||||
|
||||
bool isDvergar = IsDvergar();
|
||||
|
||||
DvergarVisuals.ApplyHood(player);
|
||||
|
||||
// Max health is recomputed by Player.UpdateFood, which runs on its own schedule. Left
|
||||
// to itself the malus would only take effect at the next food tick, so a change of
|
||||
// race or of tier is pushed through immediately - this is also what makes the health
|
||||
// bar and the number agree the instant a player becomes (or stops being) a Dvergar.
|
||||
float desiredMalus = isDvergar ? DvergarProgression.Current.HealthMalus : 0f;
|
||||
if (!Mathf.Approximately(desiredMalus, lastAppliedMalus))
|
||||
{
|
||||
lastAppliedMalus = desiredMalus;
|
||||
Traverse.Create(player).Method("UpdateFood", 0f, true).GetValue();
|
||||
}
|
||||
|
||||
if (!isDvergar || player.IsDead()) return;
|
||||
|
||||
int state = BossProgressionManager.GetCurrentProgressionState();
|
||||
|
||||
// Keep the passive carrier attached. It is re-added rather than assumed because a
|
||||
// respawn, a death or a world load all clear the player's status effects.
|
||||
if (DvergarStatusEffects.StatsSE != null)
|
||||
{
|
||||
int hash = DvergarConfig.StatsSE.GetStableHashCode();
|
||||
if (!player.GetSEMan().HaveStatusEffect(hash))
|
||||
{
|
||||
player.GetSEMan().AddStatusEffect(hash, true);
|
||||
}
|
||||
}
|
||||
|
||||
// Published for remote clients, matching how the Skeleton replicates its tier.
|
||||
ZNetView nview = player.GetComponent<ZNetView>();
|
||||
if (nview != null && nview.IsValid())
|
||||
{
|
||||
nview.GetZDO().Set(DvergarConfig.StateZdoKey, state);
|
||||
}
|
||||
|
||||
DvergarAbilities.Tick(player, state);
|
||||
}
|
||||
}
|
||||
}
|
||||
139
JotunnModStub/Dvergar/DvergarStatusEffects.cs
Normal file
139
JotunnModStub/Dvergar/DvergarStatusEffects.cs
Normal file
|
|
@ -0,0 +1,139 @@
|
|||
using HarmonyLib;
|
||||
using Jotunn.Entities;
|
||||
using Jotunn.Managers;
|
||||
using UnityEngine;
|
||||
|
||||
namespace RacesOfValheim
|
||||
{
|
||||
/// <summary>
|
||||
/// Passive carrier for the Dvergar. The stamina half of weapon affinity lives here rather than
|
||||
/// in a Harmony patch because Valheim already routes attack cost through the status effects
|
||||
/// (SEMan.ModifyAttackStaminaUsage), so there is nothing to intercept.
|
||||
/// </summary>
|
||||
public class SE_DvergarStats : SE_Stats
|
||||
{
|
||||
public override void Setup(Character character)
|
||||
{
|
||||
base.Setup(character);
|
||||
name = DvergarConfig.StatsSE;
|
||||
m_name = "Stone and Forge";
|
||||
m_tooltip = "Small, sturdy, and born to the anvil.";
|
||||
}
|
||||
|
||||
public override void ModifyAttackStaminaUsage(float baseStaminaUse, ref float staminaUse)
|
||||
{
|
||||
base.ModifyAttackStaminaUsage(baseStaminaUse, ref staminaUse);
|
||||
|
||||
if (!(m_character is Player player) || player != Player.m_localPlayer) return;
|
||||
if (!DvergarRace.IsDvergar()) return;
|
||||
|
||||
int state = BossProgressionManager.GetCurrentProgressionState();
|
||||
|
||||
// m_rightItem rather than GetCurrentWeapon(): it is what the rest of the mod reaches
|
||||
// for, and it is the item the swing is actually paying for.
|
||||
ItemDrop.ItemData weapon = Traverse.Create(player).Field<ItemDrop.ItemData>("m_rightItem").Value;
|
||||
if (weapon == null || weapon.m_shared == null) return;
|
||||
|
||||
Skills.SkillType skill = weapon.m_shared.m_skillType;
|
||||
|
||||
// Mining is a discount on the pickaxe, not a weapon affinity, so it is checked apart.
|
||||
if (skill == Skills.SkillType.Pickaxes)
|
||||
{
|
||||
if (DvergarProgression.GetRules(state).MiningAffinity)
|
||||
{
|
||||
staminaUse = Mathf.Max(0f, staminaUse * (1f - DvergarConfig.MiningStaminaPercent));
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
DvergarConfig.WeaponAffinity? affinity = DvergarProgression.GetAffinity(skill, state);
|
||||
if (!affinity.HasValue) return;
|
||||
|
||||
// Static by design: the discount is the same the day it unlocks as it is after Fader.
|
||||
staminaUse = Mathf.Max(0f, staminaUse * (1f - affinity.Value.StaminaPercent) - affinity.Value.StaminaFlat);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Runic Overcharge, held between the cast and the blow that spends it. Purely a marker with a
|
||||
/// countdown - DvergarPatches reads it when the next affine hit lands.
|
||||
/// </summary>
|
||||
public class SE_DvergarOvercharge : StatusEffect
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Ability cooldowns. They exist only so the HUD has something to count down, the way
|
||||
/// SE_SkadiAbilityCooldown does: Valheim prints the remaining time of any effect with a m_ttl.
|
||||
/// </summary>
|
||||
public class SE_DvergarAbilityCooldown : StatusEffect
|
||||
{
|
||||
}
|
||||
|
||||
public static class DvergarStatusEffects
|
||||
{
|
||||
public static SE_DvergarStats StatsSE { get; private set; }
|
||||
|
||||
public static void RegisterStatusEffects()
|
||||
{
|
||||
Sprite icon = GetItemIcon("HelmetDverger") ?? GetItemIcon("DvergrKeyFragment") ?? GetItemIcon("Copper");
|
||||
|
||||
var stats = ScriptableObject.CreateInstance<SE_DvergarStats>();
|
||||
stats.name = DvergarConfig.StatsSE;
|
||||
stats.m_name = "Stone and Forge";
|
||||
stats.m_icon = icon;
|
||||
CustomStatusEffect customStats = new CustomStatusEffect(stats, fixReference: false);
|
||||
ItemManager.Instance.AddStatusEffect(customStats);
|
||||
StatsSE = customStats.StatusEffect as SE_DvergarStats;
|
||||
|
||||
var overcharge = ScriptableObject.CreateInstance<SE_DvergarOvercharge>();
|
||||
overcharge.name = DvergarConfig.OverchargeSE;
|
||||
overcharge.m_name = "Runic Overcharge";
|
||||
overcharge.m_tooltip = "Your next blow with a favoured weapon carries the whole of the charge.";
|
||||
overcharge.m_icon = GetItemIcon("Eitr") ?? icon;
|
||||
ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(overcharge, fixReference: false));
|
||||
|
||||
var pingCd = ScriptableObject.CreateInstance<SE_DvergarAbilityCooldown>();
|
||||
pingCd.name = DvergarConfig.RunicPingCdSE;
|
||||
pingCd.m_name = "Runic Ping";
|
||||
pingCd.m_tooltip = "The runes must settle before you may call on them again.";
|
||||
pingCd.m_icon = GetItemIcon("DvergrKeyFragment") ?? icon;
|
||||
ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(pingCd, fixReference: false));
|
||||
|
||||
var overchargeCd = ScriptableObject.CreateInstance<SE_DvergarAbilityCooldown>();
|
||||
overchargeCd.name = DvergarConfig.OverchargeCdSE;
|
||||
overchargeCd.m_name = "Overcharge Cooldown";
|
||||
overchargeCd.m_tooltip = "The runes are spent.";
|
||||
overchargeCd.m_icon = GetItemIcon("Eitr") ?? icon;
|
||||
ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(overchargeCd, fixReference: false));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Drives the HUD countdown for an ability, mirroring SkadiRace.ApplyCooldownIcon: the
|
||||
/// effect only has to exist with a m_ttl for the icon to tick down by itself.
|
||||
/// </summary>
|
||||
public static void ApplyCooldownIcon(string effectName, float seconds)
|
||||
{
|
||||
if (Player.m_localPlayer == null || seconds <= 0f) return;
|
||||
|
||||
int hash = effectName.GetStableHashCode();
|
||||
SEMan seman = Player.m_localPlayer.GetSEMan();
|
||||
seman.RemoveStatusEffect(hash, true);
|
||||
seman.AddStatusEffect(hash, true);
|
||||
|
||||
StatusEffect se = seman.GetStatusEffect(hash);
|
||||
if (se != null) se.m_ttl = seconds;
|
||||
}
|
||||
|
||||
private static Sprite GetItemIcon(string prefabName)
|
||||
{
|
||||
GameObject prefab = PrefabManager.Cache.GetPrefab<ItemDrop>(prefabName)?.gameObject;
|
||||
ItemDrop drop = prefab != null ? prefab.GetComponent<ItemDrop>() : null;
|
||||
if (drop != null && drop.m_itemData.m_shared.m_icons.Length > 0)
|
||||
{
|
||||
return drop.m_itemData.m_shared.m_icons[0];
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
319
JotunnModStub/Dvergar/DvergarVisuals.cs
Normal file
319
JotunnModStub/Dvergar/DvergarVisuals.cs
Normal file
|
|
@ -0,0 +1,319 @@
|
|||
using HarmonyLib;
|
||||
using Jotunn.Managers;
|
||||
using UnityEngine;
|
||||
|
||||
namespace RacesOfValheim
|
||||
{
|
||||
/// <summary>
|
||||
/// The Dvergar's looks: a short body, dvergr skin, and a hood that is always worn.
|
||||
///
|
||||
/// The hood is a pure cosmetic override, not an equipment lock. The helmet slot stays free and
|
||||
/// whatever the player equips keeps every one of its stats - only its mesh is swapped out, so
|
||||
/// armour, resistances and set bonuses all still count.
|
||||
///
|
||||
/// Everything here runs for local and remote players alike, which is why it takes a Player
|
||||
/// rather than reading Player.m_localPlayer.
|
||||
/// </summary>
|
||||
public static class DvergarVisuals
|
||||
{
|
||||
private const string HoodName = "DvergarHood";
|
||||
|
||||
// The source is looked up once per session; the search walks a whole creature prefab and
|
||||
// would otherwise run again for every player that comes into view. The failure is cached
|
||||
// too, so a missing prefab cannot turn into a per-frame log.
|
||||
private static GameObject cachedVisual;
|
||||
private static bool visualResolved;
|
||||
|
||||
/// <summary>
|
||||
/// Reads the race off the ZDO so remote players render correctly, falling back to
|
||||
/// m_customData for the main-menu preview which has no ZNetView.
|
||||
/// </summary>
|
||||
public static string GetPlayerRace(Player player)
|
||||
{
|
||||
if (player == null) return "Human";
|
||||
|
||||
ZNetView nview = player.GetComponent<ZNetView>();
|
||||
if (nview != null && nview.IsValid())
|
||||
{
|
||||
return nview.GetZDO().GetString("RacesOfValheim_Race", "Human");
|
||||
}
|
||||
|
||||
if (player.m_customData != null && player.m_customData.TryGetValue("Race", out string race))
|
||||
{
|
||||
return race;
|
||||
}
|
||||
return "Human";
|
||||
}
|
||||
|
||||
public static bool IsDvergarPlayer(Player player) => GetPlayerRace(player) == DvergarConfig.RaceId;
|
||||
|
||||
// ─── Scale ───────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// Sizes a player, driven from a Player.Update postfix exactly the way the Trol is - which
|
||||
/// is the arrangement that actually holds. Doing it from the plugin's own MonoBehaviour
|
||||
/// left the scale in a fight it could not win: Trol's Player.Update postfix resets every
|
||||
/// non-Trol player's visual to 1 on the same frame, and whichever ran last won.
|
||||
/// </summary>
|
||||
public static void ApplyScale(Player player, bool isDvergar)
|
||||
{
|
||||
if (player == null) return;
|
||||
|
||||
// The "Visual" child, never the root: the root carries the collider and the camera
|
||||
// pivot, and shrinking those drops the player through the ground they stand on.
|
||||
GameObject visual = Traverse.Create(player).Field("m_visual").GetValue<GameObject>();
|
||||
if (visual == null) return;
|
||||
|
||||
if (isDvergar)
|
||||
{
|
||||
float target = DvergarConfig.VisualScale;
|
||||
if (Mathf.Abs(visual.transform.localScale.x - target) > 0.001f)
|
||||
{
|
||||
visual.transform.localScale = new Vector3(target, target, target);
|
||||
}
|
||||
}
|
||||
else if (Mathf.Abs(visual.transform.localScale.x - DvergarConfig.VisualScale) < 0.001f)
|
||||
{
|
||||
// Only ever undo our own scale - another race may legitimately be sizing this player.
|
||||
visual.transform.localScale = Vector3.one;
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Hood ────────────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>
|
||||
/// Keeps the hood and the hidden helmet in step. Safe to call every frame: each step
|
||||
/// checks the current value first and does nothing when it already matches.
|
||||
/// </summary>
|
||||
public static void ApplyHood(Player player)
|
||||
{
|
||||
VisEquipment visEq = player != null ? player.GetComponent<VisEquipment>() : null;
|
||||
if (visEq == null) return;
|
||||
|
||||
if (IsDvergarPlayer(player) && !player.IsDead())
|
||||
{
|
||||
EnsureHood(visEq);
|
||||
HideEquippedHelmet(visEq);
|
||||
}
|
||||
else
|
||||
{
|
||||
RemoveHood(visEq);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Blanks the mesh of whatever helmet is equipped. Scaled to zero rather than deactivated
|
||||
/// because Valheim re-enables the instance whenever it refreshes visuals, and this is the
|
||||
/// approach the Skeleton already proved out.
|
||||
/// </summary>
|
||||
private static void HideEquippedHelmet(VisEquipment visEq)
|
||||
{
|
||||
GameObject helmet = Traverse.Create(visEq).Field<GameObject>("m_helmetItemInstance").Value;
|
||||
if (helmet != null && helmet.transform.localScale != Vector3.zero)
|
||||
{
|
||||
helmet.transform.localScale = Vector3.zero;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Hangs the dvergr hood on the player's head.
|
||||
///
|
||||
/// The Dvergr ships as a single renderer whose mesh has Read/Write disabled - it reports
|
||||
/// zero triangles - so the hood cannot be carved out of it as a submesh, which is what the
|
||||
/// previous two attempts tried in one form or another. What the prefab does give us is a
|
||||
/// hat1/hat2/hat3 bone chain that nothing but the hood is skinned to.
|
||||
///
|
||||
/// So the whole dvergr body is instantiated and then made to disappear: the hat chain is
|
||||
/// detached from the skull, and the armature root is collapsed to zero scale, which drags
|
||||
/// every vertex weighted to it into a single point. Only the hood is left standing, and it
|
||||
/// is still skinned, so it keeps its own shape.
|
||||
/// </summary>
|
||||
private static void EnsureHood(VisEquipment visEq)
|
||||
{
|
||||
if (visEq.m_bodyModel == null || visEq.m_bodyModel.bones == null) return;
|
||||
|
||||
Transform playerHead = FindBoneByName(visEq.m_bodyModel.bones, DvergarConfig.PlayerHeadBoneName);
|
||||
if (playerHead == null) return;
|
||||
|
||||
if (playerHead.Find(HoodName) != null) return; // already wearing it
|
||||
|
||||
GameObject sourceVisual = ResolveDvergerVisual();
|
||||
if (sourceVisual == null) return; // already logged once by the resolver
|
||||
|
||||
bool wasActive = sourceVisual.activeSelf;
|
||||
sourceVisual.SetActive(false);
|
||||
GameObject hood = Object.Instantiate(sourceVisual, playerHead, false);
|
||||
sourceVisual.SetActive(wasActive);
|
||||
|
||||
hood.name = HoodName;
|
||||
StripComponents(hood);
|
||||
hood.SetActive(true);
|
||||
|
||||
Transform hatBone = FindChildByName(hood.transform, DvergarConfig.HoodBoneName);
|
||||
Transform bodyRoot = FindChildByName(hood.transform, DvergarConfig.BodyRootBoneName);
|
||||
|
||||
if (hatBone == null)
|
||||
{
|
||||
Jotunn.Logger.LogWarning(
|
||||
$"[Dvergar] No '{DvergarConfig.HoodBoneName}' bone in the instantiated dvergr; hood dropped.");
|
||||
Object.Destroy(hood);
|
||||
return;
|
||||
}
|
||||
|
||||
// Detached first: the hat chain hangs off the skull, so collapsing the body without
|
||||
// this would collapse the hood along with it.
|
||||
hatBone.SetParent(hood.transform, true);
|
||||
if (bodyRoot != null) bodyRoot.localScale = Vector3.zero;
|
||||
|
||||
// Scale and rotation before alignment, since both move the hat bone.
|
||||
hood.transform.localRotation = Quaternion.Euler(DvergarConfig.HoodOffsetRotation);
|
||||
hood.transform.localScale = Vector3.one * DvergarConfig.HoodExtraScale;
|
||||
|
||||
// The hat now sits wherever the dvergr's own skull was. Shifting the whole object by
|
||||
// the gap between that and the player's head bone lands it correctly without a single
|
||||
// hand-measured offset.
|
||||
hood.transform.position += playerHead.position - hatBone.position;
|
||||
hood.transform.localPosition += DvergarConfig.HoodOffsetPosition;
|
||||
|
||||
foreach (SkinnedMeshRenderer renderer in hood.GetComponentsInChildren<SkinnedMeshRenderer>(true))
|
||||
{
|
||||
// The collapsed bones leave the mesh's own bounds meaningless, and a skinned
|
||||
// renderer culls against those - without this the hood vanishes at some angles.
|
||||
renderer.updateWhenOffscreen = true;
|
||||
}
|
||||
|
||||
ApplyDitherShader(hood);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Strips everything that would make a decorative mesh behave like a creature: AI, hover
|
||||
/// prompts and physics, plus the Animator and LODGroup, which are not MonoBehaviours and
|
||||
/// would otherwise keep driving or hiding the rig.
|
||||
/// </summary>
|
||||
private static void StripComponents(GameObject obj)
|
||||
{
|
||||
foreach (MonoBehaviour comp in obj.GetComponentsInChildren<MonoBehaviour>(true))
|
||||
{
|
||||
Object.DestroyImmediate(comp);
|
||||
}
|
||||
foreach (Animator animator in obj.GetComponentsInChildren<Animator>(true))
|
||||
{
|
||||
Object.DestroyImmediate(animator);
|
||||
}
|
||||
foreach (LODGroup lod in obj.GetComponentsInChildren<LODGroup>(true))
|
||||
{
|
||||
Object.DestroyImmediate(lod);
|
||||
}
|
||||
foreach (Rigidbody body in obj.GetComponentsInChildren<Rigidbody>(true))
|
||||
{
|
||||
Object.DestroyImmediate(body);
|
||||
}
|
||||
foreach (Collider col in obj.GetComponentsInChildren<Collider>(true))
|
||||
{
|
||||
Object.DestroyImmediate(col);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Without the creature shader the hood ignores the camera's dither fade and fills the
|
||||
/// screen in first person; its own textures are kept.
|
||||
/// </summary>
|
||||
private static void ApplyDitherShader(GameObject obj)
|
||||
{
|
||||
Shader dither = Shader.Find("Custom/Creature");
|
||||
if (dither == null) return;
|
||||
|
||||
foreach (Renderer renderer in obj.GetComponentsInChildren<Renderer>(true))
|
||||
{
|
||||
if (renderer.material != null) renderer.material.shader = dither;
|
||||
}
|
||||
}
|
||||
|
||||
private static GameObject ResolveDvergerVisual()
|
||||
{
|
||||
if (visualResolved) return cachedVisual;
|
||||
visualResolved = true;
|
||||
|
||||
GameObject prefab = PrefabManager.Cache.GetPrefab<GameObject>(DvergarConfig.DvergerPrefabName);
|
||||
if (prefab == null)
|
||||
{
|
||||
Jotunn.Logger.LogWarning($"[Dvergar] Prefab '{DvergarConfig.DvergerPrefabName}' not found; no hood.");
|
||||
return null;
|
||||
}
|
||||
|
||||
Transform visual = prefab.transform.Find(DvergarConfig.DvergerVisualName);
|
||||
if (visual == null)
|
||||
{
|
||||
// Fall back to whatever holds the renderer, in case the child is ever renamed.
|
||||
SkinnedMeshRenderer renderer = prefab.GetComponentInChildren<SkinnedMeshRenderer>(true);
|
||||
visual = renderer != null ? renderer.transform.parent : null;
|
||||
}
|
||||
|
||||
if (visual == null)
|
||||
{
|
||||
Jotunn.Logger.LogWarning(
|
||||
$"[Dvergar] '{DvergarConfig.DvergerPrefabName}' has no '{DvergarConfig.DvergerVisualName}' child and no renderer; no hood.");
|
||||
return null;
|
||||
}
|
||||
|
||||
Jotunn.Logger.LogInfo($"[Dvergar] Hood source resolved to '{DvergarConfig.DvergerPrefabName}/{visual.name}'.");
|
||||
cachedVisual = visual.gameObject;
|
||||
return cachedVisual;
|
||||
}
|
||||
|
||||
private static void RemoveHood(VisEquipment visEq)
|
||||
{
|
||||
if (visEq.m_bodyModel == null || visEq.m_bodyModel.bones == null) return;
|
||||
|
||||
Transform playerHead = FindBoneByName(visEq.m_bodyModel.bones, DvergarConfig.PlayerHeadBoneName);
|
||||
Transform hood = playerHead != null ? playerHead.Find(HoodName) : null;
|
||||
if (hood == null) return; // never was a Dvergar - leave the helmet alone
|
||||
|
||||
// Destroy is deferred to the end of the frame, so the object is renamed first: without
|
||||
// that, every call until it actually goes away finds it again and re-runs the restore.
|
||||
hood.name = HoodName + "_Removed";
|
||||
Object.Destroy(hood.gameObject);
|
||||
|
||||
GameObject helmet = Traverse.Create(visEq).Field<GameObject>("m_helmetItemInstance").Value;
|
||||
if (helmet != null && helmet.transform.localScale == Vector3.zero)
|
||||
{
|
||||
helmet.transform.localScale = Vector3.one;
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Bone lookup ─────────────────────────────────────────────────────
|
||||
|
||||
private static Transform FindBoneByName(Transform[] bones, string targetBoneName)
|
||||
{
|
||||
if (bones == null || string.IsNullOrEmpty(targetBoneName)) return null;
|
||||
|
||||
foreach (Transform bone in bones)
|
||||
{
|
||||
if (bone != null && bone.name == targetBoneName) return bone;
|
||||
}
|
||||
|
||||
string target = targetBoneName.ToLower();
|
||||
foreach (Transform bone in bones)
|
||||
{
|
||||
if (bone == null) continue;
|
||||
string name = bone.name.ToLower();
|
||||
if (name == target || name.Contains(target) || target.Contains(name)) return bone;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>Depth-first search by exact name; the dvergr rig nests bones many levels deep.</summary>
|
||||
private static Transform FindChildByName(Transform root, string name)
|
||||
{
|
||||
if (root == null) return null;
|
||||
if (root.name == name) return root;
|
||||
|
||||
for (int i = 0; i < root.childCount; i++)
|
||||
{
|
||||
Transform found = FindChildByName(root.GetChild(i), name);
|
||||
if (found != null) return found;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue