diff --git a/JotunnModStub/Dvergur/DvergurAbilities.cs b/JotunnModStub/Dvergur/DvergurAbilities.cs new file mode 100644 index 0000000..bd37f69 --- /dev/null +++ b/JotunnModStub/Dvergur/DvergurAbilities.cs @@ -0,0 +1,207 @@ +using System.Collections; +using System.Collections.Generic; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// The Dvergur'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 DvergurRace.Update and both read their cost, radius, duration and + /// cooldown out of DvergurConfig. + /// + public static class DvergurAbilities + { + 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; + + DvergurProgression.DvergurRules rules = DvergurProgression.GetRules(state); + + if (rules.RunicPing && Input.GetKeyDown(DvergurConfig.RunicPingKey)) + { + TryRunicPing(player); + } + + if (rules.RunicOvercharge && Input.GetKeyDown(DvergurConfig.RunicOverchargeKey)) + { + TryRunicOvercharge(player); + } + } + + // ─── Runic Ping ────────────────────────────────────────────────────── + + private static void TryRunicPing(Player player) + { + if (Time.time - lastPingTime < DvergurConfig.RunicPingCooldown) return; + + if (player.GetEitr() < DvergurConfig.RunicPingEitrCost) + { + player.Message(MessageHud.MessageType.Center, "Not enough eitr"); + return; + } + + player.UseEitr(DvergurConfig.RunicPingEitrCost); + lastPingTime = Time.time; + DvergurStatusEffects.ApplyCooldownIcon(DvergurConfig.RunicPingCdSE, DvergurConfig.RunicPingCooldown); + + int marked = MarkSurroundings(player); + player.Message(MessageHud.MessageType.Center, + marked > 0 ? $"Runic Ping: {marked} echoes answer" : "Runic Ping: the stone is silent"); + } + + /// + /// 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. + /// + private static int MarkSurroundings(Player player) + { + Vector3 center = player.transform.position; + HashSet alreadyMarked = new HashSet(); + int marked = 0; + + foreach (Collider collider in Physics.OverlapSphere(center, DvergurConfig.RunicPingRadius)) + { + if (collider == null) continue; + + GameObject vein = FindVeinRoot(collider); + if (vein == null || !alreadyMarked.Add(vein)) continue; + + SpawnMarker(vein.transform, DvergurConfig.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) > DvergurConfig.RunicPingRadius) continue; + if (!BaseAI.IsEnemy(player, character)) continue; + if (!alreadyMarked.Add(character.gameObject)) continue; + + SpawnMarker(character.transform, DvergurConfig.RunicPingEnemyColor); + marked++; + } + + return marked; + } + + /// + /// 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. + /// + private static GameObject FindVeinRoot(Collider collider) + { + GameObject root = null; + + MineRock5 mineRock5 = collider.GetComponentInParent(); + if (mineRock5 != null) root = mineRock5.gameObject; + + if (root == null) + { + MineRock mineRock = collider.GetComponentInParent(); + if (mineRock != null) root = mineRock.gameObject; + } + + if (root == null) + { + Destructible destructible = collider.GetComponentInParent(); + 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 DvergurConfig.RunicPingVeinNames) + { + if (name.Contains(veinName)) return root; + } + return null; + } + + private static void SpawnMarker(Transform target, Color color) + { + GameObject markerObj = new GameObject("DvergurRunicMark"); + markerObj.transform.SetParent(target, false); + markerObj.transform.localPosition = Vector3.up; + + Light light = markerObj.AddComponent(); + light.type = LightType.Point; + light.color = color; + light.range = DvergurConfig.RunicPingLightRange; + light.intensity = DvergurConfig.RunicPingLightIntensity; + light.shadows = LightShadows.None; + + if (DvergurRace.Instance != null) + { + DvergurRace.Instance.StartCoroutine(DestroyAfter(markerObj, DvergurConfig.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 < DvergurConfig.RunicOverchargeCooldown) return; + + int overchargeHash = DvergurConfig.OverchargeSE.GetStableHashCode(); + if (player.GetSEMan().HaveStatusEffect(overchargeHash)) return; // already loaded + + if (player.GetEitr() < DvergurConfig.RunicOverchargeEitrCost) + { + player.Message(MessageHud.MessageType.Center, "Not enough eitr"); + return; + } + + player.UseEitr(DvergurConfig.RunicOverchargeEitrCost); + lastOverchargeTime = Time.time; + DvergurStatusEffects.ApplyCooldownIcon(DvergurConfig.OverchargeCdSE, DvergurConfig.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 = DvergurConfig.RunicOverchargeWindow; + + player.Message(MessageHud.MessageType.Center, "Runic Overcharge: your next blow is loaded"); + } + + /// + /// Spends a held charge. Called from the damage patch once it has confirmed the blow was + /// struck with a weapon the Dvergur is at home with. + /// + public static bool ConsumeOvercharge(Player player) + { + if (player == null) return false; + + int hash = DvergurConfig.OverchargeSE.GetStableHashCode(); + if (!player.GetSEMan().HaveStatusEffect(hash)) return false; + + player.GetSEMan().RemoveStatusEffect(hash, true); + return true; + } + } +} diff --git a/JotunnModStub/Dvergur/DvergurConfig.cs b/JotunnModStub/Dvergur/DvergurConfig.cs new file mode 100644 index 0000000..11e406c --- /dev/null +++ b/JotunnModStub/Dvergur/DvergurConfig.cs @@ -0,0 +1,272 @@ +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// Every tunable number the Dvergur uses, in one place. + /// + /// The race was specced with most percentages still open, so nothing here is baked into the + /// logic: DvergurProgression 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. + /// + public static class DvergurConfig + { + // ─── Identity ──────────────────────────────────────────────────────── + // "Dvergur" 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 = "Dvergur"; + + public const string StatsSE = "SE_DvergurStats"; + public const string OverchargeSE = "SE_DvergurOvercharge"; + public const string RunicPingCdSE = "SE_DvergurRunicPingCooldown"; + public const string OverchargeCdSE = "SE_DvergurOverchargeCooldown"; + + // 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_DvergurState"; + + // ─── 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 Dvergur + // 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 Dvergur must never be reduced below this, however the malus and food line up. + public static readonly float MinMaxHealth = 5f; + + // ─── 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 ───────────────────────────────────────────────────────── + /// Clamped table lookup, so a state outside 1..8 can never index out of range. + 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]; + } + } +} diff --git a/JotunnModStub/Dvergur/DvergurPatches.cs b/JotunnModStub/Dvergur/DvergurPatches.cs new file mode 100644 index 0000000..b54b3e5 --- /dev/null +++ b/JotunnModStub/Dvergur/DvergurPatches.cs @@ -0,0 +1,370 @@ +using System.Collections.Generic; +using System.Reflection; +using HarmonyLib; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// Every hook the Dvergur needs. The patches only ever decide *whether* a perk applies; *how + /// much* it applies always comes from DvergurProgression, which in turn reads DvergurConfig. + /// + public static class DvergurPatches + { + // ─── Health malus ──────────────────────────────────────────────────── + + /// + /// The Dvergur 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. + /// + [HarmonyPatch(typeof(Player), "GetTotalFoodValue")] + public static class Dvergur_GetTotalFoodValue_Patch + { + public static void Postfix(Player __instance, ref float hp) + { + if (__instance == null || __instance != Player.m_localPlayer) return; + if (!DvergurRace.IsDvergur()) return; + + float malus = DvergurProgression.Current.HealthMalus; + if (malus <= 0f) return; + + hp = Mathf.Max(DvergurConfig.MinMaxHealth, hp - malus); + } + } + + // ─── Scale ─────────────────────────────────────────────────────────── + + /// + /// 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 Dvergur on equal footing, and RaceScale keeps the + /// two from undoing each other. + /// + [HarmonyPatch(typeof(Player), "Update")] + public static class Dvergur_PlayerUpdate_Scale_Patch + { + public static void Postfix(Player __instance) + { + if (__instance == null) return; + DvergurVisuals.ApplyScale(__instance, DvergurVisuals.IsDvergurPlayer(__instance)); + } + } + + // ─── Weapon affinity: damage ───────────────────────────────────────── + + /// + /// 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 Dvergur is at home with these + /// weapons, not faster at learning them. + /// + [HarmonyPatch(typeof(Character), "Damage")] + public static class Dvergur_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 (!DvergurRace.IsDvergur()) return; + + int state = BossProgressionManager.GetCurrentProgressionState(); + DvergurConfig.WeaponAffinity? found = DvergurProgression.GetAffinity(hit.m_skill, state); + if (!found.HasValue) return; + + DvergurConfig.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 (DvergurProgression.GetRules(state).RunicOvercharge && + DvergurAbilities.ConsumeOvercharge(Player.m_localPlayer)) + { + ScalePhysical(hit, DvergurConfig.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; + default: hit.m_damage.m_damage += amount; break; + } + } + } + + // ─── Mining affinity ───────────────────────────────────────────────── + + /// + /// 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. + /// + private static bool isDvergurMining = 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 (!DvergurRace.IsDvergur()) return false; + if (!DvergurProgression.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 *= DvergurConfig.MiningDamageMultiplier; + isDvergurMining = true; + return true; + } + + private static void EndMiningHit(bool began) + { + if (began) isDvergurMining = false; + } + + [HarmonyPatch(typeof(MineRock5), "DamageArea")] + public static class Dvergur_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 Dvergur_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 Dvergur_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 Dvergur_DropTable_GetDropList_Patch + { + public static void Postfix(ref List __result) + { + if (!isDvergurMining || __result == null) return; + if (DvergurConfig.MiningExtraDropChance <= 0f) return; + + List extra = new List(); + foreach (GameObject drop in __result) + { + if (drop == null || !IsOre(drop.name)) continue; + if (Random.value <= DvergurConfig.MiningExtraDropChance) extra.Add(drop); + } + __result.AddRange(extra); + } + + private static bool IsOre(string prefabName) + { + string lower = prefabName.ToLower(); + foreach (string ore in DvergurConfig.OreDropNames) + { + if (lower.Contains(ore)) return true; + } + return false; + } + } + + // ─── Smithing and jewelry ──────────────────────────────────────────── + + /// + /// 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 DvergurConfig.DiscountedResourceNames, which is what + /// keeps this a smithing perk rather than a blanket discount on every wooden wall. + /// + [HarmonyPatch(typeof(Piece.Requirement), "GetAmount")] + public static class Dvergur_Requirement_GetAmount_Patch + { + public static void Postfix(Piece.Requirement __instance, ref int __result) + { + if (__result <= 1 || Player.m_localPlayer == null) return; + if (!DvergurRace.IsDvergur()) return; + + float discount = DvergurProgression.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 DvergurConfig.DiscountedResourceNames) + { + if (lower == resource || lower.Contains(resource)) return true; + } + return false; + } + } + + // ─── Haldor and Hildir's favour ────────────────────────────────────── + + /// + /// 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, Dvergur or not. + /// + [HarmonyPatch(typeof(Trader), "GetAvailableItems")] + public static class Dvergur_Trader_GetAvailableItems_Patch + { + public static void Postfix(ref List __result) + { + if (__result == null || Player.m_localPlayer == null) return; + if (!DvergurRace.IsDvergur()) return; + + float discount = DvergurProgression.Current.TraderBuyDiscount; + if (discount <= 0f) return; + + List discounted = new List(__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; + } + } + + /// + /// 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. + /// + [HarmonyPatch(typeof(ItemDrop.ItemData), "GetValue")] + public static class Dvergur_ItemData_GetValue_Patch + { + public static void Postfix(ref int __result) + { + if (__result <= 0 || Player.m_localPlayer == null) return; + if (!DvergurRace.IsDvergur()) return; + + float bonus = DvergurProgression.Current.TraderSellBonus; + if (bonus <= 0f) return; + + __result = Mathf.RoundToInt(__result * (1f + bonus)); + } + } + + // ─── Skin ──────────────────────────────────────────────────────────── + + /// + /// Tints the Dvergur 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 Dvergur. + /// + [HarmonyPatch(typeof(VisEquipment), "UpdateColors")] + public static class Dvergur_VisEquipment_UpdateColors_Patch + { + public static void Postfix(VisEquipment __instance) + { + if (__instance == null || !__instance.m_isPlayer) return; + + Player player = __instance.GetComponent(); + if (player == null || !DvergurVisuals.IsDvergurPlayer(player)) return; + + if (__instance.m_bodyModel != null && __instance.m_bodyModel.material != null) + { + __instance.m_bodyModel.material.SetColor("_SkinColor", DvergurConfig.SkinColor); + } + + TintRenderers(Traverse.Create(__instance).Field("m_hairItemInstance").GetValue()); + TintRenderers(Traverse.Create(__instance).Field("m_beardItemInstance").GetValue()); + } + + private static void TintRenderers(GameObject instance) + { + if (instance == null) return; + foreach (Renderer renderer in instance.GetComponentsInChildren()) + { + if (renderer.material != null) renderer.material.SetColor("_SkinColor", DvergurConfig.HairColor); + } + } + } + + // ─── Cosmetic hood ─────────────────────────────────────────────────── + + /// + /// 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. + /// + [HarmonyPatch(typeof(VisEquipment), "UpdateVisuals")] + public static class Dvergur_VisEquipment_UpdateVisuals_Patch + { + public static void Postfix(VisEquipment __instance) + { + if (__instance == null || !__instance.m_isPlayer) return; + + Player player = __instance.GetComponent(); + if (player == null) return; + + DvergurVisuals.ApplyHood(player); + } + } + } +} diff --git a/JotunnModStub/Dvergur/DvergurProgression.cs b/JotunnModStub/Dvergur/DvergurProgression.cs new file mode 100644 index 0000000..8687411 --- /dev/null +++ b/JotunnModStub/Dvergur/DvergurProgression.cs @@ -0,0 +1,82 @@ +using System.Collections.Generic; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// Turns a boss progression state into the set of Dvergur perks active at that tier, the same + /// way SkeletonProgression and SkadiProgression do for their races. + /// + /// Nothing is decided here - every figure comes out of DvergurConfig - so the tuning pass can + /// happen without touching a single patch. + /// + public static class DvergurProgression + { + public struct DvergurRules + { + /// Points subtracted from max health at this tier. + public float HealthMalus; + + /// Weapon skills the Dvergur is at home with, already filtered by tier. + public List 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 DvergurRules[] cache = new DvergurRules[BossProgressionManager.MaxState + 1]; + private static readonly bool[] cached = new bool[BossProgressionManager.MaxState + 1]; + + public static DvergurRules GetRules(int state) + { + state = Mathf.Clamp(state, BossProgressionManager.MinState, BossProgressionManager.MaxState); + if (cached[state]) return cache[state]; + + List affinities = new List(); + foreach (DvergurConfig.WeaponAffinity affinity in DvergurConfig.WeaponAffinities) + { + if (state >= affinity.UnlockState) affinities.Add(affinity); + } + + DvergurRules rules = new DvergurRules + { + HealthMalus = DvergurConfig.Lookup(DvergurConfig.HealthMalusByState, state), + Affinities = affinities, + MiningAffinity = state >= DvergurConfig.MiningAffinityState, + SmithingDiscount = DvergurConfig.Lookup(DvergurConfig.SmithingDiscountByState, state), + TraderBuyDiscount = DvergurConfig.Lookup(DvergurConfig.TraderBuyDiscountByState, state), + TraderSellBonus = DvergurConfig.Lookup(DvergurConfig.TraderSellBonusByState, state), + RunicPing = state >= DvergurConfig.RunicPingState, + RunicOvercharge = state >= DvergurConfig.RunicOverchargeState + }; + + cache[state] = rules; + cached[state] = true; + return rules; + } + + /// Rules for whatever tier the local player is currently on. + public static DvergurRules Current => GetRules(BossProgressionManager.GetCurrentProgressionState()); + + /// + /// The affinity covering a weapon skill at the current tier, or null when the Dvergur has + /// no particular feel for it. Mining counts as an affinity for stamina purposes only, so + /// it is deliberately not part of this list. + /// + public static DvergurConfig.WeaponAffinity? GetAffinity(Skills.SkillType skill, int state) + { + DvergurRules rules = GetRules(state); + foreach (DvergurConfig.WeaponAffinity affinity in rules.Affinities) + { + if (affinity.Skill == skill) return affinity; + } + return null; + } + } +} diff --git a/JotunnModStub/Dvergur/DvergurRace.cs b/JotunnModStub/Dvergur/DvergurRace.cs new file mode 100644 index 0000000..daa83c0 --- /dev/null +++ b/JotunnModStub/Dvergur/DvergurRace.cs @@ -0,0 +1,84 @@ +using HarmonyLib; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// Driver for the Dvergur: 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 + /// DvergurPatches, since that is the one place it survives; the perks are the other patches in + /// that file; the two eitr abilities are in DvergurAbilities; and every number they use comes + /// from DvergurConfig by way of DvergurProgression. + /// + public class DvergurRace : MonoBehaviour + { + public static DvergurRace 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() + { + DvergurStatusEffects.RegisterStatusEffects(); + } + + public static bool IsDvergur() + { + return Player.m_localPlayer != null && + Player.m_localPlayer.m_customData.ContainsKey("Race") && + Player.m_localPlayer.m_customData["Race"] == DvergurConfig.RaceId; + } + + private void Update() + { + Player player = Player.m_localPlayer; + if (player == null) return; + + bool isDvergur = IsDvergur(); + + DvergurVisuals.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 Dvergur. + float desiredMalus = isDvergur ? DvergurProgression.Current.HealthMalus : 0f; + if (!Mathf.Approximately(desiredMalus, lastAppliedMalus)) + { + lastAppliedMalus = desiredMalus; + Traverse.Create(player).Method("UpdateFood", 0f, true).GetValue(); + } + + if (!isDvergur || 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 (DvergurStatusEffects.StatsSE != null) + { + int hash = DvergurConfig.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(); + if (nview != null && nview.IsValid()) + { + nview.GetZDO().Set(DvergurConfig.StateZdoKey, state); + } + + DvergurAbilities.Tick(player, state); + } + } +} diff --git a/JotunnModStub/Dvergur/DvergurStatusEffects.cs b/JotunnModStub/Dvergur/DvergurStatusEffects.cs new file mode 100644 index 0000000..3e3d0b3 --- /dev/null +++ b/JotunnModStub/Dvergur/DvergurStatusEffects.cs @@ -0,0 +1,139 @@ +using HarmonyLib; +using Jotunn.Entities; +using Jotunn.Managers; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// Passive carrier for the Dvergur. 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. + /// + public class SE_DvergurStats : SE_Stats + { + public override void Setup(Character character) + { + base.Setup(character); + name = DvergurConfig.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 (!DvergurRace.IsDvergur()) 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("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 (DvergurProgression.GetRules(state).MiningAffinity) + { + staminaUse = Mathf.Max(0f, staminaUse * (1f - DvergurConfig.MiningStaminaPercent)); + } + return; + } + + DvergurConfig.WeaponAffinity? affinity = DvergurProgression.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); + } + } + + /// + /// Runic Overcharge, held between the cast and the blow that spends it. Purely a marker with a + /// countdown - DvergurPatches reads it when the next affine hit lands. + /// + public class SE_DvergurOvercharge : StatusEffect + { + } + + /// + /// 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. + /// + public class SE_DvergurAbilityCooldown : StatusEffect + { + } + + public static class DvergurStatusEffects + { + public static SE_DvergurStats StatsSE { get; private set; } + + public static void RegisterStatusEffects() + { + Sprite icon = GetItemIcon("HelmetDverger") ?? GetItemIcon("DvergrKeyFragment") ?? GetItemIcon("Copper"); + + var stats = ScriptableObject.CreateInstance(); + stats.name = DvergurConfig.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_DvergurStats; + + var overcharge = ScriptableObject.CreateInstance(); + overcharge.name = DvergurConfig.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(); + pingCd.name = DvergurConfig.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(); + overchargeCd.name = DvergurConfig.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)); + } + + /// + /// 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. + /// + 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(prefabName)?.gameObject; + ItemDrop drop = prefab != null ? prefab.GetComponent() : null; + if (drop != null && drop.m_itemData.m_shared.m_icons.Length > 0) + { + return drop.m_itemData.m_shared.m_icons[0]; + } + return null; + } + } +} diff --git a/JotunnModStub/Dvergur/DvergurVisuals.cs b/JotunnModStub/Dvergur/DvergurVisuals.cs new file mode 100644 index 0000000..0a8c43f --- /dev/null +++ b/JotunnModStub/Dvergur/DvergurVisuals.cs @@ -0,0 +1,319 @@ +using HarmonyLib; +using Jotunn.Managers; +using UnityEngine; + +namespace RacesOfValheim +{ + /// + /// The Dvergur'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. + /// + public static class DvergurVisuals + { + private const string HoodName = "DvergurHood"; + + // 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; + + /// + /// 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. + /// + public static string GetPlayerRace(Player player) + { + if (player == null) return "Human"; + + ZNetView nview = player.GetComponent(); + 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 IsDvergurPlayer(Player player) => GetPlayerRace(player) == DvergurConfig.RaceId; + + // ─── Scale ─────────────────────────────────────────────────────────── + + /// + /// 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. + /// + public static void ApplyScale(Player player, bool isDvergur) + { + 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(); + if (visual == null) return; + + if (isDvergur) + { + float target = DvergurConfig.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 - DvergurConfig.VisualScale) < 0.001f) + { + // Only ever undo our own scale - another race may legitimately be sizing this player. + visual.transform.localScale = Vector3.one; + } + } + + // ─── Hood ──────────────────────────────────────────────────────────── + + /// + /// 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. + /// + public static void ApplyHood(Player player) + { + VisEquipment visEq = player != null ? player.GetComponent() : null; + if (visEq == null) return; + + if (IsDvergurPlayer(player) && !player.IsDead()) + { + EnsureHood(visEq); + HideEquippedHelmet(visEq); + } + else + { + RemoveHood(visEq); + } + } + + /// + /// 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. + /// + private static void HideEquippedHelmet(VisEquipment visEq) + { + GameObject helmet = Traverse.Create(visEq).Field("m_helmetItemInstance").Value; + if (helmet != null && helmet.transform.localScale != Vector3.zero) + { + helmet.transform.localScale = Vector3.zero; + } + } + + /// + /// 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. + /// + private static void EnsureHood(VisEquipment visEq) + { + if (visEq.m_bodyModel == null || visEq.m_bodyModel.bones == null) return; + + Transform playerHead = FindBoneByName(visEq.m_bodyModel.bones, DvergurConfig.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, DvergurConfig.HoodBoneName); + Transform bodyRoot = FindChildByName(hood.transform, DvergurConfig.BodyRootBoneName); + + if (hatBone == null) + { + Jotunn.Logger.LogWarning( + $"[Dvergur] No '{DvergurConfig.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(DvergurConfig.HoodOffsetRotation); + hood.transform.localScale = Vector3.one * DvergurConfig.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 += DvergurConfig.HoodOffsetPosition; + + foreach (SkinnedMeshRenderer renderer in hood.GetComponentsInChildren(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); + } + + /// + /// 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. + /// + private static void StripComponents(GameObject obj) + { + foreach (MonoBehaviour comp in obj.GetComponentsInChildren(true)) + { + Object.DestroyImmediate(comp); + } + foreach (Animator animator in obj.GetComponentsInChildren(true)) + { + Object.DestroyImmediate(animator); + } + foreach (LODGroup lod in obj.GetComponentsInChildren(true)) + { + Object.DestroyImmediate(lod); + } + foreach (Rigidbody body in obj.GetComponentsInChildren(true)) + { + Object.DestroyImmediate(body); + } + foreach (Collider col in obj.GetComponentsInChildren(true)) + { + Object.DestroyImmediate(col); + } + } + + /// + /// Without the creature shader the hood ignores the camera's dither fade and fills the + /// screen in first person; its own textures are kept. + /// + private static void ApplyDitherShader(GameObject obj) + { + Shader dither = Shader.Find("Custom/Creature"); + if (dither == null) return; + + foreach (Renderer renderer in obj.GetComponentsInChildren(true)) + { + if (renderer.material != null) renderer.material.shader = dither; + } + } + + private static GameObject ResolveDvergerVisual() + { + if (visualResolved) return cachedVisual; + visualResolved = true; + + GameObject prefab = PrefabManager.Cache.GetPrefab(DvergurConfig.DvergerPrefabName); + if (prefab == null) + { + Jotunn.Logger.LogWarning($"[Dvergur] Prefab '{DvergurConfig.DvergerPrefabName}' not found; no hood."); + return null; + } + + Transform visual = prefab.transform.Find(DvergurConfig.DvergerVisualName); + if (visual == null) + { + // Fall back to whatever holds the renderer, in case the child is ever renamed. + SkinnedMeshRenderer renderer = prefab.GetComponentInChildren(true); + visual = renderer != null ? renderer.transform.parent : null; + } + + if (visual == null) + { + Jotunn.Logger.LogWarning( + $"[Dvergur] '{DvergurConfig.DvergerPrefabName}' has no '{DvergurConfig.DvergerVisualName}' child and no renderer; no hood."); + return null; + } + + Jotunn.Logger.LogInfo($"[Dvergur] Hood source resolved to '{DvergurConfig.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, DvergurConfig.PlayerHeadBoneName); + Transform hood = playerHead != null ? playerHead.Find(HoodName) : null; + if (hood == null) return; // never was a Dvergur - 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("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; + } + + /// Depth-first search by exact name; the dvergr rig nests bones many levels deep. + 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; + } + } +} diff --git a/JotunnModStub/RaceCompendium.cs b/JotunnModStub/RaceCompendium.cs index 022f25f..eee4c6a 100644 --- a/JotunnModStub/RaceCompendium.cs +++ b/JotunnModStub/RaceCompendium.cs @@ -15,7 +15,8 @@ namespace RacesOfValheim "Skeleton Secrets", "Furling Secrets", "Trol Secrets", - "Draugh Secrets" + "Draugh Secrets", + "Dvergur Secrets" }; public static void UpdateCompendiumText(Player player) @@ -67,6 +68,51 @@ namespace RacesOfValheim { GenerateDraughText(knownTexts, state, player); } + else if (currentRace == DvergurConfig.RaceId) + { + GenerateDvergurText(knownTexts, state); + } + } + + /// + /// Reads its figures straight out of the live rules rather than restating them, so the + /// entry cannot drift from the code the way a hand-written percentage would. + /// + private static void GenerateDvergurText(Dictionary knownTexts, int state) + { + DvergurProgression.DvergurRules rules = DvergurProgression.GetRules(state); + + StringBuilder sb = new StringBuilder(); + sb.AppendLine("The Dvergur's Craft\n"); + + sb.AppendLine($"[Base Passive] Small and Stubborn: You stand a third shorter than a human and carry {rules.HealthMalus:0.#} less health for it. The dvergr hood never leaves your head - wear whatever helm you please and keep every point of its protection, but the runes will always show you as one of the deep folk.\n"); + + List weapons = new List(); + foreach (DvergurConfig.WeaponAffinity affinity in rules.Affinities) + { + weapons.Add(affinity.DisplayName); + } + if (weapons.Count > 0) + { + sb.AppendLine($"Weapon Affinity (Passive): {string.Join(", ", weapons.ToArray())}. Blows struck with these land harder and cost less stamina. The saving never grows - a tier only ever hands you another weapon to feel at home with - and your skill rises no faster than anyone else's.\n"); + } + + if (rules.MiningAffinity) + sb.AppendLine("[Eikthyr Unlock] Mining Affinity (Passive): The pickaxe answers to you. Veins break faster, cost you less stamina to work, and sometimes give up more than they should.\n"); + + if (rules.SmithingDiscount > 0f) + sb.AppendLine($"[Bonemass Unlock] Smithing and Jewelry (Passive): You waste nothing at the anvil. Metal and gems cost you {rules.SmithingDiscount * 100f:0}% less when crafting and upgrading.\n"); + + if (rules.TraderBuyDiscount > 0f || rules.TraderSellBonus > 0f) + sb.AppendLine($"[Bonemass Unlock] Kin of the Traders (Passive): Haldor and Hildir know their own. Their prices drop by {rules.TraderBuyDiscount * 100f:0}% for you, and what they pay for your trophies and hunting rewards rises by {rules.TraderSellBonus * 100f:0}%.\n"); + + if (rules.RunicPing) + sb.AppendLine($"[Yagluth Unlock] Runic Ping ('{DvergurConfig.RunicPingKey}' Key): Spend {DvergurConfig.RunicPingEitrCost:0} eitr to send a pulse through the stone. For {DvergurConfig.RunicPingDuration:0} seconds every ore vein and every hidden enemy within {DvergurConfig.RunicPingRadius:0} meters is lit for you alone.\n"); + + if (rules.RunicOvercharge) + sb.AppendLine($"[Fader Unlock] Runic Overcharge ('{DvergurConfig.RunicOverchargeKey}' Key): Spend {DvergurConfig.RunicOverchargeEitrCost:0} eitr to load the runes. Your next blow with a favoured weapon lands with {DvergurConfig.RunicOverchargeMultiplier:0}x its weight. Hold the charge no longer than {DvergurConfig.RunicOverchargeWindow:0} seconds or it bleeds away.\n"); + + knownTexts["Dvergur Secrets"] = sb.ToString(); } private static void GenerateDraughText(Dictionary knownTexts, int state, Player player) diff --git a/JotunnModStub/RaceScale.cs b/JotunnModStub/RaceScale.cs new file mode 100644 index 0000000..7c8f5fe --- /dev/null +++ b/JotunnModStub/RaceScale.cs @@ -0,0 +1,35 @@ +namespace RacesOfValheim +{ + /// + /// Which races size their own body. + /// + /// Several races postfix Player.Update and set the player's "Visual" scale from there. Each of + /// them also wants to undo that scale once the player is no longer of their race, and the + /// straightforward way to write that - "if this isn't my race, force the scale back to 1" - + /// makes every such race stamp on every other one, with the winner decided by whichever + /// postfix Harmony happened to run last. + /// + /// That is what left the Dvergur at full height: Trol's reset ran on the same frame and put it + /// straight back to 1. Asking here first means a race only ever resets a player that nobody + /// else is sizing. + /// + public static class RaceScale + { + private static readonly string[] SelfSizingRaces = + { + "Trol", + "Furling", + DvergurConfig.RaceId + }; + + public static bool ManagesOwnScale(string race) + { + if (string.IsNullOrEmpty(race)) return false; + foreach (string self in SelfSizingRaces) + { + if (race == self) return true; + } + return false; + } + } +} diff --git a/JotunnModStub/RacesOfValheim.cs b/JotunnModStub/RacesOfValheim.cs index 1e1fd61..600f3ea 100644 --- a/JotunnModStub/RacesOfValheim.cs +++ b/JotunnModStub/RacesOfValheim.cs @@ -32,11 +32,13 @@ namespace RacesOfValheim gameObject.AddComponent(); gameObject.AddComponent(); gameObject.AddComponent(); + gameObject.AddComponent(); PrefabManager.OnVanillaPrefabsAvailable += CreateAllModAssets; CommandManager.Instance.AddConsoleCommand(new ResetRaceCommand()); CommandManager.Instance.AddConsoleCommand(new CheckProgressionCommand()); CommandManager.Instance.AddConsoleCommand(new IncreaseProgressionCommand()); CommandManager.Instance.AddConsoleCommand(new ResetProgressionCommand()); + CommandManager.Instance.AddConsoleCommand(new DumpDvergerCommand()); } /// @@ -72,6 +74,8 @@ namespace RacesOfValheim player.GetSEMan().RemoveStatusEffect("SE_SkeletonStats".GetStableHashCode()); player.GetSEMan().RemoveStatusEffect("SE_SkadiStats".GetStableHashCode()); player.GetSEMan().RemoveStatusEffect("SE_SkadiCooldown".GetStableHashCode()); + player.GetSEMan().RemoveStatusEffect(DvergurConfig.StatsSE.GetStableHashCode()); + player.GetSEMan().RemoveStatusEffect(DvergurConfig.OverchargeSE.GetStableHashCode()); ZNetView nview = player.GetComponent(); if (nview != null && nview.IsValid()) nview.GetZDO().Set("RacesOfValheim_Race", "Human"); @@ -93,6 +97,7 @@ namespace RacesOfValheim FurlingRace.Instance.CreateModAssets(); TrolRace.Instance.CreateModAssets(); DraughRace.Instance.CreateModAssets(); + DvergurRace.Instance.CreateModAssets(); } // --- RACE SELECTION UI --- public void ShowRaceSelectionMenu() @@ -233,6 +238,9 @@ namespace RacesOfValheim CreateRaceButtonWithConfirm("Trol", new Vector2(150, -20), GetTrolIcon(), "Massive brute strength. Towering over others but slow to react.", SelectTrol); CreateRaceButtonWithConfirm("Draugh", new Vector2(450, -20), GetDraughIcon(), "A decaying undead warrior fueled by dark magic and extreme metal.", SelectDraugh); + // Row 3 (y = -140) + CreateRaceButtonWithConfirm("Dvergur", new Vector2(-450, -140), GetDvergurIcon(), "Small, stubborn smiths of the deep. Frail of frame, but masters of metal, mine and market.", SelectDvergur); + GUIManager.BlockInput(true); } @@ -575,6 +583,45 @@ namespace RacesOfValheim return null; } + private void SelectDvergur() + { + if (Player.m_localPlayer != null) + { + Player.m_localPlayer.m_customData["Race"] = DvergurConfig.RaceId; + ZNetView nview = Player.m_localPlayer.GetComponent(); + if (nview != null && nview.IsValid()) nview.GetZDO().Set("RacesOfValheim_Race", DvergurConfig.RaceId); + + Player.m_localPlayer.GetSEMan().AddStatusEffect(DvergurConfig.StatsSE.GetStableHashCode(), true); + + // No SetSkinColor here: the tint is written onto the material by the UpdateColors + // postfix in DvergurPatches, which keys off the race and so needs nothing saved. + VisEquipment visEq = Player.m_localPlayer.GetComponent(); + if (visEq != null) + { + visEq.GetType().GetMethod("UpdateVisuals", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Public)?.Invoke(visEq, null); + } + + Player.m_localPlayer.Message(MessageHud.MessageType.Center, "You chose the path of the Dvergur."); + CloseRaceSelectionMenu(); + } + } + + private Sprite GetDvergurIcon() + { + GameObject prefab = PrefabManager.Cache.GetPrefab("HelmetDverger")?.gameObject; + if (prefab == null) prefab = PrefabManager.Cache.GetPrefab("DvergrKeyFragment")?.gameObject; + if (prefab == null) prefab = PrefabManager.Cache.GetPrefab("Copper")?.gameObject; + if (prefab != null) + { + ItemDrop drop = prefab.GetComponent(); + if (drop != null && drop.m_itemData.m_shared.m_icons.Length > 0) + { + return drop.m_itemData.m_shared.m_icons[0]; + } + } + return null; + } + public void CloseRaceSelectionMenu() { if (raceSelectionMenu != null) @@ -644,6 +691,9 @@ namespace RacesOfValheim if (visEq != null) visEq.GetType().GetMethod("UpdateColors", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Public)?.Invoke(visEq, null); } + // The Dvergur needs no entry here: its tint is applied by the UpdateColors postfix + // every time Valheim refreshes the body, rather than being stored on the player. + // Check for Race Selection if (!__instance.m_customData.ContainsKey("Race")) { @@ -722,6 +772,101 @@ namespace RacesOfValheim } } + /// + /// Dumps the Dvergr NPC prefab: its transform tree, every renderer on it, and its per-star + /// LevelEffects colours. Prefab contents live in the asset bundles and cannot be read outside + /// a running game, so this is how the hood mesh and the star tints get identified. + /// + public class DumpDvergerCommand : ConsoleCommand + { + public override string Name => "dumpdverger"; + public override string Help => "[DEBUG] Logs the Dverger prefab hierarchy, renderers and star colours"; + + public override void Run(string[] args) + { + string prefabName = args.Length > 0 ? args[0] : DvergurConfig.DvergerPrefabName; + GameObject prefab = Jotunn.Managers.PrefabManager.Cache.GetPrefab(prefabName); + if (prefab == null) + { + Console.instance.Print($"Prefab '{prefabName}' not found."); + return; + } + + Jotunn.Logger.LogInfo($"=== {prefabName} HIERARCHY ==="); + DumpTransform(prefab.transform, ""); + + // Submeshes and their materials are the part that matters: the Dvergr carries its hood, + // body and clothes in one mesh, so the hood can only be picked out by submesh index. + Jotunn.Logger.LogInfo($"=== {prefabName} RENDERERS ==="); + foreach (Renderer renderer in prefab.GetComponentsInChildren(true)) + { + Mesh mesh = null; + if (renderer is SkinnedMeshRenderer skinned) mesh = skinned.sharedMesh; + else + { + MeshFilter filter = renderer.GetComponent(); + if (filter != null) mesh = filter.sharedMesh; + } + + Jotunn.Logger.LogInfo( + $" {renderer.gameObject.name} ({renderer.GetType().Name}) " + + $"submeshes={(mesh != null ? mesh.subMeshCount : 0)} path={GetPath(renderer.transform)}"); + + Material[] materials = renderer.sharedMaterials; + for (int i = 0; i < materials.Length; i++) + { + int tris = (mesh != null && i < mesh.subMeshCount) ? mesh.GetTriangles(i).Length / 3 : 0; + Jotunn.Logger.LogInfo($" submesh {i}: material='{(materials[i] != null ? materials[i].name : "null")}' triangles={tris}"); + } + } + + LevelEffects levelEffects = prefab.GetComponentInChildren(true); + if (levelEffects != null && levelEffects.m_levelSetups != null) + { + Jotunn.Logger.LogInfo($"=== {prefabName} LEVEL SETUPS (index 0 = 1 star) ==="); + for (int i = 0; i < levelEffects.m_levelSetups.Count; i++) + { + var setup = levelEffects.m_levelSetups[i]; + if (setup == null) continue; + Jotunn.Logger.LogInfo( + $" [{i}] scale={setup.m_scale} hue={setup.m_hue} sat={setup.m_saturation} val={setup.m_value} " + + $"emissive={setup.m_setEmissiveColor}:{setup.m_emissiveColor}"); + } + } + else + { + Jotunn.Logger.LogInfo($"{prefabName} has no LevelEffects."); + } + + Console.instance.Print($"Dumped '{prefabName}' to the BepInEx log."); + } + + private static void DumpTransform(Transform t, string indent) + { + if (t == null) return; + + System.Text.StringBuilder components = new System.Text.StringBuilder(); + foreach (Component c in t.GetComponents()) + { + if (c != null) components.Append(c.GetType().Name).Append(" "); + } + + Jotunn.Logger.LogInfo($"{indent}{t.name} [{components}]"); + for (int i = 0; i < t.childCount; i++) DumpTransform(t.GetChild(i), indent + " "); + } + + private static string GetPath(Transform t) + { + string path = t.name; + while (t.parent != null) + { + t = t.parent; + path = t.name + "/" + path; + } + return path; + } + } + public class ResetProgressionCommand : ConsoleCommand { public override string Name => "resetprogression"; diff --git a/JotunnModStub/Trol/TrolPatches.cs b/JotunnModStub/Trol/TrolPatches.cs index 4492d82..a049085 100644 --- a/JotunnModStub/Trol/TrolPatches.cs +++ b/JotunnModStub/Trol/TrolPatches.cs @@ -176,8 +176,11 @@ namespace RacesOfValheim } } } - else if (Mathf.Abs(visual.transform.localScale.x - 1f) > 0.001f) + else if (!RaceScale.ManagesOwnScale(race) && Mathf.Abs(visual.transform.localScale.x - 1f) > 0.001f) { + // Races that size themselves are left alone. Without this guard the reset fires on + // every frame for a Furling or a Dvergur too, undoing their scale as fast as they + // set it, because both are applied from a postfix on this same method. visual.transform.localScale = Vector3.one; } } diff --git a/JotunnModStub/ZdoVisualSync.cs b/JotunnModStub/ZdoVisualSync.cs index b2bb17b..77b684b 100644 --- a/JotunnModStub/ZdoVisualSync.cs +++ b/JotunnModStub/ZdoVisualSync.cs @@ -81,6 +81,12 @@ namespace RacesOfValheim { // Managed externally in TrolPatches.cs } + else if (race == DvergurConfig.RaceId) + { + // Scale is handled for every player by the Player.Update postfix; this only keeps + // the hood and the hidden helmet asserted between equipment refreshes. + DvergurVisuals.ApplyHood(m_player); + } else { RevertAllVisuals(); diff --git a/dist/RacesOfValheim_Thunderstore_1.3.9.zip - collegamento.lnk b/dist/RacesOfValheim_Thunderstore_1.3.9.zip - collegamento.lnk new file mode 100644 index 0000000..61079d7 Binary files /dev/null and b/dist/RacesOfValheim_Thunderstore_1.3.9.zip - collegamento.lnk differ diff --git a/dist/icon.png b/dist/icon.png new file mode 100644 index 0000000..90b7b14 Binary files /dev/null and b/dist/icon.png differ