From c4a24c9fdf114e1edd7aa8ee8e7e343b984a367d Mon Sep 17 00:00:00 2001 From: Ferdinando Date: Thu, 30 Jul 2026 19:00:13 +0200 Subject: [PATCH] Initial commit --- .gitignore | 21 + DoPrebuild.props | 6 + GEMINI.md | 80 ++ InspectVomit.cs | 25 + JotunnModStub/Aswid/AswidExtraFoodUI.cs | 110 ++ JotunnModStub/Aswid/AswidFoodManager.cs | 88 ++ JotunnModStub/Aswid/AswidPatches.cs | 776 +++++++++++ JotunnModStub/Aswid/AswidProgression.cs | 62 + JotunnModStub/Aswid/AswidRace.cs | 1182 +++++++++++++++++ JotunnModStub/Aswid/AswidStatusEffects.cs | 145 ++ JotunnModStub/Aswid/AswidThrall.cs | 159 +++ JotunnModStub/Aswid/BatFormBehavior.cs | 54 + JotunnModStub/BossProgressionManager.cs | 51 + JotunnModStub/Fenrir/FenrirBehaviors.cs | 1030 ++++++++++++++ JotunnModStub/Fenrir/FenrirPatches.cs | 97 ++ JotunnModStub/Fenrir/FenrirProgression.cs | 84 ++ JotunnModStub/Fenrir/FenrirRace.cs | 429 ++++++ JotunnModStub/Fenrir/FenrirStatusEffects.cs | 46 + JotunnModStub/Furling/FurlingFireAbility.cs | 157 +++ JotunnModStub/Furling/FurlingKingUI.cs | 149 +++ JotunnModStub/Furling/FurlingPatches.cs | 643 +++++++++ JotunnModStub/Furling/FurlingProgression.cs | 16 + JotunnModStub/Furling/FurlingRace.cs | 44 + JotunnModStub/Furling/FurlingStatusEffects.cs | 14 + JotunnModStub/Package/README.md | 104 ++ JotunnModStub/Package/icon.png | Bin 0 -> 2368 bytes JotunnModStub/Package/manifest.json | 10 + JotunnModStub/Properties/AssemblyInfo.cs | 35 + .../Properties/IgnoreAccessModifiers.cs | 17 + JotunnModStub/README.md | 156 +++ JotunnModStub/RaceCompendium.cs | 217 +++ JotunnModStub/RaceHostilityManager.cs | 56 + JotunnModStub/RacesOfValheim.cs | 685 ++++++++++ JotunnModStub/RacesOfValheim.csproj | 107 ++ JotunnModStub/RacesOfValheim.sln | 25 + JotunnModStub/Skadi/DrakeFormBehavior.cs | 354 +++++ JotunnModStub/Skadi/SkadiPatches.cs | 144 ++ JotunnModStub/Skadi/SkadiProgression.cs | 128 ++ JotunnModStub/Skadi/SkadiRace.cs | 628 +++++++++ JotunnModStub/Skadi/SkadiStatusEffects.cs | 32 + JotunnModStub/Skadi/dummy.txt | 1 + JotunnModStub/Skeleton/SkeletonPatches.cs | 480 +++++++ JotunnModStub/Skeleton/SkeletonProgression.cs | 98 ++ JotunnModStub/Skeleton/SkeletonRace.cs | 466 +++++++ .../Skeleton/SkeletonStatusEffects.cs | 46 + JotunnModStub/Trol/TMPDebug.cs | 28 + JotunnModStub/Trol/TrolClearFoodPatch.cs | 11 + JotunnModStub/Trol/TrolDamagePatches.cs | 60 + JotunnModStub/Trol/TrolExtraFoodUI.cs | 133 ++ JotunnModStub/Trol/TrolFarmingPatches.cs | 101 ++ JotunnModStub/Trol/TrolFoodDebug.cs | 74 ++ JotunnModStub/Trol/TrolFoodDebugUI.cs | 67 + JotunnModStub/Trol/TrolFoodManager.cs | 140 ++ JotunnModStub/Trol/TrolFoodPatches.cs | 255 ++++ JotunnModStub/Trol/TrolLogWeapon.cs | 97 ++ JotunnModStub/Trol/TrolPatches.cs | 172 +++ JotunnModStub/Trol/TrolRace.cs | 392 ++++++ JotunnModStub/Trol/TrolRegenPatches.cs | 20 + JotunnModStub/Trol/TrolSkillPatches.cs | 32 + JotunnModStub/Trol/TrolStatusEffects.cs | 91 ++ JotunnModStub/ZdoVisualSync.cs | 341 +++++ JotunnModStub/app.config | 5 + JotunnModStub/packages.config | 4 + JotunnModStubUnity/.vsconfig | 6 + JotunnModStubUnity/Assets/Assemblies.meta | 8 + .../Assets/Assemblies/0Harmony.dll.meta | 33 + .../Assemblies/Assembly-CSharp.dll.meta | 63 + .../Assets/Assemblies/BepInEx.dll.meta | 33 + .../Assets/Assemblies/Jotunn.dll.meta | 33 + .../Assets/Assemblies/Mono.Cecil.dll.meta | 33 + .../Assemblies/MonoMod.RuntimeDetour.dll.meta | 33 + .../Assets/Assemblies/MonoMod.Utils.dll.meta | 33 + .../Assets/Assemblies/PlayFab.dll.meta | 63 + .../Assets/Assemblies/PlayFabParty.dll.meta | 63 + .../SoftReferenceableAssets.dll.meta | 33 + .../Assemblies/Splatform.Steam.dll.meta | 33 + .../Assets/Assemblies/Splatform.dll.meta | 33 + .../assembly_googleanalytics.dll.meta | 63 + .../Assemblies/assembly_guiutils.dll.meta | 63 + .../Assets/Assemblies/assembly_lux.dll.meta | 63 + .../assembly_postprocessing.dll.meta | 63 + .../assembly_simplemeshcombine.dll.meta | 63 + .../Assemblies/assembly_sunshafts.dll.meta | 63 + .../Assets/Assemblies/assembly_utils.dll.meta | 63 + .../Assemblies/assembly_valheim.dll.meta | 63 + .../com.rlabrecque.steamworks.net.dll.meta | 33 + .../Assets/Assemblies/gui_framework.dll.meta | 33 + JotunnModStubUnity/Packages/manifest.json | 46 + .../Packages/packages-lock.json | 355 +++++ .../ProjectSettings/AudioManager.asset | 19 + .../ProjectSettings/ClusterInputManager.asset | 6 + .../ProjectSettings/DynamicsManager.asset | 34 + .../ProjectSettings/EditorBuildSettings.asset | 8 + .../ProjectSettings/EditorSettings.asset | 35 + .../ProjectSettings/GraphicsSettings.asset | 66 + .../ProjectSettings/InputManager.asset | 295 ++++ .../ProjectSettings/MemorySettings.asset | 35 + .../ProjectSettings/MultiplayerManager.asset | 7 + .../ProjectSettings/NavMeshAreas.asset | 91 ++ .../PackageManagerSettings.asset | 38 + .../ProjectSettings/Physics2DSettings.asset | 56 + .../ProjectSettings/PresetManager.asset | 7 + .../ProjectSettings/ProjectSettings.asset | 745 +++++++++++ .../ProjectSettings/ProjectVersion.txt | 2 + .../ProjectSettings/QualitySettings.asset | 232 ++++ .../ProjectSettings/TagManager.asset | 51 + .../ProjectSettings/TimeManager.asset | 9 + .../UnityConnectSettings.asset | 34 + .../ProjectSettings/VFXManager.asset | 12 + .../VersionControlSettings.asset | 8 + .../ProjectSettings/XRSettings.asset | 10 + LICENSE | 16 + README.md | 159 +++ RacesOfValheim.sln | 25 + check.cs | 16 + check_delay.cs | 24 + check_eitr_methods.cs | 25 + check_fly.cs | 11 + check_food.cs | 21 + check_hatchling.cs | 11 + check_humanoid.cs | 18 + check_player2.cs | 17 + check_player_methods.cs | 25 + check_prep.cs | 11 + check_proj.cs | 11 + check_proj2.cs | 12 + check_seman.cs | 17 + check_sestats.cs | 16 + dump_viseq.cs | 25 + inspect.cs | 15 + manifest.json | 10 + parse_logs.ps1 | 4 + scratch.cs | 20 + script.cs | 17 + scripts/RenameSolution.ps1 | 194 +++ scripts/publish.ps1 | 70 + scripts/publish.sh | 72 + scripts/rename.sh | 16 + temp.cs | 15 + test.cs | 19 + test.ps1 | 3 + test_hud.cs | 25 + 142 files changed, 15491 insertions(+) create mode 100644 .gitignore create mode 100644 DoPrebuild.props create mode 100644 GEMINI.md create mode 100644 InspectVomit.cs create mode 100644 JotunnModStub/Aswid/AswidExtraFoodUI.cs create mode 100644 JotunnModStub/Aswid/AswidFoodManager.cs create mode 100644 JotunnModStub/Aswid/AswidPatches.cs create mode 100644 JotunnModStub/Aswid/AswidProgression.cs create mode 100644 JotunnModStub/Aswid/AswidRace.cs create mode 100644 JotunnModStub/Aswid/AswidStatusEffects.cs create mode 100644 JotunnModStub/Aswid/AswidThrall.cs create mode 100644 JotunnModStub/Aswid/BatFormBehavior.cs create mode 100644 JotunnModStub/BossProgressionManager.cs create mode 100644 JotunnModStub/Fenrir/FenrirBehaviors.cs create mode 100644 JotunnModStub/Fenrir/FenrirPatches.cs create mode 100644 JotunnModStub/Fenrir/FenrirProgression.cs create mode 100644 JotunnModStub/Fenrir/FenrirRace.cs create mode 100644 JotunnModStub/Fenrir/FenrirStatusEffects.cs create mode 100644 JotunnModStub/Furling/FurlingFireAbility.cs create mode 100644 JotunnModStub/Furling/FurlingKingUI.cs create mode 100644 JotunnModStub/Furling/FurlingPatches.cs create mode 100644 JotunnModStub/Furling/FurlingProgression.cs create mode 100644 JotunnModStub/Furling/FurlingRace.cs create mode 100644 JotunnModStub/Furling/FurlingStatusEffects.cs create mode 100644 JotunnModStub/Package/README.md create mode 100644 JotunnModStub/Package/icon.png create mode 100644 JotunnModStub/Package/manifest.json create mode 100644 JotunnModStub/Properties/AssemblyInfo.cs create mode 100644 JotunnModStub/Properties/IgnoreAccessModifiers.cs create mode 100644 JotunnModStub/README.md create mode 100644 JotunnModStub/RaceCompendium.cs create mode 100644 JotunnModStub/RaceHostilityManager.cs create mode 100644 JotunnModStub/RacesOfValheim.cs create mode 100644 JotunnModStub/RacesOfValheim.csproj create mode 100644 JotunnModStub/RacesOfValheim.sln create mode 100644 JotunnModStub/Skadi/DrakeFormBehavior.cs create mode 100644 JotunnModStub/Skadi/SkadiPatches.cs create mode 100644 JotunnModStub/Skadi/SkadiProgression.cs create mode 100644 JotunnModStub/Skadi/SkadiRace.cs create mode 100644 JotunnModStub/Skadi/SkadiStatusEffects.cs create mode 100644 JotunnModStub/Skadi/dummy.txt create mode 100644 JotunnModStub/Skeleton/SkeletonPatches.cs create mode 100644 JotunnModStub/Skeleton/SkeletonProgression.cs create mode 100644 JotunnModStub/Skeleton/SkeletonRace.cs create mode 100644 JotunnModStub/Skeleton/SkeletonStatusEffects.cs create mode 100644 JotunnModStub/Trol/TMPDebug.cs create mode 100644 JotunnModStub/Trol/TrolClearFoodPatch.cs create mode 100644 JotunnModStub/Trol/TrolDamagePatches.cs create mode 100644 JotunnModStub/Trol/TrolExtraFoodUI.cs create mode 100644 JotunnModStub/Trol/TrolFarmingPatches.cs create mode 100644 JotunnModStub/Trol/TrolFoodDebug.cs create mode 100644 JotunnModStub/Trol/TrolFoodDebugUI.cs create mode 100644 JotunnModStub/Trol/TrolFoodManager.cs create mode 100644 JotunnModStub/Trol/TrolFoodPatches.cs create mode 100644 JotunnModStub/Trol/TrolLogWeapon.cs create mode 100644 JotunnModStub/Trol/TrolPatches.cs create mode 100644 JotunnModStub/Trol/TrolRace.cs create mode 100644 JotunnModStub/Trol/TrolRegenPatches.cs create mode 100644 JotunnModStub/Trol/TrolSkillPatches.cs create mode 100644 JotunnModStub/Trol/TrolStatusEffects.cs create mode 100644 JotunnModStub/ZdoVisualSync.cs create mode 100644 JotunnModStub/app.config create mode 100644 JotunnModStub/packages.config create mode 100644 JotunnModStubUnity/.vsconfig create mode 100644 JotunnModStubUnity/Assets/Assemblies.meta create mode 100644 JotunnModStubUnity/Assets/Assemblies/0Harmony.dll.meta create mode 100644 JotunnModStubUnity/Assets/Assemblies/Assembly-CSharp.dll.meta create mode 100644 JotunnModStubUnity/Assets/Assemblies/BepInEx.dll.meta create mode 100644 JotunnModStubUnity/Assets/Assemblies/Jotunn.dll.meta create mode 100644 JotunnModStubUnity/Assets/Assemblies/Mono.Cecil.dll.meta create mode 100644 JotunnModStubUnity/Assets/Assemblies/MonoMod.RuntimeDetour.dll.meta create mode 100644 JotunnModStubUnity/Assets/Assemblies/MonoMod.Utils.dll.meta create mode 100644 JotunnModStubUnity/Assets/Assemblies/PlayFab.dll.meta create mode 100644 JotunnModStubUnity/Assets/Assemblies/PlayFabParty.dll.meta create mode 100644 JotunnModStubUnity/Assets/Assemblies/SoftReferenceableAssets.dll.meta create mode 100644 JotunnModStubUnity/Assets/Assemblies/Splatform.Steam.dll.meta create mode 100644 JotunnModStubUnity/Assets/Assemblies/Splatform.dll.meta create mode 100644 JotunnModStubUnity/Assets/Assemblies/assembly_googleanalytics.dll.meta create mode 100644 JotunnModStubUnity/Assets/Assemblies/assembly_guiutils.dll.meta create mode 100644 JotunnModStubUnity/Assets/Assemblies/assembly_lux.dll.meta create mode 100644 JotunnModStubUnity/Assets/Assemblies/assembly_postprocessing.dll.meta create mode 100644 JotunnModStubUnity/Assets/Assemblies/assembly_simplemeshcombine.dll.meta create mode 100644 JotunnModStubUnity/Assets/Assemblies/assembly_sunshafts.dll.meta create mode 100644 JotunnModStubUnity/Assets/Assemblies/assembly_utils.dll.meta create mode 100644 JotunnModStubUnity/Assets/Assemblies/assembly_valheim.dll.meta create mode 100644 JotunnModStubUnity/Assets/Assemblies/com.rlabrecque.steamworks.net.dll.meta create mode 100644 JotunnModStubUnity/Assets/Assemblies/gui_framework.dll.meta create mode 100644 JotunnModStubUnity/Packages/manifest.json create mode 100644 JotunnModStubUnity/Packages/packages-lock.json create mode 100644 JotunnModStubUnity/ProjectSettings/AudioManager.asset create mode 100644 JotunnModStubUnity/ProjectSettings/ClusterInputManager.asset create mode 100644 JotunnModStubUnity/ProjectSettings/DynamicsManager.asset create mode 100644 JotunnModStubUnity/ProjectSettings/EditorBuildSettings.asset create mode 100644 JotunnModStubUnity/ProjectSettings/EditorSettings.asset create mode 100644 JotunnModStubUnity/ProjectSettings/GraphicsSettings.asset create mode 100644 JotunnModStubUnity/ProjectSettings/InputManager.asset create mode 100644 JotunnModStubUnity/ProjectSettings/MemorySettings.asset create mode 100644 JotunnModStubUnity/ProjectSettings/MultiplayerManager.asset create mode 100644 JotunnModStubUnity/ProjectSettings/NavMeshAreas.asset create mode 100644 JotunnModStubUnity/ProjectSettings/PackageManagerSettings.asset create mode 100644 JotunnModStubUnity/ProjectSettings/Physics2DSettings.asset create mode 100644 JotunnModStubUnity/ProjectSettings/PresetManager.asset create mode 100644 JotunnModStubUnity/ProjectSettings/ProjectSettings.asset create mode 100644 JotunnModStubUnity/ProjectSettings/ProjectVersion.txt create mode 100644 JotunnModStubUnity/ProjectSettings/QualitySettings.asset create mode 100644 JotunnModStubUnity/ProjectSettings/TagManager.asset create mode 100644 JotunnModStubUnity/ProjectSettings/TimeManager.asset create mode 100644 JotunnModStubUnity/ProjectSettings/UnityConnectSettings.asset create mode 100644 JotunnModStubUnity/ProjectSettings/VFXManager.asset create mode 100644 JotunnModStubUnity/ProjectSettings/VersionControlSettings.asset create mode 100644 JotunnModStubUnity/ProjectSettings/XRSettings.asset create mode 100644 LICENSE create mode 100644 README.md create mode 100644 RacesOfValheim.sln create mode 100644 check.cs create mode 100644 check_delay.cs create mode 100644 check_eitr_methods.cs create mode 100644 check_fly.cs create mode 100644 check_food.cs create mode 100644 check_hatchling.cs create mode 100644 check_humanoid.cs create mode 100644 check_player2.cs create mode 100644 check_player_methods.cs create mode 100644 check_prep.cs create mode 100644 check_proj.cs create mode 100644 check_proj2.cs create mode 100644 check_seman.cs create mode 100644 check_sestats.cs create mode 100644 dump_viseq.cs create mode 100644 inspect.cs create mode 100644 manifest.json create mode 100644 parse_logs.ps1 create mode 100644 scratch.cs create mode 100644 script.cs create mode 100644 scripts/RenameSolution.ps1 create mode 100644 scripts/publish.ps1 create mode 100644 scripts/publish.sh create mode 100644 scripts/rename.sh create mode 100644 temp.cs create mode 100644 test.cs create mode 100644 test.ps1 create mode 100644 test_hud.cs diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..725e27b --- /dev/null +++ b/.gitignore @@ -0,0 +1,21 @@ +# .NET / C# +bin/ +obj/ +*.user +*.suo +*.sln.docstates +.vs/ +*.pdb + +# Executables and builds +*.exe +*.zip +output.txt +skills_dump.txt +temp_test_zip/ +test_extract/ +*.dll + +# OS generated files +.DS_Store +Thumbs.db diff --git a/DoPrebuild.props b/DoPrebuild.props new file mode 100644 index 0000000..873ae84 --- /dev/null +++ b/DoPrebuild.props @@ -0,0 +1,6 @@ + + + + false + + \ No newline at end of file diff --git a/GEMINI.md b/GEMINI.md new file mode 100644 index 0000000..663c0d3 --- /dev/null +++ b/GEMINI.md @@ -0,0 +1,80 @@ +# RacesOfValheim — Development Rules + +## New Race: Skin Visibility Pattern + +When creating a new race, always implement skin/visual patches following the Furling pattern: + +### 1. `UpdateColors` patch (skin color — in-game + multiplayer + main menu) + +```csharp +[HarmonyPatch(typeof(VisEquipment), "UpdateColors")] +public static class SkinColorPatch +{ + public static void Postfix(VisEquipment __instance) + { + if (!__instance.m_isPlayer) return; + Player player = __instance.GetComponent(); + if (player == null) return; + + // ZDO first (in-game + remote players), then m_customData fallback + // (main menu preview and first spawn frame — Player.m_localPlayer is null there) + // DO NOT check player == Player.m_localPlayer in the fallback. + string race = "Human"; + ZNetView nview = player.GetComponent(); + if (nview != null && nview.IsValid()) + race = nview.GetZDO().GetString("RacesOfValheim_Race", "Human"); + else if (player.m_customData != null && + player.m_customData.TryGetValue("Race", out string savedRace)) + race = savedRace; + + if (race != "") return; + + // Apply skin, hair, beard colors here... + } +} +``` + +### 2. `UpdateVisuals` patch with `GetPlayerRace()` helper (model swaps — in-game + multiplayer + main menu) + +```csharp +[HarmonyPatch(typeof(VisEquipment), "UpdateVisuals")] +public static class _VisEquipment_UpdateVisuals_Patch +{ + public static string GetPlayerRace(VisEquipment visEq) + { + Player player = visEq.GetComponent(); + if (player != null) + { + ZNetView nview = player.GetComponent(); + if (nview != null && nview.IsValid()) + return nview.GetZDO().GetString("RacesOfValheim_Race", "Human"); + // No Player.m_localPlayer check — works for menu preview too + if (player.m_customData != null && + player.m_customData.TryGetValue("Race", out string r)) + return r; + } + return "Human"; + } + + public static void Postfix(VisEquipment __instance) + { + if (!__instance.m_isPlayer) return; + string race = GetPlayerRace(__instance); + if (race != "") return; + // Apply model changes here... + } +} +``` + +### 3. `FejdStartup` patches (main menu character preview) + +These must be added to `RacesOfValheim.cs` — they are shared across all races. +The patches already exist (`FejdStartup_SetupCharacterPreview_Patch` and `FejdStartup_SetSelectedProfile_Patch`). +They call `UpdateVisuals` + `UpdateColors` on the preview player via `GetPreviewPlayer()`. +No changes needed when adding new races — they fire for all VisEquipment patches automatically. + +### Key rules summary +- Never use `player == Player.m_localPlayer` as a gate for `m_customData` fallback. +- Always use ZDO as primary source, `m_customData` as fallback — in that order. +- `UpdateColors` = skin/hair/beard tint. `UpdateVisuals` = model-level changes (head swaps, hide items). +- The FejdStartup patches already handle the menu; just make sure your `UpdateColors`/`UpdateVisuals` use the pattern above. diff --git a/InspectVomit.cs b/InspectVomit.cs new file mode 100644 index 0000000..fcc937a --- /dev/null +++ b/InspectVomit.cs @@ -0,0 +1,25 @@ +using System; +using System.Reflection; + +class Program { + static void Main() { + Assembly asm = Assembly.LoadFile(@"C:\Program Files (x86)\Steam\steamapps\common\Valheim\valheim_Data\Managed\assembly_valheim.dll"); + + var types = asm.GetTypes(); + foreach (var t in types) { + if (t.Name.Contains("Vomit") || t.Name.Contains("bukeperry") || t.Name.Contains("Puke")) { + Console.WriteLine("Found type: " + t.Name); + } + } + + Type playerType = asm.GetType("Player"); + if(playerType != null){ + var methods = playerType.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance); + foreach(var m in methods) { + if (m.Name.Contains("Food") || m.Name.Contains("Clear")) { + Console.WriteLine("Player has method: " + m.Name); + } + } + } + } +} diff --git a/JotunnModStub/Aswid/AswidExtraFoodUI.cs b/JotunnModStub/Aswid/AswidExtraFoodUI.cs new file mode 100644 index 0000000..d241e5e --- /dev/null +++ b/JotunnModStub/Aswid/AswidExtraFoodUI.cs @@ -0,0 +1,110 @@ +using HarmonyLib; +using UnityEngine; +using UnityEngine.UI; + +namespace RacesOfValheim +{ + [HarmonyPatch] + public static class AswidExtraFoodUI + { + private static GameObject AswidFoodUIBase; + private static Image AswidFoodIcon; + private static GameObject AswidFoodTimeObj; + + [HarmonyPatch(typeof(Hud), "Awake")] + [HarmonyPostfix] + public static void Awake_Postfix(Hud __instance) + { + Transform healthPanel = __instance.transform.Find("hudroot/healthpanel"); + if (healthPanel == null) return; + + Transform food1 = healthPanel.Find("food1"); + Transform food2 = healthPanel.Find("food2"); + + if (food1 == null || food2 == null) return; + + // Clone food2 + GameObject food3 = UnityEngine.Object.Instantiate(food2.gameObject, healthPanel); + food3.name = "AswidExtraFoodSlot"; + + // Calculate vertical offset (distance between slot 1 and 2) + float offset = food2.localPosition.y - food1.localPosition.y; + food3.transform.localPosition = food2.localPosition + new Vector3(0, offset, 0); + + AswidFoodUIBase = food3; + AswidFoodIcon = food3.transform.Find("foodicon2")?.GetComponent(); + if (AswidFoodIcon == null) AswidFoodIcon = food3.transform.Find("icon")?.GetComponent(); // Fallback + AswidFoodTimeObj = food3.transform.Find("time")?.gameObject; + AswidFoodUIBase.SetActive(false); + } + + [HarmonyPatch(typeof(Hud), "UpdateFood")] + [HarmonyPostfix] + public static void UpdateFood_Postfix(Hud __instance) + { + if (AswidFoodUIBase == null) return; + + bool show4th = BossProgressionManager.GetCurrentProgressionState() >= 8; + + if (Player.m_localPlayer == null || !AswidRace.IsAswid() || !show4th) + { + AswidFoodUIBase.SetActive(false); + return; + } + + AswidFoodUIBase.SetActive(true); + UpdateSlotUI(Player.m_localPlayer, AswidFoodManager.ExtraFoods, AswidFoodIcon, AswidFoodTimeObj); + } + + private static void UpdateSlotUI(Player player, System.Collections.Generic.Dictionary dict, Image icon, GameObject timeObj) + { + if (dict.TryGetValue(player, out Player.Food extraFood) && extraFood != null) + { + if (icon != null) + { + icon.sprite = extraFood.m_item.GetIcon(); + icon.gameObject.SetActive(true); + + bool canEat = extraFood.m_time >= (extraFood.m_item.m_shared.m_foodBurnTime * 0.5f); + if (canEat) icon.color = new Color(1f, 1f, 1f, Mathf.Sin(Time.time * 10f) * 0.5f + 0.5f); + else icon.color = Color.white; + } + + if (timeObj != null) + { + timeObj.SetActive(true); + float remaining = extraFood.m_item.m_shared.m_foodBurnTime - extraFood.m_time; + if (remaining < 0) remaining = 0; + + string timeStr = remaining < 60f ? Mathf.CeilToInt(remaining).ToString() + "s" : Mathf.CeilToInt(remaining / 60f).ToString() + "m"; + bool canEat = extraFood.m_time >= (extraFood.m_item.m_shared.m_foodBurnTime * 0.5f); + Color timeCol = canEat ? new Color(1f, 0.5f, 0.5f, Mathf.Sin(Time.time * 10f) * 0.5f + 0.5f) : Color.white; + UpdateTextComponent(timeObj, timeStr, timeCol); + } + } + else + { + if (icon != null) icon.gameObject.SetActive(false); + if (timeObj != null) timeObj.SetActive(false); + } + } + + private static void UpdateTextComponent(GameObject obj, string text, Color color) + { + var unityText = obj.GetComponent(); + if (unityText != null) + { + unityText.text = text; + unityText.color = color; + } + var tmpText = obj.GetComponent("TMPro.TMP_Text"); + if (tmpText != null) + { + var textProp = tmpText.GetType().GetProperty("text"); + if (textProp != null) textProp.SetValue(tmpText, text, null); + var colorProp = tmpText.GetType().GetProperty("color"); + if (colorProp != null) colorProp.SetValue(tmpText, color, null); + } + } + } +} diff --git a/JotunnModStub/Aswid/AswidFoodManager.cs b/JotunnModStub/Aswid/AswidFoodManager.cs new file mode 100644 index 0000000..3c0254e --- /dev/null +++ b/JotunnModStub/Aswid/AswidFoodManager.cs @@ -0,0 +1,88 @@ +using System.Collections.Generic; +using UnityEngine; + +namespace RacesOfValheim +{ + public static class AswidFoodManager + { + // Runtime dictionary holding the 4th food slot per player + public static Dictionary ExtraFoods = new Dictionary(); + + // Called when player spawns to load the 4th food from custom data + public static void LoadFood(Player player) + { + if (player == null) return; + + // If they are no longer an Aswid, clear it out + if (!AswidRace.IsAswid()) + { + ClearFood(player); + return; + } + + if (!player.m_customData.ContainsKey("AswidFood_Prefab")) return; + + string prefabName = player.m_customData["AswidFood_Prefab"]; + GameObject prefab = ObjectDB.instance.GetItemPrefab(prefabName); + if (prefab == null) return; + + ItemDrop itemDrop = prefab.GetComponent(); + if (itemDrop == null) return; + + // Build food object + Player.Food food = new Player.Food(); + food.m_item = itemDrop.m_itemData.Clone(); // Clone to be safe + + // Try parse remaining time + if (player.m_customData.TryGetValue("AswidFood_Time", out string timeStr) && float.TryParse(timeStr, System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out float time)) + { + food.m_time = time; + } + + food.m_health = itemDrop.m_itemData.m_shared.m_food; + food.m_stamina = itemDrop.m_itemData.m_shared.m_foodStamina; + food.m_eitr = itemDrop.m_itemData.m_shared.m_foodEitr; + + ExtraFoods[player] = food; + } + + // Called to save the current runtime 4th food to custom data for persistence + public static void SaveFood(Player player) + { + if (player == null) return; + + if (ExtraFoods.TryGetValue(player, out Player.Food food) && food != null && food.m_item != null) + { + player.m_customData["AswidFood_Prefab"] = food.m_item.m_dropPrefab.name; + player.m_customData["AswidFood_Time"] = food.m_time.ToString(System.Globalization.CultureInfo.InvariantCulture); + } + else + { + player.m_customData.Remove("AswidFood_Prefab"); + player.m_customData.Remove("AswidFood_Time"); + } + } + + public static void ClearFood(Player player) + { + ExtraFoods.Remove(player); + if (player != null) + { + player.m_customData.Remove("AswidFood_Prefab"); + player.m_customData.Remove("AswidFood_Time"); + } + } + + public static void SetExtraFood(Player player, ItemDrop.ItemData item) + { + Player.Food food = new Player.Food(); + food.m_item = item.Clone(); + food.m_time = 0f; + food.m_health = item.m_shared.m_food; + food.m_stamina = item.m_shared.m_foodStamina; + food.m_eitr = item.m_shared.m_foodEitr; + ExtraFoods[player] = food; + SaveFood(player); + } + } +} diff --git a/JotunnModStub/Aswid/AswidPatches.cs b/JotunnModStub/Aswid/AswidPatches.cs new file mode 100644 index 0000000..1808885 --- /dev/null +++ b/JotunnModStub/Aswid/AswidPatches.cs @@ -0,0 +1,776 @@ +using HarmonyLib; +using UnityEngine; +using System.Linq; + +namespace RacesOfValheim +{ + [HarmonyPatch(typeof(VisEquipment), "UpdateColors")] + public static class AswidSkinColorPatch + { + private static readonly Color SkinColor = new Color(0.96f, 0.97f, 0.98f, 1f); + private static readonly Color HairColor = new Color(1f, 1f, 1f, 1f); + + public static void Postfix(VisEquipment __instance) + { + if (!__instance.m_isPlayer) return; + Player player = __instance.GetComponent(); + if (player == null) return; + + string race = "Human"; + ZNetView nview = player.GetComponent(); + if (nview != null && nview.IsValid()) + race = nview.GetZDO().GetString("RacesOfValheim_Race", "Human"); + else if (player.m_customData != null && player.m_customData.TryGetValue("Race", out string savedRace)) + race = savedRace; + + if (race != "Aswid") return; + + int state = 0; + if (nview != null && nview.IsValid()) + state = nview.GetZDO().GetInt("RacesOfValheim_AswidState", 0); + + Color currentHairColor = state >= 8 ? new Color(0.02f, 0.02f, 0.02f, 1f) : HairColor; + + if (__instance.m_bodyModel != null && __instance.m_bodyModel.material != null) + __instance.m_bodyModel.material.SetColor("_SkinColor", SkinColor); + + var hairInst = Traverse.Create(__instance).Field("m_hairItemInstance").GetValue(); + if (hairInst != null) + foreach (var r in hairInst.GetComponentsInChildren()) + if (r.material != null) r.material.SetColor("_SkinColor", currentHairColor); + + var beardInst = Traverse.Create(__instance).Field("m_beardItemInstance").GetValue(); + if (beardInst != null) + foreach (var r in beardInst.GetComponentsInChildren()) + if (r.material != null) r.material.SetColor("_SkinColor", currentHairColor); + } + } + + + + + [HarmonyPatch(typeof(SEMan), "AddStatusEffect", new System.Type[] { typeof(int), typeof(bool), typeof(int), typeof(float) })] + public static class AswidSEManPatch + { + public static bool Prefix(SEMan __instance, ref int nameHash) + { + Character character = Traverse.Create(__instance).Field("m_character").Value; + if (character == Player.m_localPlayer && AswidRace.IsAswid()) + { + int state = BossProgressionManager.GetCurrentProgressionState(); + if (state >= 5 && nameHash == "Freezing".GetStableHashCode()) + { + return false; + } + + // Cold immunity is removed as per user request to test native Cold VFX + // if (nameHash == "Cold".GetStableHashCode()) + // { + // return false; + // } + } + return true; + } + } + + [HarmonyPatch(typeof(Attack), "Start")] + public static class Aswid_BloodMagicCost_Patch + { + private static float savedHealthCost = 0f; + private static float savedHealthPercentage = 0f; + + public static void Prefix(Attack __instance, Humanoid character, ref bool __state) + { + var weapon = Traverse.Create(__instance).Field("m_weapon").GetValue(); + if (weapon == null) weapon = Traverse.Create(__instance).Method("GetWeapon").GetValue(); + + if (character == Player.m_localPlayer && AswidRace.IsAswid() && weapon != null && weapon.m_shared.m_skillType == Skills.SkillType.BloodMagic) + { + __state = true; + savedHealthCost = weapon.m_shared.m_attack.m_attackHealth; + savedHealthPercentage = weapon.m_shared.m_attack.m_attackHealthPercentage; + + weapon.m_shared.m_attack.m_attackHealth = 0f; + weapon.m_shared.m_attack.m_attackHealthPercentage = 0f; + } + else + { + __state = false; + } + } + + public static void Postfix(Attack __instance, Humanoid character, bool __state) + { + var weapon = Traverse.Create(__instance).Field("m_weapon").GetValue(); + if (weapon == null) weapon = Traverse.Create(__instance).Method("GetWeapon").GetValue(); + + if (__state && weapon != null) + { + weapon.m_shared.m_attack.m_attackHealth = savedHealthCost; + weapon.m_shared.m_attack.m_attackHealthPercentage = savedHealthPercentage; + } + } + } + + public static class AswidPatches + { + public static System.Collections.Generic.Dictionary RecentlyLifeDrained = new System.Collections.Generic.Dictionary(); + } + + [HarmonyPatch(typeof(Character), "Damage")] + public static class Aswid_LifeDrainKill_Patch + { + public static void Postfix(Character __instance, HitData hit) + { + if (hit != null && hit.m_attacker == Player.m_localPlayer?.GetZDOID()) + { + Debug.LogWarning($"[Aswid_Patch] Local player damaged {__instance.name}. IsDead: {__instance.IsDead()}"); + } + + if (__instance.IsDead() && hit != null) + { + if (Player.m_localPlayer != null && hit.m_attacker == Player.m_localPlayer.GetZDOID()) + { + ZNetView cNetView = __instance.GetComponent(); + if (AswidRace.IsAswid() && cNetView != null && cNetView.IsValid()) + { + ZDOID zdoid = __instance.GetZDOID(); + if (AswidPatches.RecentlyLifeDrained.TryGetValue(zdoid, out float timeHit)) + { + if (Time.time - timeHit < 1.0f) + { + Debug.LogWarning($"[Aswid] {__instance.name} died within 1s of LifeDrain. Consuming!"); + AswidRace.TryConsumeMob(__instance, __instance.GetMaxHealth()); + AswidPatches.RecentlyLifeDrained.Remove(zdoid); + } + } + } + } + } + } + } + + [HarmonyPatch(typeof(Character), "Awake")] + public static class Aswid_Awake_Patch + { + public static void Postfix(Character __instance) + { + if (__instance.GetComponent() != null && !__instance.IsBoss() && __instance.m_faction != Character.Faction.Demon && __instance.GetComponent() == null) + { + if (__instance.GetComponent() == null) + { + __instance.gameObject.AddComponent(); + } + } + } + } + + [HarmonyPatch(typeof(Player), "GetBodyArmor")] + public static class Aswid_ArmorBonus_Patch + { + public static void Postfix(Player __instance, ref float __result) + { + if (__instance == Player.m_localPlayer && AswidRace.IsAswid()) + { + int state = BossProgressionManager.GetCurrentProgressionState(); + float multiplier = (EnvMan.instance != null && EnvMan.IsNight()) ? 2f : 1f; + __result += 1f * state * multiplier; + } + } + } + + [HarmonyPatch] + public static class Aswid_DamageBonus_Patch + { + [HarmonyTargetMethod] + public static System.Reflection.MethodBase TargetMethod() + { + return System.Linq.Enumerable.FirstOrDefault( + HarmonyLib.AccessTools.GetDeclaredMethods(typeof(ItemDrop.ItemData)), + m => m.Name == "GetDamage" && m.ReturnType == typeof(HitData.DamageTypes) + ); + } + + public static void Postfix(ItemDrop.ItemData __instance, ref HitData.DamageTypes __result) + { + if (Player.m_localPlayer != null && AswidRace.IsAswid() && + Player.m_localPlayer.GetInventory().ContainsItem(__instance)) + { + int state = BossProgressionManager.GetCurrentProgressionState(); + if (state > 0) + { + float multiplier = (EnvMan.instance != null && EnvMan.IsNight()) ? 2f : 1f; + float bonus = 2f * state * multiplier; + + // Add flat bonus to physical damage types that the weapon already has + if (__result.m_slash > 0) __result.m_slash += bonus; + if (__result.m_blunt > 0) __result.m_blunt += bonus; + if (__result.m_pierce > 0) __result.m_pierce += bonus; + if (__result.m_chop > 0) __result.m_chop += bonus; + if (__result.m_pickaxe > 0) __result.m_pickaxe += bonus; + } + } + } + } + + [HarmonyPatch(typeof(Humanoid), "StartAttack")] + public static class Aswid_Attack_Patch + { + public static bool Prefix(Humanoid __instance) + { + if (__instance == Player.m_localPlayer) + { + if (__instance.GetComponentInChildren() != null) + { + return false; + } + if (__instance.GetSEMan().HaveStatusEffect("SE_MistForm".GetStableHashCode())) + { + return false; + } + } + return true; + } + } + + [HarmonyPatch(typeof(Character), "SetRun")] + public static class Aswid_Run_Patch + { + public static void Prefix(Character __instance, ref bool run) + { + if (__instance == Player.m_localPlayer) + { + if (Player.m_localPlayer.GetSEMan().HaveStatusEffect("SE_MistForm".GetStableHashCode())) + { + run = false; + } + } + } + } + + [HarmonyPatch(typeof(Character), "Jump")] + public static class Aswid_Jump_Patch + { + public static bool Prefix(Character __instance) + { + if (__instance == Player.m_localPlayer) + { + if (Player.m_localPlayer.GetSEMan().HaveStatusEffect("SE_MistForm".GetStableHashCode())) + { + return false; + } + } + return true; + } + } + + [HarmonyPatch(typeof(Player), "OnSpawned")] + public static class Aswid_PlayerOnSpawned_Patch + { + public static void Postfix(Player __instance) + { + if (__instance == Player.m_localPlayer) + { + AswidFoodManager.LoadFood(__instance); + } + } + } + + [HarmonyPatch(typeof(Player), "CanConsumeItem")] + public static class Aswid_CanConsumeItem_Patch + { + public static void Postfix(Player __instance, ItemDrop.ItemData item, ref bool __result) + { + if (__instance == Player.m_localPlayer && AswidRace.IsAswid() && item != null && item.m_shared != null && item.m_shared.m_name.StartsWith("Aswid Food:")) + { + var foods = HarmonyLib.Traverse.Create(__instance).Field("m_foods").GetValue(); + if (foods != null) + { + if (foods.Count >= 3) + { + bool canUse4th = BossProgressionManager.GetCurrentProgressionState() >= 8; + bool has4th = AswidFoodManager.ExtraFoods.TryGetValue(__instance, out Player.Food extraFood) && extraFood != null; + + if (canUse4th && (!has4th || extraFood.m_time >= (extraFood.m_item.m_shared.m_foodBurnTime * 0.5f))) + { + __result = true; // Consente l'uso del 4° slot se disponibile + } + else + { + __result = false; // Nessuno spazio disponibile, cibo si disintegra + } + } + else + { + __result = true; // Spazio nei primi 3 slot + } + } + } + } + } + + [HarmonyPatch(typeof(Player), "EatFood")] + public static class Aswid_EatFood_Patch + { + private static System.Collections.Generic.List hiddenFoods = new System.Collections.Generic.List(); + + public static bool Prefix(Player __instance, ItemDrop.ItemData item, ref bool __result) + { + hiddenFoods.Clear(); + if (__instance == Player.m_localPlayer && AswidRace.IsAswid() && item != null && item.m_shared != null && item.m_shared.m_name.StartsWith("Aswid Food:")) + { + var m_foods = HarmonyLib.Traverse.Create(__instance).Field("m_foods").GetValue(); + if (m_foods != null) + { + if (m_foods.Count >= 3) + { + bool canUse4th = BossProgressionManager.GetCurrentProgressionState() >= 8; + if (canUse4th) + { + bool has4th = AswidFoodManager.ExtraFoods.TryGetValue(__instance, out Player.Food extraFood) && extraFood != null; + if (!has4th || extraFood.m_time >= (extraFood.m_item.m_shared.m_foodBurnTime * 0.5f)) + { + AswidFoodManager.SetExtraFood(__instance, item); + + // Play consume effects + var consumeEffects = HarmonyLib.Traverse.Create(__instance).Field("m_consumeItemEffects").GetValue(); + if (consumeEffects != null) + { + consumeEffects.Create(__instance.transform.position, Quaternion.identity, __instance.transform, 1f, -1); + } + var zanim = HarmonyLib.Traverse.Create(__instance).Field("m_zanim").GetValue(); + if (zanim != null) + { + zanim.SetTrigger("eat"); + } + if (item.m_shared.m_food > 0f) + { + __instance.Heal(item.m_shared.m_food, true); + } + + __result = true; + return false; // Skip native EatFood + } + } + + // Se pieno e senza 4° slot disponibile, fallisce e disintegra + __result = false; + return false; + } + else + { + // Nascondiamo temporaneamente i duplicati nei primi 3 slot per costringere Valheim ad aggiungere un NUOVO slot + for (int i = m_foods.Count - 1; i >= 0; i--) + { + var foodObj = m_foods[i]; + var foodItem = HarmonyLib.Traverse.Create(foodObj).Field("m_item").GetValue(); + if (foodItem != null && foodItem.m_shared.m_name == item.m_shared.m_name) + { + hiddenFoods.Add(foodObj); + m_foods.RemoveAt(i); + } + } + } + } + } + return true; + } + + public static void Postfix(Player __instance, ItemDrop.ItemData item, ref bool __result) + { + if (hiddenFoods.Count > 0) + { + var m_foods = HarmonyLib.Traverse.Create(__instance).Field("m_foods").GetValue(); + if (m_foods != null) + { + // Ripristiniamo i duplicati nascosti + foreach (var hf in hiddenFoods) + { + m_foods.Add(hf); + } + } + hiddenFoods.Clear(); + } + } + } + + [HarmonyPatch(typeof(Tameable), "GetHoverText")] + public static class Aswid_TameHoverText_Patch + { + public static void Postfix(Tameable __instance, ref string __result) + { + if (Player.m_localPlayer == null || !AswidRace.IsAswid()) return; + if (__instance.GetComponent()?.IsTamed() == true) return; + + string prefabName = __instance.gameObject.name.ToLower(); + int state = BossProgressionManager.GetCurrentProgressionState(); + + bool canTame = false; + if (state >= 2 && prefabName.Contains("boar")) canTame = true; + if (state >= 5 && prefabName.Contains("wolf")) canTame = true; + if (state >= 6 && prefabName.Contains("lox")) canTame = true; + if (state >= 8 && prefabName.Contains("asksvin")) canTame = true; + + if (canTame) + { + __result += "\n[] Tame"; + } + } + } + + [HarmonyPatch(typeof(Tameable), "Interact")] + public static class Aswid_TameInteract_Patch + { + public static bool Prefix(Tameable __instance, Humanoid user, bool hold, bool alt) + { + if (hold || alt) return true; + if (user != Player.m_localPlayer || !AswidRace.IsAswid()) return true; + if (__instance.GetComponent()?.IsTamed() == true) return true; + + string prefabName = __instance.gameObject.name.ToLower(); + int state = BossProgressionManager.GetCurrentProgressionState(); + + bool canTame = false; + if (state >= 2 && prefabName.Contains("boar")) canTame = true; + if (state >= 5 && prefabName.Contains("wolf")) canTame = true; + if (state >= 6 && prefabName.Contains("lox")) canTame = true; + if (state >= 8 && prefabName.Contains("asksvin")) canTame = true; + + if (canTame) + { + __instance.GetComponent()?.SetTamed(true); + HarmonyLib.Traverse.Create(__instance).Method("Tame").GetValue(); // attempt to call Tame for VFX if it exists + __instance.Command(user); + user.Message(MessageHud.MessageType.Center, "Tamed!"); + return false; // Skip original interact + } + + return true; + } + } + + [HarmonyPatch(typeof(Hud), "UpdateStamina")] + public static class Aswid_HideStamina_Patch + { + public static bool Prefix(Hud __instance, Player player) + { + if (player == Player.m_localPlayer && AswidRace.IsAswid()) + { + if (__instance.m_staminaBar2Root != null && __instance.m_staminaBar2Root.gameObject.activeSelf) + { + __instance.m_staminaBar2Root.gameObject.SetActive(false); + } + return false; + } + return true; + } + } + + [HarmonyPatch(typeof(StatusEffect), "Setup")] + public static class Aswid_ColdStatus_Patch + { + public static void Prefix(StatusEffect __instance, Character character) + { + if (character == Player.m_localPlayer && AswidRace.IsAswid() && (__instance.name.Contains("Cold") || __instance.m_name == "$se_cold_name")) + { + var wraithTrophy = Jotunn.Managers.PrefabManager.Cache.GetPrefab("TrophyWraith"); + if (wraithTrophy != null && wraithTrophy.m_itemData.m_shared.m_icons.Length > 0) + { + __instance.m_icon = wraithTrophy.m_itemData.m_shared.m_icons[0]; + } + else + { + __instance.m_icon = null; + } + + __instance.m_name = "Night Aura"; + __instance.m_startMessage = ""; // "The darkness empowers you."; + __instance.m_tooltip = "The cold strengthens your beastly senses."; + + if (__instance is SE_Stats stats) + { + stats.m_healthRegenMultiplier = 1f; + stats.m_staminaRegenMultiplier = 1f; + stats.m_staminaDrainPerSec = 0f; + stats.m_speedModifier = 0f; + } + } + } + } + [HarmonyPatch(typeof(Player), "Update")] + public static class Aswid_PlayerUpdate_Patch + { + public static void Postfix(Player __instance) + { + if (__instance == null) return; + ZNetView nview = __instance.GetComponent(); + if (nview != null && nview.IsValid() && nview.GetZDO().GetString("RacesOfValheim_Race", "Human") == "Aswid") + { + if (__instance == Player.m_localPlayer && Input.GetKeyDown(KeyCode.I)) + { + AswidRace.DevourEnabled = !AswidRace.DevourEnabled; + string msg = AswidRace.DevourEnabled ? "Abilità Divora: ATTIVATA" : "Abilità Divora: DISATTIVATA"; + __instance.Message(MessageHud.MessageType.Center, msg); + } + + int state = BossProgressionManager.GetCurrentProgressionState(); + var rules = AswidProgression.GetRules(state); + + if (AswidRace.Instance != null && !AswidRace.Instance.IsTransformed) + { + if (rules != null && rules.HasSurtlingForm) + { + __instance.transform.localScale = new Vector3(1.1f, 1.1f, 1.1f); + } + else + { + __instance.transform.localScale = Vector3.one; + } + } + } + } + } + + [HarmonyPatch(typeof(VisEquipment), "UpdateVisuals")] + public static class Aswid_MultiplayerVisuals_Patch + { + public static void Postfix(VisEquipment __instance) + { + if (!__instance.m_isPlayer) return; + Player player = __instance.GetComponent(); + if (player == null || player.IsOwner()) return; // Only process for remote players + + ZNetView nview = player.GetComponent(); + if (nview != null && nview.IsValid() && nview.GetZDO().GetString("RacesOfValheim_Race", "Human") == "Aswid") + { + bool isBat = nview.GetZDO().GetBool("Aswid_IsBatForm", false); + bool isMist = nview.GetZDO().GetBool("Aswid_IsMistForm", false); + + Transform playerVisual = player.transform.Find("Visual"); + + // Bat logic + Transform batBody = player.transform.Find("AswidBody_Bat"); + if (isBat && batBody == null) { + GameObject batPrefab = Jotunn.Managers.PrefabManager.Cache.GetPrefab("Bat"); + if (batPrefab != null) { + GameObject visualPrefab = batPrefab.GetComponentInChildren()?.gameObject; + if (visualPrefab != null) { + GameObject batInstance = UnityEngine.Object.Instantiate(visualPrefab, player.transform.position, player.transform.rotation, player.transform); + batInstance.name = "AswidBody_Bat"; + batInstance.transform.localPosition = Vector3.zero; + } + } + } else if (!isBat && batBody != null) { + UnityEngine.Object.Destroy(batBody.gameObject); + } + + // Mist logic + Transform mistBody = player.transform.Find("AswidBody_Mist"); + if (isMist && mistBody == null) { + GameObject wraithPrefab = Jotunn.Managers.PrefabManager.Cache.GetPrefab("Wraith"); + if (wraithPrefab != null) { + GameObject visualPrefab = wraithPrefab.transform.Find("Visual")?.gameObject; + if (visualPrefab != null) { + GameObject mistInstance = UnityEngine.Object.Instantiate(visualPrefab, player.transform.position, player.transform.rotation, player.transform); + mistInstance.name = "AswidBody_Mist"; + mistInstance.transform.localPosition = Vector3.zero; + mistInstance.transform.localScale = Vector3.one; + foreach (var r in mistInstance.GetComponentsInChildren()) + { + if (r.material != null && r.material.HasProperty("_Color")) + { + Color c = r.material.GetColor("_Color"); + c.a = 0.3f; // Make transparent + r.material.SetColor("_Color", c); + } + } + } + } + } else if (!isMist && mistBody != null) { + UnityEngine.Object.Destroy(mistBody.gameObject); + } + + // Toggle visibility + if (isBat || isMist) { + if (playerVisual != null) playerVisual.gameObject.SetActive(false); + } else { + if (playerVisual != null) playerVisual.gameObject.SetActive(true); + } + } + } + } + + [HarmonyPatch(typeof(Player), "Update")] + public static class Aswid_Debug_F8_Patch + { + public static void Postfix(Player __instance) + { + if (__instance == Player.m_localPlayer && UnityEngine.Input.GetKeyDown(UnityEngine.KeyCode.F8)) + { + Jotunn.Logger.LogInfo("[AswidDebug] F8 pressed! Finding nearest mob to consume..."); + Character nearest = null; + float minDist = 10f; + foreach (Character c in Character.GetAllCharacters()) + { + if (c != __instance && c.GetHealth() > 0) + { + float dist = UnityEngine.Vector3.Distance(__instance.transform.position, c.transform.position); + if (dist < minDist) + { + minDist = dist; + nearest = c; + } + } + } + + if (nearest != null) + { + Jotunn.Logger.LogInfo($"[AswidDebug] Consuming {nearest.name} via F8!"); + AswidRace.TryConsumeMob(nearest, nearest.GetMaxHealth()); + + HitData hit = new HitData(); + hit.m_damage.m_damage = 99999f; + hit.m_hitType = HitData.HitType.Undefined; + hit.m_attacker = __instance.GetZDOID(); + nearest.ApplyDamage(hit, true, false); + } + else + { + Jotunn.Logger.LogInfo("[AswidDebug] No mob found near player to consume."); + } + } + } + } + + [HarmonyPatch(typeof(Character), "Damage")] + public static class Aswid_Damage_Patch + { + public static void Prefix(Character __instance, HitData hit, out float __state) + { + __state = (__instance != null) ? __instance.GetHealth() : 0f; + } + + public static void Postfix(Character __instance, HitData hit, float __state) + { + if (hit == null || __instance == null || __instance.IsPlayer()) return; + + // Check if it died from this hit + if (__state > 0f && __instance.GetHealth() <= 0f) + { + Jotunn.Logger.LogInfo($"[AswidDebug] {__instance.name} died. __state: {__state}, CurrentHP: {__instance.GetHealth()}"); + Character attacker = hit.GetAttacker(); + if (attacker != null) Jotunn.Logger.LogInfo($"[AswidDebug] Attacker is: {attacker.name} / Player: {attacker.IsPlayer()} / Local: {attacker == Player.m_localPlayer}"); + + if (attacker != null && attacker.IsPlayer() && attacker == Player.m_localPlayer) + { + ZNetView nview = attacker.GetComponent(); + if (nview != null && nview.IsValid() && nview.GetZDO().GetString("RacesOfValheim_Race", "Human") == "Aswid") + { + Jotunn.Logger.LogInfo($"[AswidDebug] Attacker is local Aswid player. Checking damage type..."); + + // Check if physical attack + if (hit.m_damage.m_blunt > 0 || hit.m_damage.m_slash > 0 || hit.m_damage.m_pierce > 0 || hit.m_damage.m_chop > 0 || hit.m_damage.m_pickaxe > 0 || hit.m_damage.m_damage > 0) + { + Jotunn.Logger.LogInfo($"[AswidDebug] Calling TryConsumeMob for {__instance.name}"); + AswidRace.TryConsumeMob(__instance, __instance.GetMaxHealth()); + } + } + } + } + } + + [HarmonyPatch(typeof(Player), "HaveEitr")] + public static class Player_HaveEitr_Patch + { + public static void Postfix(Player __instance, ref bool __result) + { + if (__instance != null && __instance == Player.m_localPlayer && AswidRace.IsAswid()) + { + var weapon = __instance.GetCurrentWeapon(); + if (weapon != null && weapon.m_shared != null && weapon.m_shared.m_skillType == Skills.SkillType.BloodMagic) + { + __result = true; + } + } + } + } + + [HarmonyPatch(typeof(Player), "UseEitr")] + public static class Player_UseEitr_Patch + { + public static bool Prefix(Player __instance) + { + if (__instance != null && __instance == Player.m_localPlayer && AswidRace.IsAswid()) + { + var weapon = __instance.GetCurrentWeapon(); + if (weapon != null && weapon.m_shared != null && weapon.m_shared.m_skillType == Skills.SkillType.BloodMagic) + { + return false; // Skip spending Eitr + } + } + return true; + } + } + + [HarmonyPatch(typeof(Skills), "RaiseSkill")] + public static class Aswid_Skills_RaiseSkill_Patch + { + public static void Prefix(Skills __instance, Skills.SkillType skillType, ref float factor) + { + Player player = HarmonyLib.Traverse.Create(__instance).Field("m_player").GetValue(); + if (player != null && player == Player.m_localPlayer && AswidRace.IsAswid()) + { + if (skillType == Skills.SkillType.BloodMagic) + { + factor *= 2f; // Benedictus et Afflictus: Double speed for Blood Magic + } + } + } + } + } + + [HarmonyPatch(typeof(Player), "UpdateFood")] + public static class Aswid_PlayerUpdateFood_Patch + { + public static void Prefix(Player __instance, float dt, bool forceUpdate) + { + if (__instance != Player.m_localPlayer || !AswidRace.IsAswid()) return; + + if (AswidFoodManager.ExtraFoods.TryGetValue(__instance, out Player.Food extraFood) && extraFood != null) + { + extraFood.m_time += dt; + + if (extraFood.m_item != null && extraFood.m_item.m_shared != null) + { + if (extraFood.m_time >= extraFood.m_item.m_shared.m_foodBurnTime) + { + AswidFoodManager.ClearFood(__instance); + } + else + { + float factor = extraFood.m_time / extraFood.m_item.m_shared.m_foodBurnTime; + extraFood.m_health = Mathf.Lerp(extraFood.m_item.m_shared.m_food, extraFood.m_item.m_shared.m_food * 0.2f, factor); + extraFood.m_stamina = Mathf.Lerp(extraFood.m_item.m_shared.m_foodStamina, extraFood.m_item.m_shared.m_foodStamina * 0.2f, factor); + extraFood.m_eitr = Mathf.Lerp(extraFood.m_item.m_shared.m_foodEitr, extraFood.m_item.m_shared.m_foodEitr * 0.2f, factor); + } + } + } + } + } + + [HarmonyPatch(typeof(Player), "GetTotalFoodValue")] + public static class Aswid_PlayerGetTotalFoodValue_Patch + { + public static void Postfix(Player __instance, ref float hp, ref float stamina, ref float eitr) + { + if (__instance != Player.m_localPlayer || !AswidRace.IsAswid()) return; + + if (AswidFoodManager.ExtraFoods.TryGetValue(__instance, out Player.Food extraFood) && extraFood != null) + { + hp += extraFood.m_health; + stamina += extraFood.m_stamina; + eitr += extraFood.m_eitr; + } + } + } +} diff --git a/JotunnModStub/Aswid/AswidProgression.cs b/JotunnModStub/Aswid/AswidProgression.cs new file mode 100644 index 0000000..fe95061 --- /dev/null +++ b/JotunnModStub/Aswid/AswidProgression.cs @@ -0,0 +1,62 @@ +using System; +using UnityEngine; + +namespace RacesOfValheim +{ + public static class AswidProgression + { + public enum FormType + { + None, + Bat + } + + public class FormRules + { + public FormType Form = FormType.None; + public bool NeedsNight = false; + } + + public class AswidRules + { + // Add state 0 properties here + public float BonusHealth = 0f; + public float BonusStamina = 0f; + public bool HasSurtlingForm = false; + } + + public static AswidRules GetRules(int state) + { + AswidRules rules = new AswidRules(); + + // State 0 is the base state, no modifiers yet. + if (state >= 1) + { + // Future modifiers + } + + if (state >= 8) // Fader + { + rules.HasSurtlingForm = true; + } + + return rules; + } + + public static FormRules GetGKeyRules(int state) + { + FormRules rules = new FormRules(); + if (state >= 3) + { + rules.Form = FormType.Bat; + rules.NeedsNight = false; // The Elder: always + } + else if (state >= 2) + { + rules.Form = FormType.Bat; + rules.NeedsNight = true; // Eikthyr: night only + } + return rules.Form != FormType.None ? rules : null; + } + } +} diff --git a/JotunnModStub/Aswid/AswidRace.cs b/JotunnModStub/Aswid/AswidRace.cs new file mode 100644 index 0000000..124b63e --- /dev/null +++ b/JotunnModStub/Aswid/AswidRace.cs @@ -0,0 +1,1182 @@ +using HarmonyLib; +using System; +using UnityEngine; +using System.Collections.Generic; + +namespace RacesOfValheim +{ + public class AswidRace : MonoBehaviour + { + public static AswidRace Instance { get; private set; } + + private static Dictionary mobToTrophyMap = new Dictionary + { + { "Boar", "TrophyBoar" }, + { "Neck", "TrophyNeck" }, + { "Greydwarf", "TrophyGreydwarf" }, + { "Greydwarf_Elite", "TrophyGreydwarfElite" }, + { "Greydwarf_Shaman", "TrophyGreydwarfShaman" }, + { "Troll", "TrophyFrostTroll" }, + { "Deer", "TrophyDeer" }, + { "Wolf", "TrophyWolf" }, + { "Fenring", "TrophyFenring" }, + { "Draugr", "TrophyDraugr" }, + { "Draugr_Elite", "TrophyDraugrElite" }, + { "Skeleton", "TrophySkeleton" }, + { "Skeleton_Poison", "TrophySkeletonPoison" }, + { "Surtling", "TrophySurtling" }, + { "Blob", "TrophyBlob" }, + { "BlobElite", "TrophyBlobElite" }, + { "Leech", "TrophyLeech" }, + { "Wraith", "TrophyWraith" }, + { "Hatchling", "TrophyHatchling" }, + { "StoneGolem", "TrophySGolem" }, + { "Lox", "TrophyLox" }, + { "Fuling", "TrophyGoblin" }, + { "FulingShaman", "TrophyGoblinShaman" }, + { "FulingBerserker", "TrophyGoblinBrute" }, + { "Deathsquito", "TrophyDeathsquito" }, + { "Hare", "TrophyHare" }, + { "Seeker", "TrophySeeker" }, + { "SeekerBrood", "TrophySeekerBrood" }, + { "SeekerBrute", "TrophySeekerBrute" }, + { "Gjall", "TrophyGjall" }, + { "Tick", "TrophyTick" }, + { "Ulv", "TrophyUlv" }, + { "Cultist", "TrophyCultist" }, + { "Bat", "TrophyBat" }, + { "Asksvin", "TrophyAsksvin" }, + { "Charred_Melee", "TrophyCharredMelee" }, + { "Charred_Archer", "TrophyCharredArcher" }, + { "Charred_Mage", "TrophyCharredMage" }, + { "Morgen", "TrophyMorgen" }, + { "Volture", "TrophyVolture" } + }; + + private static Dictionary mobToFoodMap = new Dictionary + { + { "Boar", "CookedMeat" }, + { "Neck", "NeckTailGrilled" }, + { "Deer", "CookedDeerMeat" }, + { "Wolf", "CookedWolfMeat" }, + { "Lox", "CookedLoxMeat" }, + { "Hare", "CookedHareMeat" }, + { "Asksvin", "CookedAsksvinMeat" }, + { "Volture", "CookedVoltureMeat" }, + { "Tick", "Bloodbag" }, // Fallback to Bloodbag if BloodClot doesn't exist + { "Seeker", "CookedBugMeat" }, + { "SeekerBrute", "CookedBugMeat" }, + { "SeekerBrood", "CookedBugMeat" } + }; + + public static bool BypassAswidFoodCheck = false; + + private float lastEclipseTime = -900f; // 15 mins cooldown (900 seconds) + public bool IsEclipseActive { get; private set; } = false; + + private float updateTimer = 0f; + private const float UpdateInterval = 1f; + + public bool IsTransformed { get; private set; } = false; + private bool isTransformingSequence = false; + private GameObject currentTransformation; + private GameObject mistTransformation; + private AswidProgression.FormRules activeRules = null; + + private void Awake() + { + Instance = this; + } + + public void CreateModAssets() + { + AswidStatusEffects.RegisterStatusEffects(); + CreateFoodItems(); + + GameObject geirrhafa = Jotunn.Managers.PrefabManager.Cache.GetPrefab("Fenring_Cultist_Hildir"); + if (geirrhafa != null) + { + Jotunn.Logger.LogInfo("[Aswid] GEIRRHAFA DUMP:"); + foreach (var smr in geirrhafa.GetComponentsInChildren(true)) + { + Jotunn.Logger.LogInfo($"[Aswid] SMR: {smr.name}, RootBone: {(smr.rootBone ? smr.rootBone.name : "none")}, Bones: {smr.bones.Length}"); + } + } + } + + private void CreateFoodItems() + { + foreach (var kvp in mobToTrophyMap) + { + string mobName = kvp.Key; + string trophyName = kvp.Value; + string foodName = "AswidFood_" + mobName; + + Jotunn.Configs.ItemConfig config = new Jotunn.Configs.ItemConfig(); + config.Name = "Aswid Food: " + mobName; + config.Description = "The life force of the conquered."; + + Jotunn.Entities.CustomItem customItem = null; + + if (mobToFoodMap.TryGetValue(mobName, out string baseFoodPrefab)) + { + customItem = new Jotunn.Entities.CustomItem(foodName, baseFoodPrefab, config); + // If Jotunn failed to clone because the base prefab doesn't exist, ItemDrop will be null + if (customItem == null || customItem.ItemDrop == null) + { + Jotunn.Logger.LogWarning($"[AswidDebug] Failed to clone base prefab '{baseFoodPrefab}' for {foodName}. Falling back to 'CookedMeat'."); + customItem = new Jotunn.Entities.CustomItem(foodName, "CookedMeat", config); + } + } + else + { + customItem = new Jotunn.Entities.CustomItem(foodName, "RawMeat", config); + } + + if (customItem != null && customItem.ItemDrop != null) + { + if (!mobToFoodMap.ContainsKey(mobName)) + { + GameObject mobPrefab = Jotunn.Managers.PrefabManager.Cache.GetPrefab(mobName); + if (mobPrefab != null) + { + Character c = mobPrefab.GetComponent(); + if (c != null) + { + float foodHp = Mathf.Min(c.m_health / 2f, 150f); + customItem.ItemDrop.m_itemData.m_shared.m_food = foodHp; + customItem.ItemDrop.m_itemData.m_shared.m_foodStamina = 0f; + customItem.ItemDrop.m_itemData.m_shared.m_foodEitr = 0f; + customItem.ItemDrop.m_itemData.m_shared.m_foodBurnTime = c.m_health * 2f; + customItem.ItemDrop.m_itemData.m_shared.m_foodRegen = 1f; + } + } + } + + GameObject trophyPrefab = Jotunn.Managers.PrefabManager.Cache.GetPrefab(trophyName); + if (trophyPrefab != null) + { + ItemDrop trophyDrop = trophyPrefab.GetComponent(); + if (trophyDrop != null) + { + customItem.ItemDrop.m_itemData.m_shared.m_icons = trophyDrop.m_itemData.m_shared.m_icons; + } + } + + Jotunn.Managers.ItemManager.Instance.AddItem(customItem); + } + } + } + + public bool IsChanneling { get; private set; } = false; + private float channelDamageTimer = 0f; + + private float m_tintCheckTimer = 0f; + private float sensesCheckTimer = 0f; + + private Dictionary activeSensesLight = new Dictionary(); + + public static float GetEnslaveCooldown() + { + if (Player.m_localPlayer == null) return 0f; + string timeStr; + if (Player.m_localPlayer.m_customData.TryGetValue("AswidEnslaveTime", out timeStr)) + { + if (long.TryParse(timeStr, out long ticks)) + { + DateTime lastTime = new DateTime(ticks); + float elapsed = (float)(DateTime.Now - lastTime).TotalSeconds; + float cooldown = (15f * 60f) - elapsed; + return Mathf.Max(0f, cooldown); + } + } + return 0f; + } + + public static void StartEnslaveCooldown() + { + if (Player.m_localPlayer != null) + { + Player.m_localPlayer.m_customData["AswidEnslaveTime"] = DateTime.Now.Ticks.ToString(); + } + } + + private void UpdateSuperhumanSenses() + { + try + { + int state = BossProgressionManager.GetCurrentProgressionState(); + var seman = Player.m_localPlayer.GetSEMan(); + int myHash = "SE_SuperhumanSenses".GetStableHashCode(); + bool hasBuff = seman.HaveStatusEffect(myHash); + + if (state < 5) + { + if (hasBuff) + { + seman.RemoveStatusEffect(myHash); + } + return; + } + + if (!hasBuff) + { + seman.AddStatusEffect(myHash, true); + } + + sensesCheckTimer -= Time.deltaTime; + if (sensesCheckTimer <= 0f) + { + sensesCheckTimer = 1.0f; // Refresh every 1 second (TTL is 2s) + + List allChars = Character.GetAllCharacters(); + Vector3 myPos = Player.m_localPlayer.transform.position; + + int markHash = "SE_AswidSensesMark".GetStableHashCode(); + HashSet inRangeChars = new HashSet(); + + foreach (var c in allChars) + { + if (c == null || c == Player.m_localPlayer || c.IsDead() || c.IsTamed()) continue; + + float dist = Vector3.Distance(c.transform.position, myPos); + if (dist <= 100f) // 100 meters detection radius + { + try + { + inRangeChars.Add(c); + c.GetSEMan().AddStatusEffect(markHash, true); // Keep the malus as requested + + // Locally generate the visual + if (!activeSensesLight.ContainsKey(c)) + { + GameObject prefab = ZNetScene.instance?.GetPrefab("piece_groundtorch_green"); + if (prefab != null) + { + ZNetView.m_forceDisableInit = true; + GameObject tempObj = Instantiate(prefab); + ZNetView.m_forceDisableInit = false; + + GameObject lightObj = new GameObject("AswidSensesLight"); + lightObj.transform.SetParent(c.transform); + lightObj.transform.localPosition = Vector3.zero; + + Transform enabledNode = tempObj.transform.Find("_enabled"); + if (enabledNode != null) + { + enabledNode.SetParent(lightObj.transform); + enabledNode.localPosition = Vector3.zero; + enabledNode.localScale = new Vector3(2.2f, 2.2f, 2.2f); + + // FORCE ACTIVE because Fireplace script might have disabled it due to no fuel! + enabledNode.gameObject.SetActive(true); + + foreach (var col in enabledNode.GetComponentsInChildren(true)) Destroy(col); + foreach (var audio in enabledNode.GetComponentsInChildren(true)) Destroy(audio); + + foreach (var l in enabledNode.GetComponentsInChildren(true)) + { + if (l != null) l.range *= 2.2f; + } + + foreach (var mb in enabledNode.GetComponentsInChildren(true)) + { + if (mb == null) continue; + string typeName = mb.GetType().Name; + if (typeName != "ParticleSystem" && typeName != "LightFlicker") + { + Destroy(mb); + } + } + } + + Destroy(tempObj); + + activeSensesLight[c] = lightObj; + } + } + } + catch (Exception ex) + { + Jotunn.Logger.LogError($"[Aswid] Error processing mob {c.name}: {ex}"); + } + } + } + + List keysToRemove = new List(); + foreach (var kvp in activeSensesLight) + { + if (kvp.Key == null || kvp.Key.IsDead() || !inRangeChars.Contains(kvp.Key)) + { + if (kvp.Value != null) Destroy(kvp.Value); + keysToRemove.Add(kvp.Key); + } + } + foreach (var k in keysToRemove) activeSensesLight.Remove(k); + } + } + catch (Exception ex) + { + Jotunn.Logger.LogError($"[Aswid] Error in SuperhumanSenses: {ex}"); + } + } + + private void ClearSuperhumanSenses() + { + foreach (var kvp in activeSensesLight) + { + if (kvp.Value != null) Destroy(kvp.Value); + } + activeSensesLight.Clear(); + } + + private bool? wasNight = null; + + private void Update() + { + if (Player.m_localPlayer == null || Player.m_localPlayer.IsDead() || !IsAswid()) + { + if (IsChanneling) StopChanneling(); + wasNight = null; // reset so it triggers correctly on spawn/respawn + return; + } + + if (EnvMan.instance != null) + { + bool isNight = EnvMan.IsNight(); + if (wasNight.HasValue && wasNight.Value != isNight) + { + if (isNight) + { + Player.m_localPlayer.Message(MessageHud.MessageType.Center, "what a horrible night to have a curse"); + } + else + { + Player.m_localPlayer.Message(MessageHud.MessageType.Center, "The morning sun has vanquished the horrible night"); + } + } + wasNight = isNight; + } + + UpdateSuperhumanSenses(); + + if (Input.GetKeyDown(KeyCode.F8)) + { + Jotunn.Logger.LogInfo("[AswidDebug] F8 Pressed. Dumping Player Visuals:"); + VisEquipment vis = Player.m_localPlayer.GetComponentInChildren(); + if (vis != null) + { + Jotunn.Logger.LogInfo($"[AswidDebug] m_bodyModel.enabled: {(vis.m_bodyModel != null ? vis.m_bodyModel.enabled.ToString() : "null")}"); + + var legItems = Traverse.Create(vis).Field("m_legItemInstances").GetValue>(); + if (legItems != null) + { + foreach (var go in legItems) Jotunn.Logger.LogInfo($"[AswidDebug] LegItem: {go.name}, Active: {go.activeSelf}"); + } + + var chestItems = Traverse.Create(vis).Field("m_chestItemInstances").GetValue>(); + if (chestItems != null) + { + foreach (var go in chestItems) Jotunn.Logger.LogInfo($"[AswidDebug] ChestItem: {go.name}, Active: {go.activeSelf}"); + } + } + + Transform visual = Player.m_localPlayer.transform.Find("Visual"); + if (visual != null) + { + foreach (var smr in visual.GetComponentsInChildren(true)) + { + Jotunn.Logger.LogInfo($"[AswidDebug] Player SMR: {smr.name} | Active: {smr.gameObject.activeSelf} | Enabled: {smr.enabled}"); + } + } + + GameObject geirrhafaPrefab = Jotunn.Managers.PrefabManager.Cache.GetPrefab("Fenring_Cultist_Hildir"); + if (geirrhafaPrefab != null) + { + Jotunn.Logger.LogInfo("[AswidDebug] GEIRRHAFA PREFAB DUMP:"); + foreach (var smr in geirrhafaPrefab.GetComponentsInChildren(true)) + { + Jotunn.Logger.LogInfo($"[AswidDebug] Geirrhafa SMR: {smr.name} | Bones: {smr.bones.Length}"); + } + } + + List allChars = Character.GetAllCharacters(); + Vector3 myPos = Player.m_localPlayer.transform.position; + + int charsInRange = 0; + foreach (var c in allChars) + { + if (c == null || c == Player.m_localPlayer || c.IsDead() || c.IsTamed()) continue; + float dist = Vector3.Distance(c.transform.position, myPos); + if (dist <= 100f) + { + charsInRange++; + bool hasLight = activeSensesLight.ContainsKey(c); + bool hasMalus = c.GetSEMan() != null && c.GetSEMan().HaveStatusEffect("SE_AswidSensesMark".GetStableHashCode()); + Jotunn.Logger.LogInfo($"[AswidDebug] In range: {c.name} (Dist: {dist}), HasLight: {hasLight}, HasMalus: {hasMalus}"); + + if (hasLight) + { + GameObject lightObj = activeSensesLight[c]; + if (lightObj != null) + { + Jotunn.Logger.LogInfo($"[AswidDebug] LightObj: {lightObj.name}, ActiveSelf: {lightObj.activeSelf}, ActiveInHierarchy: {lightObj.activeInHierarchy}"); + Jotunn.Logger.LogInfo(DumpGameObject(lightObj, " ")); + } + else + { + Jotunn.Logger.LogInfo($"[AswidDebug] LightObj is NULL!"); + } + } + } + } + Jotunn.Logger.LogInfo($"[AswidDebug] Total valid chars in range: {charsInRange}"); + Jotunn.Logger.LogInfo($"[AswidDebug] activeSensesLight count: {activeSensesLight.Count}"); + + Jotunn.Logger.LogInfo("[AswidDebug] F8 pressed! Finding nearest mob to consume..."); + Character nearest = null; + float minDist = 10f; + foreach (Character c in Character.GetAllCharacters()) + { + if (c != Player.m_localPlayer && c.GetHealth() > 0) + { + float dist = UnityEngine.Vector3.Distance(Player.m_localPlayer.transform.position, c.transform.position); + if (dist < minDist) + { + minDist = dist; + nearest = c; + } + } + } + + if (nearest != null) + { + Jotunn.Logger.LogInfo($"[AswidDebug] Consuming {nearest.name} via F8!"); + TryConsumeMob(nearest, nearest.GetMaxHealth()); + + HitData hit = new HitData(); + hit.m_damage.m_damage = 99999f; + hit.m_hitType = HitData.HitType.Undefined; + hit.m_attacker = Player.m_localPlayer.GetZDOID(); + nearest.ApplyDamage(hit, true, false); + } + else + { + Jotunn.Logger.LogInfo("[AswidDebug] No mob found near player to consume."); + } + } + + try + { + if (Player.m_localPlayer.GetSEMan().HaveStatusEffect("Cold".GetStableHashCode())) + { + m_tintCheckTimer += Time.deltaTime; + if (m_tintCheckTimer > 0.1f) + { + m_tintCheckTimer = 0f; + ApplyNightAuraTint(); + } + } + } + catch (Exception ex) + { + Jotunn.Logger.LogError($"[Aswid] Error in Cold status check: {ex}"); + } + + updateTimer += Time.deltaTime; + if (updateTimer >= UpdateInterval) + { + updateTimer = 0f; + UpdateAswidState(); + } + + try + { + HandleChanneling(); + } + catch (Exception ex) + { + Jotunn.Logger.LogError($"[Aswid] Error in HandleChanneling: {ex}"); + } + + if (isTransformingSequence) return; + + // The native Cold status effect will be intercepted by Aswid_ColdStatus_Patch in AswidPatches.cs + + if (IsTransformed) + { + bool hasForm = Player.m_localPlayer.GetSEMan().HaveStatusEffect("SE_BatForm".GetStableHashCode()); + if (!hasForm) + { + ForceRevert(); + return; + } + } + + int state = BossProgressionManager.GetCurrentProgressionState(); + + bool takeInput = HarmonyLib.Traverse.Create(Player.m_localPlayer).Method("TakeInput").GetValue(); + if (takeInput) + { + if (Input.GetKeyDown(KeyCode.G)) { TryTransformWithRules(AswidProgression.GetGKeyRules(state)); return; } + if (Input.GetKeyDown(KeyCode.H)) { TryToggleMistForm(); return; } + if (Input.GetKeyDown(KeyCode.J)) + { + TryCastEclipse(state); + return; + } + } + + // Auto revert mist form at sunrise + if (EnvMan.instance != null && EnvMan.IsDay() && Player.m_localPlayer.GetSEMan().HaveStatusEffect("SE_MistForm".GetStableHashCode())) + { + StartCoroutine(RevertMistFormRoutine()); + } + } + + private string DumpGameObject(GameObject go, string indent) + { + System.Text.StringBuilder sb = new System.Text.StringBuilder(); + sb.AppendLine($"{indent}- {go.name} (Layer: {LayerMask.LayerToName(go.layer)})"); + var lights = go.GetComponents(); + foreach (var l in lights) sb.AppendLine($"{indent} [Light] {l.type}, Color: {l.color}, Range: {l.range}"); + var ps = go.GetComponents(); + foreach (var p in ps) sb.AppendLine($"{indent} [ParticleSystem]"); + foreach (Transform child in go.transform) + { + sb.Append(DumpGameObject(child.gameObject, indent + " ")); + } + return sb.ToString(); + } + + private void ApplyNightAuraTint() + { + try + { + foreach (Transform t in Player.m_localPlayer.GetComponentsInChildren()) + { + if (t.name.StartsWith("vfx_Cold") || t.name.StartsWith("vfx_cold")) + { + if (t.GetComponent() == null) + { + t.gameObject.AddComponent(); + + var renderers = t.GetComponentsInChildren(true); + foreach (var r in renderers) + { + if (r.material != null) + { + if (r.material.HasProperty("_Color")) r.material.SetColor("_Color", Color.black); + if (r.material.HasProperty("_TintColor")) r.material.SetColor("_TintColor", Color.black); + if (r.material.HasProperty("_EmissionColor")) r.material.SetColor("_EmissionColor", Color.black); + } + } + + var pss = t.GetComponentsInChildren(true); + foreach (var ps in pss) + { + var main = ps.main; + main.startColor = Color.black; + + bool hasMistForm = Player.m_localPlayer != null && Player.m_localPlayer.GetSEMan().HaveStatusEffect("SE_MistForm".GetStableHashCode()); + float multiplier = hasMistForm ? 10f : 2f; + + main.maxParticles = (int)(main.maxParticles * multiplier); + + var emission = ps.emission; + emission.rateOverTime = new ParticleSystem.MinMaxCurve(emission.rateOverTime.constant * multiplier); + + if (hasMistForm) + { + main.startSpeedMultiplier *= 3f; + main.startSizeMultiplier *= 1.2f; + } + + var col = ps.colorOverLifetime; + if (col.enabled) + { + Gradient grad = new Gradient(); + grad.SetKeys( + new GradientColorKey[] { new GradientColorKey(Color.black, 0.0f), new GradientColorKey(Color.black, 1.0f) }, + new GradientAlphaKey[] { new GradientAlphaKey(1.0f, 0.0f), new GradientAlphaKey(0.0f, 1.0f) } + ); + col.color = new ParticleSystem.MinMaxGradient(grad); + } + } + } + } + } + } + catch (Exception ex) + { + Jotunn.Logger.LogError($"[Aswid] Error in ApplyNightAuraTint: {ex}"); + } + } + + private void TryTransformWithRules(AswidProgression.FormRules rules) + { + if (rules == null || rules.Form == AswidProgression.FormType.None) return; + + if (Player.m_localPlayer.GetSEMan().HaveStatusEffect("SE_MistForm".GetStableHashCode())) return; + + if (IsTransformed) + { + StartCoroutine(RevertToHumanRoutine()); + return; + } + + StartCoroutine(TransformIntoBatRoutine(rules)); + } + + public void ForceRevert() + { + if (IsTransformed && !isTransformingSequence) + { + StartCoroutine(RevertToHumanRoutine()); + } + if (Player.m_localPlayer != null && Player.m_localPlayer.GetSEMan().HaveStatusEffect("SE_MistForm".GetStableHashCode()) && !isTransformingSequence) + { + StartCoroutine(RevertMistFormRoutine()); + } + } + + private System.Collections.IEnumerator TransformIntoBatRoutine(AswidProgression.FormRules rules) + { + isTransformingSequence = true; + activeRules = rules; + + ZSyncAnimation zAnim = Player.m_localPlayer.GetComponent(); + if (zAnim != null) zAnim.SetTrigger("gpower"); + + yield return new WaitForSeconds(1.1f); + + GameObject poofPrefab = Jotunn.Managers.PrefabManager.Cache.GetPrefab("vfx_boar_death"); + if (poofPrefab != null) Instantiate(poofPrefab, Player.m_localPlayer.transform.position, Quaternion.identity); + + // Scale down player over time to 5% size + float elapsed = 0f; + float duration = 0.5f; + Vector3 startScale = Vector3.one; + Vector3 endScale = Vector3.one * 0.05f; + + while (elapsed < duration) + { + Player.m_localPlayer.transform.localScale = Vector3.Lerp(startScale, endScale, elapsed / duration); + elapsed += Time.deltaTime; + yield return null; + } + Player.m_localPlayer.transform.localScale = endScale; + + yield return new WaitForSeconds(0.1f); + + Player.m_localPlayer.GetSEMan().AddStatusEffect("SE_BatForm".GetStableHashCode(), true); + if (Player.m_localPlayer.GetComponent() != null) { + Player.m_localPlayer.GetComponent().GetZDO().Set("Aswid_IsBatForm", true); + } + + Transform playerVisual = Player.m_localPlayer.transform.Find("Visual"); + if (playerVisual != null) + { + playerVisual.gameObject.SetActive(false); + } + + GameObject batPrefab = Jotunn.Managers.PrefabManager.Cache.GetPrefab("Bat"); + if (batPrefab != null) + { + GameObject visualPrefab = batPrefab.GetComponentInChildren()?.gameObject; + if (visualPrefab != null) + { + currentTransformation = Instantiate(visualPrefab, Player.m_localPlayer.transform.position, Player.m_localPlayer.transform.rotation, Player.m_localPlayer.transform); + currentTransformation.transform.localPosition = Vector3.zero; + currentTransformation.transform.localScale = Vector3.one; + + var behavior = currentTransformation.AddComponent(); + behavior.Initialize(rules); + } + } + + IsTransformed = true; + isTransformingSequence = false; + } + + private System.Collections.IEnumerator RevertToHumanRoutine() + { + isTransformingSequence = true; + + GameObject poofPrefab = Jotunn.Managers.PrefabManager.Cache.GetPrefab("vfx_boar_death"); + if (poofPrefab != null) Instantiate(poofPrefab, Player.m_localPlayer.transform.position, Quaternion.identity); + + if (currentTransformation != null) + { + Destroy(currentTransformation); + currentTransformation = null; + } + + Transform playerVisual = Player.m_localPlayer.transform.Find("Visual"); + if (playerVisual != null) + { + playerVisual.gameObject.SetActive(true); + } + + Player.m_localPlayer.GetSEMan().RemoveStatusEffect("SE_BatForm".GetStableHashCode(), true); + if (Player.m_localPlayer.GetComponent() != null) { + Player.m_localPlayer.GetComponent().GetZDO().Set("Aswid_IsBatForm", false); + } + + float elapsed = 0f; + float duration = 0.5f; + Vector3 startScale = Vector3.one * 0.05f; + Vector3 endScale = Vector3.one; + + while (elapsed < duration) + { + Player.m_localPlayer.transform.localScale = Vector3.Lerp(startScale, endScale, elapsed / duration); + elapsed += Time.deltaTime; + yield return null; + } + Player.m_localPlayer.transform.localScale = endScale; + + IsTransformed = false; + activeRules = null; + isTransformingSequence = false; + } + + private void TryToggleMistForm() + { + if (BossProgressionManager.GetCurrentProgressionState() < 7) return; // Requires The Queen + if (isTransformingSequence) return; + if (IsTransformed) return; // Don't allow mist form while in bat form + + if (Player.m_localPlayer.GetSEMan().HaveStatusEffect("SE_MistForm".GetStableHashCode())) + { + StartCoroutine(RevertMistFormRoutine()); + } + else + { + StartCoroutine(TransformIntoMistRoutine()); + } + } + + private System.Collections.IEnumerator TransformIntoMistRoutine() + { + isTransformingSequence = true; + + GameObject poofPrefab = Jotunn.Managers.PrefabManager.Cache.GetPrefab("vfx_surtling_death"); + if (poofPrefab != null) Instantiate(poofPrefab, Player.m_localPlayer.transform.position, Quaternion.identity); + + Player.m_localPlayer.GetSEMan().AddStatusEffect("SE_MistForm".GetStableHashCode(), true); + if (Player.m_localPlayer.GetComponent() != null) { + Player.m_localPlayer.GetComponent().GetZDO().Set("Aswid_IsMistForm", true); + } + + Transform playerVisual = Player.m_localPlayer.transform.Find("Visual"); + + GameObject wraithPrefab = Jotunn.Managers.PrefabManager.Cache.GetPrefab("Wraith"); + if (wraithPrefab != null) + { + GameObject visualPrefab = wraithPrefab.transform.Find("Visual")?.gameObject; + if (visualPrefab != null) + { + mistTransformation = Instantiate(visualPrefab, Player.m_localPlayer.transform.position, Player.m_localPlayer.transform.rotation, Player.m_localPlayer.transform); + mistTransformation.transform.localPosition = Vector3.zero; + mistTransformation.transform.localScale = Vector3.one * 0.01f; + + foreach (var r in mistTransformation.GetComponentsInChildren()) + { + if (r.material != null && r.material.HasProperty("_Color")) + { + Color c = r.material.GetColor("_Color"); + c.a = 0.3f; // Make the wraith much more transparent + r.material.SetColor("_Color", c); + } + } + } + } + + float elapsed = 0f; + float duration = 1.0f; + + while (elapsed < duration) + { + float t = elapsed / duration; + if (playerVisual != null) playerVisual.localScale = Vector3.Lerp(Vector3.one, Vector3.one * 0.01f, t); + if (mistTransformation != null) mistTransformation.transform.localScale = Vector3.Lerp(Vector3.one * 0.01f, Vector3.one, t); + elapsed += Time.deltaTime; + yield return null; + } + + if (playerVisual != null) + { + playerVisual.localScale = Vector3.one * 0.01f; + playerVisual.gameObject.SetActive(false); + } + if (mistTransformation != null) mistTransformation.transform.localScale = Vector3.one; + + isTransformingSequence = false; + yield return null; + } + + private System.Collections.IEnumerator RevertMistFormRoutine() + { + isTransformingSequence = true; + + GameObject poofPrefab = Jotunn.Managers.PrefabManager.Cache.GetPrefab("vfx_surtling_death"); + if (poofPrefab != null) Instantiate(poofPrefab, Player.m_localPlayer.transform.position, Quaternion.identity); + + Transform playerVisual = Player.m_localPlayer.transform.Find("Visual"); + if (playerVisual != null) + { + playerVisual.gameObject.SetActive(true); + } + + float elapsed = 0f; + float duration = 1.0f; + + while (elapsed < duration) + { + float t = elapsed / duration; + if (playerVisual != null) playerVisual.localScale = Vector3.Lerp(Vector3.one * 0.01f, Vector3.one, t); + if (mistTransformation != null) mistTransformation.transform.localScale = Vector3.Lerp(Vector3.one, Vector3.one * 0.01f, t); + elapsed += Time.deltaTime; + yield return null; + } + + if (playerVisual != null) + { + playerVisual.localScale = Vector3.one; + } + + if (mistTransformation != null) + { + Destroy(mistTransformation); + mistTransformation = null; + } + + Player.m_localPlayer.GetSEMan().RemoveStatusEffect("SE_MistForm".GetStableHashCode(), true); + if (Player.m_localPlayer.GetComponent() != null) { + Player.m_localPlayer.GetComponent().GetZDO().Set("Aswid_IsMistForm", false); + } + + isTransformingSequence = false; + yield return null; + } + + private void TryCastEclipse(int state) + { + if (state < 6) return; // Requires Yagluth + + if (EnvMan.instance != null && EnvMan.IsNight()) return; // Fails silently at night + + if (IsEclipseActive) return; + + float cooldown = 900f; // 15 minutes + if (Time.time - lastEclipseTime < cooldown) + { + int remaining = (int)(cooldown - (Time.time - lastEclipseTime)); + Player.m_localPlayer.Message(MessageHud.MessageType.Center, $"Eclipse is on cooldown. Remaining: {remaining}s"); + return; + } + + StartCoroutine(EclipseRoutine()); + } + + private System.Collections.IEnumerator EclipseRoutine() + { + IsEclipseActive = true; + lastEclipseTime = Time.time; + + // Trigger animation (Dead Raiser uses staff_summon or galdr_cast) + var zanim = HarmonyLib.Traverse.Create(Player.m_localPlayer).Field("m_zanim").GetValue(); + if (zanim != null) + { + zanim.SetTrigger("galdr_cast"); + } + + // Lock player for the duration of the cast (approx 2 seconds) + Player.m_localPlayer.Message(MessageHud.MessageType.Center, "An Eclipse descends..."); + + float castTimer = 0f; + while(castTimer < 2.0f) + { + // Force root player physically if possible without breaking their animator + HarmonyLib.Traverse.Create(Player.m_localPlayer).Method("SetRun", false).GetValue(); + castTimer += Time.deltaTime; + yield return null; + } + + // Force night client-side + if (EnvMan.instance != null) + { + HarmonyLib.Traverse.Create(EnvMan.instance).Field("m_debugTime").SetValue(true); + HarmonyLib.Traverse.Create(EnvMan.instance).Field("m_debugTimeOfDay").SetValue(0.5f); // Midnight + } + + yield return new WaitForSeconds(60f); + + // Revert to server time + if (EnvMan.instance != null) + { + HarmonyLib.Traverse.Create(EnvMan.instance).Field("m_debugTime").SetValue(false); + } + + IsEclipseActive = false; + Player.m_localPlayer.Message(MessageHud.MessageType.Center, "The Eclipse has ended."); + } + + private float damageTickTimer = 0f; + + private void StopChanneling() + { + if (!IsChanneling) return; + IsChanneling = false; + channelDamageTimer = 0f; + damageTickTimer = 0f; + } + + private void HandleChanneling() + { + bool hasMistForm = Player.m_localPlayer.GetSEMan().HaveStatusEffect("SE_MistForm".GetStableHashCode()); + bool hasBatForm = Player.m_localPlayer.GetSEMan().HaveStatusEffect("SE_BatForm".GetStableHashCode()); + + if (Player.m_localPlayer.IsBlocking() && (hasMistForm || hasBatForm)) + { + if (!IsChanneling) + { + IsChanneling = true; + if (mistTransformation != null) + { + var anim = mistTransformation.GetComponentInChildren(); + if (anim != null) anim.SetBool("alert", true); + } + } + + channelDamageTimer += Time.deltaTime; + damageTickTimer += Time.deltaTime; + + if (channelDamageTimer >= 0.25f) + { + channelDamageTimer = 0f; + } + + if (damageTickTimer >= 0.25f) + { + damageTickTimer = 0f; + PerformLifeDrain(); + } + } + else + { + if (IsChanneling) + { + StopChanneling(); + if (mistTransformation != null) + { + var anim = mistTransformation.GetComponentInChildren(); + if (anim != null) anim.SetBool("alert", false); + } + } + } + } + + private void PerformLifeDrain() + { + if (Player.m_localPlayer == null) return; + + try + { + Vector3 center = Player.m_localPlayer.transform.position + Player.m_localPlayer.transform.forward * 2f; + float radius = 3f; + if (EnvMan.instance != null && EnvMan.IsNight()) radius = 6f; + + int layerMask = LayerMask.GetMask("character", "character_net", "character_ghost"); + var colliders = Physics.OverlapSphere(center, radius, layerMask); + + bool hitAnything = false; + + foreach (var col in colliders) + { + Character c = col.GetComponentInParent(); + if (c != null && c != Player.m_localPlayer && !c.IsDead() && !c.IsTamed()) + { + if (c.IsPlayer() && (!c.IsPVPEnabled() || !Player.m_localPlayer.IsPVPEnabled())) + { + continue; + } + + hitAnything = true; + float maxHp = c.GetMaxHealth(); + + float baseDamage = 1.0f; // Reduced by 50% + float bloodMagicFactor = Player.m_localPlayer.GetSkillFactor(Skills.SkillType.BloodMagic); + float totalDamage = baseDamage + (baseDamage * bloodMagicFactor); + + if (Player.m_localPlayer.GetSEMan().HaveStatusEffect("SE_MistForm".GetStableHashCode())) + { + totalDamage *= 0.5f; + } + + HitData hd = new HitData(); + hd.m_damage.m_damage = totalDamage; + hd.m_point = c.GetCenterPoint(); + hd.m_attacker = Player.m_localPlayer.GetZDOID(); + c.ApplyDamage(hd, true, false); + + SpawnBloodVFX(c); + } + } + } + catch (Exception ex) + { + Jotunn.Logger.LogError($"[Aswid] Error in PerformLifeDrain: {ex}"); + } + } + + public static bool DevourEnabled = true; + private static float lastConsumeTime = 0f; + + public static void TryConsumeMob(Character c, float maxHp) + { + if (!DevourEnabled) return; + + Jotunn.Logger.LogInfo($"[AswidDebug] TryConsumeMob called for {c.name}"); + if (Time.time - lastConsumeTime < 5f) + { + Jotunn.Logger.LogInfo($"[AswidDebug] TryConsumeMob aborted: Cooldown active. Time.time={Time.time}, lastConsumeTime={lastConsumeTime}"); + return; // Cooldown active + } + + string cleanName = c.name.Replace("(Clone)", "").Trim(); + string customFoodName = "AswidFood_" + cleanName; + + Jotunn.Logger.LogInfo($"[AswidDebug] Looking for foodPrefab: {customFoodName}"); + GameObject foodPrefab = Jotunn.Managers.ItemManager.Instance.GetItem(customFoodName)?.ItemPrefab; + + // Fallback to PrefabManager cache if ItemManager doesn't find it + if (foodPrefab == null) + { + foodPrefab = Jotunn.Managers.PrefabManager.Cache.GetPrefab(customFoodName); + } + + // Fallback to RawMeat if no specific custom item was generated (e.g. mob not in trophy map) + if (foodPrefab == null) + { + Jotunn.Logger.LogWarning($"[AswidDebug] TryConsumeMob aborted: foodPrefab '{customFoodName}' is null in ObjectDB!"); + return; // Mob is not edible + } + + if (foodPrefab != null) + { + ItemDrop foodDrop = foodPrefab.GetComponent(); + if (foodDrop != null) + { + // Suppress "New Material" popup by marking it as known beforehand using reflection + var knownMaterials = HarmonyLib.Traverse.Create(Player.m_localPlayer).Field("m_knownMaterial").GetValue>(); + if (knownMaterials != null) knownMaterials.Add(foodDrop.m_itemData.m_shared.m_name); + + // Create an invisible virtual inventory so the food never goes to the real bag + Inventory virtualInv = new Inventory("AswidStomach", null, 1, 1); + ItemDrop.ItemData addedItem = virtualInv.AddItem(foodPrefab.name, 1, 1, 0, 0, ""); + + if (addedItem != null) + { + Jotunn.Logger.LogInfo($"[AswidDebug] Successfully added {addedItem.m_shared.m_name} to virtual inventory. Attempting UseItem..."); + lastConsumeTime = Time.time; + + // UseItem natively plays animation and consumes it. + // If stomach is full, EatFood fails, UseItem does not consume the item, and virtualInv is destroyed (disintegrated) + AswidRace.BypassAswidFoodCheck = true; + Player.m_localPlayer.UseItem(virtualInv, addedItem, true); + AswidRace.BypassAswidFoodCheck = false; + + if (addedItem.m_stack <= 0 || virtualInv.GetItem(addedItem.m_shared.m_name) == null) + { + Jotunn.Logger.LogInfo($"[AswidDebug] Item was successfully eaten from virtual inventory!"); + + // Show the Vae Victis message in the center of the screen + Player.m_localPlayer.Message(MessageHud.MessageType.Center, "Vae Victis"); + + // Vae Victis XP logic - similar to Dead Raiser + Player.m_localPlayer.RaiseSkill(Skills.SkillType.BloodMagic, 1f); + } + else + { + Jotunn.Logger.LogInfo($"[AswidDebug] Item was NOT eaten (likely stomach full). It will disintegrate with virtual inventory."); + } + } + else + { + Jotunn.Logger.LogWarning($"[AswidDebug] Failed to add item to virtual inventory!"); + } + } + } + } + + private static void SpawnBloodVFX(Character target) + { + try + { + GameObject bloodHitPrefab = Jotunn.Managers.PrefabManager.Cache.GetPrefab("vfx_BloodHit"); + if (bloodHitPrefab != null) + { + Instantiate(bloodHitPrefab, target.GetCenterPoint(), Quaternion.identity); + } + } + catch (Exception ex) + { + Jotunn.Logger.LogError($"[Aswid] Error in SpawnBloodVFX: {ex}"); + } + } + + private void UpdateAswidState() + { + int currentState = BossProgressionManager.GetCurrentProgressionState(); + var rules = AswidProgression.GetRules(currentState); + + ZNetView nview = Player.m_localPlayer.GetComponent(); + if (nview != null && nview.IsValid()) + { + nview.GetZDO().Set("RacesOfValheim_AswidState", currentState); + } + + var aswidSE = Player.m_localPlayer.GetSEMan().GetStatusEffect("SE_AswidStats".GetStableHashCode()) as SE_AswidStats; + if (aswidSE != null) + { + aswidSE.UpdateStats(currentState); + } + else + { + Player.m_localPlayer.GetSEMan().AddStatusEffect("SE_AswidStats".GetStableHashCode(), true); + } + } + + public static bool IsAswid() + { + return Player.m_localPlayer != null && + Player.m_localPlayer.m_customData.ContainsKey("Race") && + Player.m_localPlayer.m_customData["Race"] == "Aswid"; + } + } + + public class BloodVFXMover : MonoBehaviour + { + public Transform target; + private float speed = 10f; + + private void Update() + { + if (target == null) + { + Destroy(gameObject); + return; + } + + transform.position = Vector3.MoveTowards(transform.position, target.position, speed * Time.deltaTime); + if (Vector3.Distance(transform.position, target.position) < 0.2f) + { + Destroy(gameObject); + } + } + } + + public class NightAuraTintFlag : MonoBehaviour { } +} diff --git a/JotunnModStub/Aswid/AswidStatusEffects.cs b/JotunnModStub/Aswid/AswidStatusEffects.cs new file mode 100644 index 0000000..5d746f0 --- /dev/null +++ b/JotunnModStub/Aswid/AswidStatusEffects.cs @@ -0,0 +1,145 @@ +using Jotunn.Managers; +using Jotunn.Entities; +using System; +using UnityEngine; + +namespace RacesOfValheim +{ + public class SE_AswidStats : SE_Stats + { + public override void Setup(Character character) + { + base.Setup(character); + name = "SE_AswidStats"; + m_name = "Benedictus et Afflictus"; + m_tooltip = "Vampiric senses and life drain."; + } + + public void UpdateStats(int state) + { + m_fallDamageModifier = -1f; // No fall damage + + float multiplier = (EnvMan.instance != null && EnvMan.IsNight()) ? 2f : 1f; + + m_speedModifier = 0.01f * state * multiplier; // +3% speed per stage (*2 at night) + + // For jump, Valheim SE_Stats typically adds the y value to 1 + m_jumpModifier = new Vector3(0f, 0.01f * state * multiplier, 0f); + + if (state >= 5) + { + if (m_mods == null) m_mods = new System.Collections.Generic.List(); + m_mods.Clear(); // Refresh to avoid duplicates + m_mods.Add(new HitData.DamageModPair() { m_type = HitData.DamageType.Poison, m_modifier = HitData.DamageModifier.Immune }); + } + else + { + if (m_mods != null) m_mods.Clear(); + } + } + + public override void ModifyAttack(Skills.SkillType skill, ref HitData hitData) + { + base.ModifyAttack(skill, ref hitData); + if (m_character is Player p && p.GetComponent() != null && p.GetComponent().GetZDO() != null) + { + int state = BossProgressionManager.GetCurrentProgressionState(); + var rules = AswidProgression.GetRules(state); + if (rules != null && rules.HasSurtlingForm) + { + hitData.m_damage.m_damage += 30f; + } + } + } + } + + public class SE_BatForm : SE_Stats + { + public override void Setup(Character character) + { + base.Setup(character); + name = "SE_BatForm"; + m_name = "Like a Bat out of Hell"; + m_tooltip = "You have taken the form of a Bat. You can fly, but cannot attack."; + m_fallDamageModifier = -1f; // Immune to fall damage just in case + } + } + + public class SE_MistForm : SE_Stats + { + public override void Setup(Character character) + { + base.Setup(character); + name = "SE_MistForm"; + m_name = "Weight of Shadows"; + m_tooltip = "You are mist. Immune to physical damage and poison. Cannot attack or run."; + m_fallDamageModifier = -1f; + m_mods = new System.Collections.Generic.List + { + new HitData.DamageModPair { m_type = HitData.DamageType.Blunt, m_modifier = HitData.DamageModifier.Immune }, + new HitData.DamageModPair { m_type = HitData.DamageType.Slash, m_modifier = HitData.DamageModifier.Immune }, + new HitData.DamageModPair { m_type = HitData.DamageType.Pierce, m_modifier = HitData.DamageModifier.Immune }, + new HitData.DamageModPair { m_type = HitData.DamageType.Poison, m_modifier = HitData.DamageModifier.Immune } + }; + } + } + + public class SE_AswidSensesMark : SE_Stats + { + public override void Setup(Character character) + { + base.Setup(character); + name = "SE_AswidSensesMark"; + m_name = "Sensed"; + m_tooltip = ""; + m_ttl = 2f; + m_icon = null; // No icon needed for mobs + } + } + + public class SE_SuperhumanSenses : SE_Stats + { + public override void Setup(Character character) + { + base.Setup(character); + name = "SE_SuperhumanSenses"; + m_name = "Auspex"; + m_tooltip = "Sensing life force of nearby creatures."; + } + } + + public class AswidStatusEffects + { + public static void RegisterStatusEffects() + { + var aswidStats = ScriptableObject.CreateInstance(); + aswidStats.name = "SE_AswidStats"; + aswidStats.m_icon = PrefabManager.Cache.GetPrefab("TrophyBat")?.m_itemData.m_shared.m_icons[0]; + + ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(aswidStats, fixReference: false)); + + var batForm = ScriptableObject.CreateInstance(); + batForm.name = "SE_BatForm"; + batForm.m_icon = PrefabManager.Cache.GetPrefab("TrophyBat")?.m_itemData.m_shared.m_icons[0]; + + ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(batForm, fixReference: false)); + + var mistForm = ScriptableObject.CreateInstance(); + mistForm.name = "SE_MistForm"; + mistForm.m_icon = PrefabManager.Cache.GetPrefab("TrophyWraith")?.m_itemData.m_shared.m_icons[0]; + + ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(mistForm, fixReference: false)); + + var sensesMark = ScriptableObject.CreateInstance(); + sensesMark.name = "SE_AswidSensesMark"; + sensesMark.m_name = "Sensed"; + sensesMark.m_ttl = 2f; + ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(sensesMark, fixReference: false)); + + var senses = ScriptableObject.CreateInstance(); + senses.name = "SE_SuperhumanSenses"; + senses.m_icon = PrefabManager.Cache.GetPrefab("TrophyWolf")?.m_itemData.m_shared.m_icons[0]; + ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(senses, fixReference: false)); + } + } +} diff --git a/JotunnModStub/Aswid/AswidThrall.cs b/JotunnModStub/Aswid/AswidThrall.cs new file mode 100644 index 0000000..77bb599 --- /dev/null +++ b/JotunnModStub/Aswid/AswidThrall.cs @@ -0,0 +1,159 @@ +using UnityEngine; +using System; + +namespace RacesOfValheim +{ + public class AswidThrall : MonoBehaviour, Interactable, Hoverable + { + private Character m_character; + private MonsterAI m_ai; + private ZNetView m_nview; + private bool m_wasEnslaved = false; + private bool m_wasConsumed = false; + + private void Awake() + { + m_character = GetComponent(); + m_ai = GetComponent(); + m_nview = GetComponent(); + } + + private void Update() + { + if (m_nview == null || !m_nview.IsValid()) return; + + bool isEnslaved = m_nview.GetZDO().GetBool("AswidEnslaved", false); + if (isEnslaved) + { + if (!m_wasEnslaved) + { + m_wasEnslaved = true; + m_character.SetTamed(true); // Ensure tamed is true on client side if it missed the RPC + + if (m_ai != null) + { + // Custom AI behaviors can be set here if needed + } + } + + // If it dies, the local player who owns it tries to consume it + if (m_character.IsDead() && !m_wasConsumed) + { + m_wasConsumed = true; + if (m_nview.IsOwner() && AswidRace.IsAswid()) + { + AswidRace.TryConsumeMob(m_character, m_character.GetMaxHealth()); + } + } + + // Only the ZDO owner should track lifetime to kill it + if (m_nview.IsOwner()) + { + long enslaveTime = m_nview.GetZDO().GetLong("AswidEnslaveTime", 0); + if (enslaveTime > 0) + { + DateTime time = new DateTime(enslaveTime); + if ((DateTime.Now - time).TotalSeconds >= 60.0) + { + // Time's up! Kill the thrall. + HitData hit = new HitData(); + hit.m_damage.m_damage = 99999f; + hit.m_hitType = HitData.HitType.Undefined; + m_character.ApplyDamage(hit, true, false); + } + } + } + } + } + + public bool Interact(Humanoid user, bool hold, bool alt) + { + if (hold || alt) return false; + if (m_nview == null || !m_nview.IsValid()) return false; + if (user != Player.m_localPlayer || !AswidRace.IsAswid()) return false; + + bool isEnslaved = m_nview.GetZDO().GetBool("AswidEnslaved", false); + if (isEnslaved) + { + // Toggle follow/stay + if (m_ai != null) + { + if (m_ai.GetFollowTarget() == user.gameObject) + { + m_ai.SetFollowTarget(null); + user.Message(MessageHud.MessageType.Center, $"{m_character.m_name} is staying."); + } + else + { + m_ai.SetFollowTarget(user.gameObject); + user.Message(MessageHud.MessageType.Center, $"{m_character.m_name} is following."); + } + } + return true; + } + + // Enslave action + if (BossProgressionManager.GetCurrentProgressionState() < 6) return false; + + float cooldown = AswidRace.GetEnslaveCooldown(); + if (cooldown > 0) + { + user.Message(MessageHud.MessageType.Center, $"Dominate on cooldown ({Mathf.CeilToInt(cooldown / 60f)}m {Mathf.CeilToInt(cooldown % 60f)}s)"); + return false; + } + + // Enslave it! + AswidRace.StartEnslaveCooldown(); + + // Take ownership to set ZDO vars reliably + m_nview.ClaimOwnership(); + + m_nview.GetZDO().Set("AswidEnslaved", true); + m_nview.GetZDO().Set("AswidEnslaveTime", DateTime.Now.Ticks); + m_character.SetTamed(true); + + if (m_ai != null) + { + m_ai.SetFollowTarget(user.gameObject); + } + + GameObject vfx = ZNetScene.instance.GetPrefab("vfx_surtling_death"); + if (vfx) Instantiate(vfx, m_character.transform.position, Quaternion.identity); + + user.Message(MessageHud.MessageType.Center, $"{m_character.m_name} dominated!"); + + return true; + } + + public bool UseItem(Humanoid user, ItemDrop.ItemData item) + { + return false; + } + + public string GetHoverText() + { + if (m_nview == null || !m_nview.IsValid()) return ""; + if (Player.m_localPlayer == null || !AswidRace.IsAswid()) return ""; + + bool isEnslaved = m_nview.GetZDO().GetBool("AswidEnslaved", false); + if (isEnslaved) + { + bool following = m_ai != null && m_ai.GetFollowTarget() != null; + return following ? "[E] Stay" : "[E] Follow"; + } + else + { + if (BossProgressionManager.GetCurrentProgressionState() < 6) return ""; + + float cd = AswidRace.GetEnslaveCooldown(); + if (cd > 0) return $"[E] Dominate (Cooldown: {Mathf.CeilToInt(cd / 60f)}m)"; + return "[E] Dominate"; + } + } + + public string GetHoverName() + { + return ""; // Character component already provides the name + } + } +} diff --git a/JotunnModStub/Aswid/BatFormBehavior.cs b/JotunnModStub/Aswid/BatFormBehavior.cs new file mode 100644 index 0000000..27e9c2c --- /dev/null +++ b/JotunnModStub/Aswid/BatFormBehavior.cs @@ -0,0 +1,54 @@ +using UnityEngine; +using Jotunn.Managers; + +namespace RacesOfValheim +{ + public class BatFormBehavior : MonoBehaviour + { + private Animator anim; + private AswidProgression.FormRules formRules; + + public void Initialize(AswidProgression.FormRules rules) + { + this.formRules = rules; + } + + private void Start() + { + anim = GetComponentInChildren(); + if (Player.m_localPlayer != null) + { + HarmonyLib.Traverse.Create(Player.m_localPlayer).Field("m_debugFly").SetValue(true); + } + } + + private void Update() + { + if (Player.m_localPlayer == null || Player.m_localPlayer.IsDead()) return; + + // Ensure flight remains on continuously + HarmonyLib.Traverse.Create(Player.m_localPlayer).Field("m_debugFly").SetValue(true); + + // Sync Animator + if (anim != null) + { + Vector3 vel = Player.m_localPlayer.GetVelocity(); + vel.y = 0f; + float speed = vel.magnitude; + + // Bats don't necessarily have a complex animator like players, + // but if they do have a speed or flying parameter, we set it here. + anim.SetFloat("forward_speed", speed); + anim.SetBool("flying", true); + } + } + + private void OnDestroy() + { + if (Player.m_localPlayer != null) + { + HarmonyLib.Traverse.Create(Player.m_localPlayer).Field("m_debugFly").SetValue(false); + } + } + } +} diff --git a/JotunnModStub/BossProgressionManager.cs b/JotunnModStub/BossProgressionManager.cs new file mode 100644 index 0000000..39ce04b --- /dev/null +++ b/JotunnModStub/BossProgressionManager.cs @@ -0,0 +1,51 @@ +using Jotunn.Managers; +using System.Collections.Generic; + +namespace RacesOfValheim +{ + public static class BossProgressionManager + { + public static int DebugState = -1; // [DEBUG] Da rimuovere in seguito + + // Valheim Global Keys for bosses + public const string Eikthyr = "defeated_eikthyr"; + public const string TheElder = "defeated_gdking"; + public const string Bonemass = "defeated_bonemass"; + public const string Moder = "defeated_dragon"; + public const string Yagluth = "defeated_goblinking"; + public const string TheQueen = "defeated_queen"; + public const string Fader = "defeated_fader"; + + /// + /// Returns the current progression state of the world based on defeated bosses. + /// 1 = No bosses defeated + /// 2 = Eikthyr defeated + /// 3 = The Elder defeated + /// 4 = Bonemass defeated + /// 5 = Moder defeated + /// 6 = Yagluth defeated + /// 7 = The Queen defeated + /// 8 = Fader defeated + /// + public static int GetCurrentProgressionState() + { + if (DebugState != -1) return DebugState; // [DEBUG] + + if (ZoneSystem.instance == null) + { + return 1; // Default to 1 if ZoneSystem isn't ready + } + + // We check in reverse order (highest tier first) + if (ZoneSystem.instance.GetGlobalKey(Fader)) return 8; + if (ZoneSystem.instance.GetGlobalKey(TheQueen)) return 7; + if (ZoneSystem.instance.GetGlobalKey(Yagluth)) return 6; + if (ZoneSystem.instance.GetGlobalKey(Moder)) return 5; + if (ZoneSystem.instance.GetGlobalKey(Bonemass)) return 4; + if (ZoneSystem.instance.GetGlobalKey(TheElder)) return 3; + if (ZoneSystem.instance.GetGlobalKey(Eikthyr)) return 2; + + return 1; // No bosses defeated + } + } +} diff --git a/JotunnModStub/Fenrir/FenrirBehaviors.cs b/JotunnModStub/Fenrir/FenrirBehaviors.cs new file mode 100644 index 0000000..7954de1 --- /dev/null +++ b/JotunnModStub/Fenrir/FenrirBehaviors.cs @@ -0,0 +1,1030 @@ +using System.Collections; +using BepInEx; +using HarmonyLib; +using Jotunn.Configs; +using Jotunn.Entities; +using Jotunn.Managers; +using UnityEngine; +using UnityEngine.UI; // Added for UI + +namespace RacesOfValheim +{ + public class FenrirFormBehavior : MonoBehaviour + { + private Animator playerAnim; + private Animator fenrirAnim; + + private bool isAttacking = false; + + void Start() + { + playerAnim = Player.m_localPlayer.transform.Find("Visual").GetComponent(); + fenrirAnim = GetComponent(); + + if (fenrirAnim == null) fenrirAnim = GetComponentInChildren(); + } + + void Update() + { + if (playerAnim == null || fenrirAnim == null) return; + + // Se stiamo attaccando, l'Update smette di inviare costantemente + // "onGround", inWater, forward_speed ecc. alle variabili di base? + // Meglio continuare a sincronizzare i movimenti base. + if (!isAttacking) + { + bool isGrounded = playerAnim.GetBool("onGround"); + + fenrirAnim.SetBool("onGround", isGrounded); + fenrirAnim.SetBool("inWater", playerAnim.GetBool("inWater")); + + if (!isGrounded) + { + fenrirAnim.SetFloat("forward_speed", 0f); + fenrirAnim.SetFloat("sideway_speed", 0f); + } + else + { + if (Player.m_localPlayer.IsCrouching()) + { + fenrirAnim.SetFloat("forward_speed", 0f); + fenrirAnim.SetFloat("sideway_speed", 0f); + } + else + { + fenrirAnim.SetFloat("forward_speed", playerAnim.GetFloat("forward_speed")); + fenrirAnim.SetFloat("sideway_speed", playerAnim.GetFloat("sideway_speed")); + } + } + if (isGrounded) + { + if (Input.GetKeyDown(KeyCode.O)) + { + StartCoroutine(HowlRoutine()); + } + else if (Input.GetMouseButtonDown(1)) // Tasto destro (Heavy Claw) + { + StartCoroutine(ClawRoutine("attack_claw1", 110f, 1.2f, 0.5f)); + } + else if (Input.GetMouseButtonDown(0)) // Tasto sinistro + { + StartCoroutine(ClawRoutine("attack_claw0", 60f, 1.0f, 0.4f)); + } + else if (Input.GetMouseButtonDown(2)) // Tasto centrale + { + StartCoroutine(JumpAttackRoutine()); + } + } + } + } + + private void PlaySFX(params string[] prefabNames) + { + foreach (string name in prefabNames) + { + GameObject sfx = PrefabManager.Cache.GetPrefab(name); + if (sfx != null) + { + Instantiate(sfx, Player.m_localPlayer.transform.position, Quaternion.identity); + return; + } + } + Jotunn.Logger.LogWarning($"[FenrirForm] Nessun suono trovato tra: {string.Join(", ", prefabNames)}"); + } + + private IEnumerator HowlRoutine() + { + isAttacking = true; + + fenrirAnim.SetFloat("forward_speed", 0f); + fenrirAnim.SetFloat("sideway_speed", 0f); + + fenrirAnim.SetTrigger("attack_taunt"); + + PlaySFX("sfx_wolf_howl", "sfx_wolf_alert", "sfx_fenring_idle"); + + yield return new WaitForSeconds(2.0f); + + isAttacking = false; + } + + private IEnumerator ClawRoutine(string triggerName, float baseDamage, float lockDuration, float dmgDelay) + { + isAttacking = true; + + fenrirAnim.SetFloat("forward_speed", 0f); + fenrirAnim.SetFloat("sideway_speed", 0f); + + fenrirAnim.SetTrigger(triggerName); + PlaySFX("sfx_fenring_attack", "sfx_fenring_attack_claw", "sfx_wolf_attack"); + + yield return new WaitForSeconds(dmgDelay); + + if (ZNetScene.instance != null) + { + GameObject attackSfx = ZNetScene.instance.GetPrefab("sfx_fenring_attack"); + if (attackSfx != null) + { + Instantiate(attackSfx, Player.m_localPlayer.transform.position, Quaternion.identity); + } + } + + ExecuteClawDamage(baseDamage); + + float remainingTimeToIdle = lockDuration - dmgDelay; + if (remainingTimeToIdle > 0) + { + yield return new WaitForSeconds(remainingTimeToIdle); + } + + fenrirAnim.ResetTrigger(triggerName); + isAttacking = false; + } + + private IEnumerator JumpAttackRoutine() + { + isAttacking = true; + + fenrirAnim.SetFloat("forward_speed", 0f); + fenrirAnim.SetFloat("sideway_speed", 0f); + + fenrirAnim.SetTrigger("attack_jump"); + + // Aspettiamo che l'animazione si carichi (0.75s) + yield return new WaitForSeconds(0.75f); + + if (ZNetScene.instance != null) + { + GameObject attackSfx = ZNetScene.instance.GetPrefab("sfx_fenring_attack"); + if (attackSfx != null) + { + Instantiate(attackSfx, Player.m_localPlayer.transform.position, Quaternion.identity); + } + } + + // Invece di una singola spinta di velocità (che viene subito annullata da Valheim), + // muoviamo esplicitamente il personaggio fotogramma per fotogramma per 0.2 secondi + float dashDuration = 0.2f; + float elapsedDash = 0f; + while (elapsedDash < dashDuration) + { + if (Player.m_localPlayer != null) + { + Rigidbody rb = Player.m_localPlayer.GetComponent(); + if (rb != null) + { + Vector3 dashVelocity = Player.m_localPlayer.transform.forward * 31.5f; + // Spinta verso l'alto solo nella prima metà dello scatto + if (elapsedDash < dashDuration / 2f) + { + dashVelocity += Vector3.up * 13.1f; + } + + rb.MovePosition(rb.position + dashVelocity * Time.fixedDeltaTime); + } + } + elapsedDash += Time.fixedDeltaTime; + yield return new WaitForFixedUpdate(); + } + + // Infliggiamo il danno al termine dello scatto + ExecuteClawDamage(95f); + + // Tempo per riprendersi dall'atterraggio prima di potersi muovere di nuovo + yield return new WaitForSeconds(0.55f); + + fenrirAnim.ResetTrigger("attack_jump"); + isAttacking = false; + } + + private void ExecuteClawDamage(float baseDamage) + { + if (Player.m_localPlayer == null) return; + + Vector3 playerPos = Player.m_localPlayer.transform.position; + Vector3 attackPoint = playerPos + Player.m_localPlayer.transform.forward * 1.5f + Vector3.up * 1f; + float attackRadius = 2.5f; + + float unarmedSkillLevel = Player.m_localPlayer.GetSkillLevel(Skills.SkillType.Unarmed); + float totalDamage = baseDamage + unarmedSkillLevel; + + int layerMask = LayerMask.GetMask("Default", "static_solid", "Default_small", "piece", "piece_nonsolid", "terrain", "character", "character_net", "character_ghost", "hitbox", "character_noenv", "vehicle"); + + Collider[] hits = Physics.OverlapSphere(attackPoint, attackRadius, layerMask); + System.Collections.Generic.HashSet hitObjects = new System.Collections.Generic.HashSet(); + + foreach (Collider hit in hits) + { + if (hit.gameObject == Player.m_localPlayer.gameObject) continue; + if (hit.attachedRigidbody != null && hit.attachedRigidbody.gameObject == Player.m_localPlayer.gameObject) continue; + + IDestructible target = hit.GetComponentInParent(); + + if (target != null) + { + Character characterTarget = target as Character; + if (characterTarget != null && characterTarget == Player.m_localPlayer) continue; + + GameObject targetObj = (target as MonoBehaviour)?.gameObject; + if (targetObj != null) + { + if (hitObjects.Contains(targetObj)) continue; + hitObjects.Add(targetObj); + } + + Vector3 targetCenter = hit.bounds.center; + Vector3 dirToTarget = (targetCenter - playerPos).normalized; + + float angle = Vector3.Angle(Player.m_localPlayer.transform.forward, dirToTarget); + if (angle < 70f) + { + Vector3 eyePos = playerPos + Vector3.up * 1.5f; + if (!Physics.Linecast(eyePos, targetCenter, out RaycastHit rayHit, LayerMask.GetMask("Default", "static_solid", "terrain", "piece"))) + { + HitData hitData = new HitData(); + hitData.m_damage.m_slash = totalDamage; + hitData.m_pushForce = 30f; + hitData.m_point = targetCenter; + hitData.m_dir = Player.m_localPlayer.transform.forward; + hitData.m_skill = Skills.SkillType.Unarmed; + hitData.m_dodgeable = true; + hitData.m_blockable = true; + hitData.m_hitType = HitData.HitType.PlayerHit; + hitData.m_toolTier = 0; + hitData.SetAttacker(Player.m_localPlayer); + + target.Damage(hitData); + } + } + } + } + } + } + + // --- CLASSE CUSTOM PER L'ATTACCO "FIRE" DEL CULTIST --- + public class CultistFormBehavior : MonoBehaviour + { + private Animator playerAnim; + private Animator cultistAnim; + + private bool isAttacking = false; + private bool isShootingFire = false; + private float fireTimer = 0f; + + void Start() + { + playerAnim = Player.m_localPlayer.transform.Find("Visual").GetComponent(); + cultistAnim = GetComponent(); + + if (cultistAnim == null) cultistAnim = GetComponentInChildren(); + } + void Update() + { + if (playerAnim == null || cultistAnim == null) return; + + if (!isAttacking) + { + bool isGrounded = playerAnim.GetBool("onGround"); + + cultistAnim.SetBool("onGround", isGrounded); + cultistAnim.SetBool("inWater", playerAnim.GetBool("inWater")); + + if (!isGrounded) + { + cultistAnim.SetFloat("forward_speed", 0f); + cultistAnim.SetFloat("sideway_speed", 0f); + } + else + { + // Se tiene premuto Ctrl (Crouch), rallenta o ferma il movimento per preparare l'attacco + if (Player.m_localPlayer.IsCrouching()) + { + cultistAnim.SetFloat("forward_speed", 0f); + cultistAnim.SetFloat("sideway_speed", 0f); + } + else + { + cultistAnim.SetFloat("forward_speed", playerAnim.GetFloat("forward_speed")); + cultistAnim.SetFloat("sideway_speed", playerAnim.GetFloat("sideway_speed")); + } + } + + if (isGrounded) + { + // Fire attack on Right Click + if (Input.GetMouseButton(1)) + { + if (Player.m_localPlayer.GetEitr() > 0) + { + if (!isShootingFire) + { + StartFire(); + } + else + { + UpdateFire(); + } + } + else if (isShootingFire) + { + StopFire(); + } + } + else if (isShootingFire) + { + StopFire(); + } + + if (Input.GetKeyDown(KeyCode.O)) + { + StartCoroutine(HowlRoutine()); + } + + // Attacks on Left Click + if (Input.GetMouseButtonDown(0) && !isShootingFire) + { + StartCoroutine(ClawRoutine()); // Single claw + } + // Double claw on Middle Click + else if (Input.GetMouseButtonDown(2) && !isShootingFire) + { + StartCoroutine(DoubleClawRoutine()); + } + } + else if (isShootingFire) + { + StopFire(); + } + } + } + + private void PlaySFX(params string[] prefabNames) + { + foreach (string name in prefabNames) + { + GameObject sfx = PrefabManager.Cache.GetPrefab(name); + if (sfx != null) + { + Instantiate(sfx, Player.m_localPlayer.transform.position, Quaternion.identity); + return; + } + } + Jotunn.Logger.LogWarning($"[CultistForm] Nessun suono trovato tra: {string.Join(", ", prefabNames)}"); + } + + private IEnumerator HowlRoutine() + { + isAttacking = true; + + cultistAnim.SetFloat("forward_speed", 0f); + cultistAnim.SetFloat("sideway_speed", 0f); + + // Cultist ha una vera e propria animazione di "taunt" + cultistAnim.SetTrigger("attack_taunt"); + + PlaySFX("sfx_wolf_howl", "sfx_wolf_alert", "sfx_fenring_idle"); + + // Durata approssimativa dell'animazione di taunt + yield return new WaitForSeconds(2.0f); + + isAttacking = false; + } + + private GameObject fireEffectInstance; + + private void StartFire() + { + if (Player.m_localPlayer == null || isShootingFire) return; + + isShootingFire = true; + cultistAnim.SetFloat("forward_speed", 0f); + cultistAnim.SetFloat("sideway_speed", 0f); + cultistAnim.SetBool("attack_fire", true); + + PlaySFX("sfx_cultist_attack_fire_start"); + cultistAnim.SetTrigger("attack_flames"); + + if (ZNetScene.instance != null && fireEffectInstance == null) + { + // Un effetto che dura nel tempo, trovato dai log! + GameObject fireVfx = ZNetScene.instance.GetPrefab("fx_fenring_flames"); + if (fireVfx != null) + { + fireEffectInstance = Instantiate(fireVfx, Player.m_localPlayer.transform.position + Vector3.up * 1.5f + Player.m_localPlayer.transform.forward, Player.m_localPlayer.transform.rotation, Player.m_localPlayer.transform); + + // Aumentiamo la durata delle particelle del 20% + ParticleSystem[] pss = fireEffectInstance.GetComponentsInChildren(); + foreach (ParticleSystem ps in pss) + { + var main = ps.main; + main.startLifetimeMultiplier *= 1.2f; + } + } + } + } + + private void UpdateFire() + { + // Drain Eitr ridotto del 50% (da 25 a 12.5 per sec) + Player.m_localPlayer.UseEitr(12.5f * Time.deltaTime); + cultistAnim.SetFloat("forward_speed", 0f); + cultistAnim.SetFloat("sideway_speed", 0f); + + fireTimer += Time.deltaTime; + if (fireTimer >= 0.2f) // Damage tick every 0.2s + { + fireTimer = 0f; + ExecuteFireDamage(); + } + } + + private void StopFire() + { + isShootingFire = false; + cultistAnim.ResetTrigger("attack_flames"); + + if (fireEffectInstance != null) + { + Destroy(fireEffectInstance); + fireEffectInstance = null; + } + } + + private void ExecuteFireDamage() + { + if (Player.m_localPlayer == null) return; + + Vector3 playerPos = Player.m_localPlayer.transform.position; + Vector3 attackPoint = playerPos + Player.m_localPlayer.transform.forward * 2.5f + Vector3.up * 1f; + float attackRadius = 3f; + + float magicSkillLevel = Player.m_localPlayer.GetSkillLevel(Skills.SkillType.ElementalMagic); + float baseFireDamage = 20f; // per 0.2s + float totalDamage = baseFireDamage + (magicSkillLevel * 0.5f); + + int layerMask = LayerMask.GetMask("Default", "static_solid", "Default_small", "piece", "piece_nonsolid", "terrain", "character", "character_net", "character_ghost", "hitbox", "character_noenv", "vehicle"); + Collider[] hits = Physics.OverlapSphere(attackPoint, attackRadius, layerMask); + System.Collections.Generic.HashSet hitObjects = new System.Collections.Generic.HashSet(); + + foreach (Collider hit in hits) + { + if (hit.gameObject == Player.m_localPlayer.gameObject) continue; + if (hit.attachedRigidbody != null && hit.attachedRigidbody.gameObject == Player.m_localPlayer.gameObject) continue; + + IDestructible target = hit.GetComponentInParent(); + + if (target != null) + { + Character characterTarget = target as Character; + if (characterTarget != null && characterTarget == Player.m_localPlayer) continue; + + GameObject targetObj = (target as MonoBehaviour)?.gameObject; + if (targetObj != null) + { + if (hitObjects.Contains(targetObj)) continue; + hitObjects.Add(targetObj); + } + + Vector3 targetCenter = hit.bounds.center; + Vector3 dirToTarget = (targetCenter - playerPos).normalized; + + float angle = Vector3.Angle(Player.m_localPlayer.transform.forward, dirToTarget); + if (angle < 45f) + { + HitData hitData = new HitData(); + hitData.m_damage.m_fire = totalDamage; + hitData.m_point = targetCenter; + hitData.m_dir = Player.m_localPlayer.transform.forward; + hitData.m_skill = Skills.SkillType.ElementalMagic; + hitData.m_dodgeable = true; + hitData.m_blockable = true; + hitData.m_hitType = HitData.HitType.PlayerHit; + hitData.SetAttacker(Player.m_localPlayer); + + target.Damage(hitData); + + if (ZNetScene.instance != null) + { + GameObject hitFx = ZNetScene.instance.GetPrefab("vfx_FireballHit"); + if (hitFx != null) Instantiate(hitFx, targetCenter, Quaternion.identity); + } + } + } + } + } + + private IEnumerator ClawRoutine() + { + isAttacking = true; + + cultistAnim.SetFloat("forward_speed", 0f); + cultistAnim.SetFloat("sideway_speed", 0f); + + // Per il Cultista usiamo esplicitamente il trigger dell'artigliata + cultistAnim.SetTrigger("attack_claw"); + + yield return new WaitForSeconds(0.4f); + + PlaySFX("sfx_cultist_attack", "sfx_fenring_attack", "sfx_wolf_attack"); + + ExecuteClawDamage(85f); + + float remainingTimeToIdle = 0.5f - 0.4f; + if (remainingTimeToIdle > 0) + { + yield return new WaitForSeconds(remainingTimeToIdle); + } + + cultistAnim.ResetTrigger("attack_claw"); + isAttacking = false; + } + + private IEnumerator DoubleClawRoutine() + { + isAttacking = true; + + cultistAnim.SetFloat("forward_speed", 0f); + cultistAnim.SetFloat("sideway_speed", 0f); + + cultistAnim.SetTrigger("attack_claw_double"); + + // L'animazione double claw è più lunga, facciamo il danno un po' dopo + yield return new WaitForSeconds(0.6f); + + PlaySFX("sfx_cultist_attack_double", "sfx_cultist_attack", "sfx_fenring_attack"); + + ExecuteClawDamage(140f); + + // Attendiamo che l'animazione finisca (locking del giocatore) + // L'animazione doppia del cultista dura circa 1.5 - 2 secondi + yield return new WaitForSeconds(1.2f); + + cultistAnim.ResetTrigger("attack_claw_double"); + isAttacking = false; + } + + private void ExecuteClawDamage(float baseDamage) + { + if (Player.m_localPlayer == null) return; + + Vector3 playerPos = Player.m_localPlayer.transform.position; + Vector3 attackPoint = playerPos + Player.m_localPlayer.transform.forward * 1.5f + Vector3.up * 1f; + float attackRadius = 2.5f; + + float unarmedSkillLevel = Player.m_localPlayer.GetSkillLevel(Skills.SkillType.Unarmed); + float totalDamage = baseDamage + unarmedSkillLevel; + + int layerMask = LayerMask.GetMask("Default", "static_solid", "Default_small", "piece", "piece_nonsolid", "terrain", "character", "character_net", "character_ghost", "hitbox", "character_noenv", "vehicle"); + + Collider[] hits = Physics.OverlapSphere(attackPoint, attackRadius, layerMask); + System.Collections.Generic.HashSet hitObjects = new System.Collections.Generic.HashSet(); + + foreach (Collider hit in hits) + { + if (hit.gameObject == Player.m_localPlayer.gameObject) continue; + if (hit.attachedRigidbody != null && hit.attachedRigidbody.gameObject == Player.m_localPlayer.gameObject) continue; + + IDestructible target = hit.GetComponentInParent(); + + if (target != null) + { + Character characterTarget = target as Character; + if (characterTarget != null && characterTarget == Player.m_localPlayer) continue; + + GameObject targetObj = (target as MonoBehaviour)?.gameObject; + if (targetObj != null) + { + if (hitObjects.Contains(targetObj)) continue; + hitObjects.Add(targetObj); + } + + Vector3 targetCenter = hit.bounds.center; + Vector3 dirToTarget = (targetCenter - playerPos).normalized; + + float angle = Vector3.Angle(Player.m_localPlayer.transform.forward, dirToTarget); + if (angle < 70f) + { + Vector3 eyePos = playerPos + Vector3.up * 1.5f; + if (!Physics.Linecast(eyePos, targetCenter, out RaycastHit rayHit, LayerMask.GetMask("Default", "static_solid", "terrain", "piece"))) + { + HitData hitData = new HitData(); + hitData.m_damage.m_slash = totalDamage; + hitData.m_pushForce = 30f; + hitData.m_point = targetCenter; + hitData.m_dir = Player.m_localPlayer.transform.forward; + hitData.m_skill = Skills.SkillType.Unarmed; + hitData.m_dodgeable = true; + hitData.m_blockable = true; + hitData.m_hitType = HitData.HitType.PlayerHit; + hitData.m_toolTier = 0; + hitData.SetAttacker(Player.m_localPlayer); + + target.Damage(hitData); + } + } + } + } + } + } + + public class WolfFormBehavior : MonoBehaviour + { + private Animator playerAnim; + private Animator wolfAnim; + private bool isAttacking = false; + + void Start() + { + playerAnim = Player.m_localPlayer.transform.Find("Visual").GetComponent(); + wolfAnim = GetComponent(); + + if (wolfAnim == null) wolfAnim = GetComponentInChildren(); + } + + void Update() + { + if (playerAnim == null || wolfAnim == null) return; + + if (!isAttacking) + { + bool isGrounded = playerAnim.GetBool("onGround"); + + try { wolfAnim.SetBool("onGround", isGrounded); } catch {} + try { wolfAnim.SetBool("inWater", playerAnim.GetBool("inWater")); } catch {} + + if (!isGrounded) + { + try { wolfAnim.SetFloat("forward_speed", 0f); } catch {} + try { wolfAnim.SetFloat("sideway_speed", 0f); } catch {} + } + else + { + if (Player.m_localPlayer.IsCrouching()) + { + try { wolfAnim.SetFloat("forward_speed", 0f); } catch {} + try { wolfAnim.SetFloat("sideway_speed", 0f); } catch {} + } + else + { + try { wolfAnim.SetFloat("forward_speed", playerAnim.GetFloat("forward_speed")); } catch {} + try { wolfAnim.SetFloat("sideway_speed", playerAnim.GetFloat("sideway_speed")); } catch {} + } + } + + if (isGrounded) + { + if (Input.GetMouseButtonDown(0)) // Left Click + { + StartCoroutine(WolfAttackRoutine("attack1", 40f, 0.6f, 0.2f)); + } + else if (Input.GetMouseButtonDown(1)) // Right Click + { + StartCoroutine(WolfAttackRoutine("attack2", 60f, 0.8f, 0.3f)); + } + else if (Input.GetMouseButtonDown(2)) // Middle Click + { + StartCoroutine(WolfAttackRoutine("attack3", 80f, 1.0f, 0.4f)); + } + } + } + } + + private void PlaySFX(params string[] prefabNames) + { + foreach (string name in prefabNames) + { + GameObject sfx = PrefabManager.Cache.GetPrefab(name); + if (sfx != null) + { + Instantiate(sfx, Player.m_localPlayer.transform.position, Quaternion.identity); + return; + } + } + } + + private IEnumerator WolfAttackRoutine(string triggerName, float baseDamage, float lockDuration, float dmgDelay) + { + isAttacking = true; + + try { wolfAnim.SetFloat("forward_speed", 0f); } catch {} + try { wolfAnim.SetFloat("sideway_speed", 0f); } catch {} + + wolfAnim.SetTrigger(triggerName); + + yield return new WaitForSeconds(dmgDelay); + + if (ZNetScene.instance != null) + { + GameObject attackSfx = ZNetScene.instance.GetPrefab("sfx_wolf_attack"); + if (attackSfx != null) + { + Instantiate(attackSfx, Player.m_localPlayer.transform.position, Quaternion.identity); + } + } + + ExecuteBiteDamage(baseDamage); + + float remainingTimeToIdle = lockDuration - dmgDelay; + if (remainingTimeToIdle > 0) + { + yield return new WaitForSeconds(remainingTimeToIdle); + } + + wolfAnim.ResetTrigger(triggerName); + isAttacking = false; + } + + private void ExecuteBiteDamage(float baseDamage) + { + if (Player.m_localPlayer == null) return; + + Vector3 playerPos = Player.m_localPlayer.transform.position; + // Il lupo è basso, abbassiamo l'altezza dell'attacco + Vector3 attackPoint = playerPos + Player.m_localPlayer.transform.forward * 1.5f + Vector3.up * 0.5f; + float attackRadius = 2.0f; + + float unarmedSkillLevel = Player.m_localPlayer.GetSkillLevel(Skills.SkillType.Unarmed); + float totalDamage = baseDamage + unarmedSkillLevel; + + int layerMask = LayerMask.GetMask("Default", "static_solid", "Default_small", "piece", "piece_nonsolid", "terrain", "character", "character_net", "character_ghost", "hitbox", "character_noenv", "vehicle"); + + Collider[] hits = Physics.OverlapSphere(attackPoint, attackRadius, layerMask); + System.Collections.Generic.HashSet hitObjects = new System.Collections.Generic.HashSet(); + + foreach (Collider hit in hits) + { + if (hit.gameObject == Player.m_localPlayer.gameObject) continue; + if (hit.attachedRigidbody != null && hit.attachedRigidbody.gameObject == Player.m_localPlayer.gameObject) continue; + + IDestructible target = hit.GetComponentInParent(); + + if (target != null) + { + Character characterTarget = target as Character; + if (characterTarget != null && characterTarget == Player.m_localPlayer) continue; + + GameObject targetObj = (target as MonoBehaviour)?.gameObject; + if (targetObj != null) + { + if (hitObjects.Contains(targetObj)) continue; + hitObjects.Add(targetObj); + } + + Vector3 targetCenter = hit.bounds.center; + Vector3 dirToTarget = (targetCenter - playerPos).normalized; + + float angle = Vector3.Angle(Player.m_localPlayer.transform.forward, dirToTarget); + if (angle < 70f) + { + Vector3 eyePos = playerPos + Vector3.up * 1.0f; + if (!Physics.Linecast(eyePos, targetCenter, out RaycastHit rayHit, LayerMask.GetMask("Default", "static_solid", "terrain", "piece"))) + { + HitData hitData = new HitData(); + hitData.m_damage.m_slash = totalDamage; + hitData.m_pushForce = 20f; + hitData.m_point = targetCenter; + hitData.m_dir = Player.m_localPlayer.transform.forward; + hitData.m_skill = Skills.SkillType.Unarmed; + hitData.m_dodgeable = true; + hitData.m_blockable = true; + hitData.m_hitType = HitData.HitType.PlayerHit; + hitData.m_toolTier = 0; + hitData.SetAttacker(Player.m_localPlayer); + + target.Damage(hitData); + } + } + } + } + } + } + + // --- CLASSE CUSTOM PER L'ULV --- + public class UlvFormBehavior : MonoBehaviour + { + private Animator playerAnim; + private Animator ulvAnim; + + private bool isAttacking = false; + + void Start() + { + playerAnim = Player.m_localPlayer.transform.Find("Visual").GetComponent(); + ulvAnim = GetComponent(); + if (ulvAnim == null) ulvAnim = GetComponentInChildren(); + } + + void Update() + { + if (Player.m_localPlayer == null || playerAnim == null || ulvAnim == null) return; + + if (!isAttacking) + { + bool isGrounded = playerAnim.GetBool("onGround"); + + try { ulvAnim.SetBool("onGround", isGrounded); } catch {} + try { ulvAnim.SetBool("inWater", playerAnim.GetBool("inWater")); } catch {} + + if (!isGrounded) + { + try { ulvAnim.SetFloat("forward_speed", 0f); } catch {} + try { ulvAnim.SetFloat("sideway_speed", 0f); } catch {} + } + else + { + if (Player.m_localPlayer.IsCrouching()) + { + try { ulvAnim.SetFloat("forward_speed", 0f); } catch {} + try { ulvAnim.SetFloat("sideway_speed", 0f); } catch {} + } + else + { + try { ulvAnim.SetFloat("forward_speed", playerAnim.GetFloat("forward_speed")); } catch {} + try { ulvAnim.SetFloat("sideway_speed", playerAnim.GetFloat("sideway_speed")); } catch {} + } + } + + if (isGrounded) + { + if (Input.GetMouseButtonDown(0)) // Left Click + { + StartCoroutine(UlvAttackRoutine("attack_bite", 40f, 0.6f, 0.2f)); + } + else if (Input.GetMouseButtonDown(1)) // Right Click + { + // Right click uses bite but as a heavier attack since slash is moved to jump + StartCoroutine(UlvAttackRoutine("attack_bite", 60f, 0.8f, 0.3f)); + } + else if (Input.GetMouseButtonDown(2)) // Middle Click + { + StartCoroutine(UlvJumpAttackRoutine()); + } + } + } + } + + private void PlaySFX(params string[] prefabNames) + { + foreach (string name in prefabNames) + { + GameObject sfx = PrefabManager.Cache.GetPrefab(name); + if (sfx != null) + { + Instantiate(sfx, Player.m_localPlayer.transform.position, Quaternion.identity); + return; + } + } + } + + private IEnumerator UlvAttackRoutine(string triggerName, float baseDamage, float lockDuration, float dmgDelay) + { + isAttacking = true; + + try { ulvAnim.SetFloat("forward_speed", 0f); } catch {} + try { ulvAnim.SetFloat("sideway_speed", 0f); } catch {} + + try { ulvAnim.SetTrigger(triggerName); } catch {} + + // Scegli il suono appropriato per l'attacco + if (triggerName == "attack_bite") + { + PlaySFX("sfx_ulv_attack", "sfx_wolf_attack", "sfx_fenring_attack"); + } + else + { + PlaySFX("sfx_ulv_attack", "sfx_wolf_attack", "sfx_fenring_attack"); + } + + yield return new WaitForSeconds(dmgDelay); + + if (ZNetScene.instance != null) + { + GameObject attackSfx = ZNetScene.instance.GetPrefab("sfx_wood_hit"); + if (attackSfx != null) + { + Instantiate(attackSfx, Player.m_localPlayer.transform.position, Quaternion.identity); + } + } + + ExecuteBiteDamage(baseDamage); + + float remainingTimeToIdle = lockDuration - dmgDelay; + if (remainingTimeToIdle > 0) + { + yield return new WaitForSeconds(remainingTimeToIdle); + } + + try { ulvAnim.ResetTrigger(triggerName); } catch {} + isAttacking = false; + } + + private void ExecuteBiteDamage(float baseDamage) + { + if (Player.m_localPlayer == null) return; + + Vector3 playerPos = Player.m_localPlayer.transform.position; + Vector3 attackPoint = playerPos + Player.m_localPlayer.transform.forward * 1.5f + Vector3.up * 0.5f; + float attackRadius = 2.0f; + + float unarmedSkillLevel = Player.m_localPlayer.GetSkillLevel(Skills.SkillType.Unarmed); + float totalDamage = baseDamage + unarmedSkillLevel; + + int layerMask = LayerMask.GetMask("Default", "static_solid", "Default_small", "piece", "piece_nonsolid", "terrain", "character", "character_net", "character_ghost", "hitbox", "character_noenv", "vehicle"); + + Collider[] hits = Physics.OverlapSphere(attackPoint, attackRadius, layerMask); + System.Collections.Generic.HashSet hitObjects = new System.Collections.Generic.HashSet(); + + foreach (Collider hit in hits) + { + if (hit.gameObject == Player.m_localPlayer.gameObject) continue; + if (hit.attachedRigidbody != null && hit.attachedRigidbody.gameObject == Player.m_localPlayer.gameObject) continue; + + IDestructible target = hit.GetComponentInParent(); + + if (target != null) + { + Character characterTarget = target as Character; + if (characterTarget != null && characterTarget == Player.m_localPlayer) continue; + + GameObject targetObj = (target as MonoBehaviour)?.gameObject; + if (targetObj != null) + { + if (hitObjects.Contains(targetObj)) continue; + hitObjects.Add(targetObj); + } + + Vector3 targetCenter = hit.bounds.center; + Vector3 dirToTarget = (targetCenter - playerPos).normalized; + + float angle = Vector3.Angle(Player.m_localPlayer.transform.forward, dirToTarget); + if (angle < 70f) + { + Vector3 eyePos = playerPos + Vector3.up * 1.0f; + if (!Physics.Linecast(eyePos, targetCenter, out RaycastHit rayHit, LayerMask.GetMask("Default", "static_solid", "terrain", "piece"))) + { + HitData hitData = new HitData(); + hitData.m_damage.m_slash = totalDamage; + hitData.m_pushForce = 25f; + hitData.m_point = targetCenter; + hitData.m_dir = Player.m_localPlayer.transform.forward; + hitData.m_skill = Skills.SkillType.Unarmed; + hitData.m_dodgeable = true; + hitData.m_blockable = true; + hitData.m_hitType = HitData.HitType.PlayerHit; + hitData.m_toolTier = 0; + hitData.SetAttacker(Player.m_localPlayer); + + target.Damage(hitData); + } + } + } + } + } + + private IEnumerator UlvJumpAttackRoutine() + { + isAttacking = true; + + try { ulvAnim.SetFloat("forward_speed", 0f); } catch {} + try { ulvAnim.SetFloat("sideway_speed", 0f); } catch {} + + try { ulvAnim.SetTrigger("attack_slash"); } catch {} + PlaySFX("sfx_ulv_attack", "sfx_wolf_attack"); + + yield return new WaitForSeconds(0.3f); // Wait 0.3s before leaping + + // Leap forward (+50% range) + float leapDuration = 0.25f; + float leapSpeed = 18f; // Increased from 12f to 18f + float elapsed = 0f; + + while (elapsed < leapDuration) + { + if (Player.m_localPlayer != null) + { + Vector3 moveDir = Player.m_localPlayer.transform.forward; + Player.m_localPlayer.transform.position += moveDir * leapSpeed * Time.deltaTime; + } + elapsed += Time.deltaTime; + yield return null; + } + + if (ZNetScene.instance != null) + { + GameObject attackSfx = ZNetScene.instance.GetPrefab("sfx_wood_hit"); + if (attackSfx != null) + { + Instantiate(attackSfx, Player.m_localPlayer.transform.position, Quaternion.identity); + } + } + + ExecuteBiteDamage(80f); + + yield return new WaitForSeconds(0.4f); + + try { ulvAnim.ResetTrigger("attack_slash"); } catch {} + isAttacking = false; + } + } + +} diff --git a/JotunnModStub/Fenrir/FenrirPatches.cs b/JotunnModStub/Fenrir/FenrirPatches.cs new file mode 100644 index 0000000..c14babf --- /dev/null +++ b/JotunnModStub/Fenrir/FenrirPatches.cs @@ -0,0 +1,97 @@ +using System.Collections; +using BepInEx; +using HarmonyLib; +using Jotunn.Configs; +using Jotunn.Entities; +using Jotunn.Managers; +using UnityEngine; +using UnityEngine.UI; // Added for UI + +namespace RacesOfValheim +{ + [HarmonyPatch(typeof(Character), nameof(Character.StartAttack))] + public static class BlockPlayerLogicAttackPatch + { + public static bool Prefix(Character __instance) + { + if (__instance != null && __instance == Player.m_localPlayer) + { + if (__instance.GetSEMan().HaveStatusEffect("SE_FenrirForm".GetStableHashCode())) + { + return false; + } + } + return true; + } + } + + // --- PATCH 2: BLOCCO ANIMAZIONI ED EFFETTI SONORI NATIVI --- + [HarmonyPatch(typeof(ZSyncAnimation), nameof(ZSyncAnimation.SetTrigger))] + public static class BlockPlayerAnimationsPatch + { + public static bool Prefix(ZSyncAnimation __instance, string name) + { + if (Player.m_localPlayer != null && __instance.gameObject == Player.m_localPlayer.gameObject) + { + if (Player.m_localPlayer.GetSEMan().HaveStatusEffect("SE_FenrirForm".GetStableHashCode())) + { + string triggerName = name.ToLower(); + if (triggerName.Contains("attack") || triggerName.Contains("swing") || triggerName.Contains("punch")) + { + return false; + } + } + } + return true; + } + } + + [HarmonyPatch] + public static class FenrirDamagePatch + { + [HarmonyTargetMethod] + public static System.Reflection.MethodBase TargetMethod() + { + return System.Linq.Enumerable.FirstOrDefault( + HarmonyLib.AccessTools.GetDeclaredMethods(typeof(ItemDrop.ItemData)), + m => m.Name == "GetDamage" && m.ReturnType == typeof(HitData.DamageTypes) + ); + } + public static void Postfix(ItemDrop.ItemData __instance, ref HitData.DamageTypes __result) + { + if (Player.m_localPlayer != null && + Player.m_localPlayer.GetSEMan().HaveStatusEffect("SE_FenrirCurse".GetStableHashCode()) && + Player.m_localPlayer.GetInventory().ContainsItem(__instance)) + { + int state = BossProgressionManager.GetCurrentProgressionState(); + if (state > 0) + { + float bonus = FenrirProgression.GetDamageBonus(state); + + if (__result.m_slash > 0) __result.m_slash += bonus; + if (__result.m_blunt > 0) __result.m_blunt += bonus; + if (__result.m_pierce > 0) __result.m_pierce += bonus; + if (__result.m_chop > 0) __result.m_chop += bonus; + if (__result.m_pickaxe > 0) __result.m_pickaxe += bonus; + } + } + } + } + + [HarmonyPatch(typeof(Player), nameof(Player.GetBodyArmor))] + public static class FenrirArmorPatch + { + public static void Postfix(Player __instance, ref float __result) + { + if (__instance != null && __instance == Player.m_localPlayer) + { + if (__instance.GetSEMan().HaveStatusEffect("SE_FenrirCurse".GetStableHashCode())) + { + int state = BossProgressionManager.GetCurrentProgressionState(); + __result += FenrirProgression.GetArmorBonus(state); + } + } + } + } + +} diff --git a/JotunnModStub/Fenrir/FenrirProgression.cs b/JotunnModStub/Fenrir/FenrirProgression.cs new file mode 100644 index 0000000..6a14551 --- /dev/null +++ b/JotunnModStub/Fenrir/FenrirProgression.cs @@ -0,0 +1,84 @@ +using System; +using UnityEngine; + +namespace RacesOfValheim +{ + public static class FenrirProgression + { + public enum FormType + { + None, + Wolf, + Ulv, + Fenring, + Cultist + } + + public class FormRules + { + public FormType Form; + public bool NeedsNight; + public float DurationMinutes; + public float CooldownMinutes; + + public FormRules(FormType form, bool needsNight, float duration, float cooldown) + { + Form = form; + NeedsNight = needsNight; + DurationMinutes = duration; + CooldownMinutes = cooldown; + } + } + + public static float GetArmorBonus(int state) + { + return 3f * state; + } + + public static float GetDamageBonus(int state) + { + return 5f * state; + } + + public static float GetFallDamageModifier(int state) + { + return Mathf.Clamp(-0.1f * state, -1f, 0f); + } + + public static float GetSpeedModifier(int state) + { + return 0.03f * state; + } + + public static float GetJumpModifier(int state) + { + return 0.03f * state; + } + + // --- Transformation Rules for Keys --- + + public static FormRules GetGKeyRules(int state) + { + if (state >= 5) return new FormRules(FormType.Ulv, false, 0f, 0f); // Moder: Ulv (Day/Night) + if (state >= 4) return new FormRules(FormType.Wolf, false, 0f, 0f); // Bonemass: Wolf (Day/Night) + if (state >= 3) return new FormRules(FormType.Wolf, true, 0f, 0f); // Elder: Wolf (Night) + return null; + } + + public static FormRules GetHKeyRules(int state) + { + if (state >= 7) return new FormRules(FormType.Fenring, false, 0f, 0f); // Queen: Fenrir (Day/Night) + if (state >= 5) return new FormRules(FormType.Fenring, true, 0f, 0f); // Moder: Fenrir (Night) + if (state >= 4) return new FormRules(FormType.Ulv, true, 0f, 0f); // Bonemass: Ulv (Night) + return null; + } + + public static FormRules GetJKeyRules(int state) + { + if (state >= 8) return new FormRules(FormType.Cultist, false, 0f, 0f); // Fader: Cultist (Day/Night) + if (state >= 7) return new FormRules(FormType.Cultist, true, 1f, 5f); // Queen: Cultist (Night, 1m dur, 5m cd) + if (state >= 6) return new FormRules(FormType.Cultist, true, 1f, 10f); // Yagluth: Cultist (Night, 1m dur, 10m cd) + return null; + } + } +} diff --git a/JotunnModStub/Fenrir/FenrirRace.cs b/JotunnModStub/Fenrir/FenrirRace.cs new file mode 100644 index 0000000..3768190 --- /dev/null +++ b/JotunnModStub/Fenrir/FenrirRace.cs @@ -0,0 +1,429 @@ +using System; +using System.Collections; +using Jotunn.Configs; +using Jotunn.Entities; +using Jotunn.Managers; +using UnityEngine; + +namespace RacesOfValheim { + public class FenrirRace : MonoBehaviour { + public static FenrirRace Instance; + public static SE_FenrirCurse curseSE; + public static SE_Stats formBuffSE; + public static SE_Stats wolfFormBuffSE; + public static SE_Stats cultistFormBuffSE; + public static SE_FormCooldown fenrirCdSE; + public static SE_FormCooldown cultistCdSE; + + private GameObject currentTransformation; + private bool isTransformed = false; + private bool isTransformingSequence = false; + + private FenrirProgression.FormRules activeRules = null; + private bool wasNight = false; + private float sunSicknessTimer = 0f; + + private void Awake() + { + Instance = this; + } + + public void CreateModAssets() + { + curseSE = ScriptableObject.CreateInstance(); + curseSE.name = "SE_FenrirCurse"; + curseSE.m_name = "Fenrir's Blood"; + curseSE.m_tooltip = "You are of the Fenrir race."; + curseSE.m_mods = new System.Collections.Generic.List() + { + new HitData.DamageModPair() { m_type = HitData.DamageType.Spirit, m_modifier = HitData.DamageModifier.Weak } + }; + + GameObject fenringTrophy = PrefabManager.Cache.GetPrefab("TrophyFenring")?.gameObject; + Sprite fenringTrophyIcon = null; + if (fenringTrophy != null) + { + ItemDrop trophyDrop = fenringTrophy.GetComponent(); + if (trophyDrop != null && trophyDrop.m_itemData.m_shared.m_icons.Length > 0) + { + fenringTrophyIcon = trophyDrop.m_itemData.m_shared.m_icons[0]; + curseSE.m_icon = fenringTrophyIcon; + } + } + ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(curseSE, fixReference: false)); + + fenrirCdSE = ScriptableObject.CreateInstance(); + fenrirCdSE.name = "SE_FenrirCooldown"; + fenrirCdSE.m_name = "Fenrir Form Cooldown"; + fenrirCdSE.m_icon = fenringTrophyIcon; + ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(fenrirCdSE, fixReference: false)); + + cultistCdSE = ScriptableObject.CreateInstance(); + cultistCdSE.name = "SE_CultistCooldown"; + cultistCdSE.m_name = "Cultist Form Cooldown"; + cultistCdSE.m_icon = fenringTrophyIcon; + ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(cultistCdSE, fixReference: false)); + + formBuffSE = ScriptableObject.CreateInstance(); + formBuffSE.name = "SE_FenrirForm"; + formBuffSE.m_name = "Bestial Fury"; + formBuffSE.m_speedModifier = 1.0f; + formBuffSE.m_jumpModifier = new Vector3(0, 1.0f, 0); + formBuffSE.m_fallDamageModifier = -1f; + formBuffSE.m_staminaRegenMultiplier = 1.3f; + formBuffSE.m_runStaminaDrainModifier = -0.2f; + formBuffSE.m_icon = fenringTrophyIcon; + ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(formBuffSE, fixReference: false)); + + cultistFormBuffSE = ScriptableObject.CreateInstance(); + cultistFormBuffSE.name = "SE_CultistForm"; + cultistFormBuffSE.m_name = "Cultist Fury"; + cultistFormBuffSE.m_speedModifier = 1.0f; + cultistFormBuffSE.m_jumpModifier = new Vector3(0, 1.0f, 0); + cultistFormBuffSE.m_fallDamageModifier = -1f; + cultistFormBuffSE.m_staminaRegenMultiplier = 1.3f; + cultistFormBuffSE.m_runStaminaDrainModifier = -0.2f; + cultistFormBuffSE.m_icon = fenringTrophyIcon; + ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(cultistFormBuffSE, fixReference: false)); + + wolfFormBuffSE = ScriptableObject.CreateInstance(); + wolfFormBuffSE.name = "SE_WolfForm"; + wolfFormBuffSE.m_name = "Wolf Senses"; + wolfFormBuffSE.m_speedModifier = 0.5f; + wolfFormBuffSE.m_fallDamageModifier = -0.5f; + wolfFormBuffSE.m_staminaRegenMultiplier = 1.3f; + wolfFormBuffSE.m_runStaminaDrainModifier = -0.2f; + wolfFormBuffSE.m_icon = fenringTrophyIcon; + ItemManager.Instance.AddStatusEffect(new CustomStatusEffect(wolfFormBuffSE, fixReference: false)); + } + + private void Update() + { + if (Player.m_localPlayer == null || EnvMan.instance == null) return; + if (isTransformingSequence) return; + if (!Player.m_localPlayer.GetSEMan().HaveStatusEffect("SE_FenrirCurse".GetStableHashCode())) return; + + if (sunSicknessTimer > 0f) + { + sunSicknessTimer -= Time.deltaTime; + } + + bool isNight = EnvMan.IsNight(); + if (isNight && !wasNight) + { + Player.m_localPlayer.GetSEMan().RemoveStatusEffect("SE_FenrirCooldown".GetStableHashCode()); + Player.m_localPlayer.GetSEMan().RemoveStatusEffect("SE_CultistCooldown".GetStableHashCode()); + + var fenrirSE = Player.m_localPlayer.GetSEMan().GetStatusEffect("SE_FenrirForm".GetStableHashCode()); + if (fenrirSE != null) fenrirSE.m_ttl = 0f; + + var cultistSE = Player.m_localPlayer.GetSEMan().GetStatusEffect("SE_CultistForm".GetStableHashCode()); + if (cultistSE != null) cultistSE.m_ttl = 0f; + + var wolfSE = Player.m_localPlayer.GetSEMan().GetStatusEffect("SE_WolfForm".GetStableHashCode()); + if (wolfSE != null) wolfSE.m_ttl = 0f; + } + else if (!isNight && wasNight) + { + // Sunrise: force revert and block for 60 seconds + sunSicknessTimer = 60f; + ForceRevert(); + } + wasNight = isNight; + + if (isTransformed) + { + bool hasAnyForm = Player.m_localPlayer.GetSEMan().HaveStatusEffect("SE_FenrirForm".GetStableHashCode()) || + Player.m_localPlayer.GetSEMan().HaveStatusEffect("SE_CultistForm".GetStableHashCode()) || + Player.m_localPlayer.GetSEMan().HaveStatusEffect("SE_WolfForm".GetStableHashCode()); + if (!hasAnyForm) + { + ForceRevert(); + return; + } + } + + int state = BossProgressionManager.GetCurrentProgressionState(); + + if (Input.GetKeyDown(KeyCode.G)) { TryTransformWithRules(FenrirProgression.GetGKeyRules(state)); return; } + if (Input.GetKeyDown(KeyCode.H)) { TryTransformWithRules(FenrirProgression.GetHKeyRules(state)); return; } + if (Input.GetKeyDown(KeyCode.J)) { TryTransformWithRules(FenrirProgression.GetJKeyRules(state)); return; } + } + + private void TryTransformWithRules(FenrirProgression.FormRules rules) + { + if (rules == null || rules.Form == FenrirProgression.FormType.None) return; + + if (sunSicknessTimer > 0f) + { + Player.m_localPlayer.Message(MessageHud.MessageType.Center, "The beast is tired"); + return; + } + + if (isTransformed) + { + StartCoroutine(RevertToHumanRoutine()); + return; + } + + if (rules.NeedsNight && !EnvMan.IsNight()) + { + Player.m_localPlayer.Message(MessageHud.MessageType.Center, "The beast rests. You can only transform at night."); + return; + } + + if (rules.CooldownMinutes > 0) + { + string cdName = rules.Form == FenrirProgression.FormType.Cultist ? "SE_CultistCooldown" : "SE_FenrirCooldown"; + var cdSE = Player.m_localPlayer.GetSEMan().GetStatusEffect(cdName.GetStableHashCode()); + if (cdSE != null) + { + float m_time = HarmonyLib.Traverse.Create(cdSE).Field("m_time").Value; + float remaining = cdSE.m_ttl - m_time; + if (remaining < 0) remaining = 0; + int rMin = Mathf.FloorToInt(remaining / 60f); + int rSec = Mathf.FloorToInt(remaining % 60f); + string formName = rules.Form == FenrirProgression.FormType.Cultist ? "Cultist" : "Fenrir"; + Player.m_localPlayer.Message(MessageHud.MessageType.Center, $"{formName} form is on cooldown ({rMin}:{rSec:00})."); + return; + } + } + + StartCoroutine(TransformIntoWolfRoutine(rules)); + } + + public void ForceRevert() + { + if (isTransformed && !isTransformingSequence) + { + StartCoroutine(RevertToHumanRoutine()); + } + } + + private IEnumerator TransformIntoWolfRoutine(FenrirProgression.FormRules rules) + { + isTransformingSequence = true; + activeRules = rules; + + ZSyncAnimation zAnim = Player.m_localPlayer.GetComponent(); + if (zAnim != null) zAnim.SetTrigger("gpower"); + + yield return new WaitForSeconds(1.1f); + + SpawnPoofEffect(); + + if (ZNetScene.instance != null) + { + GameObject howlPrefab = ZNetScene.instance.GetPrefab("sfx_wolf_howl") ?? ZNetScene.instance.GetPrefab("sfx_fenring_idle"); + if (howlPrefab != null) Instantiate(howlPrefab, Player.m_localPlayer.transform.position, Quaternion.identity); + } + + yield return new WaitForSeconds(0.1f); + + ExecuteTransformation(rules); + + if (currentTransformation != null && currentTransformation.GetComponent() == null && currentTransformation.GetComponent() == null) + { + float elapsed = 0f; + float duration = 0.5f; + float startMultiplier = 0.5f; + Vector3 startScale = Vector3.one * startMultiplier; + Vector3 endScale = Vector3.one; + + currentTransformation.transform.localScale = startScale; + + while (elapsed < duration) + { + if (currentTransformation == null) break; + currentTransformation.transform.localScale = Vector3.Lerp(startScale, endScale, elapsed / duration); + elapsed += Time.deltaTime; + yield return null; + } + if (currentTransformation != null) currentTransformation.transform.localScale = endScale; + } + + isTransformingSequence = false; + } + + private IEnumerator RevertToHumanRoutine() + { + isTransformingSequence = true; + + if (currentTransformation != null) + { + FenrirFormBehavior fenrirBehavior = currentTransformation.GetComponent(); + if (fenrirBehavior != null) fenrirBehavior.enabled = false; + + CultistFormBehavior cultistBehavior = currentTransformation.GetComponent(); + if (cultistBehavior != null) cultistBehavior.enabled = false; + + WolfFormBehavior wolfBehavior = currentTransformation.GetComponent(); + if (wolfBehavior != null) wolfBehavior.enabled = false; + + UlvFormBehavior ulvBehavior = currentTransformation.GetComponent(); + if (ulvBehavior != null) ulvBehavior.enabled = false; + + if (wolfBehavior == null && ulvBehavior == null) + { + float elapsed = 0f; + float duration = 0.5f; + Vector3 startScale = currentTransformation.transform.localScale; + float endMultiplier = 0.5f; + Vector3 endScale = startScale * endMultiplier; + + while (elapsed < duration) + { + if (currentTransformation == null) break; + currentTransformation.transform.localScale = Vector3.Lerp(startScale, endScale, elapsed / duration); + elapsed += Time.deltaTime; + yield return null; + } + } + } + + SpawnPoofEffect(); + yield return new WaitForSeconds(0.1f); + ExecuteReversion(); + isTransformingSequence = false; + } + + private void SpawnPoofEffect() + { + if (Player.m_localPlayer == null) return; + Vector3 pos = Player.m_localPlayer.transform.position + Vector3.up; + + GameObject smoke = PrefabManager.Cache.GetPrefab("vfx_corpse_destruction"); + if (smoke != null) Instantiate(smoke, pos, Quaternion.identity); + + GameObject sparks = PrefabManager.Cache.GetPrefab("vfx_HitSparks"); + if (sparks != null) Instantiate(sparks, pos, Quaternion.identity); + } + + private void ExecuteTransformation(FenrirProgression.FormRules rules) + { + Transform playerVisual = Player.m_localPlayer.transform.Find("Visual"); + string prefabName = ""; + + switch (rules.Form) + { + case FenrirProgression.FormType.Wolf: prefabName = "Wolf"; break; + case FenrirProgression.FormType.Ulv: prefabName = "Ulv"; break; + case FenrirProgression.FormType.Fenring: prefabName = "Fenring"; break; + case FenrirProgression.FormType.Cultist: prefabName = "Fenring_Cultist"; break; + } + + GameObject prefab = PrefabManager.Cache.GetPrefab(prefabName); + + // Sync to ZDO + ZNetView nview = Player.m_localPlayer.GetComponent(); + if (nview != null && nview.IsValid()) + { + nview.GetZDO().Set("RacesOfValheim_FenrirForm", prefabName); + } + + if (prefab != null && playerVisual != null) + { + playerVisual.localScale = Vector3.one * 0.001f; + + Transform visual = prefab.transform.Find("Visual"); + if (visual != null) + { + currentTransformation = Instantiate(visual.gameObject, Player.m_localPlayer.transform); + currentTransformation.transform.localPosition = Vector3.zero; + currentTransformation.transform.localRotation = Quaternion.identity; + Component animEvent = currentTransformation.GetComponent("AnimEvent"); + if (animEvent != null) Destroy(animEvent); + + float ttl = rules.DurationMinutes > 0 ? (rules.DurationMinutes * 60f) : 0f; + + if (prefabName == "Ulv") + { + currentTransformation.AddComponent(); + Player.m_localPlayer.GetSEMan().AddStatusEffect("SE_WolfForm".GetStableHashCode(), true); + var se = Player.m_localPlayer.GetSEMan().GetStatusEffect("SE_WolfForm".GetStableHashCode()); + if (se != null) se.m_ttl = ttl; + Player.m_localPlayer.Message(MessageHud.MessageType.Center, "You are an Ulv!"); + } + else if (prefabName == "Wolf") + { + currentTransformation.AddComponent(); + Player.m_localPlayer.GetSEMan().AddStatusEffect("SE_WolfForm".GetStableHashCode(), true); + var se = Player.m_localPlayer.GetSEMan().GetStatusEffect("SE_WolfForm".GetStableHashCode()); + if (se != null) se.m_ttl = ttl; + Player.m_localPlayer.Message(MessageHud.MessageType.Center, "You are a Wolf!"); + } + else if (prefabName == "Fenring_Cultist") + { + currentTransformation.AddComponent(); + Player.m_localPlayer.GetSEMan().AddStatusEffect("SE_CultistForm".GetStableHashCode(), true); + var se = Player.m_localPlayer.GetSEMan().GetStatusEffect("SE_CultistForm".GetStableHashCode()); + if (se != null) se.m_ttl = ttl; + Player.m_localPlayer.Message(MessageHud.MessageType.Center, "You are a Cultist!"); + } + else + { + currentTransformation.AddComponent(); + Player.m_localPlayer.GetSEMan().AddStatusEffect("SE_FenrirForm".GetStableHashCode(), true); + var se = Player.m_localPlayer.GetSEMan().GetStatusEffect("SE_FenrirForm".GetStableHashCode()); + if (se != null) se.m_ttl = ttl; + Player.m_localPlayer.Message(MessageHud.MessageType.Center, "You are a Fenring!"); + } + + isTransformed = true; + } + } + } + + private void DestroyAllForms() + { + if (Player.m_localPlayer == null) return; + var forms1 = Player.m_localPlayer.GetComponentsInChildren(true); + foreach (var f in forms1) Destroy(f.gameObject); + + var forms2 = Player.m_localPlayer.GetComponentsInChildren(true); + foreach (var f in forms2) Destroy(f.gameObject); + + var forms3 = Player.m_localPlayer.GetComponentsInChildren(true); + foreach (var f in forms3) Destroy(f.gameObject); + + var forms4 = Player.m_localPlayer.GetComponentsInChildren(true); + foreach (var f in forms4) Destroy(f.gameObject); + } + + private void ExecuteReversion() + { + Transform playerVisual = Player.m_localPlayer.transform.Find("Visual"); + if (currentTransformation != null) Destroy(currentTransformation); + DestroyAllForms(); // Safety check to remove any leaked forms + + // Sync to ZDO + ZNetView nview = Player.m_localPlayer.GetComponent(); + if (nview != null && nview.IsValid()) + { + nview.GetZDO().Set("RacesOfValheim_FenrirForm", ""); + } + + if (playerVisual != null) + { + playerVisual.localScale = Vector3.one; + playerVisual.gameObject.SetActive(true); + } + + Player.m_localPlayer.GetSEMan().RemoveStatusEffect("SE_FenrirForm".GetStableHashCode()); + Player.m_localPlayer.GetSEMan().RemoveStatusEffect("SE_CultistForm".GetStableHashCode()); + Player.m_localPlayer.GetSEMan().RemoveStatusEffect("SE_WolfForm".GetStableHashCode()); + + isTransformed = false; + Player.m_localPlayer.Message(MessageHud.MessageType.Center, "You returned to human form."); + + if (activeRules != null && activeRules.CooldownMinutes > 0) + { + string cdName = activeRules.Form == FenrirProgression.FormType.Cultist ? "SE_CultistCooldown" : "SE_FenrirCooldown"; + Player.m_localPlayer.GetSEMan().AddStatusEffect(cdName.GetStableHashCode(), true); + var cdSE = Player.m_localPlayer.GetSEMan().GetStatusEffect(cdName.GetStableHashCode()); + if (cdSE != null) cdSE.m_ttl = activeRules.CooldownMinutes * 60f; + } + activeRules = null; + } + } +} diff --git a/JotunnModStub/Fenrir/FenrirStatusEffects.cs b/JotunnModStub/Fenrir/FenrirStatusEffects.cs new file mode 100644 index 0000000..eab5005 --- /dev/null +++ b/JotunnModStub/Fenrir/FenrirStatusEffects.cs @@ -0,0 +1,46 @@ +using System.Collections; +using BepInEx; +using HarmonyLib; +using Jotunn.Configs; +using Jotunn.Entities; +using Jotunn.Managers; +using UnityEngine; +using UnityEngine.UI; // Added for UI + +namespace RacesOfValheim +{ + + public class SE_FormCooldown : StatusEffect + { + public override void Stop() + { + base.Stop(); + if (Player.m_localPlayer != null) + { + Player.m_localPlayer.Message(MessageHud.MessageType.Center, $"{m_name} is Ready!"); + } + } + } + + public class SE_FenrirCurse : SE_Stats + { + public override void Setup(Character character) + { + base.Setup(character); + if (character == Player.m_localPlayer) + { + Player.m_localPlayer.m_customData["FenrirCurse_Active"] = "true"; + } + } + + public override void UpdateStatusEffect(float dt) + { + base.UpdateStatusEffect(dt); + int state = BossProgressionManager.GetCurrentProgressionState(); + + m_fallDamageModifier = FenrirProgression.GetFallDamageModifier(state); + m_speedModifier = 1.0f + FenrirProgression.GetSpeedModifier(state); + m_jumpModifier = new Vector3(0, FenrirProgression.GetJumpModifier(state), 0); + } + } +} diff --git a/JotunnModStub/Furling/FurlingFireAbility.cs b/JotunnModStub/Furling/FurlingFireAbility.cs new file mode 100644 index 0000000..baf1920 --- /dev/null +++ b/JotunnModStub/Furling/FurlingFireAbility.cs @@ -0,0 +1,157 @@ +using HarmonyLib; +using UnityEngine; +using System.Collections.Generic; + +namespace RacesOfValheim +{ + /// + /// "Through Fire and Flames" — unlocks after Fader (state >= 8). + /// + /// Effects: + /// 1. Player has SE_Burning applied ONCE (999-min duration), like walking on a bonfire. + /// Reapplied automatically after respawn, load, or state unlock. + /// 2. No fire damage taken (handled in FurlingPatches.Furling_Character_Damage_Patch). + /// 3. The Burning icon is hidden from the HUD. + /// 4. All physical attacks apply SE_Burning to the target. + /// + public static class FurlingFireAbility + { + private static int _lastState = -1; + private static bool _burningApplied = false; + + private static readonly int BurningHash = "Burning".GetStableHashCode(); + private const float BURN_DURATION = 999f * 60f; // 999 minutes in seconds + + // ─── Called from FurlingRace.Update() — cheap check, no timer ──────── + public static void Tick() + { + if (Player.m_localPlayer == null || !FurlingRace.IsFurling()) + { + _burningApplied = false; + _lastState = -1; + return; + } + + int state = BossProgressionManager.GetCurrentProgressionState(); + + if (state < 8) + { + _burningApplied = false; + _lastState = state; + return; + } + + bool stateJustUnlocked = (_lastState < 8); + bool seMissing = !Player.m_localPlayer.GetSEMan() + .HaveStatusEffect(BurningHash); + + // Apply only when: first time, state just reached 8, or SE was lost (respawn/load) + if (!_burningApplied || stateJustUnlocked || seMissing) + { + ApplyPermanentBurning(); + _burningApplied = true; + } + + _lastState = state; + } + + private static void ApplyPermanentBurning() + { + var seman = Player.m_localPlayer.GetSEMan(); + + // Allow our application through the suppression patch + FurlingFire_SuppressExternalBurning_Patch.AllowNextBurning = true; + seman.AddStatusEffect(BurningHash, true); + + // Override the duration to 999 minutes so it never expires naturally + StatusEffect se = seman.GetStatusEffect(BurningHash); + if (se != null) + { + se.m_ttl = BURN_DURATION; + // Reset elapsed time so we start fresh + HarmonyLib.Traverse.Create(se).Field("m_time").Value = 0f; + } + } + + // ─── Hide Burning icon from HUD ─────────────────────────────────────── + [HarmonyPatch(typeof(SEMan), "GetStatusEffects")] + public static class FurlingFire_HideHUDBurning_Patch + { + public static void Postfix(SEMan __instance, List __result) + { + if (__result == null || __result.Count == 0) return; + + Character character = HarmonyLib.Traverse.Create(__instance) + .Field("m_character").Value; + if (character == null || character != Player.m_localPlayer) return; + if (!FurlingRace.IsFurling()) return; + if (BossProgressionManager.GetCurrentProgressionState() < 8) return; + + __result.RemoveAll(se => se != null && se.name != null && + se.name.IndexOf("Burning", System.StringComparison.OrdinalIgnoreCase) >= 0); + } + } + + // ─── Block external Burning (fire pits, arrows) from being applied ──── + [HarmonyPatch(typeof(SEMan), "AddStatusEffect", + new System.Type[] { typeof(int), typeof(bool), typeof(int), typeof(float) })] + public static class FurlingFire_SuppressExternalBurning_Patch + { + public static bool AllowNextBurning = false; + + public static bool Prefix(SEMan __instance, ref int nameHash) + { + if (nameHash != BurningHash) return true; + + Character character = HarmonyLib.Traverse.Create(__instance) + .Field("m_character").Value; + if (character == null || character != Player.m_localPlayer) return true; + if (!FurlingRace.IsFurling()) return true; + if (BossProgressionManager.GetCurrentProgressionState() < 8) return true; + + if (AllowNextBurning) + { + AllowNextBurning = false; + return true; // our own application — allow + } + + return false; // external source — block (player is immune) + } + } + + // ─── Physical attacks set enemies on fire ───────────────────────────── + [HarmonyPatch(typeof(Character), "Damage")] + public static class FurlingFire_IgniteOnHit_Patch + { + public static void Prefix(Character __instance, HitData hit) + { + if (__instance == null || __instance is Player) return; + if (Player.m_localPlayer == null || !FurlingRace.IsFurling()) return; + if (BossProgressionManager.GetCurrentProgressionState() < 8) return; + + Character attacker = hit.GetAttacker(); + if (attacker == null || attacker != Player.m_localPlayer) return; + + if (hit.m_damage.m_blunt > 0 || hit.m_damage.m_slash > 0 || + hit.m_damage.m_pierce > 0 || hit.m_damage.m_chop > 0 || + hit.m_damage.m_pickaxe > 0) + { + hit.m_damage.m_fire = Mathf.Max(hit.m_damage.m_fire, 10f); + } + } + + public static void Postfix(Character __instance, HitData hit) + { + if (__instance == null || __instance is Player) return; + if (Player.m_localPlayer == null || !FurlingRace.IsFurling()) return; + if (BossProgressionManager.GetCurrentProgressionState() < 8) return; + + Character attacker = hit.GetAttacker(); + if (attacker == null || attacker != Player.m_localPlayer) return; + + if (!__instance.IsDead()) + __instance.GetSEMan().AddStatusEffect(BurningHash, true); + } + } + } +} diff --git a/JotunnModStub/Furling/FurlingKingUI.cs b/JotunnModStub/Furling/FurlingKingUI.cs new file mode 100644 index 0000000..2589031 --- /dev/null +++ b/JotunnModStub/Furling/FurlingKingUI.cs @@ -0,0 +1,149 @@ +using HarmonyLib; +using UnityEngine; +using UnityEngine.UI; +using Jotunn.Managers; + +namespace RacesOfValheim +{ + /// + /// Displays a small "King / Queen" status indicator in the top-right corner of the HUD + /// when the local Furling player is inside the Plains biome and has unlocked the Yagluth ability (state >= 8). + /// Shows the unmodified Midsummer Crown icon above the gendered title. + /// + public static class FurlingKingUI + { + private static GameObject _hudRoot; // root panel anchored top-right + private static Image _crownImage; // the crown sprite + private static Text _titleText; // "King" / "Queen" + + private const float UPDATE_INTERVAL = 1.0f; + private static float _timer = 0f; + + // ─── Harmony patch: hook onto Hud.Update ───────────────────────────── + [HarmonyPatch(typeof(Hud), "Update")] + public static class FurlingKingUI_Hud_Update_Patch + { + public static void Postfix(Hud __instance) + { + _timer += Time.deltaTime; + if (_timer < UPDATE_INTERVAL) return; + _timer = 0f; + + Tick(__instance); + } + } + + // ─── Core update logic ──────────────────────────────────────────────── + private static void Tick(Hud hud) + { + bool shouldShow = ShouldShowKingStatus(); + + if (!shouldShow) + { + if (_hudRoot != null) _hudRoot.SetActive(false); + return; + } + + // Build the UI the first time it's needed + if (_hudRoot == null) + { + BuildUI(hud); + if (_hudRoot == null) return; // build failed (prefab not ready yet) + } + + _hudRoot.SetActive(true); + + // Update label based on player model (0 = male → King, 1 = female → Queen) + if (_titleText != null && Player.m_localPlayer != null) + { + int modelIndex = HarmonyLib.Traverse.Create( + Player.m_localPlayer.GetComponent() + ).Field("m_modelIndex").Value; + + _titleText.text = (modelIndex == 1) ? "Queen" : "King"; + } + } + + // ─── Condition check ────────────────────────────────────────────────── + private static bool ShouldShowKingStatus() + { + if (Player.m_localPlayer == null) return false; + if (!FurlingRace.IsFurling()) return false; + if (BossProgressionManager.GetCurrentProgressionState() < 8) return false; + + // Check Plains biome + Heightmap.Biome biome = Player.m_localPlayer.GetCurrentBiome(); + return biome == Heightmap.Biome.Plains; + } + + // ─── Build the HUD panel ────────────────────────────────────────────── + private static void BuildUI(Hud hud) + { + // Fetch the crown item icon + Sprite crownSprite = null; + var crownPrefab = PrefabManager.Cache.GetPrefab("HelmetMidsummerCrown"); + if (crownPrefab != null) + crownSprite = crownPrefab.m_itemData.m_shared.m_icons.Length > 0 + ? crownPrefab.m_itemData.m_shared.m_icons[0] + : null; + + // Parent to the Hud root canvas + Canvas canvas = hud.GetComponentInChildren(); + if (canvas == null) return; + + // Root panel + _hudRoot = new GameObject("FurlingKingStatus", typeof(RectTransform)); + _hudRoot.transform.SetParent(canvas.transform, false); + + RectTransform rt = _hudRoot.GetComponent(); + rt.anchorMin = new Vector2(1f, 1f); + rt.anchorMax = new Vector2(1f, 1f); + rt.pivot = new Vector2(1f, 1f); + rt.sizeDelta = new Vector2(90f, 110f); + rt.anchoredPosition = new Vector2(-10f, -10f); // 10px from top-right edge + + // ── Crown icon ────────────────────────────────────────────────── + GameObject iconGO = new GameObject("CrownIcon", typeof(RectTransform), typeof(Image)); + iconGO.transform.SetParent(_hudRoot.transform, false); + + RectTransform iconRt = iconGO.GetComponent(); + iconRt.anchorMin = new Vector2(0.5f, 1f); + iconRt.anchorMax = new Vector2(0.5f, 1f); + iconRt.pivot = new Vector2(0.5f, 1f); + iconRt.sizeDelta = new Vector2(72f, 72f); + iconRt.anchoredPosition = Vector2.zero; + + _crownImage = iconGO.GetComponent(); + _crownImage.preserveAspect = true; + if (crownSprite != null) + _crownImage.sprite = crownSprite; + else + _crownImage.color = new Color(1f, 0.9f, 0.2f, 1f); // gold fallback + + // ── Title text ────────────────────────────────────────────────── + GameObject textGO = new GameObject("TitleText", typeof(RectTransform), typeof(Text)); + textGO.transform.SetParent(_hudRoot.transform, false); + + RectTransform textRt = textGO.GetComponent(); + textRt.anchorMin = new Vector2(0f, 0f); + textRt.anchorMax = new Vector2(1f, 0f); + textRt.pivot = new Vector2(0.5f, 0f); + textRt.sizeDelta = new Vector2(0f, 28f); + textRt.anchoredPosition = Vector2.zero; + + _titleText = textGO.GetComponent(); + _titleText.text = "King"; + _titleText.alignment = TextAnchor.MiddleCenter; + _titleText.fontSize = 18; + _titleText.fontStyle = FontStyle.Bold; + _titleText.color = new Color(1f, 0.92f, 0.4f, 1f); // gold text + + // Try to match Valheim's font + _titleText.font = Resources.GetBuiltinResource("Arial.ttf"); + + // ── Subtle dark backing for readability ───────────────────────── + CanvasGroup cg = _hudRoot.AddComponent(); + cg.alpha = 0.92f; + } + } +} diff --git a/JotunnModStub/Furling/FurlingPatches.cs b/JotunnModStub/Furling/FurlingPatches.cs new file mode 100644 index 0000000..29074cc --- /dev/null +++ b/JotunnModStub/Furling/FurlingPatches.cs @@ -0,0 +1,643 @@ +using HarmonyLib; +using UnityEngine; +using Jotunn.Managers; + +namespace RacesOfValheim +{ + public static class FurlingPatches + { + [HarmonyPatch(typeof(Player), "Update")] + public static class Furling_PlayerUpdate_Patch + { + public static void Postfix(Player __instance) + { + if (__instance == null || __instance != Player.m_localPlayer) return; + + if (FurlingRace.IsFurling()) + { + // Scale player visuals down by 19% (0.9 * 0.9 = 0.81) + GameObject visual = Traverse.Create(__instance).Field("m_visual").GetValue(); + if (visual != null && visual.transform.localScale != new Vector3(0.81f, 0.81f, 0.81f)) + { + visual.transform.localScale = new Vector3(0.81f, 0.81f, 0.81f); + } + } + else + { + // Reset scale if not Furling + GameObject visual = Traverse.Create(__instance).Field("m_visual").GetValue(); + if (visual != null && visual.transform.localScale == new Vector3(0.81f, 0.81f, 0.81f)) + { + visual.transform.localScale = Vector3.one; + } + } + } + } + + // +10% movement speed — fixed, does not scale with progression + [HarmonyPatch(typeof(Character), "GetRunSpeedFactor")] + public static class Furling_GetRunSpeedFactor_Patch + { + public static void Postfix(Character __instance, ref float __result) + { + if (__instance == null || __instance != Player.m_localPlayer) return; + if (!FurlingRace.IsFurling()) return; + __result *= 1.1f; + } + } + + [HarmonyPatch(typeof(BaseAI), "IsEnemy", typeof(Character), typeof(Character))] + public static class Furling_BaseAI_IsEnemy_Patch + { + public static void Postfix(Character a, Character b, ref bool __result) + { + if (!__result || !FurlingRace.IsFurling() || Player.m_localPlayer == null) return; + + Character playerChar = Player.m_localPlayer; + Character otherChar = null; + + if (a == playerChar) otherChar = b; + else if (b == playerChar) otherChar = a; + + if (otherChar != null) + { + string name = otherChar.gameObject.name.Replace("(Clone)", "").ToLower(); + if (name == "goblin" || + name == "goblinbrute" || + name == "goblinshaman" || + name == "lox" || + name == "deathsquito" || + name == "troll") + { + // Exclude minibosses/bosses explicitly if needed, but normally bosses are handled separately (Yagluth is GoblinKing). + if (name != "goblinking") + { + __result = false; + } + } + } + } + } + + [HarmonyPatch(typeof(VisEquipment), "UpdateVisuals")] + public static class Furling_VisEquipment_UpdateVisuals_Patch + { + public static string GetPlayerRace(VisEquipment visEq) + { + Player player = visEq.GetComponent(); + if (player != null) + { + ZNetView nview = player.GetComponent(); + if (nview != null && nview.IsValid()) + { + return nview.GetZDO().GetString("RacesOfValheim_Race", "Human"); + } + + // Main Menu handling and local fallback + if (player.m_customData != null && player.m_customData.TryGetValue("Race", out string r)) + { + return r; + } + } + return "Human"; + } + + public static void Postfix(VisEquipment __instance) + { + if (!__instance.m_isPlayer) return; + + string race = GetPlayerRace(__instance); + + if (race == "Furling") + { + // Ensure the base model IS shown + if (__instance.m_bodyModel != null) + { + __instance.m_bodyModel.enabled = true; + + Transform headBone = FindBoneByName(__instance.m_bodyModel.bones, "Head"); + if (headBone != null) + { + Transform furlingHead = headBone.Find("FurlingHead_Trophy"); + if (furlingHead == null) + { + GameObject trophyPrefab = PrefabManager.Cache.GetPrefab("TrophyGoblin")?.gameObject; + if (trophyPrefab != null) + { + // instantiateInWorldSpace = false per ereditare esattamente la trasformazione base + GameObject trophyVisual = UnityEngine.Object.Instantiate(trophyPrefab, headBone, false); + trophyVisual.name = "FurlingHead_Trophy"; + + // Rimuoviamo tutti gli script (HoverText, ZNetView, ItemDrop, ecc.) per evitare prompt a schermo + foreach (var comp in trophyVisual.GetComponentsInChildren()) + { + UnityEngine.Object.Destroy(comp); + } + if (trophyVisual.GetComponent() != null) + UnityEngine.Object.Destroy(trophyVisual.GetComponent()); + foreach (var col in trophyVisual.GetComponentsInChildren()) + { + UnityEngine.Object.Destroy(col); + } + // Valheim rig scales are huge (100). + // Spostiamo la testa leggermente in alto (asse Y = 0.0015) e 5cm indietro rispetto al centro (asse X positivo = 0.0005) + trophyVisual.transform.localPosition = new Vector3(0.0005f, 0.0015f, 0f); + // Torniamo allo stato precedente (Z=90) ma ruotiamo sull'asse delle orecchie (X) di -90 + trophyVisual.transform.localRotation = Quaternion.Euler(-90, 0, 90); + // Rimpiccioliamo la testa affinché entri in quella umana (ulteriore 20% in meno -> 0.005832) + trophyVisual.transform.localScale = new Vector3(0.005832f, 0.005832f, 0.005832f); + // Risolve il problema della trasparenza (dither): + // Non possiamo applicare m_bodyModel.material perché i modelli (UV map) non coincidono e l'oggetto diventa invisibile. + // Ripristiniamo il materiale originale del trofeo, ma cambiamo il suo shader in Custom/Creature per fargli + // supportare la dissolvenza (dither) della telecamera, mantenendo le sue texture originali (che sono già verdi). + foreach (var mr in trophyVisual.GetComponentsInChildren()) + { + if (mr.material != null) + { + Shader ditherShader = Shader.Find("Custom/Creature"); + if (ditherShader != null) + { + mr.material.shader = ditherShader; + } + } + } + } + } + else + { + furlingHead.gameObject.SetActive(true); + } + } + + int modelIndex = Traverse.Create(__instance).Field("m_modelIndex").Value; + if (modelIndex == 0) + { + HideItem(__instance, "m_hairItemInstance"); + HideItem(__instance, "m_hairItemInstances"); // In case it's a list in some versions + } + HideItem(__instance, "m_beardItemInstance"); + HideItem(__instance, "m_beardItemInstances"); + // Restore helmet visibility — let the game manage it normally + ShowItem(__instance, "m_helmetItemInstance"); + } + } + else + { + // Not a furling, cleanup + if (__instance.m_bodyModel != null) + { + __instance.m_bodyModel.enabled = true; + + Transform headBone = FindBoneByName(__instance.m_bodyModel.bones, "Head"); + if (headBone != null) + { + Transform furlingHead = headBone.Find("FurlingHead_Trophy"); + if (furlingHead != null) + { + furlingHead.gameObject.SetActive(false); + } + + // Distruggiamo il tappo del collo (se c'era in precedenza) per sicurezza + Transform neckCap = headBone.Find("FulingNeckCap"); + if (neckCap != null) + { + UnityEngine.Object.Destroy(neckCap.gameObject); + } + } + + ShowItem(__instance, "m_hairItemInstance"); + ShowItem(__instance, "m_beardItemInstance"); + ShowItem(__instance, "m_hairItemInstances"); + ShowItem(__instance, "m_beardItemInstances"); + } + } + } + + private static void HideItem(VisEquipment visEq, string fieldName) + { + try + { + var field = typeof(VisEquipment).GetField(fieldName, System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance); + if (field != null) + { + object val = field.GetValue(visEq); + if (val is GameObject go && go != null) + { + go.SetActive(false); + } + else if (val is System.Collections.Generic.List list) + { + foreach (var item in list) if (item != null) item.SetActive(false); + } + } + } + catch (System.Exception) { } + } + + private static void ShowItem(VisEquipment visEq, string fieldName) + { + try + { + var field = typeof(VisEquipment).GetField(fieldName, System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance); + if (field != null) + { + object val = field.GetValue(visEq); + if (val is GameObject go && go != null) + { + go.SetActive(true); + } + else if (val is System.Collections.Generic.List list) + { + foreach (var item in list) if (item != null) item.SetActive(true); + } + } + } + catch (System.Exception) { } + } + + private static Transform FindBoneByName(Transform[] bones, string targetBoneName) + { + // Exact match first + foreach (Transform b in bones) + { + if (b != null && b.name == targetBoneName) return b; + } + + // Fuzzy match + string sName = targetBoneName.ToLower().Replace("goblin_", "").Replace("furling_", "").Replace(" goblin", ""); + + // Common valheim mappings + if (sName == "pelvis") sName = "hips"; + if (sName == "clavicle.l") sName = "leftshoulder"; + if (sName == "clavicle.r") sName = "rightshoulder"; + if (sName == "upperarm.l") sName = "leftarm"; + if (sName == "upperarm.r") sName = "rightarm"; + if (sName == "lowerarm.l") sName = "leftforearm"; + if (sName == "lowerarm.r") sName = "rightforearm"; + if (sName == "thigh.l") sName = "leftupleg"; + if (sName == "thigh.r") sName = "rightupleg"; + if (sName == "calf.l") sName = "leftleg"; + if (sName == "calf.r") sName = "rightleg"; + + foreach (Transform b in bones) + { + if (b != null) + { + string pName = b.name.ToLower(); + if (pName == sName || pName.Contains(sName) || sName.Contains(pName)) + { + return b; + } + } + } + + return null; + } + } + + [HarmonyPatch(typeof(Skills), "RaiseSkill")] + public static class Furling_Skills_RaiseSkill_Patch + { + public static void Prefix(Skills __instance, Skills.SkillType skillType, ref float factor) + { + // Check if this Skills instance belongs to the local player + Player player = HarmonyLib.Traverse.Create(__instance).Field("m_player").GetValue(); + if (player != null && player == Player.m_localPlayer && FurlingRace.IsFurling()) + { + // The Art of War: Double XP for weapon skills (always active) + bool isWeaponSkill = (skillType == Skills.SkillType.Swords || + skillType == Skills.SkillType.Knives || + skillType == Skills.SkillType.Clubs || + skillType == Skills.SkillType.Polearms || + skillType == Skills.SkillType.Spears || + skillType == Skills.SkillType.Axes || + skillType == Skills.SkillType.Bows || + skillType == Skills.SkillType.Crossbows || + skillType == Skills.SkillType.Unarmed || + skillType == Skills.SkillType.Blocking); + + if (isWeaponSkill) + { + factor *= 2f; + } + else if (BossProgressionManager.GetCurrentProgressionState() >= 6) + { + // The King is Dead: in Plains, ALL other skills (including magic) get 2x XP + if (EnvMan.instance != null && EnvMan.instance.GetCurrentBiome() == Heightmap.Biome.Plains) + { + factor *= 2f; + } + } + } + } + } + + [HarmonyPatch(typeof(Character), "AddNoise")] + public static class Furling_Character_AddNoise_Patch + { + public static bool Prefix(Character __instance, float range) + { + if (__instance != null && __instance == Player.m_localPlayer && FurlingRace.IsFurling()) + { + // Check if it's nighttime or inside a dungeon + if (BossProgressionManager.GetCurrentProgressionState() >= 2) // Master of Shadows (Eikthyr) + { + if (range <= 15f) + { + return false; + } + } + } + return true; + } + } + + [HarmonyPatch(typeof(Character), "Damage")] + public static class Furling_Character_Damage_Patch + { + public static void Prefix(Character __instance, HitData hit) + { + if (__instance != null && __instance == Player.m_localPlayer && FurlingRace.IsFurling()) + { + int state = BossProgressionManager.GetCurrentProgressionState(); + if (state >= 8) // Through Fire and Flames (Fader): full fire immunity + { + hit.m_damage.m_fire = 0f; + if (hit.m_damage.m_poison > 0) hit.m_damage.m_poison *= 0.5f; + } + else if (state >= 3) // The Wickerman: -50% fire and poison + { + if (hit.m_damage.m_fire > 0) hit.m_damage.m_fire *= 0.5f; + if (hit.m_damage.m_poison > 0) hit.m_damage.m_poison *= 0.5f; + } + } + } + } + + [HarmonyPatch(typeof(Projectile), "Setup")] + public static class Furling_Projectile_Setup_Patch + { + public static void Prefix(Character owner, Vector3 velocity, float hitNoise, HitData hitData, ItemDrop.ItemData item, ItemDrop.ItemData ammo) + { + if (owner != null && owner == Player.m_localPlayer && FurlingRace.IsFurling()) + { + if (BossProgressionManager.GetCurrentProgressionState() >= 3) // The Wickerman (Elder) + { + // Check if it's an arrow (either by skill or by checking if a bow/ammo was used) + if ((hitData != null && hitData.m_skill == Skills.SkillType.Bows) || + (ammo != null && ammo.m_shared.m_skillType == Skills.SkillType.Bows)) + { + // If the arrow doesn't already have significant fire damage, add it + if (hitData != null && hitData.m_damage.m_fire < 22f) + { + // Adds fire damage equivalent to a standard fire arrow + hitData.m_damage.m_fire = Mathf.Max(hitData.m_damage.m_fire, 22f); + } + } + } + } + } + } + + [HarmonyPatch(typeof(InventoryGui), "DoCrafting")] + public static class Furling_InventoryGui_DoCrafting_Patch + { + public static void Postfix(InventoryGui __instance, Player player) + { + if (Player.m_localPlayer != null && FurlingRace.IsFurling()) + { + if (BossProgressionManager.GetCurrentProgressionState() >= 4) // Dance of the Dead (Bonemass) + { + Recipe craftRecipe = HarmonyLib.Traverse.Create(__instance).Field("m_craftRecipe").GetValue(); + if (craftRecipe == null || craftRecipe.m_item == null) return; + + ItemDrop itemDrop = craftRecipe.m_item; + string prefabName = itemDrop.gameObject.name.ToLower(); + ItemDrop.ItemData.ItemType type = itemDrop.m_itemData.m_shared.m_itemType; + + bool isMead = prefabName.Contains("mead") || prefabName.Contains("potion") || prefabName.Contains("wine"); + bool isBomb = prefabName.Contains("bomb") || prefabName.Contains("oozeboomb") || prefabName.Contains("bile"); + bool isAmmo = type == ItemDrop.ItemData.ItemType.Ammo; + + if (isMead || isBomb || isAmmo) + { + int amount = craftRecipe.m_amount; + ItemDrop.ItemData craftUpgradeItem = HarmonyLib.Traverse.Create(__instance).Field("m_craftUpgradeItem").GetValue(); + int quality = craftUpgradeItem != null ? craftUpgradeItem.m_quality + 1 : 1; + int craftVariant = HarmonyLib.Traverse.Create(__instance).Field("m_craftVariant").GetValue(); + + ItemDrop.ItemData addedItem = player.GetInventory().AddItem(itemDrop.gameObject.name, amount, quality, craftVariant, player.GetPlayerID(), player.GetPlayerName()); + + if (addedItem == null) + { + // Inventory full, drop on ground + GameObject go = UnityEngine.Object.Instantiate(itemDrop.gameObject, player.transform.position + player.transform.forward + Vector3.up, Quaternion.identity); + ItemDrop drop = go.GetComponent(); + drop.m_itemData.m_stack = amount; + drop.m_itemData.m_quality = quality; + drop.m_itemData.m_variant = craftVariant; + } + } + } + } + } + } + + [HarmonyPatch(typeof(VisEquipment), "UpdateColors")] + public static class FurlingSkinColorPatch + { + public static void Postfix(VisEquipment __instance) + { + if (!__instance.m_isPlayer) return; + + string race = Furling_VisEquipment_UpdateVisuals_Patch.GetPlayerRace(__instance); + if (race == "Furling") + { + if (__instance.m_bodyModel != null && __instance.m_bodyModel.material != null) + { + // Verde più acceso/brillante (Goblin) + Color furlingColor = new Color(0.4f, 0.75f, 0.25f, 1f); + __instance.m_bodyModel.material.SetColor("_SkinColor", furlingColor); + } + int modelIndex = Traverse.Create(__instance).Field("m_modelIndex").Value; + if (modelIndex == 1) // Female + { + var hairInst = Traverse.Create(__instance).Field("m_hairItemInstance").GetValue(); + if (hairInst != null) + { + foreach (var r in hairInst.GetComponentsInChildren()) + { + if (r.material != null) r.material.SetColor("_SkinColor", Color.red); + } + } + } + } + } + } + + public static bool IsMining = false; + + [HarmonyPatch(typeof(CharacterDrop), "GenerateDropList")] + public static class Furling_CharacterDrop_GenerateDropList_Patch + { + public static void Postfix(CharacterDrop __instance, ref System.Collections.Generic.List> __result) + { + if (Player.m_localPlayer == null || !FurlingRace.IsFurling()) return; + if (BossProgressionManager.GetCurrentProgressionState() < 5) return; + + Character character = __instance.GetComponent(); + if (character != null && (character.IsBoss() || character.gameObject.name.ToLower().Contains("boss"))) return; + + float distance = Vector3.Distance(Player.m_localPlayer.transform.position, __instance.transform.position); + if (distance > 25f) return; + + var newList = new System.Collections.Generic.List>(); + foreach (var drop in __result) + { + var go = drop.Key; + int amount = drop.Value; + if (go != null) + { + var itemDrop = go.GetComponent(); + if (itemDrop != null && itemDrop.m_itemData.m_shared.m_itemType == ItemDrop.ItemData.ItemType.Trophy) + { + amount *= 2; + } + } + newList.Add(new System.Collections.Generic.KeyValuePair(go, amount)); + } + + Character character2 = __instance.GetComponent(); + int stars = character2 != null ? character2.GetLevel() - 1 : 0; + if (stars > 0) + { + GameObject coinsPrefab = Jotunn.Managers.PrefabManager.Cache.GetPrefab("Coins"); + if (coinsPrefab != null) + { + int extraCoins = stars * UnityEngine.Random.Range(1, 26); + newList.Add(new System.Collections.Generic.KeyValuePair(coinsPrefab, extraCoins)); + } + } + + __result = newList; + } + } + + [HarmonyPatch(typeof(MineRock5), "DamageArea")] + public static class Furling_MineRock5_DamageArea_Patch + { + public static void Prefix(HitData hit, out bool __state) + { + __state = false; + if (hit == null) return; + Character attacker = hit.GetAttacker(); + if (attacker != null && attacker == Player.m_localPlayer && FurlingRace.IsFurling() && BossProgressionManager.GetCurrentProgressionState() >= 5) + { + IsMining = true; + __state = true; + } + } + public static void Postfix(bool __state) + { + if (__state) IsMining = false; + } + } + + [HarmonyPatch(typeof(MineRock), "RPC_Hit")] + public static class Furling_MineRock_RPC_Damage_Patch + { + public static void Prefix(HitData hit, out bool __state) + { + __state = false; + if (hit == null) return; + Character attacker = hit.GetAttacker(); + if (attacker != null && attacker == Player.m_localPlayer && FurlingRace.IsFurling() && BossProgressionManager.GetCurrentProgressionState() >= 5) + { + IsMining = true; + __state = true; + } + } + public static void Postfix(bool __state) + { + if (__state) IsMining = false; + } + } + + [HarmonyPatch(typeof(Destructible), "RPC_Damage")] + public static class Furling_Destructible_RPC_Damage_Patch + { + public static void Prefix(HitData hit, out bool __state) + { + __state = false; + if (hit == null) return; + Character attacker = hit.GetAttacker(); + if (attacker != null && attacker == Player.m_localPlayer && FurlingRace.IsFurling() && BossProgressionManager.GetCurrentProgressionState() >= 5) + { + IsMining = true; + __state = true; + } + } + public static void Postfix(bool __state) + { + if (__state) IsMining = false; + } + } + + [HarmonyPatch(typeof(DropTable), "GetDropList", new System.Type[] { typeof(int) })] + public static class Furling_DropTable_GetDropList_Patch + { + public static void Postfix(ref System.Collections.Generic.List __result) + { + if (IsMining && __result != null) + { + var extraDrops = new System.Collections.Generic.List(); + foreach (var go in __result) + { + if (go == null) continue; + string lower = go.name.ToLower(); + if (lower.Contains("copperore") || lower.Contains("tinore") || lower.Contains("ironscrap") || lower.Contains("silverore") || lower.Contains("blackmetalscrap") || lower.Contains("flametalore")) + { + extraDrops.Add(go); + } + } + __result.AddRange(extraDrops); + } + } + } + + // ── "In the Mist He/She Was Standing" (The Queen, state >= 7) ───────── + // Eitr foods (blue foods) have double digestion time. + // We halve the rate at which food m_time decrements for eitr foods. + [HarmonyPatch(typeof(Player), "UpdateFood")] + public static class Furling_UpdateFood_EitrDuration_Patch + { + // Prefix: halve dt for eitr foods by doubling the denominator via a custom flag + // Easiest approach: Postfix after the vanilla update, then undo half the time consumed. + public static void Postfix(Player __instance, float dt) + { + if (__instance != Player.m_localPlayer) return; + if (!FurlingRace.IsFurling()) return; + if (BossProgressionManager.GetCurrentProgressionState() < 7) return; + + // Valheim decrements food.m_time by dt each call. + // We give back half of dt for eitr foods, effectively halving consumption. + var foods = HarmonyLib.Traverse.Create(__instance).Field>("m_foods").Value; + if (foods == null) return; + + foreach (var food in foods) + { + if (food == null || food.m_item == null) continue; + // Blue food = eitr > 0 + if (food.m_item.m_shared.m_foodEitr > 0f) + { + // Give back half of dt that vanilla subtracted + food.m_time += dt * 0.5f; + // Clamp to max burn time so we don't exceed the original duration + float maxTime = food.m_item.m_shared.m_foodBurnTime; + if (food.m_time > maxTime) food.m_time = maxTime; + } + } + } + } + } +} diff --git a/JotunnModStub/Furling/FurlingProgression.cs b/JotunnModStub/Furling/FurlingProgression.cs new file mode 100644 index 0000000..3158cb7 --- /dev/null +++ b/JotunnModStub/Furling/FurlingProgression.cs @@ -0,0 +1,16 @@ +using System; + +namespace RacesOfValheim +{ + public static class FurlingProgression + { + public static void UpdateProgression() + { + if (!FurlingRace.IsFurling()) return; + + int state = BossProgressionManager.GetCurrentProgressionState(); + + // Progression logic based on defeated bosses + } + } +} diff --git a/JotunnModStub/Furling/FurlingRace.cs b/JotunnModStub/Furling/FurlingRace.cs new file mode 100644 index 0000000..80939ad --- /dev/null +++ b/JotunnModStub/Furling/FurlingRace.cs @@ -0,0 +1,44 @@ +using BepInEx; +using HarmonyLib; +using UnityEngine; +using System.Collections.Generic; + +namespace RacesOfValheim +{ + public class FurlingRace : MonoBehaviour + { + private static FurlingRace _instance; + public static FurlingRace Instance + { + get + { + if (_instance == null) + { + GameObject go = new GameObject("FurlingRace"); + _instance = go.AddComponent(); + DontDestroyOnLoad(go); + } + return _instance; + } + } + + public static bool IsFurling() + { + return Player.m_localPlayer != null && Player.m_localPlayer.GetPlayerModel() == 5; // Assumed ID for Furling + } + + public void CreateModAssets() + { + Jotunn.Logger.LogInfo("Initializing Furling Race..."); + FurlingStatusEffects.RegisterStatusEffects(); + } + + private void Update() + { + if (!IsFurling()) return; + + // Through Fire and Flames (Fader) + FurlingFireAbility.Tick(); + } + } +} diff --git a/JotunnModStub/Furling/FurlingStatusEffects.cs b/JotunnModStub/Furling/FurlingStatusEffects.cs new file mode 100644 index 0000000..c5cc25f --- /dev/null +++ b/JotunnModStub/Furling/FurlingStatusEffects.cs @@ -0,0 +1,14 @@ +using Jotunn.Managers; +using Jotunn.Entities; +using UnityEngine; + +namespace RacesOfValheim +{ + public static class FurlingStatusEffects + { + public static void RegisterStatusEffects() + { + // Register custom status effects for Furling + } + } +} diff --git a/JotunnModStub/Package/README.md b/JotunnModStub/Package/README.md new file mode 100644 index 0000000..dbbcde8 --- /dev/null +++ b/JotunnModStub/Package/README.md @@ -0,0 +1,104 @@ +# RacesOfValheim + +A comprehensive Valheim mod that allows you to play as different unique races, each offering distinct mechanics, visual transformations, and a deep progression system tailored to your journey in Valheim. + +## Features + +This mod currently introduces 4 custom races: + +### 1. Skeleton +- **Stamina-less Combat**: Skeletons do not consume stamina and do not use the stamina bar. +- **Undead Diet**: You cannot eat standard food. Instead, you gain maximum health automatically as you defeat Valheim's bosses to compensate for the lack of food buffs. +### 2. Skadi +- **Ice Affinity**: Gain unique resistance and affinity to the cold. + +### 3. Fenrir +- **Beast Form**: Transform into a powerful wolf-like beast. +- **Cultist Form**: Transform into a Cultist to wield fire abilities. +- **Progression**: The beast and cultist forms evolve as you defeat Valheim's bosses, granting new abilities, cooldown reductions, and power scaling. Immune to fall damage in both forms. + +### 4. Aswid +- **The Vampire**: A creature of the night with powerful life-draining abilities. +- **Bat Transformation**: Press `G` to transform into a bat, allowing you to fly over obstacles and travel quickly. +- **Blood Magic**: Block to channel a life-draining aura that saps the life of enemies in an area around you (doubled radius at night). +- **Blood Magic Mastery**: You can cast Blood Magic items with infinite Eitr, relying purely on their health costs. +- **Night Prowler**: Your passive speed and jump bonuses double during the night. +- **Undead Vigor**: Like the skeleton, the Aswid has infinite stamina. You consume the lifeforce of fallen foes directly instead of eating standard food. + +## Installation (manual) +1. Install BepInExPack Valheim. +2. Install Jotunn. +3. Extract the contents of this mod into your `BepInEx/plugins` folder. + +## Changelog +**v1.0.0** +- Initial release with 4 distinct races. +- Added Aswid life-draining and night transformations. +- Complete progression system tied to Valheim's bosses. + +**v1.1.0** +- **Aswid**: Passive abilities (Speed and Jump) are now properly doubled during the night. +- **Aswid**: New Enslavement Power (Yagluth tier)! Press E on non-tameable, non-boss enemies to enslave them for 60 seconds (15-min cooldown). Enslaved thralls fight alongside you and drop standard loot. +- **Aswid**: Edible thralls are automatically consumed upon death, granting you their lifeforce (Fader tier). +- **Aswid**: Complete overhaul of the Food system. Added Mistlands and Ashlands creatures to the consumption map. Accurately scaled food stats based on creature health. +- **Aswid**: Excluded undead and inorganic creatures (Skeletons, Draugrs, Golems, etc.) from being edible. +- **Aswid**: Added a dynamic green light effect to all forms (Bonemass tier). + +**v1.2.0** +- **Multiplayer Sync**: Fully implemented visual syncing for Aswid forms (Bat, Mist) and Skadi forms (Bear, Wolf, Hatchling, Fader) so other players can see your transformations in multiplayer! +- **Aswid**: Scrapped the Fader (Surtling) visual override; reaching the final progression state now makes the player 10% taller and adds a flat +30 physical damage bonus. +- **Aswid**: Defeating enemies with physical attacks in the final state now automatically consumes them if you have food slots available. +- **General**: Eradicated remaining localizations of the old "Strigoi" name. + +**v1.3.0** +- **Progression Fix**: Fixed a massive bug where boss progression states were misaligned. Players no longer receive Eikthyr or higher-tier powers immediately upon starting a new game (State 1). All unlocks now perfectly match the corresponding boss defeat global keys. +- **Furling**: Fine-tuned the custom 3D Goblin Head trophy alignment and scaling. It now fits perfectly inside the player's skull, revealing only the goblin ears! +- **Documentation**: Added complete level-by-level progression lists to the README for all races. + +## Race Progressions (Level-by-Level) + +### Aswid Progression +- **Base (No Bosses)**: Vampiric Aura (heal 20% on magic AoE damage). Progressive stats (+3 Armor, +5 Damage, +3% Speed, +3% Jump per boss killed). All passive bonuses are doubled at night! You can cast Blood Magic items with infinite Eitr. +- **Eikthyr**: Bat Transformation (Night only). +- **The Elder**: Bat Transformation (Always active). +- **Bonemass**: Superhuman Senses (Aura reveals untamed creatures). +- **Moder**: Freezing Blood (Permanent immunity to Freezing and Poison). +- **Yagluth**: Enslavement Power (E Key - Enslave non-tameable enemies). +- **The Queen**: Mist Form (H Key - Immune to physical/poison, double aura damage, weak to fire/frost/spirit. Breaks at sunrise). +- **Fader**: +10% Size, +30 Physical Damage. Physical kills automatically consume enemies. + +### Skadi Progression +- **Base (No Bosses)**: Immune to Cold, Bonus Frost Damage, 50% Frost Resistance. +- **Eikthyr**: +20% Eitr Regen, Freezing to Cold (mountains act as normal cold), Cold Spell. +- **The Elder**: Drake Form (Cannot attack). +- **Bonemass**: Drake Form (Can attack). +- **Moder**: Moder Form (1 min duration, 10 min cooldown). +- **Yagluth**: Improved Cold Spell. Moder Form (1 min duration, 5 min cooldown). +- **The Queen**: Moder Form (Unlimited duration, no cooldown). +- **Fader**: Skeleton Dragon Form. + +### Skeleton Progression +- **Base (No Bosses)**: +50 Max Health. Undead Diet (Cannot eat mortal food, no stamina bar). +- **Eikthyr**: Poison Skeleton Model, Poison Immunity, 5% Lifesteal, +80 Max Health. +- **The Elder**: 10% Lifesteal, Auto-Stun on First Hit, +110 Max Health. +- **Bonemass**: 15% Lifesteal, Poison Attacks, +140 Max Health. +- **Moder**: Fire Skeleton Model, 20% Lifesteal, Fire Aura, Enhanced Regen, +170 Max Health. +- **Yagluth**: 25% Lifesteal, Auto Resurrect, +200 Max Health. +- **The Queen**: 30% Lifesteal, Summon on Kill (Max 3 Skeletons), +230 Max Health. +- **Fader**: 35% Lifesteal, Max 5 Summons, +275 Max Health. + +### Fenrir Progression +- **Base (No Bosses)**: Progressive stats (+3 Armor, +5 Damage, -10% Fall Damage, +3% Speed, +3% Jump per boss killed). +- **The Elder**: Wolf Form (Night). +- **Bonemass**: Wolf Form (Day/Night). Ulv Form (Night). +- **Moder**: Ulv Form (Day/Night). Fenring Form (Night). +- **Yagluth**: Cultist Form (Night - 1 min duration, 10 min cooldown). +- **The Queen**: Fenring Form (Day/Night). Cultist Form (Night - 1 min duration, 5 min cooldown). +- **Fader**: Cultist Form (Day/Night). + +### Furling Progression +- **Eikthyr**: Master of Shadows (Bonus attack damage when in the dark or at night). +- **The Elder**: The Wickerman (-50% Fire and Poison damage, increased to -90% if it's from an arrow). +- **Bonemass**: Dance of the Dead (Ignore certain crafting costs). +- **Moder**: The Man/Woman on the Silver Mountain (Doubles normal enemy trophy drops, yields gold coins based on stars within 25 meters, and doubles mined raw ore yield). +- **Yagluth**: The King is Dead, Hail to the King/Queen (In the Plains biome, the 2x XP multiplier is extended to all non-combat skills). diff --git a/JotunnModStub/Package/icon.png b/JotunnModStub/Package/icon.png new file mode 100644 index 0000000000000000000000000000000000000000..26748d692279ad4fcef08b1230938a9f2efaa4e1 GIT binary patch literal 2368 zcmeHJ=~vPT7ybe6PT)+MOCgOmQDdd4R4zzbrZ!Hrm_~%=WSR@&7A_3J=xb(YJX5+gvrs5f=&o z&<|e#M*0sxf`r_;7B5$+Pv3~uIx=9!^`2_bFHeojV@?2tZQd<_T6PrVPs*1wTB z+;QDs{~`uMzxhBz&`rQ}^Z)SgIq(Lf%Nq;f^x1G9(6DK=MOh@<-B=jM{bZWkdecsL z+Le3TRC?2f-gMZ?JKQ%s@C!cFX@X4QJ!H1dknKA{&WSeQQ}-qFgf9(fVRbdZn9ums zgv#EKpl`~qdSF;E=Wb?1?cq8Oibd_KAs)(licCTE2U<1;07-RxfuunGsx$Ab#0B-E zj)h~BA*}a#*cvNdN!*DHdDg2B3(Hy6I>R0HjM zi%sw>RMxOolAw)#W|_w96kE|tY@G!X@E|(?fO%j3sucdMG7br;Ze(0 zkjh1J35^(vR0t|FBnEiM|Clrrx7nwEWVhGmQbsuFvr$+kyl?Z&KoYu&0zX#9>M2&6 zL0SG@WCjj8a}^DinLSH+ZKRFy@4tX5wkRL&e;TD8lyj8ZZnQC4AM1d17ZX>C+Cq|& zYG)q->uU9gZ>cficSevcY%32zZqlm02uI(zE90E|Gx_sp%YFao7vGEz=4E8dvHI=n+#9{dWrm60h&w>t z)K_2jja&mGmCt7pMmAZHpqxFzRMKxTO2=*HMs-s$(2Tsq?X|yJ=xS+@yrg@b?M3n< zwnCqppeyoaL~_fbZ>$ zLh{B-$$(%=jJsEF2URq&D6PD&9hv#9PVYahpoofDSxveX2Jnfw!)Xw-H-}8;N55ah_vFS+E6>rF1{9V`4Ih0bDR{k%AD)>2Oog5<1o>b zSXwssXv6v`)7Gs^zpk=iMtM-Zo~+FhnRDY#UoPyX4eQc_KzHGQh%K&_8AL^(ZT;xb4xjahkU9@rmVu)_L% zUYSp`ZaEre@QZ`ze)^N;7fFHU^p`04d^sTMFk(hyfrbU`kCJL=OADeqQ^3HIm-XMQ zF;JnPeGo3a995lbZ!;`rdPC}W<mMH+w!|C$mdUSFs_m8nY|UDn%pK76`uC)z(77xH3ePh!=@!3%xt7M zd%-hwh14h5HIx7;ivF4 literal 0 HcmV?d00001 diff --git a/JotunnModStub/Package/manifest.json b/JotunnModStub/Package/manifest.json new file mode 100644 index 0000000..6b2a327 --- /dev/null +++ b/JotunnModStub/Package/manifest.json @@ -0,0 +1,10 @@ +{ + "name": "RacesOfValheim", + "description": "A Valheim mod that adds custom playable races (Skeleton, Skadi, Fenrir, Aswid, Furling) each with unique abilities, traits, and a deep boss-driven progression system.", + "version_number": "1.3.2", + "website_url": "", + "dependencies": [ + "denikson-BepInExPack_Valheim-5.4.2333", + "ValheimModding-Jotunn-2.26.1" + ] +} diff --git a/JotunnModStub/Properties/AssemblyInfo.cs b/JotunnModStub/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..b986107 --- /dev/null +++ b/JotunnModStub/Properties/AssemblyInfo.cs @@ -0,0 +1,35 @@ +using System.Reflection; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("RacesOfValheim")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("RacesOfValheim")] +[assembly: AssemblyCopyright("Copyright © 2021")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("e3243d22-4307-4008-ba36-9f326008cde5")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +//[assembly: AssemblyVersion(JotunnModStub.JotunnModStub.PluginVersion)] +//[assembly: AssemblyFileVersion(JotunnModStub.JotunnModStub.PluginVersion)] diff --git a/JotunnModStub/Properties/IgnoreAccessModifiers.cs b/JotunnModStub/Properties/IgnoreAccessModifiers.cs new file mode 100644 index 0000000..cc1f3aa --- /dev/null +++ b/JotunnModStub/Properties/IgnoreAccessModifiers.cs @@ -0,0 +1,17 @@ +// Veilheim +// a Valheim mod +// +// File: IgnoreAccessModifiers.cs +// Project: Veilheim + +using System.Security.Permissions; + +// SecurityPermision set to minimum +// for skipping access modifiers check from the mono JIT +// The same attribute are added to the assembly when ticking +// Unsafe Code in the Project settings +// This is done here to allow an explanation of the trick and +// not in an outside source you could potentially miss. + +#pragma warning disable CS0618 // Type or member is obsolete +[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] diff --git a/JotunnModStub/README.md b/JotunnModStub/README.md new file mode 100644 index 0000000..e9389e3 --- /dev/null +++ b/JotunnModStub/README.md @@ -0,0 +1,156 @@ +# RacesOfValheim + +A comprehensive Valheim mod that allows you to play as different unique races, each offering distinct mechanics, visual transformations, and a deep progression system tailored to your journey in Valheim. + +## Features + +This mod currently introduces 6 custom races: + +### 1. Skeleton +- **Stamina-less Combat**: Skeletons do not consume stamina and do not use the stamina bar. +- **Undead Diet**: You cannot eat standard food. Instead, you gain maximum health automatically as you defeat Valheim's bosses to compensate for the lack of food buffs. + +### 2. Skadi +- **Ice Affinity**: Gain unique resistance and affinity to the cold. +- **Drake Form**: Transform into a frost Drake, taking to the skies and attacking from above. +- **Dragon Form**: Evolve your form into the mighty Moder and, eventually, unleash the terrifying power of the Skeleton Dragon. + +### 3. Fenrir +- **Beast Form**: Transform into a powerful wolf-like beast. +- **Cultist Form**: Transform into a Cultist to wield fire abilities. +- **Progression**: The beast and cultist forms evolve as you defeat Valheim's bosses, granting new abilities, cooldown reductions, and power scaling. Immune to fall damage in both forms. + +### 4. Aswid +- **The Vampire**: A creature of the night with powerful life-draining abilities. +- **Bat Transformation**: Press G to transform into a bat, allowing you to fly over obstacles and travel quickly. +- **Blood Magic**: Block to channel a life-draining aura that saps the life of enemies in an area around you (doubled radius at night). **Only available while in Bat or Mist form.** +- **Blood Magic Mastery**: You can cast Blood Magic items with infinite Eitr, relying purely on their health costs. +- **Day walker, Night stalker**: Your passive speed and jump bonuses double during the night. +- **Undead Vigor**: Like the skeleton, the Aswid has infinite stamina. You consume the lifeforce of fallen foes directly instead of eating standard food. + +### 5. Furling +- **Goblin Heritage**: You play as a Goblin (Fuling). No beard, no hair (for males). +- **Combat Mastery**: All weapon and combat skills gain 2x XP permanently. +- **Boss-Driven Progression**: Each major boss defeat unlocks a new passive ability. + +### 6. Trol +- **Trol Heritage**: Play as a massive Trol! You are natively 20% larger than a human. +- **Immense Strength**: Your carry weight is vastly increased and your armor naturally scales as you defeat bosses. +- **Rock Throwing**: You can hurl boulders at your enemies for massive physical damage. +- **Tree Weaponry**: At higher levels, transform into your True Form to rip logs directly out of trees and wield them as devastating weapons or throw them! + +## Installation (manual) +1. Install BepInExPack Valheim. +2. Install Jotunn. +3. Extract the contents of this mod into your BepInEx/plugins folder. + +## Race Progressions (Level-by-Level) + +### Trol Progression +- **Base (No Bosses)**: +20% Size. +200 Max Carry Weight. Gain +3 Armor per boss defeated. +- **Eikthyr**: Increased XP gain for physical labor and blunt combat (Clubs, Unarmed, Axes, Pickaxes, WoodCutting). +- **The Elder**: Unlock Rock Throwing ability. +10% passive health regeneration. +- **Bonemass**: +5% Size. +50 Carry Weight. +10 Damage to Clubs/Unarmed. +10 Rock Throwing Damage. Unlocks a **4th Food Slot**. +- **Moder**: Unlock True Form (Transformation ability). +- **Yagluth**: +5% Size. +50 Carry Weight. +10 Damage to Clubs/Unarmed. +5 Rock Throwing Damage. Unlocks a **5th Food Slot**. +- **The Queen**: Unlock Log Weapon (in True Form, interact with trees to wield them as weapons). True Form size is massively increased (2.5x). +- **Fader**: Your wielded trees can now instantly smash through the toughest materials in the Ashlands. + +### Furling Progression +- **Base (No Bosses)**: Goblin head model. All weapon & combat skills gain 2x XP permanently. +- **Eikthyr**: Master of Shadows — sounds ≤15m are suppressed (near-silent movement). +- **The Elder**: The Wickerman — -50% Fire & Poison damage; arrows gain bonus fire damage. +- **Bonemass**: Dance of the Dead — Crafting meads, bombs, and ammo yields double quantity. +- **Moder**: The Man/Woman on the Silver Mountain — doubles trophy drops from normal enemies within 25m, drops bonus gold from starred enemies, doubles ore mining yield. +- **Yagluth**: The King is Dead, Hail to the King/Queen — while in the Plains biome, ALL skills gain 2x XP (including magic). HUD status icon shown. +- **The Queen**: In the Mist He/She Was Standing — blue (Eitr) foods last twice as long. +- **Fader**: Through Fire and Flames — permanently on fire (visual only), immune to fire damage, physical attacks set targets on fire. + +### Aswid Progression +- **Base (No Bosses)**: Physical kills automatically consume enemies (if edible). Progressive stats (+1 Armor, +2 Damage, +1% Speed, +1% Jump per boss killed). All passive bonuses are doubled at night! You can cast Blood Magic items with infinite Eitr. +- **Eikthyr**: Bat Transformation (Night only). Vampiric Aura (heal 20% on magic AoE damage). +- **The Elder**: Bat Transformation (Always active). +- **Bonemass**: Superhuman Senses (Aura reveals untamed creatures). +- **Moder**: Freezing Blood (Permanent immunity to Freezing and Poison). +- **Yagluth**: Enslavement Power (E Key — Enslave non-tameable enemies). +- **The Queen**: Mist Form (H Key — Immune to physical/poison, double aura damage, weak to fire/frost/spirit. Breaks at sunrise). +- **Fader**: +10% Size, +30 Physical Damage. Physical kills automatically consume enemies. + +### Skadi Progression +- **Base (No Bosses)**: Immune to Cold, Bonus Frost Damage, 50% Frost Resistance. +- **Eikthyr**: +20% Eitr Regen, Freezing to Cold, Cold Spell. +- **The Elder**: Drake Form (Cannot attack). +- **Bonemass**: Drake Form (Can attack). +- **Moder**: Moder Form (1 min duration, 10 min cooldown). +- **Yagluth**: Improved Cold Spell. Moder Form (1 min duration, 5 min cooldown). +- **The Queen**: Moder Form (Unlimited duration, no cooldown). +- **Fader**: Skeleton Dragon Form. + +### Skeleton Progression +- **Base (No Bosses)**: +50 Max Health. Undead Diet (Cannot eat mortal food, no stamina bar). +- **Eikthyr**: Poison Skeleton Model, Poison Immunity, 5% Lifesteal, +80 Max Health. +- **The Elder**: 10% Lifesteal, Auto-Stun on First Hit, +110 Max Health. +- **Bonemass**: 15% Lifesteal, Poison Attacks, +140 Max Health. +- **Moder**: Fire Skeleton Model, 20% Lifesteal, Fire Aura, Enhanced Regen, +170 Max Health. +- **Yagluth**: 25% Lifesteal, Auto Resurrect, +200 Max Health. +- **The Queen**: 30% Lifesteal, Summon on Kill (Max 3 Skeletons), +230 Max Health. +- **Fader**: 35% Lifesteal, Max 5 Summons, +275 Max Health. + +### Fenrir Progression +- **Base (No Bosses)**: Progressive stats (+3 Armor, +5 Damage, -10% Fall Damage, +3% Speed, +3% Jump per boss killed). +- **The Elder**: Wolf Form (Night). +- **Bonemass**: Wolf Form (Day/Night). Ulv Form (Night). +- **Moder**: Ulv Form (Day/Night). Fenring Form (Night). +- **Yagluth**: Cultist Form (Night — 1 min duration, 10 min cooldown). +- **The Queen**: Fenring Form (Day/Night). Cultist Form (Night — 1 min duration, 5 min cooldown). +- **Fader**: Cultist Form (Day/Night). + +## Development & Feedback + +This is a stable release of Races of Valheim, but the mod is actively in development! We plan to add more races, gameplay elements, and refine the mechanics in future updates. +Any feedback, bug reports, or suggestions for new features are more than welcome. +Please write to us on my Discord server: **https://discord.gg/gbBEK2VTE** + +## Changelog + +**v1.3.2** +- **Aswid**: Blood Magic (Vampiric Aura) is now only active when blocking in Bat or Mist form. Base damage reduced by 50%. +- **Aswid**: Added thematic day/night transition messages ("what a horrible night to have a curse"). +- **Bugfix**: Fixed an issue where the new automatic food consumption logic for Aswid physical kills failed to find the correct prefabs for basic animals like Deer and Boars. + +**v1.3.1** +- **NEW RACE — Trol**: Added the sixth playable race, the Trol. Huge size, immense strength, rock throwing, and the ability to wield trees as weapons! +- **Trol Combat**: The Trol starts with increased size and carry weight, scaling stats as bosses are killed, and unlocking the ability to throw massive rocks at The Elder tier. +- **Trol True Form**: Unlocked at Moder, allowing you to transform. Once you defeat The Queen, you can look at trees while in True Form to rip a log out and use it as a massive 2-handed weapon! +- **Trol Stomachs**: As you progress, you unlock a 4th (Bonemass) and a 5th (Yagluth) stomach slot, allowing you to consume up to 5 foods simultaneously! +- **Bugfixes**: Fixed various item/food duplication bugs and polished the new eating logic to perfectly integrate with the native UI. + +**v1.3.0** +- **NEW RACE — Furling**: Added the fifth playable race, the Furling (Goblin). Unique goblin head model, full progression tied to all 7 bosses. +- **Furling — Eikthyr (Master of Shadows)**: Sounds below 15m range are suppressed, making you nearly silent at night or in dungeons. +- **Furling — The Elder (The Wickerman)**: Gain -50% Fire and Poison damage resistance. Arrows gain bonus fire damage. +- **Furling — Bonemass (Dance of the Dead)**: Crafting meads, bombs, and ammo yields double the quantity. +- **Furling — Moder (The Man/Woman on the Silver Mountain)**: Trophy drops from normal enemies are doubled, starred enemies drop bonus coins, and ore mining yields are doubled. +- **Furling — Yagluth (The King is Dead, Hail to the King/Queen)**: In the Plains biome, the 2x XP multiplier extends to ALL skills (including Elemental and Blood Magic). A HUD status icon appears in the top-right when active. +- **Furling — The Queen (In the Mist He/She Was Standing)**: Eitr (blue) foods last twice as long for you. +- **Furling — Fader (Through Fire and Flames)**: You are permanently wreathed in native fire flames (SE_Burning visual, no damage, no HUD warning). Full fire immunity. All physical attacks set targets on fire. +- **Bugfix**: Fixed MineRock.RPC_Damage → MineRock.RPC_Hit Harmony patch after a Valheim update renamed the method. + +**v1.2.0** +- **Multiplayer Sync**: Fully implemented visual syncing for Aswid forms (Bat, Mist) and Skadi forms (Bear, Wolf, Hatchling, Fader) so other players can see your transformations in multiplayer! +- **Aswid**: Scrapped the Fader (Surtling) visual override; reaching the final progression state now makes the player 10% taller and adds a flat +30 physical damage bonus. +- **Aswid**: Defeating enemies with physical attacks in the final state now automatically consumes them if you have food slots available. +- **General**: Eradicated remaining localizations of the old "Strigoi" name. + +**v1.1.0** +- **Aswid**: Passive abilities (Speed and Jump) are now properly doubled during the night. +- **Aswid**: New Enslavement Power (Yagluth tier)! Press E on non-tameable, non-boss enemies to enslave them for 60 seconds (15-min cooldown). Enslaved thralls fight alongside you and drop standard loot. +- **Aswid**: Edible thralls are automatically consumed upon death, granting you their lifeforce (Fader tier). +- **Aswid**: Complete overhaul of the Food system. Added Mistlands and Ashlands creatures to the consumption map. Accurately scaled food stats based on creature health. +- **Aswid**: Excluded undead and inorganic creatures (Skeletons, Draugrs, Golems, etc.) from being edible. +- **Aswid**: Added a dynamic green light effect to all forms (Bonemass tier). + +**v1.0.0** +- Initial release with 4 distinct races. +- Added Aswid life-draining and night transformations. +- Complete progression system tied to Valheim's bosses. diff --git a/JotunnModStub/RaceCompendium.cs b/JotunnModStub/RaceCompendium.cs new file mode 100644 index 0000000..180472b --- /dev/null +++ b/JotunnModStub/RaceCompendium.cs @@ -0,0 +1,217 @@ +using UnityEngine; +using HarmonyLib; +using System.Text; +using System.Collections.Generic; + +namespace RacesOfValheim +{ + public static class RaceCompendium + { + private static readonly string[] RaceTitles = new string[] + { + "Aswid Secrets", + "Fenrir Secrets", + "Skadi Secrets", + "Skeleton Secrets", + "Furling Secrets", + "Trol Secrets" + }; + + public static void UpdateCompendiumText(Player player) + { + if (player == null) return; + var knownTexts = HarmonyLib.Traverse.Create(player).Field("m_knownTexts").GetValue>(); + if (knownTexts == null) return; + + // 1. Remove all old race texts to keep it clean + foreach (var title in RaceTitles) + { + if (knownTexts.ContainsKey(title)) + { + knownTexts.Remove(title); + } + } + + // 2. Determine current race + ZNetView nview = player.GetComponent(); + if (nview == null || !nview.IsValid()) return; + string currentRace = nview.GetZDO().GetString("RacesOfValheim_Race", "Human"); + int state = BossProgressionManager.GetCurrentProgressionState(); + + if (currentRace == "Aswid") + { + GenerateAswidText(knownTexts, state); + } + else if (currentRace == "Fenrir") + { + GenerateFenrirText(knownTexts, state); + } + else if (currentRace == "Skadi") + { + GenerateSkadiText(knownTexts, state); + } + else if (currentRace == "Skeleton") + { + GenerateSkeletonText(knownTexts, state); + } + else if (currentRace == "Furling") + { + GenerateFurlingText(knownTexts, state, player); + } + else if (currentRace == "Trol") + { + GenerateTrolText(knownTexts, state, player); + } + } + + private static void GenerateTrolText(Dictionary knownTexts, int state, Player player) + { + StringBuilder sb = new StringBuilder(); + sb.AppendLine("The Trol's Heritage\n"); + + sb.AppendLine($"Base Passive: Physical kills automatically consume enemies (if edible). You are natively 20% larger than a human with immense strength. You have +200 Max Carry Weight and gain +3 Armor per boss defeated.\n"); + + if (state >= 1) + sb.AppendLine("Eikthyr Defeated: Increased XP gain for physical labor and blunt combat (Clubs, Unarmed, Axes, Pickaxes, WoodCutting).\n"); + + if (state >= 2) + sb.AppendLine("The Elder Defeated: Unlocked Rock Throwing ability. +10% passive health regeneration.\n"); + + if (state >= 3) + sb.AppendLine("Bonemass Defeated: +5% Size, +50 Carry Weight, +10 Damage to Clubs/Unarmed, +10 Rock Throwing Damage. Unlocked 4th Food Slot.\n"); + + if (state >= 4) + sb.AppendLine("Moder Defeated: Unlocked True Form (Transformation ability).\n"); + + if (state >= 5) + sb.AppendLine("Yagluth Defeated: +5% Size, +50 Carry Weight, +10 Damage to Clubs/Unarmed, +5 Rock Throwing Damage. Unlocked 5th Food Slot.\n"); + + if (state >= 6) + sb.AppendLine("The Queen Defeated: Unlocked Log Weapon (in True Form, interact with trees to wield them as weapons). True Form size is massively increased.\n"); + + if (state >= 7) + sb.AppendLine("Fader Defeated: Your wielded trees can now instantly smash through the toughest materials in the Ashlands.\n"); + + knownTexts["Trol Secrets"] = sb.ToString(); + } + + private static void GenerateAswidText(Dictionary knownTexts, int state) + { + int spd = state * 3; + int jmp = state * 3; + int arm = state * 3; + int dmg = state * 5; + + StringBuilder sb = new StringBuilder(); + sb.AppendLine("The Aswid's Curse\n"); + + sb.AppendLine($"[Base Passive] Benedictus et Afflictus:"); + sb.AppendLine($"Physical kills automatically consume enemies (Vae Victis) granting Blood Magic XP. Your physical stats scale progressively as you defeat Valheim's Bosses: +{arm} Armor, +{dmg} Damage, +{spd}% Speed, and +{jmp}% Jump. All your passive bonuses are doubled during the night. You can cast Blood Magic items with infinite Eitr, and your Blood Magic skill increases twice as fast.\n"); + sb.AppendLine("Vampiric Aura (Like a Bat out of Hell/Weight of Shadows Only): Block with your shield (Mouse 2) while in bat or mist form to channel an AoE magic damage aura against nearby enemies, healing for 20% of the damage dealt and converting them into food when they die.\n"); + if (state >= 1) + { + // Eikthyr - Base passives already covered + } + + if (state >= 5) + { + sb.AppendLine("[Moder Unlock] Freezing Blood (Passive):"); + sb.AppendLine("You gain permanent immunity to the Freezing status (mountains/snowstorms) and Poison damage.\n"); + sb.AppendLine("[Moder Unlock] Auspex (Passive):"); + sb.AppendLine("You emit a 10-meter aura that reveals the presence of untamed creatures by wreathing them in ethereal flames.\n"); + } + + if (state >= 6) + { + sb.AppendLine("[Yagluth Unlock] Dominate (E Key):"); + sb.AppendLine("Press E on non-tameable, non-boss enemies to dominate them for 60 seconds (15-min cooldown). Dominated thralls fight alongside you and drop standard loot.\n"); + } + + if (state >= 7) + { + sb.AppendLine("[The Queen Unlock] Weight of Shadows (H Key):"); + sb.AppendLine("You transform into an elusive mist. You become immune to physical and poison damage, but weak to fire, frost, and spirit. Your Vampiric Aura deals double damage, but you cannot attack or run. Sunrise breaks the transformation.\n"); + } + + if (state >= 8) + { + sb.AppendLine("[Fader Unlock] Asmund (Passive):"); + sb.AppendLine("Your hair and beard turn as dark as the abyss. You become 10% taller and gain a flat +30 to Physical Damage.\n"); + } + + knownTexts["Aswid Secrets"] = sb.ToString(); + } + + private static void GenerateFenrirText(Dictionary knownTexts, int state) + { + int spd = state * 3; + int jmp = state * 3; + int arm = state * 3; + int dmg = state * 5; + knownTexts["Fenrir Secrets"] = $"The secrets of the pack will be revealed soon...\n\nBase Passive: Physical kills automatically consume enemies (if edible). Your physical stats scale progressively as you defeat Valheim's Bosses: +{arm} Armor, +{dmg} Damage, +{spd}% Speed, and +{jmp}% Jump."; + } + + private static void GenerateSkadiText(Dictionary knownTexts, int state) + { + knownTexts["Skadi Secrets"] = "The secrets of winter will be revealed soon..."; + } + + private static void GenerateSkeletonText(Dictionary knownTexts, int state) + { + knownTexts["Skeleton Secrets"] = "The secrets of the crypt will be revealed soon..."; + } + + private static void GenerateFurlingText(Dictionary knownTexts, int state, Player player) + { + StringBuilder sb = new StringBuilder(); + sb.AppendLine("The secrets of the hoard will be revealed soon...\n"); + + sb.AppendLine("[Base Passive] Combat Mastery:"); + sb.AppendLine("All weapon and combat skills gain 2x XP permanently. You're short, but very fast — your movement speed is permanently increased by 10%.\n"); + + if (state >= 5) + { + int modelIndex = Traverse.Create(player.GetComponent()).Field("m_modelIndex").Value; + string title = modelIndex == 1 ? "The Woman on the Silver Mountain" : "The Man on the Silver Mountain"; + sb.AppendLine($"[Moder Unlock] {title} (Passive):"); + sb.AppendLine("Whenever a normal enemy dies within 25 meters, its trophy drops are doubled and it drops guaranteed gold coins based on its stars. Furthermore, whenever you mine raw ore deposits, your yield is doubled.\n"); + } + + if (state >= 6) + { + int modelIndex = Traverse.Create(player.GetComponent()).Field("m_modelIndex").Value; + string title = modelIndex == 1 ? "The King is Dead, Hail to the Queen" : "The King is Dead, Hail to the King"; + sb.AppendLine($"[Yagluth Unlock] {title} (Passive):"); + sb.AppendLine("While you are in the Plains biome, your 2x XP multiplier is extended to all non-combat skills (including Elemental Magic and Blood Magic).\n"); + } + + if (state >= 7) + { + int modelIndex = Traverse.Create(player.GetComponent()).Field("m_modelIndex").Value; + string title = modelIndex == 1 ? "In the Mist She Was Standing" : "In the Mist He Was Standing"; + sb.AppendLine($"[The Queen Unlock] {title} (Passive):"); + sb.AppendLine("Blue foods (those that restore Eitr) last twice as long for you compared to normal players.\n"); + } + + if (state >= 8) + { + sb.AppendLine("[Fader Unlock] Through Fire and Flames (Passive):"); + sb.AppendLine("You are permanently wreathed in flames. You are completely immune to fire damage. All your physical attacks (regardless of weapon or unarmed) set the target on fire.\n"); + } + + knownTexts["Furling Secrets"] = sb.ToString(); + } + } + + [HarmonyPatch(typeof(TextsDialog), "Setup")] + public static class CompendiumSetup_Patch + { + public static void Prefix(Player player) + { + if (player != null) + { + RaceCompendium.UpdateCompendiumText(player); + } + } + } +} diff --git a/JotunnModStub/RaceHostilityManager.cs b/JotunnModStub/RaceHostilityManager.cs new file mode 100644 index 0000000..8fc028a --- /dev/null +++ b/JotunnModStub/RaceHostilityManager.cs @@ -0,0 +1,56 @@ +using HarmonyLib; +using UnityEngine; + +namespace RacesOfValheim +{ + // --- RACE HOSTILITY MANAGER --- + // This script manages which mobs should not attack the player based on their race. + // For now, it manages wolves, ulvs, fenrings, and cultists for the Fenrir race. + + [HarmonyPatch(typeof(BaseAI), nameof(BaseAI.IsEnemy), new System.Type[] { typeof(Character), typeof(Character) })] + public static class RaceHostilityManager + { + public static void Postfix(Character a, Character b, ref bool __result) + { + if (!__result) return; // If already not enemies, skip + + if (a == null || b == null) return; + + Character playerCharacter = a.IsPlayer() ? a : (b.IsPlayer() ? b : null); + Character monster = a.IsPlayer() ? b : (b.IsPlayer() ? a : null); + + if (playerCharacter != null && monster != null) + { + Player p = playerCharacter as Player; + if (p != null) + { + // Fenrir Race Logic + if (p.m_customData.ContainsKey("Race") && p.m_customData["Race"] == "Fenrir") + { + string prefabName = monster.gameObject.name.ToLower(); + if (prefabName.Contains("wolf") || prefabName.Contains("fenring") || + prefabName.Contains("ulv") || prefabName.Contains("cultist")) + { + __result = false; + } + } + + // Aswid Race Logic + if (p.m_customData.ContainsKey("Race") && p.m_customData["Race"] == "Aswid") + { + string prefabName = monster.gameObject.name.ToLower(); + int state = BossProgressionManager.GetCurrentProgressionState(); + + if (state >= 2 && prefabName.Contains("boar")) __result = false; + if (state >= 3 && prefabName.Contains("bear")) __result = false; + if (state >= 4 && (prefabName.Contains("leech") || prefabName.Contains("ghost") || prefabName.Contains("wraith"))) __result = false; + if (state >= 5 && prefabName.Contains("wolf")) __result = false; + if (state >= 6 && (prefabName.Contains("lox") || prefabName.Contains("deathsquito"))) __result = false; + if (state >= 7 && (prefabName.Contains("hare") || prefabName.Contains("gjall"))) __result = false; + if (state >= 8 && (prefabName.Contains("asksvin") || prefabName.Contains("volture") || prefabName.Contains("vulture") || prefabName.Contains("valkyrie"))) __result = false; + } + } + } + } + } +} diff --git a/JotunnModStub/RacesOfValheim.cs b/JotunnModStub/RacesOfValheim.cs new file mode 100644 index 0000000..079e3b1 --- /dev/null +++ b/JotunnModStub/RacesOfValheim.cs @@ -0,0 +1,685 @@ +using System.Collections; +using BepInEx; +using HarmonyLib; +using Jotunn.Configs; +using Jotunn.Entities; +using Jotunn.Managers; +using UnityEngine; +using UnityEngine.UI; // Added for UI + +namespace RacesOfValheim +{ + [BepInPlugin(PluginGUID, PluginName, PluginVersion)] + [BepInDependency(Jotunn.Main.ModGuid)] + public class RacesOfValheim : BaseUnityPlugin + { + public const string PluginGUID = "com.nandor.racesofvalheim"; + public const string PluginName = "Races Of Valheim"; + public const string PluginVersion = "1.3.2"; + + private readonly Harmony harmony = new Harmony(PluginGUID); + + public static RacesOfValheim Instance; + private GameObject raceSelectionMenu; + + private void Awake() { + Instance = this; + harmony.PatchAll(); + gameObject.AddComponent(); + gameObject.AddComponent(); + 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()); + } + + private void CreateAllModAssets() { + PrefabManager.OnVanillaPrefabsAvailable -= CreateAllModAssets; + FenrirRace.Instance.CreateModAssets(); + SkadiRace.Instance.CreateModAssets(); + SkeletonRace.Instance.CreateModAssets(); + AswidRace.Instance.CreateModAssets(); + FurlingRace.Instance.CreateModAssets(); + TrolRace.Instance.CreateModAssets(); + } + // --- RACE SELECTION UI --- + public void ShowRaceSelectionMenu() + { + if (raceSelectionMenu != null) return; + if (GUIManager.Instance == null || GUIManager.CustomGUIFront == null) + { + Jotunn.Logger.LogWarning("GUIManager.CustomGUIFront is null, cannot show race menu."); + return; + } + + raceSelectionMenu = new GameObject("RaceSelectionMenu"); + raceSelectionMenu.transform.SetParent(GUIManager.CustomGUIFront.transform, false); + + RectTransform rect = raceSelectionMenu.AddComponent(); + rect.anchorMin = new Vector2(0, 0); + rect.anchorMax = new Vector2(1, 1); + rect.offsetMin = Vector2.zero; + rect.offsetMax = Vector2.zero; + + Image bg = raceSelectionMenu.AddComponent(); + bg.color = new Color(0, 0, 0, 0.9f); + + GameObject selectionPanel = new GameObject("SelectionPanel"); + selectionPanel.transform.SetParent(raceSelectionMenu.transform, false); + RectTransform spRect = selectionPanel.AddComponent(); + spRect.anchorMin = Vector2.zero; spRect.anchorMax = Vector2.one; + spRect.offsetMin = Vector2.zero; spRect.offsetMax = Vector2.zero; + + GameObject confirmationPanel = new GameObject("ConfirmationPanel"); + confirmationPanel.transform.SetParent(raceSelectionMenu.transform, false); + RectTransform cpRect = confirmationPanel.AddComponent(); + cpRect.anchorMin = Vector2.zero; cpRect.anchorMax = Vector2.one; + cpRect.offsetMin = Vector2.zero; cpRect.offsetMax = Vector2.zero; + confirmationPanel.SetActive(false); + + GameObject titleObj = new GameObject("Title"); + titleObj.transform.SetParent(selectionPanel.transform, false); + Text titleText = titleObj.AddComponent(); + titleText.font = GUIManager.Instance.AveriaSerifBold; + titleText.text = "Choose your Race"; + titleText.fontSize = 50; + titleText.alignment = TextAnchor.MiddleCenter; + titleText.color = Color.white; + RectTransform titleRect = titleObj.GetComponent(); + titleRect.anchoredPosition = new Vector2(0, 200); + titleRect.sizeDelta = new Vector2(600, 100); + + GameObject confTitleObj = new GameObject("ConfTitle"); + confTitleObj.transform.SetParent(confirmationPanel.transform, false); + Text confTitleText = confTitleObj.AddComponent(); + confTitleText.font = GUIManager.Instance.AveriaSerifBold; + confTitleText.fontSize = 50; + confTitleText.alignment = TextAnchor.MiddleCenter; + confTitleText.color = Color.white; + RectTransform confTitleRect = confTitleObj.GetComponent(); + confTitleRect.anchoredPosition = new Vector2(0, 150); + confTitleRect.sizeDelta = new Vector2(600, 100); + + GameObject confDescObj = new GameObject("ConfDesc"); + confDescObj.transform.SetParent(confirmationPanel.transform, false); + Text confDescText = confDescObj.AddComponent(); + confDescText.font = GUIManager.Instance.AveriaSerifBold; + confDescText.fontSize = 24; + confDescText.alignment = TextAnchor.MiddleCenter; + confDescText.color = Color.white; + RectTransform confDescRect = confDescObj.GetComponent(); + confDescRect.anchoredPosition = new Vector2(0, 0); + confDescRect.sizeDelta = new Vector2(800, 200); + + GameObject btnOkObj = new GameObject("OkButton"); + btnOkObj.transform.SetParent(confirmationPanel.transform, false); + RectTransform btnOkRect = btnOkObj.AddComponent(); + btnOkRect.sizeDelta = new Vector2(200, 60); + btnOkRect.anchoredPosition = new Vector2(120, -150); + Image btnOkImg = btnOkObj.AddComponent(); + btnOkImg.color = new Color(0.2f, 0.5f, 0.2f, 1f); + Button btnOk = btnOkObj.AddComponent